dedent Strips Common Leading Indent
Strip the smallest common leading indent from multi-line template text so nested call sites still produce flush, presentable output.
Page 16 of 50
Strip the smallest common leading indent from multi-line template text so nested call sites still produce flush, presentable output.
Parse untrusted HTML strings with DOMParser into a detached document where scripts never run and images never load, then extract safe text.
Register a process exit handler that synchronously flushes pending writes, because async work started inside exit handlers cannot finish.
Listen once on a container because focusin and focusout bubble, so fields added later are tracked without rebinding per-element listeners.
Remove whole scratch directories with fs.rm recursive, and let force turn missing paths into no-ops so cleanup code is safe to run twice.
List active CSS transitions with getAnimations and await their finished promises instead of hardcoding durations; snapshot after the new style has rendered.
Load node builtins synchronously inside a function with process.getBuiltinModule, so request paths skip top-level await and import hoisting.
Wrap text greedily so each line takes as many words as fit the width, keeping every returned line within the limit for terminal output.
Map location.hash to view state with a hashchange listener so every tab change is a shareable URL and back navigation rewinds the view.
Listen for the image error event and swap in a fallback source exactly once, so a broken avatar never survives a failed request.
Read process.memoryUsage around a workload and correlate rss, heapUsed, and heapTotal deltas so leaks show up as deltas, not folklore.
Order callbacks across nextTick, promise microtasks, and timers so a ready signal fires before anything asynchronous can interleave.
Mark wheel and touch listeners as passive so the browser scrolls immediately without waiting for preventDefault decisions in handlers.
Read pasted clipboard text from clipboardData, normalize it, and reject values that fail the input's expected shape before they land.
Read named radio groups via form.elements and RadioNodeList.value, and clear the group by unchecking each input: assigning '' is not a reset.
Choose manual or auto scroll restoration per route so long lists do not jump back to the top on reload or on back navigation.
Compare scrollWidth with clientWidth to detect hidden content overflow, and read the offsetWidth gap that a scrollbar leaves behind.
Read chosen items from a multi-select through selectedOptions so form payloads keep every picked value without scanning all option elements.
Queue analytics with navigator.sendBeacon on pagehide, where fetch can be cancelled mid-unload and the payload would be lost.
Express asymmetric difference and symmetric difference with Set operations so changed keys and both-sided drift fall out of the comparison.
Register setImmediate from inside an I/O callback so the check phase runs right after poll — before the timers phase of the next loop iteration.
Share one symbol across modules through the Symbol.for registry, so hidden metadata keys match even when modules load separately.
Decode byte chunks with streaming: true so multi-byte characters split across reads survive, and final flush drops nothing at the boundary.
Show that a throw inside setTimeout never reaches the surrounding try catch, and route it to an uncaughtException handler instead.
Read <input type="date"> through valueAsDate to get a UTC-midnight Date object, because the raw .value string has no timezone at all.
Track which objects a traversal has touched with WeakSet — members can be garbage collected, so the bookkeeping never pins the graph in memory.
constructable CSSStyleSheet objects are adopted by document and shadow roots at once, so replaceSync updates and un-adoption apply everywhere simultaneously.
Promise.any settles with the first success; when every attempt rejects it throws AggregateError carrying each member error for inspection.
Array.prototype.entries yields index-and-value pairs for for-of, .keys and .values give each half alone, and sparse arrays report holes as undefined.
Iterate arrays as [index, value] pairs with entries(), take keys() or values() alone, and stop early because the trio returns real iterators.
Array.from converts array-likes, iterables, and strings, and its mapFn argument builds transformed arrays in one pass without intermediate copies.
async functions always return promises: a throw before any await becomes a rejected promise, while plain functions raise synchronous errors.
Propagate per-request data through deep awaits with AsyncLocalStorage: each requestContext.run gets an isolated store reachable anywhere inside.
attachShadow scopes markup and queries inside a shadow root and keeps its styles from leaking out; closed mode additionally hides the shadowRoot reference.
await using calls Symbol.asyncDispose when the block exits and awaits the cleanup, so locks and handles release even when the work in between throws.
Computed property keys turn variables and expressions into literal keys, building index tables and reading names that dot syntax cannot express.
decodeURIComponent throws URIError on bare percent signs, truncated escapes, and invalid hex, so decode user-controlled values inside a catching boundary.
details and summary give a native disclosure widget whose open property is both state and API, and the toggle event reports each open/close transition.
before, after, replaceWith, and remove edit the tree around a node directly: insertions anchor to siblings and removal needs no parent reference.
generator .next(value) passes input into the paused yield expression, and the generator's return value surfaces as the final done result object.
the hidden attribute stops rendering and focus while the element stays in the DOM; a stronger author display rule can defeat it until [hidden] restores it.
input fires on every value mutation while change waits for a commit; dispatching both shows which handler updates UI live versus on blur.
JSON.stringify throws TypeError on BigInt values, so big ids need string encoding, a toJSON method, or a replacer that converts every bigint at once.
Gate window messages by event.origin before touching data: unmatched senders are dropped and payload shape is verified independently.
wrapping Promise.all jobs so the first rejection aborts a shared signal stops sibling tasks mid-flight instead of letting them finish into an unread result.
A promise locks its state on the first resolve or reject; every later settle call is a no-op, while extra then observers still see the settled value.
replace with a callback builds substitutions from the match and its capture groups, and returns them literally where $ sequences would have expanded.
Subclasses of Array control what slice and map return through Symbol.species: default keeps the subclass, override restores plain Array.
TypedArray.set copies source data into an optional offset, converts across element widths with wrapping, and never shares memory with the source.
WeakSet records which objects a traversal has handled without pinning them in memory, rejects primitives, and exposes no size or iteration surface.
literal_eval parses literal data — lists, dicts, tuples, strings — and refuses calls, arithmetic, and name lookups with ValueError instead of running them.
Size bitmasks and buffers with int.bit_length and int.bit_count: needed bits, popcount, and the Kernighan loop agree on every value shown.
Turn setup and teardown into a @contextmanager generator: commit on clean exit, roll back and re-raise on error, all without a class.
Compute CRC-32 checksums over byte payloads and chain chunked calls by passing the previous value back in, so streamed bytes hash identically to the whole.
Clone dataclass records with asdict, astuple, and replace: copies run deep through nested dataclasses, and replace rewrites fields without touching originals.
Compute quotients and remainders with //, %, and divmod: Python floors toward negative infinity, so negative operands still satisfy q*b+r==a.
Split an ExceptionGroup by type with except*: each clause runs for every matching member, and unmatched types pass through untouched.
generators accept injected values through .send() after priming with next(), and close() ends them permanently by raising GeneratorExit inside.
getsizeof reports one object's own bytes including its header, excluding referenced contents — the nested-container test shows outer lists store pointers.
min and max take a key function to rank derived values and a default to answer empty sequences instead of raising ValueError; the original objects come back.
Derive password verifiers with hashlib.pbkdf2_hmac under a per-record salt, then confirm candidates with secrets.compare_digest for constant-time comparison.
monotonic and perf_counter clocks only move forward, making them the tools for durations; time.time() stays reserved for wall-clock timestamps.
re.match anchors at string start while re.search scans for the first hit; the two agree only when the pattern pins to position zero.
repr targets developers with an unambiguous form, str targets readers; containers render items with repr only, and each method falls back differently.
reprlib caps entries per container and nesting depth when stringifying large structures, so logs and reports stay readable without hand-rolled truncation.
round() breaks exact .5 ties toward the even neighbor while binary float storage decides the rest; printed results show both, plus the Decimal escape hatch.
list.sort is stable, so sorting by the least significant key first, then bigger keys, composes multi-pass orderings; tuple keys fold it into one pass.
sys.intern returns the canonical object for each string value, so equal strings built at runtime share identity, trimming memory and speeding comparisons.
timeit repeats a statement many times and repeat() returns one result per round, so the minimum — least disturbed by background load — is the honest number.
Pack fixed-shape records as tuples: they are immutable on assignment, hashable as dict keys, and single-element forms need the trailing comma.
UserDict routes every write and read through __setitem__ and __getitem__, so normalization and validation survive update(), construction, and setdefault too.
utf-8-sig writes the BOM on encode and consumes it on decode, while plain utf-8 leaves U+FEFF glued to the first CSV field after a round trip.
Define Money-style value objects where equality compares fields: __eq__ without __hash__ makes instances unhashable, so the pair must agree.
The walrus operator assigns inside expressions: bound-and-tested conditions, chunked while loops that end on empty reads, and deduplication in comprehensions.
Box errors as dyn Error + Send + Sync so failures from worker threads carry context and still move across thread boundaries.
Store eight boolean flags in a single u8 with shift and mask operations, then read, set, clear, and toggle individual bits without any allocation.
str::bytes iterates u8 while chars iterates Unicode scalars, so counts differ for multi-byte runes and len() reports the byte total directly.
Rewrite camelCase identifiers to snake_case by scanning chars and inserting an underscore before each uppercase letter.
Parse single characters into digits with to_digit under any radix, composing with iterators to read hex input without allocations.
collect::<Option<Vec<_>>> returns None at the first None, so parsing a list of digits or fields fails as a whole without manual early exits.
Propagate a stop signal through recursive visitors with std::ops::ControlFlow, so the first failing node halts the whole walk without Result plumbing.
Add next and next_back to a custom inclusive range so consumers can walk it forward with next or in reverse with rev, one step at a time.
Struct fields drop in declaration order while locals drop in reverse, so paired resources release in a predictable, observable sequence.
An enum over an mpsc channel carries typed commands; the worker matches Add, Greet, and Stop arms, and recv returning Err ends the loop naturally.
Call f64 math methods — sqrt, powf, powi, log2, ln, and exp — directly on number literals and combine them with the constants in std::f64::consts.
Dispatch on a leading byte with slice patterns and byte literals, binding payload fields per opcode while unknown codes fall into a catch-all arm.
Finalize an upload by renaming the staged temp file to its object key: same-directory rename is atomic and a missing stage maps to a clear NotFound error.
u32::try_from(char) reports Infallible as its error type: an empty match compiles because that Err arm is logically unreachable and unwrap never panics.
Measure wall-clock work with Instant::now and elapsed, and rely on Instant's monotonic guarantee so later reads never precede earlier ones.
Implement IntoIterator for a reference so for loops receive borrowed items, the collection survives the loop, and generic fns can consume &shelf directly.
Prepend one lazily computed element to a stream with once_with: the closure runs only when the iterator is consumed, never at construction time.
Verify two sequences agree element-wise under a custom predicate with eq_by, so whitespace-normalized comparisons and length mismatches need no index loop.
Duration implements Sum, so one iterator pass adds step timings; dividing by the step count with Div<u32> yields the average without a manual loop.
Yield mutable references from a custom iterator without unsafe: mem::take swaps the remaining slice out, split_first_mut peels one element off the front.
Join a panicking worker and recover its payload: JoinError::is_panic plus into_panic downcasts the boxed Any back to the message the thread panicked with.
Kadane's scan folds over deltas, resetting negative running sums and tracking the best seen, handling all-negative and empty inputs.
str::lines recognizes and and strips them, yielding no trailing empty line, while split('\n') keeps and produces one.
Define a declarative macro_rules! macro that expands k => v pairs into HashMap insert calls, giving collection literals without repeating boilerplate.
Majority vote tracks a candidate and counter in one pass, then verifies the candidate truly exceeds half the input before returning it.
Match counts.entry(key) on Occupied and Vacant: vacant slots insert, occupied slots mutate in place via get_mut, one probe per lookup.