ThreadPoolExecutor beforeExecute afterExecute Hooks
Subclass ThreadPoolExecutor to time every task: beforeExecute stamps the start, afterExecute reports elapsed time and whether the task ended with a throwable.
Page 13 of 50
Subclass ThreadPoolExecutor to time every task: beforeExecute stamps the start, afterExecute reports elapsed time and whether the task ended with a throwable.
Checked IOException cannot cross a stream lambda; wrap it in UncheckedIOException at the boundary and unwrap the cause where the consumer handles it.
compareAndExchange returns the witness value: the expected value on success, but on failure the actual current value, which boolean CAS cannot reveal.
flat() unwraps one level by default, a depth argument digs deeper, sparse holes disappear, and flatMap is just map followed by flat(1).
push and unshift return the new length while pop, shift, and splice return removed elements — array mutator return values differ by design.
The beforeinput event carries an inputType for the pending edit, so a contenteditable can preventDefault formatting commands before they land.
BigInt.asUintN and asIntN reinterpret values at a fixed bit width, giving counters and checksum fields the modular wrap hardware registers have.
Buffer write and read methods take a byte offset argument, so wire-format headers place each field at a fixed home and round-trip exactly.
Multiplying the canvas backing store by window.devicePixelRatio and scaling the context keeps lines crisp on high-DPI displays.
compositionend carries the IME-committed string, so validators can skip compositionupdate drafts and check only final input values.
console.time/timeEnd bracket a span under one label, timeLog prints mid-span checkpoints, and count tracks how often a label fired with deterministic output.
Default parameter expressions re-evaluate at call time and can read earlier parameters, so counters and dependent defaults behave predictably.
DOMContentLoaded marks a parsed DOM while load waits for every subresource; late scripts guard on readyState instead of assuming the phase.
Error.isError tests the internal slot, so fake message objects fail, cloned errors pass, and unknown catch values get one honest classification.
events.on exposes an EventEmitter as an async iterable; when the passed AbortSignal fires the loop raises AbortError, so consumers can bound how much they read.
readAsDataURL turns a picked image file into a data: URL string, giving an img preview without any object URL that must be revoked.
forEach calls async callbacks without awaiting them, so the loop ends before the work does; for...of awaits sequentially and Promise.all waits in parallel.
fs.watch streams change and rename events for a directory; debounce writes deliberately and always close the watcher so the process can exit.
A finally block inside a generator executes when return() or throw() terminates it — the cleanup hook fires on every shutdown path, not just next().
getComputedStyle returns the effective value after cascade and unit resolution, so 2em reads back as pixels, and only the inline style stays writable.
Headers.append joins repeated values with a comma while set replaces them, and getSetCookie returns Set-Cookie entries individually because joining corrupts.
formatRange renders two numbers as one localized range with collapsed units and percents, instead of concatenating two separately formatted values.
roundingPriority picks between fraction and significant digit limits, roundingMode picks the direction, and trailingZeroDisplay trims whole numbers only.
Checking process.stdout.isTTY before styling keeps piped and redirected output clean, which is what every CLI does before it emits ANSI colors.
JSON.rawJSON embeds the exact digit text into JSON output, keeping 9007199254740993 and 1.00 intact where regular numbers round and normalize.
Reading layout after every style write forces synchronous reflow; collect all offsetHeight reads first, then apply writes so the browser lays out once.
map passes (element, index, array) to callbacks, so parseInt treats the index as a radix and returns NaN; wrap it or call Number instead.
Math.fround rounds a double to the nearest float32 value kept as a double: 1.1 drifts, 1.5 survives, integers past 2^24 and huge magnitudes clamp.
Math.hypot sums squares without the intermediate overflow that a hand-written sqrt(x*x + y*y) hits for large components.
Math.imul performs real 32-bit integer multiplication with wrap-around, where plain * continues in double precision and silently loses low bits.
Math.max and Math.min with an empty spread return -Infinity and Infinity, and a single NaN poisons the whole aggregate.
mouseover and mouseout bubble up from children, so moving inside a container re-fires it; mouseenter and mouseleave fire only on real boundary crossings.
Underscore separators group digits inside numeric literals — decimal, binary, and floats included — without changing the value they denote.
Object.keys sorts integer-like keys ascending before insertion-ordered string keys, while Map keeps pure insertion order — prefix numbered keys to opt out.
os.hostname, freemem, totalmem, uptime, loadavg, and availableParallelism read the running machine, with loadavg documented as zero on Windows.
The path.posix namespace applies forward-slash rules on every OS, keeping join, normalize, and relative output identical across contributor machines.
PerformanceObserver collects mark and measure entries through a callback with entryTypes filtering, so timing data arrives instead of being polled manually.
event.preventDefault cancels the default action while other listeners still run; stopPropagation blocks other listeners while the default action proceeds.
The in operator with a private field tests the slot itself, so structural branding passes for class instances and fakes with matching public shapes fail.
Positive and negative lookbehind anchor matches to preceding text without including it, so key prefixes and price signs stay out of captured values.
A rest parameter gathers trailing arguments into a real array, replacing arguments; the spread call syntax and destructuring rest feed the same mechanism.
follower.scrollTop = driver.scrollTop keeps two panes aligned; scrollHeight minus clientHeight is the maximum reachable offset.
stepUp and stepDown move a number input by its step attribute and clamp at min and max, keeping the value valid without manual math.
Sign payloads with a non-extractable HMAC key from the WebCrypto API and verify with subtle.verify, so secrets never need byte-by-byte comparison.
super() must run before this exists in a subclass constructor, and super.method() reaches the parent implementation from an override.
toggleAttribute flips boolean attributes with an optional force argument, unlike setAttribute which always writes a string value.
pipeThrough slots a TransformStream between readable and writable so each chunk passes through transform while backpressure flows down the whole chain.
new URL resolves relative references against a base: plain segments replace the tail, .. climbs, and a leading slash restarts from the root.
new URL splits scheme, host, port, path, and hash without string surgery, while searchParams.get, set, and append keep every mutation URL-safe.
Each input.validity flag mirrors one HTML5 rule — typeMismatch, valueMissing, rangeUnderflow — so messages can target the exact failed check.
yield* delegates iteration to another generator, forwarding next() calls and handing its return value back to the outer generator.
A function with *args, keyword-only defaults, and **kwargs accepts extra positional names and keyword values, and call sites unpack them back.
BytesIO wraps an in-memory byte buffer in the file interface: writes, seeks, readline, getvalue, and readinto all work without touching disk.
A class with __call__ produces instances that work anywhere a function fits, such as sort keys, and callable() reports the capability.
Python compares chained relations left to right with the middle operand evaluated once, so 0 < x < 10 reads like math and works like it.
@classmethod factories take strings, dicts, or foreign units and return real instances, and subclasses inherit them because cls is the actual receiver.
A loop variable is captured by name, not by value, so late-running lambdas all see the final count; a default parameter pins the value at definition time.
Without __bool__, truthiness falls back to __len__, and objects with neither are always truthy — define one to keep empty containers from sneaking through.
The else clause attached to a for loop runs only when no break fired, turning a search miss into structured control flow.
__len__ and __getitem__ alone make len, indexing, membership, and list() work, because Python falls back to the old sequence protocol for iteration.
is compares object identity while == compares contents; aliasing one list shows mutations propagating, and is None is the idiomatic test.
next() pulls one item with an optional default, and iter(callable, sentinel) streams calls until the sentinel shows up — no lists needed.
math.hypot computes Euclidean length from components and math.dist measures the gap between two points, both in n dimensions.
math.isclose replaces == on floats: relative tolerance absorbs rounding error, and abs_tol covers comparisons against zero that rel_tol cannot express.
typing.NewType stamps distinct types onto primitives for static checkers while the runtime value stays a plain int with zero overhead.
The / marker forces positional-only arguments and * forces keyword-only ones, so call sites stay self-documenting and misorders fail loudly.
A bounded queue.Queue plus a None sentinel lets producer and consumer threads hand work across safely, with blocking puts acting as built-in backpressure.
raise ... from keeps the caught exception as __cause__ so tracebacks and log aggregators show the root failure next to the rewritten error.
startswith and endswith accept tuples, so one call matches any of several prefixes or suffixes instead of chaining or-ed string comparisons.
strip, lstrip, and rstrip trim whitespace or any characters in a set from the ends; set-based stripping is not prefix removal, so use removeprefix for affixes.
Return codes travel through sys.exit: usage errors conventionally return 2, validation failures 1, and the value handed to sys.exit becomes the process status.
Locking each read-modify-write with `with lock:` makes four threads incrementing a shared counter lose no updates, and the lock releases automatically.
typing.Literal names an exact set of allowed values for static checkers; at runtime the annotation is documentation with no enforcement.
The same word can be one precomposed codepoint or a base letter plus a combining mark; unicodedata.normalize('NFC') makes both spellings compare equal.
urlsplit and parse_qs dissect a URL without touching the network, and urlencode with doseq=True turns list values back into repeated query keys.
Sort each word chars into a shared signature, then group with the entry API so anagrams land in one bucket keyed by sorted letters.
Arc::unwrap_or_clone moves the inner value out when only one handle remains and falls back to a clone when other handles still exist.
Process fixed arrays in constant-size groups with chunks_exact, upgrading each chunk to a &[T; N] view with try_into so fixed-size batch logic stays compile-che
Iterate fixed-size batches with slice::chunks_exact, which skips the final short chunk, and recover the leftover through take_remainder.
assert!, assert_eq!, assert_ne!, and debug_assert! turn broken invariants into panics carrying the values and messages needed to diagnose them.
compare_exchange_weak claims stock atomically and retries on contention, so concurrent buyers decrement exactly once each and never oversell.
AtomicU32::fetch_or sets a bit and returns the prior value, so concurrent tasks claim status flags exactly once without holding a mutex.
BinaryHeap::into_sorted_vec drains every element in ascending order and leaves the heap empty, replacing manual repeated pops.
Box moves a large buffer off the stack: the array lives on the heap while the binding itself stays one machine word.
Rotate lowercase letters through the 26-letter ring with rem_euclid so negative shifts decode correctly and non-letters pass through.
Build multi-word arithmetic on u64 with carrying_add and borrowing_sub, which expose the carry and borrow bits so 128-bit sums stay exact.
flat_map drives a move closure per outer item over the whole inner list, producing the cartesian product as owned combos in one collect.
Parse every line and collect the failures with their line numbers, so one pass reports all bad rows instead of the first.
Score two vectors with zip and sum: paired multiplications fold into one total, and mismatched lengths return None before any math.
drop(value) runs the Drop impl immediately instead of at scope end; Drop::drop cannot be called directly by name.
Implement methods on enums and match on self: &self predicates read variants, matches! compresses boolean tests, and consuming self advances state.
Math APIs speak radians while users speak degrees; to_radians and to_degrees translate at the boundary and round-trip within one ulp.
mul_add computes a*b+c with a single rounding; on huge factors the naive a*b+c loses the final unit that fused math keeps.
Pack integers into fixed byte arrays with to_be_bytes and parse them back with from_be_bytes, keeping big-endian wire layouts exact.
Build the transpose of a grid with nested iterators: one value per row per output column, with the original grid only ever borrowed.
Store fn pointers in a HashMap and dispatch commands by name, handling unknown operations through the Option returned by get.
Interleave two sequences by zipping until the shorter side runs out and chaining the leftover tail, so no element from either input drops.
io::IsTerminal reports whether stdin and stdout are attached to a TTY, letting CLIs choose colored interactive output or plain text for pipes.
advance_by and nth(n) move an iterator forward by a position count without allocating anything for the items they skip.
One fold pass tracks min and max together, instead of walking the data twice with separate min and max calls.