Free reusable code examples, reviewed by the community.
Start a shell script with strict error handling and a useful exit message.
#!/usr/bin/env bash set -euo pipefail trap 'printf "Script failed on line %s\\n" "$LINENO" >&2' ERR printf 'Starting task...\\n' # Add your commands here.
Use a consistent sort column and a parameterized cursor when paging results.
-- Bind :last_id as a parameter (use 0 for the first page). SELECT id, title, created_at FROM posts WHERE id > :last_id ORDER BY id ASC LIMIT 20;
Display flexible cards across mobile, tablet, and desktop screens.
.card-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(min(100%, 18rem), 1fr));
gap: 1rem;
}
.card {
border: 1px solid #e5e7eb;
border-radius: 1rem;
padding: 1.25rem;
}An accessible, keyboard-friendly search form with a visible label.
<form role="search" method="get" action="/search"> <label for="site-search">Search the library</label> <input id="site-search" name="q" type="search" required> <button type="submit">Search</button> </form>
Protect HTML output when rendering user-controlled text.
<?php
function escapeHtml(string $value): string {
return htmlspecialchars(
$value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'
);
}
echo escapeHtml($userInput);Load a UTF-8 JSON document with clear errors for invalid or missing files.
import json
from pathlib import Path
def load_json(path: str):
try:
return json.loads(Path(path).read_text(encoding='utf-8'))
except (OSError, json.JSONDecodeError) as error:
raise ValueError(f'Cannot read {path}: {error}') from errorA small reusable wrapper that handles HTTP failures and parses JSON.
async function fetchJson<T>(url: string): Promise<T> {
const response = await fetch(url);
if (!response.ok) {
throw new Error('HTTP ' + response.status);
}
return (await response.json()) as T;
}Delay a function call until the user stops typing to avoid unnecessary requests.
function debounce(callback, delay = 300) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => callback(...args), delay);
};
}
const onSearch = debounce((query) => console.log(query));