html
star
A native modal with focus handling, Escape to close and a backdrop.
<button id="open">Delete project</button>
<dialog id="confirm" aria-labelledby="confirm-title">
<form method="dialog">
<h2 id="confirm-title">Delete this project?</h2>
beginner
#accessibility#dialog#ui
flask
star
Create the app in a function so tests and production can each build their own.
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
beginner
#structure#config#blueprints
javascript
star
Run a function only after the user stops typing or resizing.
function debounce(fn, wait = 300) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), wait);
beginner
#performance#events#functions
javascript
star
Abort a fetch that takes too long and handle HTTP errors.
async function getJSON(url, { timeout = 8000, ...options } = {}) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeout);
try {
const res = await fetch(url, { ...options, signal: controller.signal });
intermediate
#fetch#network#async
python
star
Load a JSON file and get a readable message when it is missing or malformed.
import json
from pathlib import Path
def load_json(path: str | Path) -> dict:
beginner
#json#files#errors
css
star
Cards wrap to as many columns as fit, with a sensible minimum width.
.grid {
display: grid;
gap: 20px;
grid-template-columns: repeat(auto-fill, minmax(min(100%, 260px), 1fr));
}
beginner
#grid#layout#responsive
python
star
A decorator that retries a function on chosen exceptions, waiting longer after each failure.
import functools
import random
import time
intermediate
#retry#decorators#network
flask
star
Check the extension, size and filename before saving an upload.
import os
import uuid
from flask import request, abort
from werkzeug.utils import secure_filename
intermediate
#uploads#security#files
bash
star
Stop on errors, unset variables and failed pipes, and clean up on exit.
#!/usr/bin/env bash
set -Eeuo pipefail
tmp="$(mktemp -d)"
cleanup() { rm -rf "$tmp"; }
beginner
#scripting#errors
sql
star
Insert a row, or update it when the unique key already exists.
INSERT INTO page_views (path, day, views)
VALUES ('/pricing', CURRENT_DATE, 1)
ON CONFLICT (path, day)
DO UPDATE SET views = page_views.views + EXCLUDED.views;
intermediate
#postgres#upsert#writes
bash
Dump, compress, and keep only the last 14 backups.
#!/usr/bin/env bash
set -Eeuo pipefail
: "${DATABASE_URL:?set DATABASE_URL}"
dir="/var/backups/app"
intermediate
#postgres#backups#cron
python
Memoize a pure function with functools.lru_cache.
from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n: int) -> int:
beginner
#performance#functools#recursion
html
Labels, input types and constraints that browsers validate for free.
<form action="/contact" method="post" novalidate>
<label for="email">Email</label>
<input id="email" name="email" type="email" required autocomplete="email">
<label for="msg">Message</label>
beginner
#forms#validation#accessibility
javascript
Use the async clipboard API with a fallback for older browsers.
async function copyText(text) {
if (navigator.clipboard && window.isSecureContext) {
await navigator.clipboard.writeText(text);
return true;
}
beginner
#clipboard#dom#ux
css
Define colours once, switch them with a data attribute.
:root {
--bg: #07080b; --surface: #101318; --text: #eceef3; --muted: #a7aebc; --accent: #2f6bff;
color-scheme: dark;
}
:root[data-theme="light"] {
intermediate
#theming#dark-mode#variables
javascript
structuredClone copies nested objects, Dates, Maps and Sets correctly.
const original = { user: { name: "Ada" }, created: new Date(), tags: new Set(["js"]) };
const copy = structuredClone(original);
copy.user.name = "Grace";
console.log(original.user.name); // Ada (unchanged)
beginner
#objects#data
javascript
One listener on a parent handles clicks for current and future children.
document.body.innerHTML = `
<ul id="todo">
<li>Write tests <button data-action="done">Done</button></li>
<li>Deploy <button data-action="done">Done</button></li>
</ul>`;
intermediate
#dom#events#performance
sql
List values that appear more than once, with their count.
SELECT lower(email) AS email, COUNT(*) AS copies
FROM users
GROUP BY lower(email)
HAVING COUNT(*) > 1
ORDER BY copies DESC;
beginner
#data-quality#group-by