Enjoy these free Code Nuggets?

Your support helps us create more high-quality content and unlocks exclusive premium nuggets via a personal activation link.

Support Our Work & Get Exclusive Access
🤖 New — AI Training

Learn to code with AI, not just about it.

Beyond free snippets, we run hands-on training in AI-assisted coding — teaching developers, teams and beginners how to build real software faster using modern AI tools. You bring the ideas; we show you how to ship them with an AI pair-programmer at your side.

  • ✔ Prompting & pairing with AI coding assistants to write, debug and refactor real code
  • ✔ Turning plain-English ideas into working apps, scripts and automations
  • ✔ Reviewing AI output safely — spotting bugs, security gaps and hallucinations
  • ✔ Live cohorts, team workshops and 1-on-1 mentoring — remote or on-site in Kenya
ai-pair-session.md

# You describe it…

"Build me a booking form that emails the client."

# …the AI drafts it…

▸ generating form + mailer…

â–¸ 24 lines written, 0 errors

# …and we teach you to lead it.

✱ You stay the engineer. AI is the tool.

All Code Nuggets

45 nuggets found

Encapsulating Queries in a Custom Django Manager (Premium)

Django python

Sprinkling filter(is_published=True) across your codebase invites bugs. A custom manager gives your model expressive, reusable query methods like Article.objects.published().

from django.db import models
from django.utils import timezone

class ArticleQuerySet(models.QuerySet):
    def published(self):
        return self.filter(is_published=True, published_at__lte=timezone.now())

    def by_author(self, user):
        return self.filter(author=user)

class Article(mode...

Reacting to Model Events with Django Signals (Premium)

Django python

Need a profile created automatically whenever a user signs up? Signals let you run code in response to model events without cluttering your save logic.

from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth import get_user_model
from .models import Profile

User = get_user_model()

@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
    if created:...

Cleaner Data Objects with Python Dataclasses: Strict Typing & Immutability

Python python

Replacing Plain Dictionaries with Type-Safe Python Dataclasses Relying on loose dictionaries across Python applications causes runtime KeyError exceptions. Python's built-in dataclasses module provides an elegant, memory-efficient domain model structure. frozen=True:...

from dataclasses import dataclass, field
from datetime import datetime
from decimal import Decimal
from typing import Optional

@dataclass(frozen=True, slots=True, kw_only=True)
class MpesaTransactionRecord:
    transaction_id: str
    phone_number: str
    amount: Decimal
    account_reference: str...

Concurrent HTTP Requests with AsyncIO and HTTPX in Python

Python python

Speeding Up Batch API Integrations with Asynchronous Concurrency When fetching data from 500 external endpoints sequentially, execution takes hundreds of seconds. Using asyncio and httpx, requests run concurrently in parallel...

import asyncio
import httpx
from typing import List, Dict, Any

async def fetch_status(client: httpx.AsyncClient, semaphore: asyncio.Semaphore, url: str) -> Dict[str, Any]:
    async with semaphore:
        try:
            resp = await client.get(url, timeout=10.0)
            return {'url': url, '...

Streaming Large Files with Python Generators (Premium)

Python python

Loading a multi-gigabyte file into memory will crash your process. A generator yields one chunk (or line) at a time, so memory stays flat no matter how big the file...

def read_in_chunks(path, size=1024 * 1024):
    """Yield a file one megabyte at a time."""
    with open(path, "rb") as f:
        while chunk := f.read(size):
            yield chunk

def count_lines(path):
    total = 0
    for chunk in read_in_chunks(path):
        total += chunk.count(b"\n")...

A Minimal Image Classifier with Keras (Premium)

You do not need a research lab to train a working classifier. This compact Keras model learns to tell classes apart from a folder of labelled images and reports its...

import tensorflow as tf
from tensorflow.keras import layers, models

model = models.Sequential([
    layers.Rescaling(1./255, input_shape=(128, 128, 3)),
    layers.Conv2D(32, 3, activation="relu"),
    layers.MaxPooling2D(),
    layers.Conv2D(64, 3, activation="relu"),
    layers.MaxPooling2D(),...

Building an Image Preprocessing Pipeline with tf.data (Premium)

Clean, well-batched input is half the battle in machine learning. tf.data loads images from disk, resizes and augments them, then prefetches batches so your GPU never sits idle.

import tensorflow as tf

AUTOTUNE = tf.data.AUTOTUNE

train_ds = tf.keras.utils.image_dataset_from_directory(
    "data/train", image_size=(128, 128), batch_size=32, label_mode="int")

augment = tf.keras.Sequential([
    tf.keras.layers.RandomFlip("horizontal"),
    tf.keras.layers.RandomRotation(0....

Serving a Trained Model Behind a REST Endpoint (Premium)

A model is only useful once other apps can call it. FastAPI wraps your saved model in a tiny JSON API: load once at startup, then return predictions on every...

from fastapi import FastAPI, UploadFile
import tensorflow as tf
import numpy as np
from PIL import Image
import io

app = FastAPI()
model = tf.keras.models.load_model("model.keras")   # loaded once
CLASSES = ["normal", "review", "urgent"]

@app.post("/predict")
async def predict(file: UploadFile):...

Fetching Server State with TanStack Query (React Query) v5

Mastering Server State Synchronization, Caching, and Optimistic Updates Managing server state manually with useEffect causes race conditions and stale UI data. TanStack Query (v5) provides battle-tested declarative caching and query...

import React from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import axios from 'axios';

export const QuotesTable = () => {
  const queryClient = useQueryClient();
  const { data: quotes, isLoading } = useQuery({
    queryKey: ['quotes'],
    queryFn: asy...