Float Rounding Half Away From Zero
Compare f64 round, floor, ceil, and trunc on negative values, then use round_ties_even when banking-style halves are required.
Page 5 of 50
Compare f64 round, floor, ceil, and trunc on negative values, then use round_ties_even when banking-style halves are required.
Count decimal digits with ilog10 and probe powers with checked_pow, which answers None where plain multiplication would overflow.
position stops at the first hit, enumerate with filter_map collects every matching index, and rposition scans the same predicate from the back.
fold carries a HashMap accumulator to count words and group them by first letter; sorted keys keep the printed output stable across runs.
into_iter hands each element by value so map moves owned Strings down the chain, while iter borrows and leaves the source usable.
Read fixed-size frames from any iterator with next_chunk, which returns [T; N] on success or the remaining iterator when fewer items are left.
Encode letters to dot-dash tables and decode them back with match arms per symbol, keeping word gaps as slash separators.
Open one handle with both read(true) and write(true), seek to a fixed record offset, and overwrite bytes in place without recreating the file.
Convert OS strings deliberately at boundaries: to_str for strict UTF-8, to_string_lossy for display, and into_string to reclaim an owned String.
Pin values to the heap with Box::pin: Unpin types keep mutable access, while !Unpin futures expose only shared references and set swaps the box.
Match the discriminant's Ordering to report two roots, one repeated root, no real roots, or undefined for NaN input.
Bundle a one-shot reply Sender into each enum query so the requestor blocks on a typed answer while the server thread dispatches with match.
Race scoped worker threads through an mpsc channel, skip failed replicas, and keep the first successful answer while the scope joins the losers.
Start a child process with spawn and probe it non-blockingly via try_wait: None means still running, and wait() finally blocks for the exit status.
Decode UTF-16 units with String::from_utf16, which rejects lone surrogates, and fall back to from_utf16_lossy when substitution is fine.
Reverse integer byte order with swap_bytes and pair it with to_be_bytes and from_be_bytes so wire formats survive a host switch.
Cap a channel with sync_channel so producer sends block while the consumer is behind: capacity 1 forces strict send and receive alternation.
Check every winning line of a tic tac toe board with index triples and a guard, because repeated bindings in one arm are illegal.
Strip only ASCII whitespace with trim_ascii while trim honours Unicode spaces, and split fields with split_ascii_whitespace.
Key a handler registry by std::any::TypeId so dispatch on Any values happens without matching every concrete type by hand.
Split byte input into valid UTF-8 runs and invalid bytes with utf8_chunks, then rebuild the text with U+FFFD replacements like from_utf8_lossy does.
Indexing yields a place, not a movable value: Copy fields read directly, while mem::take, swap_remove, and remove each hand ownership back.
push transfers ownership of the whole value into the vector's buffer, the source binding stops existing, and pop hands ownership back out.
Table-level reloptions override global autovacuum triggers for hot tables: fixed thresholds instead of size ratios, with RESET to fall back.
A stored generated column computes load from crates times unit weight, and a CHECK constraint validates that derived total on every write.
COPY ingests JSONL line by line into a jsonb column, keeping nested structure intact where row-wise CSV parsing would flatten or fail.
count(DISTINCT (user_id, day)) treats the row constructor as one key, separating unique pairs from plain row and column counts.
CREATE STATISTICS with dependencies and mcv records how strongly columns correlate, so the planner stops underestimating conjunctive filters on paired columns.
A foreign key can reference a partitioned table once its columns match a unique constraint that includes the partition key.
A filtered view is read-only until an INSTEAD OF trigger routes inserts into the base table, stamping the hidden column the view never exposes.
ISO week numbering moves the year boundary to the Monday containing January 1, so late December days can belong to the next year.
With work_mem tiny, a bitmap heap scan spills to lossy whole-page bits and EXPLAIN ANALYZE reports rows removed by the index recheck.
IN returns any-of matches; grouping joined tags and comparing HAVING count(DISTINCT tag) with the required count yields rows carrying every tag.
Collapse overlapping shift records into merged spans by sorting on start and tracking the running maximum end with a window function frame.
Target the conflict by constraint name with ON CONFLICT ON CONSTRAINT, pinning the arbitration to one explicit unique constraint.
ON CONFLICT (col) errors out when col only has a plain index; only a unique index or primary key gives the clause a constraint to arbitrate on.
pg_inherits lists every partition of a table; joined with pg_class it exposes partition bounds and the reltuples row estimates ANALYZE refreshes.
pg_settings exposes value, source, and context together, so you can tell session-tunable knobs from ones waiting on reload or restart.
pgp_sym_encrypt seals text into a bytea with a passphrase and pgp_sym_decrypt opens it; random session keys make identical plaintexts encrypt differently.
PL/pgSQL SELECT INTO STRICT raises no_data_found or too_many_rows on bad row counts, while the loose form silently takes the first row.
A recursive CTE walks nested jsonb children with jsonb_array_elements, tracking depth and path until every leaf array runs out.
Postgres 15 regexp functions split the work: regexp_count tallies hits, regexp_substr grabs the nth match, regexp_instr locates it, regexp_like decides.
On an unindexed column the planner seq-scans everything; Rows Removed by Filter in EXPLAIN ANALYZE shows how many rows the predicate discarded.
The tableoid system column identifies the physical partition holding each row, so queries can attribute and count rows per partition.
A BEFORE trigger recomputes the tsvector on title or body changes, keeping search hits in step with edits on the same statement.
unnest accepts several arrays at once and zips them row by index, padding shorter arrays with nulls so ragged inputs still expand to a clean table.
array_agg works as a window function: collect rows seen so far into a running array, or gather the one-preceding-to-one-following neighbors per row.
Inline handlers get parameter types from context; extracting one into a variable loses that context, leaving an implicit any until you annotate it.
document.fonts.load requests the faces for glyphs about to render and resolves with FontFace[], so icons draw only after the family is really available.
Global key handlers fire for every focused window, so document.hasFocus() gates shortcuts and stops a page from consuming keystrokes another window owns.
form.reset() restores controls natively but custom UI state is yours; the reset event runs before the revert, so deferred reads see the restored values.
inputMode picks the virtual keyboard layout and enterKeyHint labels the action key, taming mobile form fields without changing the input type.
The invalid event fires per failing control and does not bubble, so a form-level listener uses capture to route validationMessage into field slots.
Repeated DOM edits leave adjacent text nodes where the reader sees one string; normalize() merges them and drops empty ones so ranges see a single node.
pageshow fires on every load and on back-forward cache restores; persisted means timers and sockets were frozen, so live subscriptions must be re-established.
Relative selectors passed to element.querySelector still run against the whole document; prefixing :scope anchors them to the element the query was called on.
The selectionchange event fires on the document for every caret move, so the active element decides whose selectionStart the toolbar should read.
attachShadow with delegatesFocus sends host focus to the first focusable node in the shadow root, and focus events retarget to the host for outside listeners.
strictFunctionTypes checks property-signature callbacks contravariantly while method shorthand stays bivariant, so narrow params slip through methods.
Turn a block cipher into a stream with cipher.NewCTR: one keystream per direction, XORKeyStream both ways, and why an IV must never repeat under the same key.
Group anagrams by their sorted rune key so listen, silent, and enlist share one map entry, with sorted keys keeping printed output deterministic.
Distribute dynamic work with one atomic counter: each worker claims the next index, writes its own slot, and exits when exhausted.
A slice used as a stack matches every closer against the top opener; leftovers at the end or a mismatched pop both mean the sequence is broken.
Track the lowest buy price in one pass and sell later for the largest gain, so one scan finds the best profit without nested loops.
Flatten a stream of streams with bridge: consume <-chan (<-chan T), drain each source under the same done, and yield one merged result channel.
Read newline-framed input with bufio.Reader.ReadString, which returns the delimiter attached and reports io.EOF when the stream ends mid-line.
Hit bufio.ErrTooLong on a line past the 64KiB default, then raise the cap with Scanner.Buffer so oversized records still parse.
A generator goroutine yields values through a receive-only channel, closes it on exit, and watches a done channel so early consumers never leak the producer.
len on a buffered channel reports pending items and cap reports capacity; a nil channel reports zero for both and blocks forever on receive.
Chmod changes a file's permission bits and Stat reads them back, so secret files can drop to owner-only 0600 before any data is written.
Reset a map or slice in one builtin call: clear empties every map key and stores zero values while keeping slice length and capacity.
Compose multi-key ordering with cmp.Compare inside cmp.Or: the first non-equal field decides, and equal elements keep their relative input order.
Squeeze two pointers inward always moving the shorter wall, since it caps the area, so the maximum container is found in one pass.
Attach request-scoped data with context.WithValue, keyed by an unexported struct type so package boundaries cannot collide and lookups stay type-safe.
Point csv.Reader and csv.Writer at a semicolon delimiter with the Comma field, so European dialect files roundtrip without any manual splitting.
Define a custom error with an Unwrap method so errors.Unwrap peels one layer at a time and errors.Is still matches the sentinel cause underneath.
Solve daily-wait-until-warmer with a monotonic stack of unresolved indexes, settling each in O(1) amortized instead of scanning forward from every day.
Resolve command names through exec.LookPath, handle the ErrNotFound path, and see why names containing separators bypass the PATH search.
Feed a child process through cmd.Stdin with any io.Reader, avoiding temp files while the command consumes the data as a stream.
Register in-process metrics with expvar Ints and Maps, retrieve them by name with Get, and walk every published variable with Do — no metrics library.
Write into fixed regions of a file with os.File.WriteAt: disjoint offsets compose independently and a later patch rewrites only the targeted byte range.
os.FileMode packs type and permission bits: String renders them rwx style, Perm strips the type bits, and IsDir or IsRegular classify the mode.
Turn absolute targets into root-relative paths with filepath.Rel for reports and allowlist checks, expecting the leading .. when a target escapes the root.
Count runes with a map, then rescan for the first rune whose count is one, returning its byte index so the winner can be sliced out of the string.
Durations parse with flag.Duration while TextVar routes richer types like netip.Addr through encoding.TextUnmarshaler, so bad text aborts the run early.
Distinguish user-set flags from declared defaults with flag.Visit and VisitAll, so help output only shows what was actually passed.
format.Source reformats complete Go snippets with the same rules as gofmt and returns a parse error instead of panicking on broken syntax.
Validate path shape with fs.ValidPath before any fs.FS read, rejecting absolute paths, dot segments, and empty elements at the gate.
Wrap any cmp.Ordered type in a container/heap min-heap with the five heap.Interface methods, so pop always yields the smallest value.
Copy unread response bodies to io.Discard before Close so keep-alive connections return to the pool and subsequent requests reuse them.
ParseForm decodes an application/x-www-form-urlencoded body so repeated keys become string slices and Form.Get returns the first submitted value.
StripPrefix removes a fixed path prefix before a FileServer, so static assets live under one URL subtree without moving files on disk.
Insert a comma every three digits by walking the formatted bytes, so reports read 1,234,567 without pulling in any formatting library.
io.NopCloser satisfies io.ReadCloser for a bare io.Reader; Close is a no-op and the underlying reader keeps its position after reads.
strconv.Itoa renders decimal digits while string(n) treats the integer as a Unicode code point, so the two are rarely interchangeable.
After decoding the first JSON value, Decoder.Buffered hands back everything left unread so another consumer can take over.
Each json.Encoder.Encode call appends a newline, so looping over records writes one compact JSON object per line that readers can parse row by row.
Show that json.Encoder.Encode appends a trailing newline while json.Marshal does not, so hashing, diffing, and bytes.Equal checks diverge.
Decode MaxInt64+1 into an int64 field to get UnmarshalTypeError, while the uint64 field beside it accepts the same number.
encoding/json detects reference cycles while marshaling and returns an unsupported-value error, so flat DTOs keep nested graphs serializable.