Reference Documentation

Quick cheat sheets for Python, JavaScript, SQL, HTML, CSS, NumPy, Pandas, Git and more. Click any code block to copy.

Python

Built-ins & Methods
str.methods()
Common string methods
Try
s = "hello world"
s.upper()          # 'HELLO WORLD'
s.lower()          # 'hello world'
s.title()          # 'Hello World'
s.split(" ")       # ['hello', 'world']
s.strip()          # removes whitespace
s.replace("o","0") # 'hell0 w0rld'
s.startswith("he") # True
s.find("world")    # 6
s.count("l")       # 3
f"Hello {name}"    # f-string format
",".join(["a","b"])# 'a,b'
list.methods()
Common list operations
Try
lst = [1, 2, 3]
lst.append(4)      # [1,2,3,4]
lst.insert(0, 0)   # [0,1,2,3,4]
lst.remove(2)      # [0,1,3,4]
lst.pop()          # 4 (last item)
lst.sort()         # sort in-place
sorted(lst)        # returns new list
lst.reverse()      # reverse in-place
lst.index(1)       # 0 (first index)
len(lst)           # length
[x**2 for x in lst]  # list comp
dict.methods()
Dictionary operations
d = {"name": "Alice", "age": 30}
d["name"]          # 'Alice'
d.get("x", 0)      # 0 (default)
d.keys()           # dict_keys(['name','age'])
d.values()         # dict_values(['Alice', 30])
d.items()          # key-value pairs
d.update({"city":"NY"})
d.pop("age")       # removes key
"name" in d        # True
{k:v for k,v in d.items()} # dict comp
File I/O
Reading and writing files
# Read entire file
with open("file.txt", "r") as f:
    content = f.read()
    lines   = f.readlines()

# Write file
with open("out.txt", "w") as f:
    f.write("Hello World\n")

# Append
with open("log.txt", "a") as f:
    f.write("new line\n")

# JSON
import json
data = json.loads(text)
json.dumps(data, indent=2)
Functions & Lambda
Defining and using functions
def greet(name, greeting="Hello"):
    return f"{greeting}, {name}!"

# *args and **kwargs
def func(*args, **kwargs):
    print(args, kwargs)

# Lambda
square = lambda x: x ** 2
double = lambda x: x * 2

# Higher-order
nums = [1,2,3,4,5]
evens  = list(filter(lambda x: x%2==0, nums))
squares= list(map(lambda x: x**2, nums))
Exception Handling
try / except / finally
try:
    result = 10 / 0
except ZeroDivisionError as e:
    print(f"Error: {e}")
except (TypeError, ValueError):
    print("Type or Value error")
except Exception as e:
    print(f"Unexpected: {e}")
else:
    print("No exception!")
finally:
    print("Always runs")

# Raise custom exception
raise ValueError("Invalid input")

JavaScript

ES2024
Array Methods
map, filter, reduce and more
const arr = [1, 2, 3, 4, 5];

arr.map(x => x * 2)        // [2,4,6,8,10]
arr.filter(x => x > 2)     // [3,4,5]
arr.reduce((a,b) => a+b,0) // 15
arr.find(x => x > 3)       // 4
arr.findIndex(x => x > 3)  // 3
arr.some(x => x > 4)       // true
arr.every(x => x > 0)      // true
arr.flat()                 // flattens nested
arr.flatMap(x => [x, x*2]) // interleaved
arr.includes(3)            // true
arr.slice(1, 3)            // [2,3]
arr.splice(1, 2, 99)       // mutates
Async / Fetch
Promises, async/await, fetch API
// async / await
async function getData(url) {
  try {
    const res  = await fetch(url);
    if (!res.ok) throw new Error(res.status);
    const data = await res.json();
    return data;
  } catch (err) {
    console.error(err);
  }
}

// POST request
await fetch('/api/data', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ key: 'value' }),
});

// Promise.all
const [a, b] = await Promise.all([f1(), f2()]);
DOM Manipulation
Select, modify, events
// Select elements
document.getElementById('id')
document.querySelector('.cls')
document.querySelectorAll('p')

// Modify
el.textContent = 'Hello'
el.innerHTML   = 'Bold'
el.classList.add('active')
el.classList.toggle('dark')
el.style.color = 'red'
el.setAttribute('href', '/path')

// Events
el.addEventListener('click', e => {
  console.log(e.target)
})

// Create & append
const div = document.createElement('div')
document.body.appendChild(div)
ES6+ Syntax
Destructuring, spread, optional chaining
// Destructuring
const { name, age = 0 } = user;
const [first, ...rest] = array;

// Spread
const merged = { ...obj1, ...obj2 };
const copy   = [...arr1, ...arr2];

// Optional chaining & nullish coalescing
user?.profile?.avatar ?? 'default.png'

// Template literals
`Hello ${name}, you are ${age} years old`

// Short-circuit
const val = config && config.value;
const x   = input || 'default';

// Object shorthand
const name = 'Alice';
const obj  = { name, age: 30 };  // {name:'Alice', age:30}

SQL

SQLite / MySQL / PostgreSQL
SELECT Queries
Basic to advanced SELECT
Try
-- Basic select
SELECT name, age FROM users;
SELECT * FROM products WHERE price > 50;

-- Filtering & sorting
SELECT * FROM orders
WHERE status = 'shipped'
  AND created_at > '2024-01-01'
ORDER BY total DESC
LIMIT 10 OFFSET 20;

-- Distinct & count
SELECT COUNT(*), category FROM products
GROUP BY category
HAVING COUNT(*) > 5;
JOINs
INNER, LEFT, RIGHT, FULL JOIN
-- INNER JOIN (matching rows only)
SELECT u.name, o.total
FROM users u
INNER JOIN orders o ON u.id = o.user_id;

-- LEFT JOIN (all left + matching right)
SELECT u.name, COUNT(o.id) AS order_count
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
GROUP BY u.id, u.name;

-- Self join
SELECT a.name, b.name AS manager
FROM employees a
JOIN employees b ON a.manager_id = b.id;
INSERT / UPDATE / DELETE
Data modification statements
-- Insert
INSERT INTO users (name, email, age)
VALUES ('Alice', 'a@x.com', 30);

-- Insert multiple
INSERT INTO tags (name) VALUES ('ai'),('python'),('data');

-- Update
UPDATE users SET age = 31
WHERE email = 'a@x.com';

-- Delete (always use WHERE!)
DELETE FROM sessions WHERE expires_at < NOW();

-- Create table
CREATE TABLE posts (
  id      INTEGER PRIMARY KEY AUTOINCREMENT,
  title   TEXT NOT NULL,
  content TEXT,
  created DATETIME DEFAULT CURRENT_TIMESTAMP
);

HTML

HTML5 Semantic
Semantic Structure
HTML5 semantic elements
<header>   <!-- site header, logo, nav -->
<nav>      <!-- navigation links -->
<main>     <!-- primary content -->
<article>  <!-- self-contained content -->
<section>  <!-- grouped content -->
<aside>    <!-- sidebar -->
<footer>   <!-- page footer -->
<figure> + <figcaption>  <!-- images -->
<time datetime="2024-01-01">Jan 1</time>
<details> + <summary>    <!-- accordion -->
<dialog>   <!-- modal dialog -->
<template> <!-- hidden template -->
Forms & Inputs
All input types and attributes
<form method="post" action="/submit">
  <input type="text"     required placeholder="Name" />
  <input type="email"    required />
  <input type="password" minlength="8" />
  <input type="number"   min="0" max="100" />
  <input type="date" />
  <input type="file"     accept=".pdf,.jpg" />
  <input type="checkbox" checked />
  <input type="radio"    name="group" />
  <textarea rows="4"></textarea>
  <select>
    <option value="a">Option A</option>
  </select>
  <button type="submit">Submit</button>
</form>
Head / Meta / SEO
Essential head tags
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="description" content="Page description" />
<meta name="robots" content="index, follow" />
<!-- Open Graph -->
<meta property="og:title" content="Title" />
<meta property="og:description" content="..." />
<meta property="og:image" content="/img.jpg" />
<meta property="og:url" content="https://..." />
<!-- Twitter Card -->
<meta name="twitter:card" content="summary_large_image" />
<link rel="canonical" href="https://..." />
<link rel="icon" href="/favicon.ico" />

CSS

CSS3 / Variables / Grid
Flexbox
One-dimensional layout
.container {
  display: flex;
  flex-direction: row;      /* row | column */
  justify-content: center;  /* flex-start | end | space-between | around */
  align-items: center;      /* flex-start | end | stretch | baseline */
  gap: 16px;
  flex-wrap: wrap;
}
.item {
  flex: 1;                  /* grow + shrink + basis */
  flex: 0 0 200px;          /* fixed width */
  order: 2;
  align-self: flex-end;
}
CSS Grid
Two-dimensional layout
.grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  /* or: 200px auto 1fr */
  grid-template-rows: auto;
  gap: 20px;
  /* Named areas */
  grid-template-areas:
    "header header header"
    "sidebar main main"
    "footer footer footer";
}
.header  { grid-area: header; }
.sidebar { grid-area: sidebar; }

/* Auto-fill responsive */
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
CSS Variables & Animations
Custom properties and keyframes
:root {
  --primary: #4f46e5;
  --spacing: 16px;
  --radius: 8px;
}

.element {
  color: var(--primary);
  padding: var(--spacing);
  border-radius: var(--radius);
  transition: all 0.3s ease;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(20px); }
  to   { opacity: 1; transform: translateY(0); }
}

.animated { animation: fadeIn 0.6s ease forwards; }

NumPy

Scientific Computing
Array Creation
Creating NumPy arrays
Try
import numpy as np

np.array([1, 2, 3])           # from list
np.zeros((3, 4))              # 3x4 zeros
np.ones((2, 3))               # 2x3 ones
np.eye(3)                     # 3x3 identity
np.arange(0, 10, 2)           # [0,2,4,6,8]
np.linspace(0, 1, 5)          # 5 evenly spaced
np.random.rand(3, 3)          # uniform [0,1)
np.random.randn(100)          # standard normal
np.random.randint(0, 10, 5)   # 5 random ints
Array Operations
Math and statistics
a = np.array([1, 2, 3, 4, 5])

a.sum()           # 15
a.mean()          # 3.0
a.std()           # 1.41...
a.min(), a.max()  # 1, 5
a.argmin()        # 0 (index of min)
np.sort(a)        # sorted copy
np.cumsum(a)      # [1,3,6,10,15]

# Broadcasting
a * 2             # element-wise
a + np.array([10,20,30,40,50])

# Reshape
a.reshape(5, 1)   # column vector
np.vstack([a, a]) # stack vertically

Pandas

Data Analysis
DataFrame Basics
Create, read and explore data
Try
import pandas as pd

# Create
df = pd.DataFrame({'A':[1,2,3], 'B':[4,5,6]})
df = pd.read_csv('data.csv')
df = pd.read_excel('data.xlsx')

# Explore
df.head(5)         # first 5 rows
df.tail(3)         # last 3 rows
df.shape           # (rows, cols)
df.info()          # dtypes & nulls
df.describe()      # stats summary
df.columns         # column names
df.dtypes          # data types
df.isnull().sum()  # count nulls per col
Filter, Group & Aggregate
Select and summarize data
# Select
df['col']                 # Series
df[['col1','col2']]       # DataFrame
df.loc[0:5, 'A':'C']      # by label
df.iloc[0:5, 0:3]         # by position

# Filter
df[df['age'] > 30]
df[(df['age'] > 30) & (df['city']=='NY')]
df[df['name'].str.contains('Alice')]

# GroupBy
df.groupby('category')['sales'].sum()
df.groupby('city').agg({'salary':'mean','age':'max'})

# Sort
df.sort_values('score', ascending=False)

# Apply
df['grade'] = df['score'].apply(lambda x: 'A' if x>=90 else 'B')

Regular Expressions

Python re / JS RegExp
Python re Module
Pattern matching and groups
import re

# Patterns
# .   any char   \d digit    \w word char
# \s  whitespace \b word boundary
# *   0+         +  1+       ?  0 or 1
# ^   start      $  end      [] char class
# {3} exactly 3  {2,5} 2-5   | OR

# Methods
re.match(r'\d+', text)      # start of string
re.search(r'\d+', text)     # anywhere
re.findall(r'\d+', text)    # all matches
re.sub(r'\s+', ' ', text)   # replace

# Groups
m = re.search(r'(\d{4})-(\d{2})-(\d{2})', '2024-01-15')
m.group(1)  # '2024' (year)

# Email validation
re.match(r'^[\w.-]+@[\w.-]+\.\w{2,}$', email)

Git

Version Control
Everyday Git
Most-used commands
git init                    # initialize repo
git clone https://...       # clone remote

git status                  # what changed?
git add .                   # stage all
git add src/                # stage folder
git commit -m "message"     # commit
git push origin main        # push to remote
git pull origin main        # pull latest

git checkout -b feature/x   # create branch
git switch main             # switch branch
git merge feature/x         # merge branch
git branch -d feature/x     # delete branch

git log --oneline           # compact history
git diff HEAD~1             # compare with last commit
git stash                   # save temp changes
git stash pop               # restore stash
Undo & Reset
Fixing mistakes
# Undo staged changes
git restore --staged file.txt

# Undo working directory changes
git restore file.txt

# Undo last commit (keep changes)
git reset --soft HEAD~1

# Undo last commit (discard changes) ⚠️
git reset --hard HEAD~1

# Create a revert commit (safe for shared)
git revert HEAD

# Fix last commit message
git commit --amend -m "new message"

# Find lost commits
git reflog

Linux CLI

Bash / Shell
File System
Navigate and manage files
pwd                 # print working directory
ls -la              # list all with details
cd /path/to/dir     # change directory
mkdir -p a/b/c      # create nested dirs
cp file.txt backup/ # copy file
mv old.txt new.txt  # move / rename
rm file.txt         # delete file ⚠️
rm -rf dir/         # delete folder ⚠️
find . -name "*.py" # find files
cat file.txt        # print file
head -n 20 file.txt # first 20 lines
tail -f log.txt     # follow log
grep -r "todo" .    # search in files
wc -l file.txt      # count lines
chmod +x script.sh  # make executable
Processes & Pipes
Process management and redirection
ps aux              # list processes
kill -9 PID         # force kill
top / htop          # interactive monitor
nohup cmd &         # run in background

# Pipes and redirection
cat file.txt | grep "error" | wc -l
command > output.txt    # overwrite
command >> output.txt   # append
command 2>&1            # redirect stderr

# Curl
curl https://api.example.com/data
curl -X POST -H "Content-Type: application/json" \
  -d '{"key":"value"}' https://api.example.com

# Grep power
grep -i "pattern" file.txt   # case insensitive
grep -v "exclude" file.txt   # invert match