SaveSnippets
Community
Pricing
Sign In
Get Started
@admin
ADMIN
Member since Apr 2026
770
Public snippets
5
Net score
5
Total upvotes
Showing
631–660
of
770
public snippets
Rust
macro_rules! — Simple Declarative Macros
Declarative macros let you write functions that take token trees instead of values. Great for boilerplate reduction; cleaner than copy-paste, simpler than proc macros.
1h ago
0
Go
database/sql — Transaction Helper
Wrap your transaction in a function that commits on success and rolls back on error or panic. Drop-in: pass any `func(*sql.Tx) error` and forget about manual cleanup.
1h ago
0
Java
Sorting with Comparator
`Comparator.comparing`, `thenComparing`, and `reversed()` chain into expressive multi-field sorts. Way cleaner than the old Comparable spaghetti.
1h ago
0
Java
HttpClient — Synchronous GET (Java 11+)
`java.net.http.HttpClient` ships in the JDK — no Apache HttpClient or OkHttp needed for most cases. Reuse one client across the app; configure timeouts and follow-redirects up front.
1h ago
0
SQL
JSONB Columns (PostgreSQL)
`jsonb` stores binary-optimized JSON. Index sub-fields with GIN for fast containment queries. Most-used operators: `->` (get field), `->>` (get as text), `@>` (contains), `?` (key exists).
1h ago
0
PHP
Validate Uploaded File
A defense-in-depth check for $_FILES uploads: confirms the upload completed, the size is within bounds, the MIME type matches an allow-list (by libmagic, not by extension), and the file landed where PHP expected.
1h ago
0
PHP
UPSERT (INSERT ... ON DUPLICATE KEY UPDATE)
A MySQL upsert helper: insert a row, or if a unique key collides, update the same row with the new values. Returns whether the row was inserted (true) or updated (false).
1h ago
0
TypeScript
Result / Either Type
Encode "this might fail" in the type signature instead of throwing. Force the caller to handle both branches at compile time. Better than try/catch for foreseeable failures.
1h ago
0
TypeScript
partition — Split by Predicate
Split an array into [pass, fail] in a single pass. Type guard overload lets the truthy bucket get a narrowed type when you pass a `x is T` predicate.
1h ago
0
TypeScript
Format Relative Time ("3 days ago")
Use the built-in Intl.RelativeTimeFormat to render "3 days ago" / "in 5 hours". Localized for free — pass any BCP 47 locale. No date library needed.
1h ago
0
Python
Sliding Window Iterator
Iterate over an iterable with a rolling window of N items. itertools.batched (Python 3.12+) gives you NON-overlapping chunks; this helper gives overlapping ones, common for moving averages or n-gram analysis.
1h ago
0
Python
Bulk Insert with executemany
Insert many rows in one round-trip using executemany. Orders-of-magnitude faster than a loop of single inserts — and the driver handles batching/parametrization for you.
1h ago
0
Bash
Split String into Array on Delimiter
Use IFS + read or readarray to split safely. Don't use word-splitting tricks — they break on edge cases (empty fields, spaces in values).
1h ago
0
Bash
Days Between Two Dates
Convert both dates to epoch seconds, subtract, divide. Works for hours/minutes too with the obvious divisor.
1h ago
0
Rust
impl Trait — Static Dispatch Returns
When you want to return a complex iterator chain or closure, you don't need to spell out the type. `impl Trait` lets the compiler infer the concrete type while exposing only the API contract.
1h ago
0
Kotlin
inline Functions — Zero-Cost Lambdas
`inline fun` copies the body (including lambda bodies) into the call site at compile time. Result: no `Function` object allocated for the lambda; `return` from inside the lambda exits the enclosing function.
1h ago
0
Kotlin
Compose Modifier Chain
`Modifier` is how you customize composables — padding, click handlers, background, size, alignment. Order matters: each modifier wraps the previous one.
1h ago
0
Kotlin
Exposed — Kotlin-First ORM
JetBrains' Exposed combines a SQL DSL with a lightweight ORM. Either style is fully type-safe; both compile to plain SQL.
1h ago
0
Go
time.Ticker — Periodic Tasks
`time.NewTicker(d)` fires on a channel every `d` interval. Combine with select + a done channel for a clean way to run periodic work that can be cancelled.
1h ago
0
PHP
Partition Array Into Two Buckets
Split an array into [matches, non-matches] using a predicate callback. Single pass, preserves order, returns two lists.
1h ago
0
Python
sqlite3 with Row Factory + Context
Stdlib sqlite3 is fine for embedded / small workloads. Use `with conn:` for automatic commit/rollback, and a row_factory so you get dicts (or namedtuples) instead of bare tuples.
1h ago
0
Bash
Heredoc with Variable Interpolation Control
Heredocs are the cleanest way to embed multi-line text. Unquote the delimiter to allow variable expansion; QUOTE it to keep the body literal (no $foo expansion).
1h ago
0
Bash
Count Occurrences of a Pattern
Several ways to count matches: lines containing X, total matches across a file, matches grouped by capture, etc.
1h ago
0
Java
Builder Pattern
For objects with many optional parameters, a Builder beats a constructor with 12 args (or a half-initialized object you have to call setters on). Method chaining + a `build()` step that validates.
1h ago
0
HTML
Navigation with aria-current
Use `<nav>` for primary navigation. Mark the currently-active link with `aria-current="page"` — screen readers will announce it, and you get a free CSS hook with `[aria-current]`.
1h ago
0
PHP
JSON Structured Logger
Append a single JSON object per line to a log file. Easy to grep and to ship into Datadog / Loki / CloudWatch later without re-parsing.
1h ago
0
Python
Dataclass with frozen + slots + defaults
Modern dataclass essentials: immutable instances (frozen=True), tighter memory + faster attribute access (slots=True), and default_factory for mutable defaults so every instance gets its own list.
1h ago
0
Bash
Tail Last N Lines (no `tail` shortcuts)
`tail -n 20` works for any case where tail is available. The pure-bash version below is useful inside containers or rescue shells where coreutils is missing.
1h ago
0
Bash
Filter Lines by Regex
grep -E (extended regex) is the right tool 95% of the time. Combine -i (case-insensitive), -v (invert), -n (line numbers), -B/-A (context lines).
1h ago
0
Rust
unsafe — When and How
Most Rust is safe. `unsafe` only lets you do 5 things the compiler can't check (raw pointer deref, mutable static, unsafe fn / trait, FFI, union access). Wrap unsafe operations in safe abstractions.
1h ago
0
1
…
20
21
22
23
24
…
26