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.

Python nuggets

7 nuggets found

Clear filter

Network SIEM: Wazuh Syslog Collector & Automated IP Containment (Premium)

Python python

Real-time threat monitoring pipeline ingesting Syslog streams, identifying SSH/Nginx brute-force attacks, and executing automated IPTables / UFW firewall IP drops.

# Network SIEM Automated Containment Handler
import sys
import json
import subprocess

def handle_wazuh_alert(alert_data):
    rule_id = alert_data.get("rule", {}).get("id")
    src_ip = alert_data.get("data", {}).get("srcip")
    
    # Rule 5712: SSH Brute force attack detected
    if rule_id in [...

Polling the Meta Graph API with Auto-Pagination in Python

Python python

The Meta Graph API returns results one page at a time. Every response that has more data includes a paging.next cursor URL. The pattern below wraps that into a single...

import requests
import time
from collections import Counter

BASE = "https://graph.facebook.com/v20.0"


# ── helpers ──────────────────────────────────────────────────────────────
def g(url: str, token: str, params: dict = None) -> dict:
    """GET a Graph API endpoint, automatically injecting the...

Generating Styled Excel & PowerPoint Reports Automatically with Python

Python python

After collecting data from APIs or scraping, the next step is usually turning it into a document a non-technical stakeholder can open and read. openpyxl writes styled Excel workbooks; python-pptx...

# pip install openpyxl python-pptx

import openpyxl
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
from openpyxl.utils import get_column_letter

from pptx import Presentation
from pptx.util import Inches, Pt
from pptx.dml.color import RGBColor


# ── shared theme ────────────...

Automating FTP Deployments in Python with Smart Change Detection & Retry

Python python

Manually uploading files over FTP after every code change is error-prone and slow. A Python script using the built-in ftplib module can automate this completely β€” uploading only changed files,...

"""
ftp_deploy.py β€” upload only changed files, retry on drop, clear caches.

Usage:
    python ftp_deploy.py
"""
import ftplib
import io
import os
import socket
import time
import urllib.request
import urllib.error

# ── config ────────────────────────────────────────────────────────────────
FTP_HOS...

Cleaner Data Objects with Python dataclasses (Premium)

Python python

Writing __init__, __repr__ and __eq__ by hand is tedious. A @dataclass generates them for you, with type hints, defaults and immutability baked in.

from dataclasses import dataclass, field

@dataclass(frozen=True, slots=True)
class Money:
    amount: int          # store minor units (cents) to avoid float errors
    currency: str = "KES"

    def __post_init__(self):
        if self.amount < 0:
            raise ValueError("amount cannot be neg...

Concurrent HTTP Requests with asyncio and httpx (Premium)

Python python

Fetching 50 URLs one after another is painfully slow. With asyncio and httpx you can fire them concurrently and gather the results, turning minutes into seconds.

import asyncio
import httpx

async def fetch(client, url):
    r = await client.get(url, timeout=10)
    r.raise_for_status()
    return url, len(r.content)

async def main(urls):
    async with httpx.AsyncClient() as client:
        tasks = [fetch(client, u) for u in urls]
        return await asyn...

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")...