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

Showing 301–330 of 770 public snippets

Bash
Read File Line-By-Line (the safe way)
The classic `for line in $(cat file)` is wrong — it word-splits and globbing fires on filenames. Use `while IFS= read -r line` with input redirection.
44m ago 0
JavaScript
Random Hex Color
Generates a random 6-digit hex colour string. Useful for seeding avatar backgrounds, chart series colours, placeholder UI elements, and testing colour-dependent components. The crypto version produces a more unpredictable result suitable for generating unique palette tokens.
44m ago 0
Rust
String vs &str — The Cheat Sheet
`String` is an owned, growable heap allocation; `&str` is a borrowed view into a UTF-8 buffer. Function params should usually take `&str`; return types use `String` when ownership is needed.
44m ago 0
Bash
Create User With Sensible Defaults
Provision a new user account with a home directory, default shell, and sudo membership. Idempotent — re-running on an existing user is a no-op.
44m ago 0
Python
Safe JSON Read/Write
Idiomatic helpers for reading + writing JSON to disk, with atomic writes and pretty-printed output. Catches the common "edit and save → corrupt file on crash" failure mode.
44m ago 0
JavaScript
Promise All with Concurrency Limit
Runs an array of async tasks with a maximum concurrency cap, preventing you from firing hundreds of requests simultaneously. Processes items in batches, moving to the next as slots free up. Essential when hitting rate-limited APIs or processing large datasets without overwhelming the server.
44m 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.
44m 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.
44m ago 0
Bash
Sum a Column with awk
Awk's default field splitter is whitespace; pass a single character with -F. Perfect for summing the Nth column of a log file or CSV.
44m ago 0
TypeScript
Environment Variable Validator
Validate process.env at boot-time and exit fast if anything's missing. The returned object is typed so the rest of the code reads `env.DATABASE_URL` instead of `process.env.DATABASE_URL!`.
44m ago 0
TypeScript
invariant() — Always-On Assertion
Throw if a condition is false, with TypeScript narrowing the type afterwards. Replaces ad-hoc `if (!x) throw` ladders and gives you type-safe guards in one line.
44m ago 0
Go
Custom Generic Constraints
Type constraints are interfaces with type sets. Use them to express "any numeric" or "any ordered" without resorting to `any`.
44m ago 0
TypeScript
Chunk Array Into Fixed-Size Pieces
Split an array into chunks of `size` items. Common building block for batch APIs — "send 50 rows per request" — and for paginated grids.
44m ago 0
Rust
Result Combinators + the ? Operator
`Result<T, E>` chains like `Option`. The `?` operator unwraps `Ok` or early-returns the `Err`, converting via `From` so callers can use one error type for many sources.
44m ago 0
PHP
Slack Incoming-Webhook Notification
Fire a quick notification to a Slack channel via an incoming webhook URL. Includes basic markdown-style mentions and an attachment color for severity.
44m ago 0
Java
Stream Basics — filter / map / collect
The fluent pipeline for transforming collections. `filter` keeps matching elements, `map` transforms each one, `collect(toList())` materializes the result.
44m ago 0
Kotlin
Star Projections (List<*>, etc.)
`List<*>` means "list of something I don't need to know exactly" — read-only with Any? as element type. Useful when you genuinely don't care about the parameter.
44m ago 0
HTML
Skip-to-Main-Content Link
Keyboard users (and screen-reader users) tab through every nav link before reaching content. A skip-link as the first focusable element jumps straight to <main>. Required for WCAG 2.1 AA.
44m ago 0
Python
chunked — Split Iterable into Fixed-Size Pieces
Lazy chunker that works on any iterable, not just lists. Common building block for batch APIs — "send 50 rows per request" — without loading the source into memory.
44m ago 0
Bash
Unique While Preserving Order
`sort -u` re-orders. `awk '!seen[$0]++'` is the classic order-preserving dedupe — and it's a single line.
44m ago 0
TypeScript
URL Builder with Type-Safe Query
Build URLs with a clean query-param API. Skips null/undefined automatically, encodes everything, and accepts arrays for repeated keys. Avoids manual string concatenation.
44m ago 0
Bash
SSH to Multiple Hosts in Parallel
Run the same command on a fleet of hosts. Three patterns: serial loop (simplest), GNU parallel (fastest), pssh (purpose-built).
44m ago 0
Kotlin
fold and scan
`fold` accumulates from a seed across all items. `runningFold` / `scan` yields every intermediate accumulator value — running totals, cumulative metrics.
44m ago 0
SQL
Views and Materialized Views
A view is a named query — no data stored. A materialized view caches the result; refresh it on demand. Great for expensive joins or aggregations that don't need to be real-time.
44m ago 0
Java
Optional Chains — flatMap, filter
`flatMap` lets you chain Optional-returning methods without nested `if`. `filter` short-circuits to empty if the predicate fails. The functional equivalent of safe-navigation `?.`.
44m ago 0
Python
take / drop / takewhile
Take the first N items of an iterable (or while a predicate holds). drop is the complement. Lazy via islice + itertools.dropwhile — works on infinite generators.
44m ago 0
Go
Read File — Whole / Lines / Bytes
Three common patterns: load it all (`os.ReadFile`), iterate line-by-line with `bufio.Scanner`, or stream chunks via `io.Reader`. Pick by file size.
44m ago 0
Bash
Sort by a Specific Column
Sort takes -k for column-based ordering and -t to set the delimiter. -h sorts human-readable sizes ("1.5G", "300K") correctly.
44m ago 0
SQL
EXISTS vs IN — Subquery Filtering
Both check membership. `EXISTS` is usually faster for big subqueries (stops at first hit). `IN` is more readable for small fixed lists. `NOT IN` is dangerous with NULLs — prefer `NOT EXISTS`.
44m ago 0
Kotlin
Cheatsheet: let / apply / also / run / with
Five scope functions cover ~95% of "do something with x" patterns. Pick by two axes: receiver (this vs it) and return value (object itself vs block result).
44m ago 0