evens = [x for x in range(20) if x % 2 == 0]
names = [u["name"] for u in users if u["active"]]
flat = [x for row in matrix for x in row] # flatten 2D list
Concise filtering and transformation in one expression.
Decorator with Arguments PY
import functools, time
def retry(max_retries=3, delay=1):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
for attempt in range(max_retries):
try:
return func(*args, **kwargs)
except Exception as e:
if attempt == max_retries - 1:
raise
time.sleep(delay)
return wrapper
return decorator
@retry(max_retries=5, delay=2)
def fetch_data(url): ...
A retry decorator with configurable attempts and delay.
Dataclass Example PY
from dataclasses import dataclass, field
@dataclass
class User:
name: str
email: str
roles: list[str] = field(default_factory=list)
active: bool = True
@property
def is_admin(self):
return "admin" in self.roles
Clean data containers with auto __init__, __repr__, __eq__.
Context Manager PY
from contextlib import contextmanager
import time
@contextmanager
def timer(label="Block"):
start = time.perf_counter()
yield
elapsed = time.perf_counter() - start
print(f"{label}: {elapsed:.4f}s")
with timer("DB query"):
results = db.execute(query)
Three ways to merge dictionaries. Later keys override earlier ones.
File Path Handling (pathlib) PY
from pathlib import Path
p = Path("data/reports")
p.mkdir(parents=True, exist_ok=True)
for f in p.glob("*.csv"):
print(f.stem, f.suffix, f.stat().st_size)
text = (p / "report.txt").read_text()
(p / "output.txt").write_text("Hello")
Modern file/path operations with pathlib. Replaces os.path.
HTTP Request (requests) PY
import requests
resp = requests.get("https://api.example.com/users", timeout=10)
resp.raise_for_status()
users = resp.json()
# POST with JSON body
resp = requests.post(
"https://api.example.com/users",
json={"name": "Alice"},
headers={"Authorization": "Bearer TOKEN"}
)
Functional-style collection processing with Java Streams.
Optional Handling JAVA
Optional<User> user = repository.findById(id);
String name = user
.map(User::getName)
.orElse("Unknown");
user.ifPresent(u -> sendEmail(u.getEmail()));
User u = user.orElseThrow(() -> new NotFoundException("User not found"));
Safe null handling with Optional. Avoid NullPointerException.
Async programming with CompletableFuture. Chain, combine, handle errors.
Singleton Pattern JAVA
public class Config {
private static volatile Config instance;
private Config() {} // private constructor
public static Config getInstance() {
if (instance == null) {
synchronized (Config.class) {
if (instance == null) {
instance = new Config();
}
}
}
return instance;
}
}
Thread-safe Singleton using double-checked locking.
Builder Pattern JAVA
public class User {
private final String name;
private final String email;
private final int age;
private User(Builder b) { name = b.name; email = b.email; age = b.age; }
public static class Builder {
private String name, email;
private int age;
public Builder name(String n) { name = n; return this; }
public Builder email(String e) { email = e; return this; }
public Builder age(int a) { age = a; return this; }
public User build() { return new User(this); }
}
}
// Usage: new User.Builder().name("Alice").email("[email protected]").age(30).build();
Fluent builder for objects with many optional parameters.
HashMap Operations JAVA
Map<String, Integer> freq = new HashMap<>();
// Count frequency
for (String word : words) {
freq.merge(word, 1, Integer::sum);
}
// Get with default
int count = freq.getOrDefault("hello", 0);
// Compute if absent
map.computeIfAbsent(key, k -> new ArrayList<>()).add(value);
Common test expressions for files, dirs, and variables.
Parse Command-Line Args BASH
while [[ $# -gt 0 ]]; do
case "$1" in
-n|--name) NAME="$2"; shift 2 ;;
-v|--verbose) VERBOSE=true; shift ;;
-h|--help) usage; exit 0 ;;
*) echo "Unknown: $1"; exit 1 ;;
esac
done
echo "Name: ${NAME:-default}"
Simple argument parsing with case/shift. No getopt needed.
Read File Line by Line BASH
while IFS= read -r line; do
echo "Line: $line"
done < input.txt
# Skip comments and empty lines
while IFS= read -r line; do
[[ "$line" =~ ^#|^$ ]] && continue
process "$line"
done < config.txt
Safe line-by-line reading with IFS= and -r to preserve whitespace.
SQL Snippets
Advanced queries and patterns
Common Table Expression (CTE) SQL
WITH active_users AS (
SELECT id, name, email
FROM users
WHERE active = true AND created_at > NOW() - INTERVAL '30 days'
)
SELECT au.name, COUNT(o.id) AS order_count
FROM active_users au
LEFT JOIN orders o ON o.user_id = au.id
GROUP BY au.name
ORDER BY order_count DESC;
CTEs make complex queries readable by defining named subqueries.
Window Functions SQL
SELECT
name,
department,
salary,
ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS rn,
RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS rnk,
DENSE_RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS dense_rnk,
LAG(salary) OVER (PARTITION BY department ORDER BY salary DESC) AS prev_salary,
SUM(salary) OVER (PARTITION BY department) AS dept_total
FROM employees;
ROW_NUMBER, RANK, DENSE_RANK, LAG, LEAD, and running aggregates.
UPSERT (INSERT ON CONFLICT) SQL
-- PostgreSQL
INSERT INTO users (email, name, updated_at)
VALUES ('[email protected]', 'Alice', NOW())
ON CONFLICT (email)
DO UPDATE SET
name = EXCLUDED.name,
updated_at = EXCLUDED.updated_at;
-- MySQL
INSERT INTO users (email, name) VALUES ('[email protected]', 'Alice')
ON DUPLICATE KEY UPDATE name = VALUES(name);
Insert or update if a unique constraint is violated.
Recursive CTE SQL
WITH RECURSIVE org_tree AS (
-- Base case: top-level managers
SELECT id, name, manager_id, 1 AS level
FROM employees WHERE manager_id IS NULL
UNION ALL
-- Recursive case
SELECT e.id, e.name, e.manager_id, t.level + 1
FROM employees e
JOIN org_tree t ON e.manager_id = t.id
)
SELECT * FROM org_tree ORDER BY level, name;
Traverse hierarchical data (org charts, categories, file trees).
Conditional Aggregation (Pivot) SQL
SELECT
product,
SUM(CASE WHEN month = 'Jan' THEN revenue ELSE 0 END) AS jan,
SUM(CASE WHEN month = 'Feb' THEN revenue ELSE 0 END) AS feb,
SUM(CASE WHEN month = 'Mar' THEN revenue ELSE 0 END) AS mar,
SUM(revenue) AS total
FROM sales
GROUP BY product;
Pivot rows to columns using CASE inside aggregate functions.
JSON Operations (PostgreSQL) SQL
-- Extract value
SELECT data->>'name' AS name FROM users;
-- Query inside JSON
SELECT * FROM users WHERE data->'address'->>'city' = 'NYC';
-- Build JSON from rows
SELECT json_agg(json_build_object('id', id, 'name', name)) FROM users;