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

Showing 631–660 of 770 public snippets

Rust
Fan-Out with try_join_all
Run N async operations concurrently and collect every Result. Fails fast on the first error; `join_all` is the variant that always waits for everyone.
46m 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.
46m ago 0
Go
HTTP POST JSON Body
Build a request with `http.NewRequestWithContext`, set headers, send via your client. The context plumbing is what lets callers cancel mid-request.
46m ago 0
Go
Interface Segregation — Small Interfaces
"The bigger the interface, the weaker the abstraction." Go encourages small, focused interfaces (often just one method) — io.Reader, io.Writer, fmt.Stringer. Define them at the consumer side.
46m ago 0
Go
Build Tags + Conditional Compilation
`//go:build` constraints control which files compile under which conditions — different code for Linux vs Windows, dev vs prod, with/without a feature. Standard library uses this heavily.
46m ago 0
Java
Switch Expressions (Java 14+)
`switch` is now also an expression — it returns a value. Use `->` arrows for fall-through-free arms; `yield` inside `{ }` blocks for multi-statement arms. No more accidental forgotten `break`.
46m ago 0
Kotlin
minOf / maxOf / sumOf / averageOf
Numerical reducers with a selector lambda — much cleaner than `.map { ... }.max()` chains. `sumOf` is type-aware (returns Int, Long, Double, BigDecimal as appropriate).
46m ago 0
PHP
Simple cURL GET with Timeout
A no-dependency HTTP GET helper with sensible defaults: short timeout, follow redirects, return body as string, throw on transport error. Pass extra headers as a simple associative array.
46m ago 0
TypeScript
Capitalize / Title-Case
Two common case transforms. `capitalize` for the first letter only; `titleCase` for every word, with small "stop words" left lowercase except at the edges.
46m ago 0
JavaScript
Validate URL
Validates whether a string is a well-formed URL using the native URL constructor, which matches browser parsing behaviour exactly. Optionally restricts to specific protocols (defaults to http and https). No regex maintenance required — if the browser can parse it as a URL, this returns true.
46m ago 0
JavaScript
Retry Promise with Backoff
Retries a Promise-returning function up to a specified number of times with configurable exponential backoff and optional jitter. Accepts a shouldRetry predicate so you can skip retries on specific error types (e.g. 401 Unauthorized). Returns the resolved value or re-throws the last error after exhausting retries.
46m ago 0
JavaScript
Worker Pool (Web Workers)
Manages a pool of Web Workers for CPU-intensive tasks (image processing, crypto, parsing). Distributes tasks across available workers using a round-robin strategy and returns a Promise per task. Falls back gracefully to inline execution in environments where workers are unavailable.
46m ago 0
PHP
Validate Credit Card (Luhn check)
Apply the Luhn checksum algorithm to a credit card number. Strips spaces/dashes first. This validates the format — not whether the card actually exists or has funds.
46m ago 0
PHP
Validate Hex Color
Accept #RGB, #RGBA, #RRGGBB, or #RRGGBBAA hex colors (with or without the leading #). Returns the normalized 6/8-digit lowercase form.
46m ago 0
PHP
Singleton Trait
A reusable trait that turns any class into a lazily-instantiated singleton with a single ::instance() accessor. Throws on clone/wakeup to prevent accidental duplication.
46m ago 0
Python
Async Retry with Exponential Backoff
Retry an async operation up to N times, doubling the wait each attempt with random jitter to avoid thundering herd. Predicate controls retryability so 4xx errors stop immediately.
46m ago 0
Java
java.time — Instant, LocalDate, ZonedDateTime
Java 8's `java.time` package replaced the broken `Date`/`Calendar`. Three types you actually use: `Instant` (UTC moment), `LocalDate` (date with no tz), `ZonedDateTime` (date+time in a zone).
46m ago 0
Java
HttpClient — Async (CompletableFuture)
`sendAsync` returns a `CompletableFuture<HttpResponse<T>>` — chain it like any other CF. Fan out N requests, wait for all with `CompletableFuture.allOf`.
46m ago 0
JavaScript
Detect Mobile / Device Type
Detects whether the user is on a mobile, tablet, or desktop device. The navigator.userAgentData API (Chromium) is preferred for its structured data; falls back to a User-Agent regex for Safari and Firefox. Useful for conditional rendering, touch event handling, and analytics segmentation.
46m ago 0
Python
asyncio.to_thread — Run Blocking Code
Wrap a blocking function so it doesn't freeze the event loop. asyncio.to_thread (3.9+) schedules the call onto the default executor and awaits the result.
46m ago 0
Go
Minimal net/http Server
The standard library ships a production-quality HTTP server. `http.HandleFunc` registers a function; `http.ListenAndServe` blocks forever serving requests.
46m ago 0
HTML
Modern Meta Tags (viewport, theme-color, etc.)
The non-obvious meta tags that improve mobile rendering, status-bar coloring, and dark-mode behavior in 2025 browsers. Copy this block whole.
46m ago 0
Kotlin
windowed and chunked
`chunked(n)` splits a list into NON-overlapping pieces of size n. `windowed(n)` slides a fixed-size window across — overlapping. Useful for moving averages, n-grams, batch APIs.
46m ago 0
PHP
Average / Median / Mode
Three classic descriptive statistics over a numeric array. Built without any external math library — just sort + count.
46m ago 0
PHP
RGB ↔ Hex Conversion
Two-way conversion between #RRGGBB hex strings and [R, G, B] arrays. Handy when working with theme colors that come from both sources (CSS strings vs. RGB sliders).
46m ago 0
TypeScript
Debounce (typed)
Wait until the caller stops invoking for `delay` ms, then call the function with the most recent arguments. The TS version preserves the original signature so the returned function has the same parameters.
46m ago 0
Rust
axum — Hello World HTTP Server
axum is the tokio-team's web framework — composable, type-safe handlers built on tower middleware. The hello-world is small enough to read in one screen.
46m ago 0
Go
Pipeline (channel chain)
A pipeline is a chain of stages connected by channels — each stage runs in its own goroutine. Classic Go pattern for streaming transformations with backpressure built in.
46m ago 0
Java
java.time — Duration and Period
`Duration` for elapsed time (hours/minutes/seconds). `Period` for calendar amounts (days/months/years). Don't mix — calendar math respects month lengths and DST; clock math doesn't.
46m ago 0
PHP
CSRF Token Generate + Verify
Per-session CSRF token helpers using hash_equals for constant-time comparison. Token is regenerated on logout but persists across requests within a session.
46m ago 0