admin
@admin ADMIN
Member since Apr 2026
770
Public snippets
5
Net score
5
Total upvotes

Showing 601–630 of 770 public snippets

SQL
Recursive CTE — Date Spine Generator
Generate a row per day (or month, year, hour) without a calendar table. Useful for filling gaps when a date has no events but you still want it in your output.
52m ago 0
PHP
Constant-Time String Compare
Compare two strings in constant time to avoid timing-attack leaks when checking secrets like API keys, session tokens, or HMAC signatures. Always use hash_equals — never ===.
52m ago 0
Bash
Get Script's Own Directory
The "where am I" boilerplate that every nontrivial bash script needs. Resolves symlinks correctly with realpath, falls back gracefully if realpath is missing.
52m ago 0
Rust
axum with Shared State + Extractors
Use `State` to inject shared application state (DB pool, config, etc.) into every handler. `Path` and `Json` extractors deserialize URL params and request bodies for you.
52m ago 0
Go
Custom Error Type with Fields
Implement the `error` interface (`Error() string`) on your own type to carry structured data. Pair with `errors.As` so callers can extract the fields.
52m ago 0
Go
JSON API Endpoint
Decode an incoming JSON body into a typed struct, do work, encode a JSON response. The whole roundtrip is ~20 lines of standard library.
52m ago 0
Kotlin
Ktor Client — POST JSON with Serialization
Combine Ktor + kotlinx.serialization: register the JSON plugin, declare `@Serializable` data classes, the client (de)serializes automatically.
52m ago 0
JavaScript
IndexedDB Wrapper
A Promise-based wrapper for the IndexedDB API — simplifies the verbose request/onsuccess/onerror pattern into clean async/await calls. Supports get, set, delete, and getAll operations on a named object store. Ideal for storing large client-side datasets, offline data, and blobs that exceed localStorage limits.
52m ago 0
TypeScript
Slugify (Unicode-aware)
Turn any string into a URL-safe slug. Uses Intl normalize + diacritic stripping so "Café" becomes "cafe". No external dependency.
52m ago 0
Bash
Convert Between Timezones
Set TZ inline to print a date in a specific timezone, then read with another TZ. Avoids messing with the system timezone.
52m ago 0
Rust
reqwest GET + JSON Deserialize
`reqwest` is the standard HTTP client. Combined with serde, you can fetch and parse a JSON API response into a typed struct in three lines.
52m ago 0
Go
database/sql — Open + Query
`database/sql` is driver-agnostic — pick a driver (`pgx/stdlib`, `go-sql-driver/mysql`, `mattn/sqlite3`). Always `defer db.Close()` only on app exit; the pool is meant to be long-lived.
52m ago 0
Java
HttpClient — POST JSON
POST a JSON body with `HttpRequest.BodyPublishers.ofString` + the right Content-Type. Pair with Jackson / Gson to serialize objects to JSON.
52m ago 0
JavaScript
Shuffle Array (Fisher-Yates)
Randomly shuffles an array in-place using the Fisher-Yates algorithm, which produces a uniformly random permutation. Widely considered the correct way to shuffle — avoids the bias inherent in sort(() => Math.random() - 0.5). Returns the same array reference after shuffling.
52m ago 0
JavaScript
Format File Size
Converts a raw byte count into a human-readable string with the appropriate unit (B, KB, MB, GB, TB). Uses 1024-based (binary) units by default or optionally 1000-based (SI) units. Useful for upload progress indicators, file browsers, and storage dashboards.
52m ago 0
PHP
Human-Readable File Size
Format a byte count as a human-friendly string (KB / MB / GB / TB). Defaults to base-1024 sizes; pass base 1000 for SI units.
52m 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.
52m ago 0
Bash
Default Value for Unset Variable
Three parameter-expansion idioms for "use this if the variable is empty / unset". Replaces the verbose `if [[ -z "$VAR" ]]; then VAR=default; fi` everywhere.
52m ago 0
Rust
Async/Await with tokio
`async fn` returns a future; `.await` drives it. tokio is the de-facto runtime. The `#[tokio::main]` attribute turns `main` into the runtime entry point.
52m ago 0
Go
base64 Encode / Decode
`encoding/base64` has Standard, URL-safe, and Raw (no padding) variants. URL-safe replaces `+/` with `-_` so the output is safe in query strings and filenames.
52m ago 0
Go
context.WithValue — Request-Scoped Values
Attach data to a context that flows down through your call chain — request IDs, authenticated user, trace spans. Use a private key type to avoid collisions across packages.
52m 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.
52m ago 0
JavaScript
Observable / Reactive State
A minimal reactive state container. Wrap any object with observable() and it returns a Proxy that notifies subscribers whenever a property is set. subscribe() registers a listener that receives the changed key and new value. A lightweight alternative to MobX or Vue's reactive() for small-scale reactivity needs.
52m ago 0
PHP
Tail Last N Lines of File
Efficiently read the last N lines of a (possibly large) file by seeking to the end and walking backwards in fixed-size chunks. Avoids loading the entire file into memory.
52m ago 0
PHP
HMAC Webhook Signature Verify
Verify an inbound webhook (Stripe / GitHub / etc.) is genuine using HMAC-SHA256 and a shared secret. Includes timestamp tolerance to block replay attacks.
52m ago 0
PHP
Rotating Log Writer
Append to a single log file but auto-rotate to .1/.2/.3 once the file exceeds a configurable size. No external dependencies — just rename + size check.
52m ago 0
TypeScript
Retry with Exponential Backoff + Jitter
Retry an async operation up to N times, doubling the delay each attempt with random jitter to avoid thundering herd. Decide retryability via an optional predicate so 4xx errors stop immediately.
52m 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.
52m 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.
52m ago 0
Bash
Pretty-Print Last Exit Code
A tiny prompt-trick that shows the previous command's exit code in red when it failed. Stops you from missing silent errors in long terminal sessions.
52m ago 0