Code snippets templates
Ready-to-paste commands and code: git, shell, SQL, regex, Swift, JavaScript, Python, Docker and HTTP. 268 free templates. Open one to fill in the blanks and copy it.
Git
Commands you look up every week.
- Undo last commit, keep changes Snippet Soft reset. git reset soft HEAD~1
- Discard local changes to a file Snippet Restore a file. git restore [File]
- New branch from main Snippet Start a branch. git switch main && git pull && git switch -c [Branch]
- Rebase on main Snippet Update a branch. git fetch origin && git rebase origin/main
- Interactive rebase last N Snippet Squash commits. git rebase -i HEAD~3
- Amend last commit message Snippet Fix a message. git commit amend -m "[Message]"
- Stash with a name Snippet Save work in progress. git stash push -m "[Description]"
- Apply a stash Snippet Bring it back. git stash pop
- Cherry-pick a commit Snippet Copy one commit. git cherry-pick [Hash]
- Delete merged branches Snippet Tidy local branches. git branch merged main | grep -v "main" | xargs git branch -d
- Pretty log Snippet Compact history graph. git log oneline graph decorate all -n 20
- Who changed this line Snippet Blame a range. git blame -L [Start],[End] [File]
- Find the commit that broke it Snippet Bisect. git bisect start && git bisect bad && git bisect good [Good commit]
- Show a file at a commit Snippet Old version of a file. git show [Commit]:[File]
- Undo a pushed commit Snippet Revert safely. git revert [Hash]
- Force push safely Snippet Lease protection. git push force-with-lease
- Tag a release Snippet Annotated tag. git tag -a v[Version] -m "Release [Version]" && git push origin v[Version]
- Set upstream Snippet Push a new branch. git push -u origin [Branch]
- Search commit messages Snippet Find by message. git log grep="[Text]" oneline
- Remove file from tracking Snippet Keep file locally. git rm cached [File]
- Clean untracked files Snippet Dry run first. git clean -nd
- Diff staged changes Snippet Review before commit. git diff staged
- Worktree for a branch Snippet Second checkout. git worktree add ../[Folder] [Branch]
- Rename a branch Snippet Local rename. git branch -m [Old name] [New name]
Shell
Terminal one-liners for macOS and Linux.
- Find large files Snippet Biggest files here. find . -type f -size +100M -exec ls -lh {} \; | sort -k5 -h
- Disk usage by folder Snippet Top folders. du -sh * | sort -h
- Find text in files Snippet Recursive search. grep -rn "[Text]" .
- Replace text in files Snippet sed in place (macOS). sed -i '' 's/[Old]/[New]/g' [File]
- Kill process on a port Snippet Free a port. lsof -ti :[Port] | xargs kill -9
- What is using a port Snippet Port lookup. lsof -i :[Port]
- Count lines of code Snippet Line counts by type. find . -name "*.[Extension]" | xargs wc -l | tail -1
- Watch a log Snippet Follow a log file. tail -f [Log file]
- Make and enter a folder Snippet mkdir and cd. mkdir -p [Folder] && cd [Folder]
- Rename files in bulk Snippet Change extension. for f in *.[From]; do mv "$f" "${f%.[From]}.[To]"; done
- Compress a folder Snippet tar and gzip. tar -czf [Archive].tar.gz [Folder]
- Extract an archive Snippet Untar. tar -xzf [Archive].tar.gz
- Download a file Snippet curl download. curl -L -o [File] [URL]
- Check a URL status Snippet HTTP status only. curl -sI [URL] | head -1
- Copy file to server Snippet scp upload. scp [File] [User]@[Host]:[Path]
- SSH with a key Snippet Connect. ssh -i ~/.ssh/[Key] [User]@[Host]
- Generate SSH key Snippet New ed25519 key. ssh-keygen -t ed25519 -C "[Email]"
- Copy output to clipboard Snippet macOS pbcopy. [Command] | pbcopy
- Show hidden files in Finder Snippet macOS toggle. defaults write com.apple.finder AppleShowAllFiles -bool true && killall Finder
- Flush DNS cache Snippet macOS DNS. sudo dscacheutil -flushcache; sudo killall -HUP mDNSResponder
- Run every N seconds Snippet Repeat a command. while true; do [Command]; sleep 5; done
- Environment variable for one command Snippet Inline env. [NAME]=[value] [Command]
- Sum a column Snippet awk sum. awk '{s+=$1;} END {print(s);}' [File]
- Unique sorted lines Snippet Dedupe. sort [File] | uniq -c | sort -rn
- Batch resize images Snippet macOS sips. sips -Z 1200 *.jpg
SQL
Queries for everyday data work.
- Select with filter Snippet Basic query. SELECT * FROM [Table] WHERE [Condition] ORDER BY [Column] DESC LIMIT 100;
- Count by group Snippet Group and count. SELECT [Column], COUNT(*) AS total FROM [Table] GROUP BY [Column] ORDER BY total DESC;
- Find duplicates Snippet Rows appearing more than once. SELECT [Column], COUNT(*) FROM [Table] GROUP BY [Column] HAVING COUNT(*) > 1;
- Inner join Snippet Join two tables. SELECT a.*, b.[Column] FROM [Table A] a JOIN [Table B] b ON b.[Key] = a.[Key];
- Left join missing rows Snippet Rows with no match. SELECT a.* FROM [Table A] a LEFT JOIN [Table B] b ON b.[Key] = a.[Key] WHERE b.[Key] IS NULL;
- Last N days Snippet Recent rows. SELECT * FROM [Table] WHERE [Date column] >= CURRENT_DATE - INTERVAL '7 days';
- Daily totals Snippet Group by day. SELECT DATE([Date column]) AS day, SUM([Amount]) AS total FROM [Table] GROUP BY day ORDER BY day;
- Running total Snippet Window function. SELECT [Date column], [Amount], SUM([Amount]) OVER (ORDER BY [Date column]) AS running_total FROM [Table];
- Rank within groups Snippet Top per group. SELECT * FROM ( SELECT *, ROW_NUMBER() OVER (PARTITION BY [Group] ORDER BY [Order] DESC) AS rn FROM [Table]…
- Common table expression Snippet WITH query. WITH [Name] AS ( SELECT FROM [Table] ) SELECT * FROM [Name];
- Insert row Snippet Insert values. INSERT INTO [Table] ([Columns]) VALUES ([Values]);
- Update rows Snippet Update with where. UPDATE [Table] SET [Column] = [Value] WHERE [Condition];
- Delete safely Snippet Check first, then delete. Check first: SELECT COUNT(*) FROM [Table] WHERE [Condition]; Then: DELETE FROM [Table] WHERE [Condition];
- Create table Snippet New table. CREATE TABLE [Table] ( id SERIAL PRIMARY KEY, created_at TIMESTAMP NOT NULL DEFAULT NOW() );
- Add index Snippet Speed up lookups. CREATE INDEX idx_[Table]_[Column] ON [Table] ([Column]);
- Add column Snippet Alter table. ALTER TABLE [Table] ADD COLUMN [Column] [Type];
- Case expression Snippet Bucket values. SELECT [Column], CASE WHEN [Condition 1] THEN '[Label 1]' WHEN [Condition 2] THEN '[Label 2]' ELSE '[Other]'…
- Percent of total Snippet Share of each group. SELECT [Column], COUNT(*) * 100.0 / SUM(COUNT(*)) OVER () AS pct FROM [Table] GROUP BY [Column];
- Explain query Snippet See the plan. EXPLAIN ANALYZE
- Table sizes (Postgres) Snippet Largest tables. SELECT relname, pg_size_pretty(pg_total_relation_size(relid)) FROM pg_catalog.pg_statio_user_tables ORDER BY…
Regular expressions
Patterns you can trust.
- Email address Snippet Practical email pattern. ^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$
- URL Snippet http or https URL. https?://[\w.-]+(?:\.[\w.-]+)+[\w\-._~:/?#\[\]@!$&'()*+,;=%]*
- ISO date Snippet YYYY-MM-DD. ^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$
- Time 24h Snippet HH:MM. ^([01]\d|2[0-3]):[0-5]\d$
- Hex colour Snippet #RGB or #RRGGBB. ^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$
- IPv4 address Snippet Dotted quad. ^((25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(25[0-5]|2[0-4]\d|1?\d?\d)$
- Whole word Snippet Match a word exactly. \b[Word]\b
- Trailing whitespace Snippet Spaces at line ends. [ \t]+$
- Blank lines Snippet Empty or whitespace lines. ^\s*$
- Digits only Snippet Numbers. ^\d+$
- Slug Snippet URL slug. ^[a-z0-9]+(?:-[a-z0-9]+)*$
- Semantic version Snippet 1.2.3 style. ^\d+\.\d+\.\d+(?:-[\w.]+)?$
- Strong password check Snippet Upper, lower, digit, 12+. ^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{12,}$
- Duplicate words Snippet Repeated word. \b(\w+)\s+\1\b
- HTML tag Snippet Match tags. <[^>]+>
- Capture key=value Snippet Config pairs. ^(\w+)\s*=\s*(.*)$
Swift
Swift and SwiftUI patterns.
- Guard let Snippet Early exit. guard let [name] = [optional] else { return }
- Async function Snippet async throws. func [name]() async throws [ReturnType] { }
- Task on main actor Snippet Hop to main. Task { @MainActor in }
- Codable struct Snippet Model type. struct [Name]: Codable, Identifiable { let id: UUID var [property]: [Type] }
- Decode JSON Snippet JSONDecoder. let [value] = try JSONDecoder().decode([Type].self, from: data)
- URLSession request Snippet Fetch data. let (data, response) = try await URLSession.shared.data(from: URL(string: "[URL]")!)
- SwiftUI view Snippet Basic view. struct [Name]View: View { var body: some View { } }
- SwiftUI list Snippet List with ForEach. List([items]) { item in Text(item.[property]) }
- State property Snippet @State. @State private var [name]: [Type] = [Starting text]
- Enum with switch Snippet Exhaustive switch. switch [value] { case .[first]: case .[second]: break }
- Extension Snippet Add behaviour. extension [Type] { }
- DispatchQueue after Snippet Delay on main. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { }
- Unit test Snippet XCTest case. func test[Name]() throws { // Given // When // Then XCTAssertEqual(actual, expected) }
- Print debug Snippet Labelled print. print("[Label]:", [value])
JavaScript and TypeScript
Front-end and Node snippets.
- Arrow function Snippet Const function. const [name] = ([params]) => { };
- Fetch JSON Snippet async fetch. const res = await fetch('[URL]'); if (!res.ok) throw new Error('HTTP ' + res.status); const data = await…
- POST JSON Snippet Send JSON. await fetch('[URL]', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body:…
- Try catch async Snippet Error handling. try { } catch (error) { console.error(error); }
- Debounce Snippet Limit calls. function debounce(fn, ms = 300) { let t; return (...args) => { clearTimeout(t); t = setTimeout(() =>…
- React component Snippet Function component. export function [Name]({ [props] }) { return ( <div></div> ); }
- useState hook Snippet React state. const [[value], set[Value]] = useState([Starting text]);
- useEffect hook Snippet Side effect. useEffect(() => { return () => {}; }, [[deps]]);
- TypeScript interface Snippet Shape a type. interface [Name] { [property]: [type]; }
- Array group by Snippet Group items. const grouped = [items].reduce((acc, item) => { (acc[item.[key]] = []).push(item); return acc; }, {});
- Express route Snippet Node route. app.get('[Path]', async (req, res) => { res.json({ ok: true }); });
- Console table Snippet Readable logging. console.table([data]);
- Local storage Snippet Save and load. localStorage.setItem('[key]', JSON.stringify([value])); const saved =…
- Copy to clipboard Snippet Browser clipboard. await navigator.clipboard.writeText([text]);
Python
Scripting and data snippets.
- Main guard Snippet Script entry point. def main(): if name == "main": main()
- Read a file Snippet Read text. with open("[File]", encoding="utf-8") as f: text = f.read()
- Write a file Snippet Write text. with open("[File]", "w", encoding="utf-8") as f: f.write([content])
- Read JSON Snippet Load JSON. import json with open("[File]") as f: data = json.load(f)
- Read CSV Snippet csv.DictReader. import csv with open("[File]", newline="") as f: rows = list(csv.DictReader(f))
- HTTP request Snippet requests GET. import requests r = requests.get("[URL]", timeout=10) r.raise_for_status() data = r.json()
- List comprehension Snippet Filter and map. [[expr] for [item] in [items] if [condition]]
- Dataclass Snippet Simple model. from dataclasses import dataclass @dataclass class [Name]: [field]: [type]
- Argparse CLI Snippet Command-line args. import argparse parser = argparse.ArgumentParser(description="[Description]") parser.add_argument("[arg]")…
- Pandas load and summarise Snippet Quick look at data. import pandas as pd df = pd.read_csv("[File]") print(df.head()) print(df.describe())
- Virtual environment Snippet Create and activate. python3 -m venv .venv && source .venv/bin/activate
- Logging setup Snippet Basic logging. import logging logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") log =…
- Timer Snippet Measure time. import time start = time.perf_counter() print(f"took {time.perf_counter() - start:.2f}s")
- Pytest test Snippet A test function. def test_[name](): assert [actual] == [expected]
Docker and deployment
Containers and infrastructure.
- Dockerfile for Node Snippet Minimal Node image. FROM node:20-alpine WORKDIR /app COPY package*.json ./ RUN npm ci omit=dev COPY . . EXPOSE 3000 CMD ["node",…
- Dockerfile for Python Snippet Minimal Python image. FROM python:3.12-slim WORKDIR /app COPY requirements.txt . RUN pip install no-cache-dir -r requirements.txt…
- Build and run Snippet Docker commands. docker build -t [Image] . && docker run rm -p [Port]:[Port] [Image]
- Shell into container Snippet exec. docker exec -it [Container] sh
- Compose service Snippet docker-compose block. services: [Service]: image: [Image] ports: - "[Port]:[Port]" environment: - [KEY]=[value]
- Clean up Docker Snippet Remove unused data. docker system prune -f
- Container logs Snippet Follow logs. docker logs -f tail 100 [Container]
- Kubernetes pods Snippet List pods. kubectl get pods -n [Namespace]
- Kubernetes logs Snippet Pod logs. kubectl logs -f [Pod] -n [Namespace]
- GitHub Actions job Snippet CI workflow. name: CI on: [push, pull_request] jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 -…
- Nginx reverse proxy Snippet Proxy block. location / { proxy_pass http://127.0.0.1:[Port]; proxy_set_header Host $host; proxy_set_header X-Real-IP…
- Env file example Snippet Sample .env. Copy to .env and fill in [KEY]= DATABASE_URL= PORT=3000
HTTP and APIs
Requests and responses.
- curl GET with header Snippet Authenticated GET. curl -s -H "Authorization: Bearer [Token]" [URL]
- curl POST JSON Snippet Send JSON. curl -s -X POST [URL] -H "Content-Type: application/json" -d '[JSON]'
- JSON error response Snippet Error shape. { "error": { "code": "[Code]", "message": "[Message]" } }
- Pagination response Snippet Paged list shape. { "data": [], "page": 1, "per_page": 20, "total": [Total] }
- HTTP status cheat sheet Snippet Common codes. 200 OK 201 Created 204 No Content 301 Moved Permanently 304 Not Modified 400 Bad Request 401 Unauthorized…
- Webhook payload Snippet Event shape. { "event": "[Event]", "created_at": "[today]", "data": {} }
- GraphQL query Snippet Query with variables. query [Name]($id: ID!) { [field](id: $id) { id } }
- OpenAPI path Snippet Spec fragment. /[path]: get: summary: [Summary] responses: '200': description: OK
CSS
Layout and styling.
- Centre with flexbox Snippet Centre anything. .[class] { display: flex; align-items: center; justify-content: center; }
- CSS grid columns Snippet Responsive grid. .[class] { display: grid; grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); gap: 16px; }
- Media query Snippet Breakpoint. @media (max-width: 768px) { }
- Dark mode query Snippet Prefers dark. @media (prefers-color-scheme: dark) { :root { bg: #111; fg: #eee; } }
- CSS variables Snippet Custom properties. :root { [name]: [value]; }
- Truncate text Snippet Ellipsis. .[class] { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
- Clamp lines Snippet Multi-line clamp. .[class] { display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden; }
- Smooth transition Snippet Hover transition. .[class] { transition: all 200ms ease; }
- Visually hidden Snippet Accessible hide. .sr-only { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space:…
- Keyframe animation Snippet Fade in. @keyframes fade-in { from { opacity: 0; } to { opacity: 1; } }
- Box sizing reset Snippet Reset. *, *::before, *::after { box-sizing: border-box; }
- Sticky header Snippet Stick to top. header { position: sticky; top: 0; z-index: 10; }
- Aspect ratio box Snippet Fixed ratio. .[class] { aspect-ratio: 16 / 9; }
- Focus visible Snippet Keyboard focus ring. :focus-visible { outline: 2px solid #ff7a1a; outline-offset: 2px; }
Go
Go snippets.
- Go main Snippet Entry point. package main import "fmt" func main() { fmt.Println([Message]) }
- Go error check Snippet If err. if err != nil { return , err }
- Go struct Snippet Type with tags. type [Name] struct { [Field] [Type] `json:"[json]"` }
- Go HTTP handler Snippet net/http. func [name]Handler(w http.ResponseWriter, r *http.Request) { }
- Go goroutine with WaitGroup Snippet Concurrency. var wg sync.WaitGroup wg.Add(1) go func() { defer wg.Done() }() wg.Wait()
- Go table test Snippet Table-driven test. func Test[Name](t *testing.T) { tests := []struct { name string in [InType] want [OutType] }{} for _, tt :=…
- Go read file Snippet os.ReadFile. data, err := os.ReadFile("[File]") if err != nil { log.Fatal(err) }
- Go JSON decode Snippet Unmarshal. var v [Type] if err := json.Unmarshal(data, &v); err != nil { return err }
Rust
Rust snippets.
- Rust main Snippet Entry point. fn main() { println!("[Message]"); }
- Rust struct Snippet Struct with derive. #[derive(Debug, Clone)] struct [Name] { [field]: [Type], }
- Rust Result function Snippet Returns Result. fn [name]() Result<[Ok], Box<dyn std::error::Error { Ok(value) }
- Rust match Snippet Match expression. match [value] { [Pattern] => , _ => todo!(), }
- Rust test Snippet Unit test. #[cfg(test)] mod tests { use super::*; #[test] fn [name]() { assert_eq!([actual], [expected]); } }
- Rust impl block Snippet Methods. impl [Type] { pub fn new() Self { } }
- Cargo add Snippet Add a crate. cargo add [Crate]
Java and Kotlin
JVM snippets.
- Java main Snippet Entry point. public class [Name] { public static void main(String[] args) { } }
- Java record Snippet Data record. public record [Name]([Type] [field]) {}
- Java stream filter Snippet Filter a list. List<[Type]> result = [list].stream() .filter(x [condition]) .toList();
- Java try with resources Snippet Auto close. try (var [resource] = function Object() { [native code] }) { }
- Kotlin data class Snippet Data class. data class [Name](val [field]: [Type])
- Kotlin coroutine Snippet Launch. scope.launch { }
- Kotlin when Snippet When expression. when ([value]) { [case] else TODO() }
- Kotlin extension function Snippet Extend a type. fun [Type].[name](): { }
PHP, Ruby and C#
More languages.
- PHP function Snippet Typed function. function [name]([Type] $[param]): { }
- PHP array map Snippet array_map. $result = array_map(fn($x) => [expr], $[array]);
- Laravel route Snippet Route definition. Route::get('/[path]', [[Controller]::class, '[method]']);
- Ruby method Snippet Method. def [name]([args]) end
- Ruby each Snippet Iterate. [collection].each do |[item]| end
- Rails migration Snippet Add column. rails generate migration Add[Column]To[Table] [column]:[type]
- C# class Snippet Class. public class [Name] { public [Type] [Property] { get; set; } }
- C# async method Snippet Task. public async Task<[Type]> [Name]Async() { }
- C# LINQ Snippet Query. var result = [items].Where(x => [condition]).Select(x => [selector]).ToList();
macOS and Apple
Mac commands and Apple dev.
- Open current folder in Finder Snippet open . open .
- Quick Look a file Snippet Preview from Terminal. qlmanage -p [File]
- Prevent sleep Snippet Keep awake. caffeinate -d -t 3600
- Show Mac serial Snippet Hardware info. system_profiler SPHardwareDataType | grep Serial
- Screenshot to clipboard Snippet Capture. screencapture -c
- Say text aloud Snippet Speech. say "[Text]"
- Remove quarantine Snippet Allow a downloaded app. xattr -d com.apple.quarantine [App path]
- Homebrew install Snippet Install a formula. brew install [Formula]
- Homebrew update all Snippet Update everything. brew update && brew upgrade && brew cleanup
- Xcode clean derived data Snippet Free space. rm -rf ~/Library/Developer/Xcode/DerivedData
- List simulators Snippet iOS simulators. xcrun simctl list devices available
- Swift package init Snippet New package. swift package init type executable
- Code sign check Snippet Verify signature. codesign -dv verbose=4 [App path]
- Defaults read Snippet Read a preference. defaults read [Domain] [Key]
Git more
Less common but handy.
- Show changed files Snippet Files in last commit. git show name-only oneline HEAD
- Undo git add Snippet Unstage. git restore staged [File]
- Diff between branches Snippet Compare branches. git diff main...[Branch]
- Delete remote branch Snippet Clean up. git push origin delete [Branch]
- Fetch and prune Snippet Tidy remotes. git fetch prune
- Squash merge Snippet Merge as one commit. git merge squash [Branch] && git commit
- Recover deleted branch Snippet Reflog. git reflog | grep [Branch] git branch [Branch] [Hash]
- Set user for repo Snippet Local identity. git config user.name "[Name]" && git config user.email "[Email]"
- Ignore file locally Snippet Personal ignore. echo "[Pattern]" .git/info/exclude
- Shallow clone Snippet Faster clone. git clone depth 1 [URL]
- Count commits by author Snippet Shortlog. git shortlog -sn no-merges
- Stash list Snippet See stashes. git stash list
Bash scripting
Script building blocks.
- Script header Snippet Safe bash header. #!/usr/bin/env bash set -euo pipefail
- If file exists Snippet File test. if [[ -f "[File]" ]]; then fi
- Loop over files Snippet For loop. for f in *.txt; do echo "$f" done
- Read lines from file Snippet While read. while IFS= read -r line; do echo "$line" done < [File]
- Function Snippet Bash function. [name]() { local arg="$1" }
- Check command exists Snippet Dependency check. command -v [Command] >/dev/null { echo "[Command] is required"; exit 1; }
- Default variable Snippet Fallback value. NAME="${NAME:-[Default]}"
- Case statement Snippet Switch on argument. case "$1" in [Option A]) ;; *) echo "Usage: $0 [[Option A]]" ;; esac
- Trap cleanup Snippet Clean up on exit. cleanup() { rm -rf "$TMP"; } TMP=$(mktemp -d) trap cleanup EXIT
- Parse flags Snippet getopts. while getopts "vh" opt; do case $opt in v) VERBOSE=1 ;; h) echo "help"; exit 0 ;; esac done
- Timestamped backup Snippet Copy with date. cp [File] [File].$(date +%Y%m%d-%H%M%S).bak
- Parallel jobs Snippet xargs parallel. cat [List] | xargs -P 4 -I {} [Command]
Database admin
Postgres, MySQL and SQLite.
- Postgres connect Snippet psql. psql -h [Host] -U [User] -d [Database]
- Postgres dump Snippet Backup. pg_dump -h [Host] -U [User] -Fc [Database] > [Database]-$(date +%F).dump
- Postgres restore Snippet Restore a dump. pg_restore -h [Host] -U [User] -d [Database] [File]
- Postgres active queries Snippet What is running. SELECT pid, state, query_start, query FROM pg_stat_activity WHERE state <> 'idle' ORDER BY query_start;
- Postgres kill query Snippet Stop a query. SELECT pg_cancel_backend([PID]);
- Postgres list tables Snippet Describe. \dt public.*
- MySQL connect Snippet mysql client. mysql -h [Host] -u [User] -p [Database]
- MySQL dump Snippet Backup. mysqldump -h [Host] -u [User] -p [Database] > [Database].sql
- MySQL show processes Snippet Running queries. SHOW FULL PROCESSLIST;
- SQLite open Snippet sqlite3. sqlite3 [File].db
- SQLite tables Snippet List tables. .tables
- SQLite export CSV Snippet CSV out. .headers on .mode csv .output [File].csv SELECT * FROM [Table];
- Create user Postgres Snippet New role. CREATE ROLE [User] WITH LOGIN PASSWORD '[Password]'; GRANT CONNECT ON DATABASE [Database] TO [User];
- Upsert Postgres Snippet Insert or update. INSERT INTO [Table] ([Key], [Column]) VALUES ([Key value], [Value]) ON CONFLICT ([Key]) DO UPDATE SET…
- JSON column query Snippet Postgres JSON. SELECT [Column]'[Field]' AS [Field] FROM [Table] WHERE [Column]'[Field]' = '[Value]';
JavaScript utilities
Small helpers.
- Sleep Snippet Promise delay. const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
- Unique array Snippet Remove duplicates. const unique = [...new Set([array])];
- Sort by key Snippet Sort objects. [array].sort((a, b) => a.[key].localeCompare(b.[key]));
- Format currency Snippet Intl.NumberFormat. new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format([amount]);
- Format date Snippet Intl.DateTimeFormat. new Intl.DateTimeFormat('en-GB', { dateStyle: 'medium' }).format(new Date());
- Query string Snippet URLSearchParams. const params = new URLSearchParams(window.location.search); const [name] = params.get('[name]');
- Deep clone Snippet structuredClone. const copy = structuredClone([object]);
- Chunk array Snippet Split into chunks. const chunk = (arr, n) => Array.from({ length: Math.ceil(arr.length / n) }, (_, i) => arr.slice(i * n, i * n…
- Random ID Snippet Crypto random. const id = crypto.randomUUID();
- Event listener Snippet Add a listener. document.querySelector('[Selector]').addEventListener('click', (e) => { });
- Retry with backoff Snippet Retry async. async function retry(fn, tries = 3) { for (let i = 0; i < tries; i++) { try { return await fn(); } catch (e)…
- Download JSON Snippet Save a file. const blob = new Blob([JSON.stringify([data], null, 2)], { type: 'application/json' }); const a =…
Swift extras
More Swift.
- Result type switch Snippet Handle Result. switch result { case .success(let value): case .failure(let error): print(error) }
- Defer Snippet Run at scope exit. defer { }
- Actor Snippet Thread-safe state. actor [Name] { private var [property]: [Type] }
- Combine sink Snippet Subscribe. [publisher] .receive(on: DispatchQueue.main) .sink { value in } .store(in: &cancellables)
- UserDefaults read write Snippet Preferences. UserDefaults.standard.set([value], forKey: "[key]") let [name] = UserDefaults.standard.string(forKey: "[key]")
- NSAlert Snippet Mac alert. let alert = NSAlert() alert.messageText = "[Title]" alert.informativeText = "[Message]"…
- SwiftUI button Snippet Button with action. Button("[Title]") { }
- SwiftUI navigation Snippet NavigationStack. NavigationStack { List([items]) { item in NavigationLink(item.[title], value: item) } }
- Preview macro Snippet SwiftUI preview. #Preview { [View]() }
- Localized string Snippet Localisation. String(localized: "[Text]")