}).observe({ type: 'largest-contentful-paint', buffered: true }) // Helpers ///////////////////////////////////////////////////////////////////// function dedupe(arr, key) { return [...new Map(arr.map((item) => [item[key], item])).values()] } function getActivationStart() { const navEntry = getNavigationEntry() return (navEntry...
...getNavigationEntry() { const navigationEntry = self.performance && performance.getEntriesByType && performance.getEntriesByType('navigation')[0] if ( navigationEntry && navigationEntry.responseStart > 0 && navigationEntry.responseStart < performance.now() ) { return navigationEntry } } When optimizing LCP, these extra steps may be helpful: # media_performance_steps.rb Then(/^the image "(.*)" should...
Let's say we want Peter to respond to a method age that returns his age. On the other hand, Alice should not respond to this method as you...
...is empty, it's just discarded. Careful: In peter's case peter.class does not return his eigenclass now. It still returns User. This means the klass reference in the C...
...an expression like User.where(email: 'foo@bar.com') does not make an SQL query. It simply returns a scope object for further chaining with #where, #order, etc. Scopes will make an SQL...
...A scope like User.where(email: 'foo@bar.com') does not make an SQL query. It simply returns a scope object for further chaining with #where, #order, etc. It can be confusing that...
...hour format, @: same, but in 12-hour am/pm format \n: newline \r: carriage return \\: backslash Colors & Styles colors have to be escaped (see General), color codes should be followed by...
...30m\]>\[\033[00m\] ' => ✔ mycomputer ~/projects/platforms master > _ # Arne's epic timestamped prompt with return status indicator and status-colored (green if fresh, or red if unstaged, or yellow if staged) git...
...binary cannot run at all, but won't raise an error if the binary returns an exit code > 0. This will instead be reflected in status. stdout_str, error_str...
...str = stderr.read # read stderr to string status = wait_thr.value # will block until the command finishes; returns status that responds to .success? etc end This form is useful for long running commands...
...e.g. Article#name becomes Article#name_de and Article#name_en and Article#name returns the variant in the current locale. You also need a migration strategy to fill those...
...You can set it up to store timestamps as UTC in the database, but return magic, zone-aware values when accessing ActiveRecord time or date attributes. In practice this solution...
...Makes a color less saturated. grayscale($color) Converts a color to grayscale. complement($color) Returns the complement of a color. invert($color) Returns the inverse of a color...
...this object. Here are some tools to do so: Relevant methods @object.methods - Object.instance_methods returns a list of methods excluding methods inherited from Object. This makes the methods list drastically...
...filters the list of method names with a regular expression. Instance variables @object.instance_variables returns all instance variables defined on the object. Access them with @object.instance_variable_get :@varname, modify...
...probably only care about seconds. This means that two consecutive calls of Time.now probably return two inequal values. Consider freezing time in your tests so it is not dependent on...
Rails extends Time with a method #end_of_day which returns the latest possible Time on the same day. The exact value for this is...
...probably looks "nothing special", which is good. export async function deleteComment({ uuid }: { uuid: string }) { return withAuthorizedUser(async ({ accessibleBy }) => { const prisma = await prismaClient() const comment = await prisma.comment.findUnique({ where: { uuid }, include: { file...
}) if (!comment) { return notFound() } await prisma.comment.delete({ where: { uuid, AND: accessibleBy('delete').Comment, }, }) revalidatePath(`/backend/files/${comment.file.directoryUuid}`, 'layout') return 'ok' }) } Set up prettier First, add the prettier npm package.
...implemented both a version for loaded Ruby objects (Interval#overlaps?) and a scope that returns all overlapping intervals (Interval.overlapping). Depending on your problem you might need one or both or...
...this interval def overlaps?(other) start_date <= other.end_date && other.start_date <= end_date end # Return a scope for all interval overlapping the given interval, excluding the given interval itself
...scrollable element for the main viewport. On Chrome, Firefox and modern Safari, document.scrollingElement will return the element. The behavior varies on legacy browsers that we no longer support:
...versions, document.scrollingElement will return the element. On the legacy Edge engine (EdgeHTML), document.scrollingElement will return the element. IE11 does not support document.scrollingElement, but you can assume its . Setting overflow-y...
...falls back to a COUNT query count If a counter cache is set up, returns the cached value Issues a COUNT query else Caveats If you trigger a COUNT query...
...assertion. Using .size avoids this problem. length Loads all records from the database, then returns the number of elements
...String, Integer, Float, Boolean, Array, Hash Control flow: if, each, case, break... Functions: def, return, implicit return in methods and blocks Errors, raise and rescue Classes and inheritance The difference...
...addresses.size # => 3 Now write a method AddressBook#search that takes a query string and returns an array of Contact objects that match the given word in any of their properties...
...record, as well as to query the record for registered errors. This object is returned when calling .errors: errors = @user.errors # => # Here are some helpful messages of its API: [ ]
...error message from the locale files. get( ) (Almost) an alias of []. Calls messages[ ] and returns an array of error messages for that attribute. include?( ) Returns whether there is an error...
...can, don't permit! everything but permit only known good keys. Use request.path_parameters returns a Hash with all parameters relevant for building a path with e.g. url_for (excluding...
...and similar). Note that it does not include query parameters. Use params.to_unsafe_h returns a HashWithIndifferentAccess with everything from params. If none of the above was enough for you...
...it considers your connection to be offline. async function isOnline({ path, timeout } = {}) { if (!navigator.onLine) return false path ||= document.querySelector('link[rel*=icon]')?.href || '/favicon.ico' timeout ||= 6000 const controller = new AbortController()
...timeoutTimer = setTimeout(() => controller.abort(), timeout); try { await fetch(path, { cache: 'no-store', signal: controller.signal }) return true } catch(error) { return false } finally { clearTimeout(timeoutTimer) } } Limitations of built-in navigator.onLine
def __init__(self): GObject.Object.__init__(self) def get_background_items(self, window, file): """Returns the menu items to display when no file/folder is selected (i.e. when right-clicking the...
...file.is_directory() and file.get_uri_scheme() == "file": if os.path.exists(TERMINAL_PATH): items += [self._create_terminal_item(file)] return items def _setup_gettext(self): """Initializes gettext to localize strings.""" try: # prevent a possible exception...
...an array with a block that is called with each element. The block must return a [key, value] tuple. This is useful if both the hash key and value can...
...a block. The block is called for each element in the array and should return a 2-tuple where the first element is the key and the second element is...
...In the example above, there will be the local variable weather_counter defined, which returns a counter of the currently rendered item in the collection. Furthermore it will add a...
...One can avoid ifs and any? calls in templates and make use of the return value of render. <%= render(@collection) || render('empty_state') %> Caching collections Fragment caching a rendered collection...
...attached files to config/initializers. It gives your strings a method #to_sort_atoms that returns an object that compares as expected. You can now say: ["Schwertner", "Schöler"].sort_by(&:to...
...of #to_sort_atoms: describe String do describe '#to_sort_atoms' do it 'should return an object that correctly compares German umlauts' do expect('Äa'.to_sort_atoms <=> 'Az'.to...
...Version uploader and original uploader can be distinguished by checking #version_name: version uploaders return the version name, whereas the original uploader instance returns nil Version instances do not have...
...string properties and a function property: let user = { firstName: 'Max', lastName: 'Muster', fullName: function() { return this.firstName + ' ' + this.lastName } } user.fullName() // => 'Max Muster' In ES6 we can define a function property using the...
...following shorthand syntax: let user = { firstName: 'Max', lastName: 'Muster', fullName() { return this.firstName + ' ' + this.lastName } } user.fullName() // => 'Max Muster' We can also define a getter inside the object literal, without using Object.defineProperty():
...method to detect the end of the scrolling animation. Methods like scrollTo() don't return a promise. We may eventually get a scrollend event, but that is still some time...
Until then I'm using the following awaitScrollEnd() function as a workaround. It returns a promise that resolves when the given Document or Element does not receive a scroll...