Regex Cheat Sheet 2026 — Patterns, Quantifiers, and Examples

Bookmark this page. Use Ctrl+F (or Cmd+F on Mac) to find what you need. This cheat sheet covers regex patterns that work in most languages (JavaScript, Python, Java, Rust, Go). Test your patterns at regex101.com. Last updated: March 2026 Basic Patterns Pattern Matches Example abc Literal text “abc” abc matches “abcdef” . Any character (except newline) a.c matches “abc”, “a1c” ^ Start of string/line ^Hello matches “Hello world” $ End of string/line world$ matches “Hello world” \ Escape special character \. matches a literal dot Character Classes Pattern Matches [abc] a, b, or c [a-z] Any lowercase letter [A-Z] Any uppercase letter [0-9] Any digit [a-zA-Z0-9] Any letter or digit [^abc] NOT a, b, or c [^0-9] NOT a digit Shorthand Classes Pattern Matches Equivalent \d Any digit [0-9] \D NOT a digit [^0-9] \w Word character [a-zA-Z0-9_] \W NOT a word character [^a-zA-Z0-9_] \s Whitespace [ \t\n\r\f] \S NOT whitespace [^ \t\n\r\f] \b Word boundary Between \w and \W \B NOT a word boundary Quantifiers Pattern Meaning Example a* 0 or more bo* matches “b”, “bo”, “boooo” a+ 1 or more bo+ matches “bo”, “boooo” (not “b”) a? 0 or 1 (optional) colou?r matches “color”, “colour” a{3} Exactly 3 \d{3} matches “123” a{2,4} 2 to 4 \d{2,4} matches “12”, “123”, “1234” a{2,} 2 or more \d{2,} matches “12”, “12345” Greedy vs Lazy Greedy (default): .* matches as MUCH as possible Lazy (add ?): .*? matches as LITTLE as possible Text: <div>hello</div><div>world</div> Greedy: <.*> matches "<div>hello</div><div>world</div>" Lazy: <.*?> matches "<div>" Groups and Capturing Pattern Description (abc) Capture group — matches “abc” and captures it (?:abc) Non-capturing group — matches but does not capture (a|b) Alternation — matches “a” OR “b” \1 Back-reference — matches same text as group 1 Pattern: (\w+)\s+\1 Text: "the the quick brown fox" Matches: "the the" (repeated word) Named Groups Pattern: (?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2}) Text: "2026-03-15" Groups: year=2026, month=03, day=15 Lookahead and Lookbehind Pattern Name Description (?=abc) Positive lookahead Followed by “abc” (?!abc) Negative lookahead NOT followed by “abc” (?<=abc) Positive lookbehind Preceded by “abc” (?<!abc) Negative lookbehind NOT preceded by “abc” Lookaround does NOT consume characters — it only checks. ...

July 17, 2026 · 4 min

Markdown Cheat Sheet 2026 — Syntax and Formatting Guide

Bookmark this page. Use Ctrl+F (or Cmd+F on Mac) to find what you need. This cheat sheet covers standard Markdown and GitHub-flavored extensions. Try examples at markdownlivepreview.com. Last updated: March 2026 Headings # Heading 1 ## Heading 2 ### Heading 3 #### Heading 4 ##### Heading 5 ###### Heading 6 Text Formatting Markdown Result **bold** bold *italic* italic ***bold and italic*** bold and italic ~~strikethrough~~ strikethrough `inline code` inline code > blockquote blockquote Links and Images [Link text](https://example.com) [Link with title](https://example.com "Hover text") <https://example.com> <!-- auto-link --> ![Alt text](image.png) ![Alt text](image.png "Image title") [![Clickable image](image.png)](https://example.com) <!-- Reference-style links --> [Read more][1] [1]: https://example.com Lists <!-- Unordered --> - Item one - Item two - Nested item - Another nested <!-- Ordered --> 1. First 2. Second 3. Third <!-- Task list (GitHub) --> - [x] Completed task - [ ] Incomplete task - [ ] Another task Code Inline: `const x = 42;` Code block with language: ```javascript function greet(name) { return `Hello ${name}`; } ``` Code block without language: ``` plain text here ``` Supported Languages for Syntax Highlighting javascript, typescript, python, rust, kotlin, java, go, bash, sql, html, css, json, yaml, toml, markdown, diff, dockerfile ...

July 16, 2026 · 3 min

JavaScript/TypeScript Cheat Sheet 2026 — Syntax, Types, and Patterns

Bookmark this page. Use Ctrl+F (or Cmd+F on Mac) to find what you need. This cheat sheet covers modern JavaScript (ES6+) and TypeScript essentials. Try examples at typescriptlang.org/play. Last updated: March 2026 Variables const name = "Alex"; // constant — cannot reassign let count = 0; // block-scoped — can reassign // var — avoid (function-scoped, hoisted, error-prone) TypeScript Types // Basic types let name: string = "Alex"; let age: number = 25; let active: boolean = true; let items: string[] = ["a", "b"]; let tuple: [string, number] = ["Alex", 25]; let anything: any = "skip type checking"; // avoid let safe: unknown = "must check before use"; // safer than any // Type inference — no annotation needed when obvious const name = "Alex"; // TypeScript infers string // Union types let id: string | number = "abc"; // Literal types type Direction = "north" | "south" | "east" | "west"; // Interfaces interface User { name: string; age: number; email?: string; // optional readonly id: number; // cannot modify after creation } // Type aliases type Point = { x: number; y: number }; type StringOrNumber = string | number; // Generics function first<T>(items: T[]): T | undefined { return items[0]; } Utility Types Type Description Example Partial<T> All properties optional Partial<User> Required<T> All properties required Required<User> Pick<T, K> Select properties Pick<User, "name" | "email"> Omit<T, K> Remove properties Omit<User, "id"> Record<K, V> Key-value map type Record<string, number> Readonly<T> All properties readonly Readonly<User> ReturnType<F> Function return type ReturnType<typeof fn> Parameters<F> Function parameter types Parameters<typeof fn> Functions // Arrow function const greet = (name: string): string => `Hello ${name}`; // Default parameters const greet = (name = "World") => `Hello ${name}`; // Rest parameters const sum = (...nums: number[]) => nums.reduce((a, b) => a + b, 0); // Destructured parameters const greet = ({ name, age }: User) => `${name}, ${age}`; // Function overloads (TypeScript) function format(value: string): string; function format(value: number): string; function format(value: string | number): string { return String(value); } Strings const name = "Alex"; `Hello ${name}` // template literal `Total: ${price * 1.2}` // expression `Line 1 Line 2` // multi-line "hello".toUpperCase() // "HELLO" "hello".includes("ell") // true "hello".startsWith("he") // true "hello world".split(" ") // ["hello", "world"] " hello ".trim() // "hello" "hello".padStart(10, ".") // ".....hello" "hello".repeat(3) // "hellohellohello" "hello".at(-1) // "o" (last char) "hello".replaceAll("l", "r") // "herro" Arrays const nums = [1, 2, 3, 4, 5]; // Transform nums.map(x => x * 2) // [2, 4, 6, 8, 10] nums.filter(x => x > 2) // [3, 4, 5] nums.reduce((sum, x) => sum + x, 0) // 15 [1, [2, 3], [4, 5]].flat() // flatten nested arrays: [1, 2, 3, 4, 5] nums.flatMap(x => [x, x * 10]) // [1, 10, 2, 20, ...] // Search nums.find(x => x > 3) // 4 nums.findIndex(x => x > 3) // 3 nums.includes(3) // true nums.some(x => x > 4) // true nums.every(x => x > 0) // true nums.indexOf(3) // 2 // Modify nums.push(6) // add to end nums.pop() // remove from end nums.unshift(0) // add to start nums.shift() // remove from start nums.splice(1, 2) // remove 2 items at index 1 nums.slice(1, 3) // [2, 3] (no mutation) // Sort nums.sort((a, b) => a - b) // ascending (MUTATES original!) nums.sort((a, b) => b - a) // descending (MUTATES original!) nums.toSorted((a, b) => a - b) // new sorted array (no mutation, ES2023+) nums.toReversed() // new reversed array // Create Array.from({ length: 5 }, (_, i) => i) // [0, 1, 2, 3, 4] Array.from("hello") // ["h", "e", "l", "l", "o"] [...new Set(nums)] // remove duplicates Objects // Destructuring const { name, age } = user; const { name, ...rest } = user; // rest = everything except name // Spread const updated = { ...user, age: 26 }; // clone + update const merged = { ...obj1, ...obj2 }; // merge // Computed property names const key = "name"; const obj = { [key]: "Alex" }; // { name: "Alex" } // Optional chaining user?.address?.city // undefined if any is null/undefined user?.getName?.() // call method if it exists // Nullish coalescing const name = user.name ?? "Unknown"; // "Unknown" only if null/undefined // Unlike ||, does NOT fall back on "" or 0 or false // Logical assignment operators (ES2021) x ??= 10; // x = x ?? 10 (assign if null/undefined) x &&= 10; // x = x && 10 (assign if truthy) x ||= 10; // x = x || 10 (assign if falsy) // Object methods Object.keys(obj) // ["name", "age"] Object.values(obj) // ["Alex", 25] Object.entries(obj) // [["name", "Alex"], ["age", 25]] Object.fromEntries(entries) // back to object Object.assign({}, obj1, obj2) // merge (older syntax) Async/Await // Async function async function fetchUser(id: number): Promise<User> { const response = await fetch(`/api/users/${id}`); if (!response.ok) throw new Error("Failed to fetch"); return response.json(); } // Error handling try { const user = await fetchUser(1); } catch (error) { console.error("Error:", error); } // Parallel execution const [users, posts] = await Promise.all([ fetchUsers(), fetchPosts() ]); // Race — first to resolve wins const result = await Promise.race([fetchData(), timeout(5000)]); // Promise.allSettled — wait for all, never rejects const results = await Promise.allSettled([fetchA(), fetchB()]); results.forEach(r => { if (r.status === "fulfilled") console.log(r.value); if (r.status === "rejected") console.log(r.reason); }); Modules // Named exports export const API_URL = "https://api.example.com"; export function fetchData() { } // Default export export default class UserService { } // Import import UserService from "./user-service"; import { API_URL, fetchData } from "./api"; import * as api from "./api"; // Dynamic import (lazy loading) const module = await import("./heavy-module"); Classes (TypeScript) class User { private id: number; public name: string; readonly email: string; constructor(id: number, name: string, email: string) { this.id = id; this.name = name; this.email = email; } // Shorthand constructor // constructor(private id: number, public name: string) {} greet(): string { return `Hi, I'm ${this.name}`; } } // Abstract class abstract class Shape { abstract area(): number; } class Circle extends Shape { constructor(private radius: number) { super(); } area(): number { return Math.PI * this.radius ** 2; } } Type Guards (TypeScript) // typeof if (typeof value === "string") { value.toUpperCase(); // TypeScript knows it's string } // instanceof if (error instanceof TypeError) { error.message; // TypeScript knows it's TypeError } // Custom type guard function isUser(obj: unknown): obj is User { return ( typeof obj === "object" && obj !== null && "name" in obj && "age" in obj && "id" in obj ); } // Discriminated union type Result = | { status: "success"; data: string } | { status: "error"; message: string }; function handle(result: Result) { if (result.status === "success") { result.data; // TypeScript knows data exists } } Modern TypeScript Features // satisfies — validate type without widening const config = { port: 3000, host: "localhost" } satisfies Record<string, string | number>; // config.port is still number (not string | number) // as const — immutable literal type const COLORS = ["red", "green", "blue"] as const; type Color = typeof COLORS[number]; // "red" | "green" | "blue" // template literal types type EventName = `on${Capitalize<string>}`; // "onClick", "onHover", etc. Common Mistakes == vs === — == does type coercion ("1" == 1 is true). Always use === for strict equality. The only exception: value == null checks both null and undefined. ...

July 15, 2026 · 7 min

Linux/Terminal Commands Cheat Sheet 2026 — Essential Commands

Bookmark this page. Use Ctrl+F (or Cmd+F on Mac) to find what you need. This cheat sheet covers essential terminal commands for macOS and Linux. Last updated: March 2026 Navigation Command Description pwd Print current directory ls List files ls -la List all files with details (including hidden) ls -lh List with human-readable sizes cd /path Change directory cd ~ Go to home directory cd .. Go up one directory cd - Go to previous directory tree Show directory tree (install: brew install tree) tree -L 2 Tree with max depth 2 Files and Directories Command Description touch file.txt Create empty file mkdir mydir Create directory mkdir -p a/b/c Create nested directories cp file.txt copy.txt Copy file cp -r dir/ newdir/ Copy directory recursively mv file.txt newname.txt Rename/move file rm file.txt Delete file rm -r dir/ Delete directory recursively rm -rf dir/ Force delete (no confirmation) ln -s target link Create symbolic link cat file.txt Print file contents head -20 file.txt First 20 lines tail -20 file.txt Last 20 lines tail -f file.log Follow file in real-time (logs) less file.txt Paginated viewer (q to quit) wc -l file.txt Count lines wc -w file.txt Count words diff file1 file2 Compare two files stat file.txt File details (size, dates, permissions) Searching Command Description grep "text" file.txt Search for text in file grep -r "text" dir/ Search recursively in directory grep -i "text" file.txt Case-insensitive search grep -n "text" file.txt Show line numbers grep -c "text" file.txt Count matches grep -v "text" file.txt Show lines NOT matching find . -name "*.txt" Find files by name find . -type d -name "src" Find directories by name find . -size +10M Find files larger than 10MB find . -mtime -7 Files modified in last 7 days which python Find where a command lives locate file.txt Fast file search (uses index) Pipes and Redirection # Pipe — send output of one command to another ls -la | grep ".txt" cat file.txt | sort | uniq ps aux | grep node # Redirect output to file echo "hello" > file.txt # overwrite echo "world" >> file.txt # append # Redirect errors command 2> errors.log # stderr to file command > output.log 2>&1 # stdout + stderr to file command &> all.log # same (bash shorthand) # /dev/null — discard output command > /dev/null 2>&1 # silence everything cmd1 | cmd2 pipe: stdout of cmd1 → stdin of cmd2 cmd > file redirect stdout to file (overwrite) cmd >> file redirect stdout to file (append) cmd 2> file redirect stderr to file cmd < file use file as stdin Permissions -rwxr-xr-- 1 alex staff 4096 Mar 15 file.txt │├─┤├─┤├─┤ │ │ │ │ │ │ │ └── Others: read only │ │ └───── Group: read + execute │ └───────── Owner: read + write + execute └─────────── File type (- = file, d = directory, l = link) Command Description chmod 755 file rwxr-xr-x (owner all, group/others read+exec) chmod 644 file rw-r–r– (owner read+write, others read) chmod +x script.sh Add execute permission chmod -w file.txt Remove write permission chown user:group file Change owner and group chown -R user dir/ Change owner recursively Number Permission 7 rwx (read + write + execute) 6 rw- (read + write) 5 r-x (read + execute) 4 r– (read only) 0 — (no permission) Processes Command Description ps aux List all processes ps aux | grep node Find a specific process top Live process monitor htop Better process monitor (install separately) kill <pid> Send SIGTERM (graceful stop) kill -9 <pid> Send SIGKILL (force stop) killall node Kill all processes by name lsof -i :3000 Find what is using port 3000 jobs List background jobs bg Resume job in background fg Bring job to foreground command & Run command in background nohup command & Run and keep running after logout Disk and System Command Description df -h Disk usage (human-readable) du -sh dir/ Directory size du -sh * | sort -rh Largest items in current dir free -h Memory usage (Linux) uname -a System info hostname Machine name uptime System uptime and load date Current date/time cal Calendar Networking Command Description curl https://example.com Fetch a URL curl -o file.html https://example.com Download to file curl -X POST -d '{"key":"value"}' -H "Content-Type: application/json" url POST JSON wget https://example.com/file.zip Download a file ping example.com Test connectivity ifconfig / ip addr Show network interfaces netstat -tlnp / ss -tlnp Show listening ports ssh user@host Connect via SSH scp file.txt user@host:/path Copy file to remote scp user@host:/path/file.txt . Copy file from remote Archives Command Description tar -czf archive.tar.gz dir/ Create gzip archive tar -xzf archive.tar.gz Extract gzip archive tar -xzf archive.tar.gz -C /dest Extract to directory zip -r archive.zip dir/ Create zip archive unzip archive.zip Extract zip Text Processing # Sort lines sort file.txt sort -r file.txt # reverse sort -n file.txt # numeric sort sort -u file.txt # unique only # Unique lines (file must be sorted first) sort file.txt | uniq sort file.txt | uniq -c # count occurrences # Cut columns cut -d',' -f1,3 data.csv # columns 1 and 3 (comma delimiter) # Replace text sed 's/old/new/g' file.txt # replace all occurrences sed -i 's/old/new/g' file.txt # in-place edit (Linux) sed -i '' 's/old/new/g' file.txt # in-place edit (macOS — needs empty '') # Print specific lines awk '{print $1, $3}' file.txt # columns 1 and 3 (space delimiter) awk -F',' '{print $1}' data.csv # with custom delimiter # Count and summarize cat access.log | awk '{print $1}' | sort | uniq -c | sort -rn | head -10 # → top 10 IP addresses in an access log Keyboard Shortcuts (Terminal) Shortcut Action Ctrl+C Cancel current command Ctrl+D Exit shell / close terminal Ctrl+Z Suspend current process Ctrl+L Clear screen Ctrl+R Search command history Ctrl+A Move cursor to start of line Ctrl+E Move cursor to end of line Ctrl+W Delete word before cursor Ctrl+U Delete entire line before cursor Tab Auto-complete file/command name !! Repeat last command !$ Last argument of previous command Environment Variables echo $HOME # print variable export MY_VAR="value" # set for current session echo 'export MY_VAR="value"' >> ~/.zshrc # permanent (Zsh) echo 'export MY_VAR="value"' >> ~/.bashrc # permanent (Bash) env # list all env variables printenv PATH # print specific variable Common Mistakes rm -rf / or rm -rf * — There is no recycle bin in the terminal. Deleted files are gone. Always double-check your path before running rm -rf. Use ls first to preview what will be deleted. ...

July 14, 2026 · 6 min

Rust Cheat Sheet 2026 — Syntax, Ownership, and Common Patterns

Bookmark this page. Use Ctrl+F (or Cmd+F on Mac) to find what you need. This cheat sheet covers Rust syntax, ownership, traits, error handling, and common patterns. Try examples at play.rust-lang.org. Last updated: March 2026 Variables and Types let name = "Alex"; // immutable (default) let mut count = 0; // mutable let age: i32 = 25; // explicit type const MAX: u32 = 100; // compile-time constant Type Description Example i8, i16, i32, i64, i128 Signed integers let x: i32 = -42; u8, u16, u32, u64, u128 Unsigned integers let x: u32 = 42; f32, f64 Floating point let x: f64 = 3.14; bool Boolean true, false char Unicode character 'A', '🚀' &str String slice (borrowed) "hello" String Owned string (heap) String::from("hello") () Unit type (void) fn do_thing() { } [T; N] Fixed array [1, 2, 3] Vec<T> Dynamic array vec![1, 2, 3] (T, U) Tuple (42, "hello") Option<T> Nullable value Some(42) or None Result<T, E> Success or error Ok(42) or Err("fail") Type Conversions let x: i32 = 42; let y: f64 = x as f64; // 42.0 let s: String = x.to_string(); // "42" let n: i32 = "42".parse().unwrap(); // 42 let n: i32 = "42".parse().unwrap_or(0); // 42 (or 0 on error) Strings // &str — string slice, borrowed, immutable let greeting: &str = "hello"; // String — owned, heap-allocated, growable let mut name = String::from("Alex"); name.push_str(" Smith"); // append name.push('!'); // append char // Conversions let s: String = "hello".to_string(); let s: &str = &name; // String → &str (auto-deref) // Common methods name.len() // byte length name.is_empty() // true if empty name.contains("Alex") // substring check name.starts_with("A") name.to_uppercase() name.to_lowercase() name.trim() // remove whitespace name.replace("Alex", "Sam") name.split(" ") // iterator of parts // Format let msg = format!("Hello {name}, age {age}"); Ownership and Borrowing // Ownership — each value has one owner let s1 = String::from("hello"); let s2 = s1; // s1 is MOVED to s2 // println!("{s1}"); // ERROR: s1 no longer valid // Clone — deep copy let s1 = String::from("hello"); let s2 = s1.clone(); // both valid // Borrowing — reference without taking ownership fn print_len(s: &String) { // immutable borrow println!("{}", s.len()); } fn add_excl(s: &mut String) { // mutable borrow s.push('!'); } // Rules: // 1. Many immutable references (&T) OR one mutable reference (&mut T) // 2. References must always be valid (no dangling) Structs struct User { name: String, age: u32, active: bool, } let user = User { name: String::from("Alex"), age: 25, active: true, }; // Access println!("{}", user.name); // Update syntax let user2 = User { age: 26, ..user }; // Tuple struct struct Point(f64, f64); let p = Point(1.0, 2.0); // Methods impl User { // Constructor (convention) fn new(name: &str, age: u32) -> Self { Self { name: name.to_string(), age, active: true } } // Method (takes &self) fn greet(&self) -> String { format!("Hi, I'm {}", self.name) } } Enums and Pattern Matching enum Direction { North, South, East, West } // Enums with data enum Shape { Circle(f64), // radius Rectangle(f64, f64), // width, height Triangle { base: f64, height: f64 }, } // Pattern matching with match match shape { Shape::Circle(r) => std::f64::consts::PI * r * r, Shape::Rectangle(w, h) => w * h, Shape::Triangle { base, height } => 0.5 * base * height, } // if let — match a single pattern if let Some(value) = optional { println!("Got: {value}"); } // let else — match or diverge let Some(value) = optional else { return; }; Option and Result // Option<T> — value or nothing let name: Option<&str> = Some("Alex"); let empty: Option<&str> = None; name.unwrap() // "Alex" (panics if None) name.unwrap_or("Unknown") // "Alex" (or default) name.is_some() // true name.is_none() // false name.map(|n| n.len()) // Some(4) // Result<T, E> — success or error fn divide(a: f64, b: f64) -> Result<f64, String> { if b == 0.0 { Err("division by zero".to_string()) } else { Ok(a / b) } } // ? operator — propagate errors fn read_file(path: &str) -> Result<String, std::io::Error> { let content = std::fs::read_to_string(path)?; // returns Err early Ok(content) } // Handle Result match divide(10.0, 3.0) { Ok(result) => println!("{result}"), Err(e) => println!("Error: {e}"), } Traits // Define a trait trait Greet { fn greet(&self) -> String; // Default implementation fn hello(&self) -> String { format!("Hello from {}", self.greet()) } } // Implement for a type impl Greet for User { fn greet(&self) -> String { self.name.clone() } } // Trait as parameter fn print_greeting(item: &impl Greet) { println!("{}", item.greet()); } // Trait bound syntax fn print_greeting<T: Greet>(item: &T) { println!("{}", item.greet()); } // Common derive traits #[derive(Debug, Clone, PartialEq, Eq, Hash)] struct Point { x: i32, y: i32 } Collections // Vec — dynamic array let mut v = vec![1, 2, 3]; v.push(4); v.pop(); // Some(4) v.len(); // 3 v[0]; // 1 (panics if out of bounds) v.get(0); // Some(&1) (safe) v.contains(&2); // true v.iter().filter(|&&x| x > 1).collect::<Vec<_>>(); // HashMap use std::collections::HashMap; let mut map = HashMap::new(); map.insert("name", "Alex"); map.get("name"); // Some(&"Alex") map.contains_key("name"); // true map.entry("age").or_insert("25"); for (key, value) in &map { } // HashSet use std::collections::HashSet; let mut set = HashSet::new(); set.insert(1); set.contains(&1); // true Iterators let nums = vec![1, 2, 3, 4, 5]; nums.iter().map(|x| x * 2).collect::<Vec<_>>(); // [2, 4, 6, 8, 10] nums.iter().filter(|&&x| x > 2).collect::<Vec<_>>(); // [3, 4, 5] nums.iter().sum::<i32>(); // 15 nums.iter().any(|&x| x > 3); // true nums.iter().all(|&x| x > 0); // true nums.iter().find(|&&x| x > 3); // Some(&4) nums.iter().position(|&x| x == 3); // Some(2) nums.iter().enumerate(); // (index, &value) nums.iter().zip(other.iter()); // pair elements nums.iter().take(3).collect::<Vec<_>>(); // [1, 2, 3] nums.iter().skip(2).collect::<Vec<_>>(); // [3, 4, 5] nums.iter().flat_map(|x| vec![x, x * 10]); nums.iter().fold(0, |acc, &x| acc + x); // 15 Control Flow // if / else (is an expression) let status = if age >= 18 { "adult" } else { "minor" }; // loop (infinite, break with value) let result = loop { if condition { break 42; } }; // while while count > 0 { count -= 1; } // for for i in 0..5 { } // 0, 1, 2, 3, 4 for i in 0..=5 { } // 0, 1, 2, 3, 4, 5 for item in &vec { } // iterate by reference for item in vec { } // iterate by value (moves) Closures let add = |a: i32, b: i32| -> i32 { a + b }; let double = |x| x * 2; // types inferred let greet = || println!("Hello"); // Closures capture variables let name = String::from("Alex"); let greet = || println!("Hello {name}"); // borrows name let greet = move || println!("Hello {name}"); // takes ownership Cargo Commands Command Description cargo new my_app Create a new project cargo run Build and run cargo build Build (debug) cargo build --release Build (optimized) cargo test Run tests cargo check Fast compile check (no binary) cargo clippy Lint your code cargo fmt Auto-format code cargo add serde Add a dependency cargo doc --open Generate and open docs Lifetimes // Lifetimes tell the compiler how long references are valid fn longest<'a>(a: &'a str, b: &'a str) -> &'a str { if a.len() > b.len() { a } else { b } } // Struct with a reference needs a lifetime struct Excerpt<'a> { text: &'a str, } Rule: if a function returns a reference, it must come from one of the inputs (annotated with the same lifetime). ...

July 13, 2026 · 7 min

Vibe Coding Cheat Sheet — The Complete Reference

Everything from the Vibe Coding series in one reference page. Bookmark this. Come back to it often. Tool Comparison Matrix Feature Claude Code Cursor GitHub Copilot Interface Terminal VS Code fork IDE extension Best at Complex tasks, multi-file changes, debugging UI generation, scaffolding, Composer mode Inline completions, quick suggestions Agent mode Yes (primary mode) Yes (Composer, Background Agents) Yes (Copilot Workspace) Multi-agent Yes (Agent Teams) Limited Limited Context window 200K tokens 200K tokens 128K tokens Local models No Yes (OpenAI-compatible) No MCP support Yes (native) Partial No CLI support Yes (primary) No Yes (gh copilot) Price $20/mo (Pro), $100-200/mo (Max) $20/mo (Pro) $10/mo (Individual) Best for Backend, architecture, complex tasks Frontend, UI, full-stack scaffolding Quick completions, simple edits When to use which: ...

June 30, 2026 · 9 min

Docker Cheat Sheet 2026 — All Commands in One Page

This is the complete Docker reference for 2026. All essential commands in one place. Versions covered: Docker Engine 29+, Docker Compose v2 (Compose Specification v5). Container Commands # Run a container docker run nginx # Run in detached mode (background) docker run -d nginx # Run interactively with a shell docker run -it ubuntu:24.04 bash # Run and remove when stopped docker run --rm nginx # Run with a name docker run --name mywebserver nginx # Run with port mapping (host:container) docker run -p 8080:80 nginx # Run with environment variables docker run -e APP_ENV=production myapp:1.0 # Run with environment file docker run --env-file .env myapp:1.0 # Run with volume docker run -v mydata:/data nginx # Run with bind mount docker run -v /host/path:/container/path nginx # Run with resource limits docker run --memory 512m --cpus 1.0 myapp:1.0 # Run as non-root user docker run --user 1001:1001 myapp:1.0 # Run with read-only filesystem docker run --read-only myapp:1.0 # Run with network docker run --network mynetwork myapp:1.0 # Run with restart policy docker run --restart unless-stopped nginx # List running containers docker ps # List all containers (including stopped) docker ps -a # Stop a container (SIGTERM) docker stop mywebserver # Kill a container (SIGKILL) docker kill mywebserver # Start a stopped container docker start mywebserver # Restart a container docker restart mywebserver # Remove a stopped container docker rm mywebserver # Force-remove a running container docker rm -f mywebserver # Remove all stopped containers docker container prune # View container logs docker logs mywebserver # Follow logs in real time docker logs -f mywebserver # Show last 50 lines docker logs --tail 50 mywebserver # Execute a command in a running container docker exec -it mywebserver bash # Copy files to/from a container docker cp mywebserver:/etc/nginx/nginx.conf ./nginx.conf docker cp ./nginx.conf mywebserver:/etc/nginx/nginx.conf # Inspect container details (JSON) docker inspect mywebserver # View real-time resource usage docker stats # View stats for one container docker stats mywebserver # View running processes inside a container docker top mywebserver Image Commands # Pull an image from Docker Hub docker pull nginx # Pull specific version docker pull nginx:1.27 # List local images docker images # Build an image from Dockerfile docker build -t myapp:1.0 . # Build from specific Dockerfile docker build -f Dockerfile.prod -t myapp:prod . # Build with build args docker build --build-arg APP_VERSION=2.0 -t myapp:2.0 . # Tag an image docker tag myapp:1.0 myapp:latest docker tag myapp:1.0 kemalcodes/myapp:1.0 # Push to Docker Hub docker push kemalcodes/myapp:1.0 # Remove an image docker rmi nginx # Remove all unused images docker image prune # Remove all unused images (including tagged but not referenced) docker image prune -a # View image history (layers) docker history nginx # Inspect image details (JSON) docker inspect nginx # Save image to tar file docker save myapp:1.0 -o myapp.tar # Load image from tar file docker load -i myapp.tar Volume Commands # Create a named volume docker volume create mydata # List all volumes docker volume ls # Inspect a volume docker volume inspect mydata # Remove a volume docker volume rm mydata # Remove all unused volumes docker volume prune Network Commands # List all networks docker network ls # Create a network docker network create mynetwork # Create with specific driver docker network create --driver bridge mynetwork # Inspect a network docker network inspect mynetwork # Connect a container to a network docker network connect mynetwork mycontainer # Disconnect a container from a network docker network disconnect mynetwork mycontainer # Remove a network docker network rm mynetwork # Remove all unused networks docker network prune Docker Compose Commands Always use docker compose (v2 plugin), not docker-compose (v1, deprecated). ...

June 26, 2026 · 7 min

AI Coding Tools Cheat Sheet 2026 — Claude, Cursor, Copilot, and More

Bookmark this page. Use Ctrl+F (or Cmd+F on Mac) to find what you need. This cheat sheet compares AI coding tools, their features, pricing, and best use cases. Last updated: March 2026 Tool Comparison Tool Type Best For Pricing (Mar 2026) Claude Code CLI agent Multi-file edits, refactoring, debugging $20/mo Pro, $100/$200 Max Cursor IDE (VS Code fork) Day-to-day coding with AI inline $20/mo (Pro) GitHub Copilot IDE extension Autocomplete, inline suggestions Free (limited), $10/mo Pro, $39/mo Pro+ Windsurf IDE (VS Code fork) Chat + agent workflows $15/mo (Pro) ChatGPT Chat Explaining code, brainstorming $20/mo (Plus) Gemini CLI CLI Quick questions, code review Free (1K req/day), Pro/Ultra plans Codex CLI CLI Code review, autonomous tasks OpenAI API pricing Feature Matrix Feature Claude Code Cursor Copilot Windsurf Autocomplete — Yes Yes Yes Chat Yes Yes Yes Yes Multi-file editing Yes Yes Limited Yes Terminal commands Yes Yes (Cmd+K in terminal) — — Agent mode Yes Yes Yes Yes Git integration Yes Yes Yes Yes MCP support Yes Yes Yes Yes Custom rules CLAUDE.md .cursorrules .github/copilot-instructions.md .windsurfrules Context window 200K (up to 1M on Max) 128K 128K 128K Claude Code Shortcuts Command Description /help Show available commands /clear Clear conversation /compact Compress context to save tokens /cost Show token usage and cost /init Create CLAUDE.md project file Esc Cancel current generation Shift+Tab Accept file edit Ctrl+C Exit Claude Code Tips # Run Claude Code claude # Start with a prompt claude "fix the failing tests" # Non-interactive mode claude -p "explain this function" < file.py # Use a specific model claude --model sonnet # or opus, haiku # Continue last conversation claude --continue CLAUDE.md — Project Instructions # CLAUDE.md - Use TypeScript strict mode - Tests: Jest with React Testing Library - Style: Tailwind CSS, no inline styles - Always run tests before committing Place CLAUDE.md in your project root. Claude reads it automatically. ...

March 25, 2026 · 4 min

Python Cheat Sheet 2026 — Syntax, Data Structures, and Common Patterns

Bookmark this page. Use Ctrl+F (or Cmd+F on Mac) to find what you need. This cheat sheet covers Python syntax from basics to advanced patterns. Try examples at pythontutor.com. Last updated: March 2026 Variables and Types name = "Alex" # str age = 25 # int height = 1.75 # float is_active = True # bool nothing = None # NoneType Type Example Notes int 42 No size limit float 3.14 64-bit decimal str "hello" Immutable bool True, False Capitalized None None Null equivalent list [1, 2, 3] Mutable, ordered tuple (1, 2, 3) Immutable, ordered dict {"a": 1} Key-value pairs set {1, 2, 3} Unique values, unordered Type Conversions int("42") # 42 float("3.14") # 3.14 str(42) # "42" list((1, 2, 3)) # [1, 2, 3] tuple([1, 2, 3]) # (1, 2, 3) set([1, 1, 2]) # {1, 2} bool(0) # False bool("") # False bool([]) # False bool("hello") # True Strings name = "Alex" f"Hello {name}" # f-string: Hello Alex f"Age: {age + 1}" # f-string with expression f"{price:.2f}" # format: 9.99 f"{name!r}" # repr: 'Alex' f"{num:,}" # thousands separator: 1,000,000 f"{value:>10}" # right-align, width 10 f"{value:<10}" # left-align, width 10 # Common methods "hello".upper() # "HELLO" "HELLO".lower() # "hello" "hello world".title() # "Hello World" " hello ".strip() # "hello" "hello world".split() # ["hello", "world"] "hello world".split("o") # ["hell", " w", "rld"] ", ".join(["a", "b", "c"]) # "a, b, c" "hello".replace("l", "r") # "herro" "hello".startswith("he") # True "hello".endswith("lo") # True "hello world".find("world") # 6 (-1 if not found) "hello world".count("l") # 3 "42".isdigit() # True # Multi-line strings text = """ First line Second line """ # Raw strings (no escape processing) path = r"C:\Users\name\folder" Lists nums = [1, 2, 3, 4, 5] # Access nums[0] # 1 (first) nums[-1] # 5 (last) nums[1:3] # [2, 3] (slice) nums[:3] # [1, 2, 3] (first 3) nums[2:] # [3, 4, 5] (from index 2) nums[::2] # [1, 3, 5] (every 2nd) nums[::-1] # [5, 4, 3, 2, 1] (reversed) # Modify nums.append(6) # add to end nums.insert(0, 0) # insert at index nums.extend([7, 8]) # add multiple nums.remove(3) # remove first occurrence nums.pop() # remove and return last nums.pop(0) # remove and return at index nums.sort() # sort in place nums.sort(reverse=True) # sort descending nums.reverse() # reverse in place nums.clear() # remove all # Functions len(nums) # length min(nums) # smallest max(nums) # largest sum(nums) # total sorted(nums) # new sorted list reversed(nums) # reversed iterator Dictionaries user = {"name": "Alex", "age": 25, "city": "Berlin"} # Access user["name"] # "Alex" (KeyError if missing) user.get("name") # "Alex" user.get("phone", "N/A") # "N/A" (default if missing) # Modify user["age"] = 26 # update user["email"] = "alex@mail.com" # add new key del user["city"] # delete key user.pop("age") # remove and return value # Iterate user.keys() # dict_keys(["name", "age", ...]) user.values() # dict_values(["Alex", 25, ...]) user.items() # dict_items([("name", "Alex"), ...]) for key, value in user.items(): print(f"{key}: {value}") # Merge (Python 3.9+) merged = dict1 | dict2 # dict2 values win on conflict Sets and Tuples # Sets — unique values, unordered colors = {"red", "green", "blue"} colors.add("yellow") colors.remove("red") # KeyError if missing colors.discard("red") # no error if missing a | b # union a & b # intersection a - b # difference a ^ b # symmetric difference # Tuples — immutable point = (10, 20) x, y = point # unpacking name, *rest = ("Alex", 25, "Berlin") # name="Alex", rest=[25, "Berlin"] Control Flow # if / elif / else if age < 18: print("minor") elif age < 65: print("adult") else: print("senior") # Ternary status = "adult" if age >= 18 else "minor" # for loop for item in items: print(item) for i in range(5): # 0, 1, 2, 3, 4 for i in range(2, 10): # 2, 3, ..., 9 for i in range(0, 10, 2): # 0, 2, 4, 6, 8 for i, item in enumerate(items): # index + value print(f"{i}: {item}") for a, b in zip(list1, list2): # parallel iteration print(a, b) # while loop while count > 0: count -= 1 # break / continue for item in items: if item == "skip": continue # skip this iteration if item == "stop": break # exit loop Pattern Matching (Python 3.10+) match status_code: case 200: print("OK") case 404: print("Not Found") case 500: print("Server Error") case _: print(f"Unknown: {status_code}") # Match with destructuring match point: case (0, 0): print("Origin") case (x, 0): print(f"On x-axis at {x}") case (0, y): print(f"On y-axis at {y}") case (x, y): print(f"Point at ({x}, {y})") # Match with guards match user: case {"role": "admin", "name": name}: print(f"Admin: {name}") case {"role": "user", "name": name} if name != "blocked": print(f"User: {name}") Comprehensions # List comprehension squares = [x**2 for x in range(10)] evens = [x for x in nums if x % 2 == 0] pairs = [(x, y) for x in range(3) for y in range(3)] # Dict comprehension word_lengths = {word: len(word) for word in words} filtered = {k: v for k, v in data.items() if v > 0} # Set comprehension unique_lengths = {len(word) for word in words} # Generator expression (lazy, memory-efficient) total = sum(x**2 for x in range(1000000)) Functions # Basic function def greet(name): return f"Hello {name}" # Default parameters def greet(name="World"): return f"Hello {name}" # *args and **kwargs def func(*args, **kwargs): print(args) # tuple of positional args print(kwargs) # dict of keyword args # Lambda double = lambda x: x * 2 sorted(users, key=lambda u: u["age"]) # Type hints (Python 3.10+) def greet(name: str) -> str: return f"Hello {name}" def process(items: list[int]) -> dict[str, int]: return {"sum": sum(items), "count": len(items)} Classes class User: def __init__(self, name: str, age: int): self.name = name self.age = age def greet(self) -> str: return f"Hi, I'm {self.name}" def __repr__(self) -> str: return f"User({self.name!r}, {self.age})" user = User("Alex", 25) # Dataclass (Python 3.7+) — auto-generates __init__, __repr__, __eq__ from dataclasses import dataclass @dataclass class User: name: str age: int city: str = "Unknown" # Inheritance class Admin(User): def __init__(self, name, age, level): super().__init__(name, age) self.level = level Error Handling try: result = 10 / 0 except ZeroDivisionError: print("Cannot divide by zero") except (ValueError, TypeError) as e: print(f"Error: {e}") else: print("Success") # runs if no exception finally: print("Always runs") # cleanup # Raise an exception raise ValueError("Invalid input") File I/O # Read entire file with open("file.txt", "r") as f: content = f.read() # Read lines with open("file.txt", "r") as f: lines = f.readlines() # list of lines # or for line in f: print(line.strip()) # Write with open("file.txt", "w") as f: # overwrite f.write("Hello\n") with open("file.txt", "a") as f: # append f.write("More text\n") # JSON import json data = json.loads('{"name": "Alex"}') # parse string text = json.dumps(data, indent=2) # to string with open("data.json", "r") as f: data = json.load(f) # parse file with open("data.json", "w") as f: json.dump(data, f, indent=2) # write file Async / Await import asyncio async def fetch_data(url: str) -> str: # simulate async work await asyncio.sleep(1) return f"Data from {url}" # Run async function async def main(): result = await fetch_data("https://api.example.com") print(result) asyncio.run(main()) # Run tasks in parallel async def main(): results = await asyncio.gather( fetch_data("https://api1.example.com"), fetch_data("https://api2.example.com"), ) print(results) # both complete in ~1 second, not 2 Common Built-in Functions Function Description Example len(x) Length len([1,2,3]) → 3 range(n) Sequence 0..n-1 range(5) → 0,1,2,3,4 enumerate(x) Index + value enumerate(["a","b"]) zip(a, b) Pair elements zip([1,2], ["a","b"]) map(fn, x) Apply function map(str, [1,2,3]) filter(fn, x) Filter elements filter(bool, [0,1,"",2]) any(x) True if any truthy any([False, True]) → True all(x) True if all truthy all([True, True]) → True sorted(x) New sorted list sorted([3,1,2]) → [1,2,3] reversed(x) Reversed iterator list(reversed([1,2,3])) isinstance(x, type) Type check isinstance(42, int) → True type(x) Get type type(42) → <class 'int'> dir(x) List attributes dir([]) help(x) Show docs help(str.split) Virtual Environments python -m venv .venv # create source .venv/bin/activate # activate (macOS/Linux) .venv\Scripts\activate # activate (Windows) pip install requests # install package pip freeze > requirements.txt # save dependencies pip install -r requirements.txt # install from file deactivate # deactivate Common Mistakes Mutable default arguments — def add(item, items=[]) shares the same list across all calls. Use def add(item, items=None) and items = items or [] inside the function. ...

March 22, 2026 · 7 min

SQL Cheat Sheet 2026 — Queries, JOINs, and Performance

Bookmark this page. Use Ctrl+F (or Cmd+F on Mac) to find what you need. This cheat sheet covers SQL from basic queries to window functions and performance. Try examples at db-fiddle.com. Last updated: March 2026 SELECT Basics SELECT * FROM users; -- all columns SELECT name, email FROM users; -- specific columns SELECT DISTINCT city FROM users; -- unique values SELECT name AS full_name FROM users; -- column alias SELECT * FROM users LIMIT 10; -- first 10 rows SELECT * FROM users LIMIT 10 OFFSET 20; -- rows 21-30 (pagination) WHERE — Filtering Rows SELECT * FROM users WHERE age > 18; SELECT * FROM users WHERE city = 'Berlin'; SELECT * FROM users WHERE age BETWEEN 18 AND 30; SELECT * FROM users WHERE city IN ('Berlin', 'Munich', 'Hamburg'); SELECT * FROM users WHERE name LIKE 'A%'; -- starts with A SELECT * FROM users WHERE name LIKE '%son'; -- ends with son SELECT * FROM users WHERE name LIKE '%alex%'; -- contains alex SELECT * FROM users WHERE email IS NULL; -- null check SELECT * FROM users WHERE email IS NOT NULL; SELECT * FROM users WHERE age > 18 AND city = 'Berlin'; SELECT * FROM users WHERE age > 65 OR age < 18; SELECT * FROM users WHERE NOT city = 'Berlin'; ORDER BY and LIMIT SELECT * FROM users ORDER BY name; -- ascending (default) SELECT * FROM users ORDER BY age DESC; -- descending SELECT * FROM users ORDER BY city, name; -- multiple columns SELECT * FROM users ORDER BY age DESC LIMIT 5; -- top 5 oldest INSERT, UPDATE, DELETE -- Insert one row INSERT INTO users (name, email, age) VALUES ('Alex', 'alex@example.com', 25); -- Insert multiple rows INSERT INTO users (name, email, age) VALUES ('Sam', 'sam@example.com', 30), ('Jordan', 'jordan@example.com', 22); -- Update UPDATE users SET age = 26 WHERE name = 'Alex'; -- Update multiple columns UPDATE users SET city = 'Munich', age = 27 WHERE id = 1; -- Delete DELETE FROM users WHERE id = 5; -- Delete all rows (use with caution!) DELETE FROM users; -- Faster delete all (resets table) TRUNCATE TABLE users; -- UPSERT — insert or update if exists (PostgreSQL) INSERT INTO users (email, name) VALUES ('alex@example.com', 'Alex') ON CONFLICT (email) DO UPDATE SET name = EXCLUDED.name; -- MySQL equivalent INSERT INTO users (email, name) VALUES ('alex@example.com', 'Alex') ON DUPLICATE KEY UPDATE name = VALUES(name); Warning: Always use WHERE with UPDATE and DELETE. Without it, every row is affected. ...

March 21, 2026 · 8 min