惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Blog — PlanetScale
Blog — PlanetScale
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
The Last Watchdog
The Last Watchdog
AI
AI
Recent Announcements
Recent Announcements
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Stack Overflow Blog
Stack Overflow Blog
V
Visual Studio Blog
J
Java Code Geeks
TaoSecurity Blog
TaoSecurity Blog
L
LangChain Blog
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Project Zero
Project Zero
Microsoft Security Blog
Microsoft Security Blog
量子位
T
Threatpost
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
博客园 - Franky
博客园 - 聂微东
L
LINUX DO - 最新话题
Security Archives - TechRepublic
Security Archives - TechRepublic
Hugging Face - Blog
Hugging Face - Blog
T
The Blog of Author Tim Ferriss
P
Proofpoint News Feed
The GitHub Blog
The GitHub Blog
C
Check Point Blog
宝玉的分享
宝玉的分享
G
Google Developers Blog
Spread Privacy
Spread Privacy
Cloudbric
Cloudbric
SecWiki News
SecWiki News
有赞技术团队
有赞技术团队
www.infosecurity-magazine.com
www.infosecurity-magazine.com
W
WeLiveSecurity
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
美团技术团队
V
Vulnerabilities – Threatpost
Cyberwarzone
Cyberwarzone
A
Arctic Wolf
P
Privacy & Cybersecurity Law Blog
P
Palo Alto Networks Blog
H
Help Net Security
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Cisco Talos Blog
Cisco Talos Blog
Hacker News - Newest:
Hacker News - Newest: "LLM"
A
About on SuperTechFans
N
Netflix TechBlog - Medium
罗磊的独立博客
月光博客
月光博客

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Animating Japan's Population Pyramid From 1950 to 2070 — Why You Need Cohort-Specific Mortality to Get the 1950 Triangle Right
SEN LLC · 2026-05-08 · via DEV Community

"Have you ever seen Japan's ageing?" — I knew the data, but I'd never watched the shape of the country's population pyramid actually deform in front of me. So I built a 250-line page that does it: year slider plus auto-play, 1950 to 2070, with the first baby-boom cohort visibly rising from the bottom of the chart all the way to the top.

jp-population-pyramid in 2020 mode: a diverging bar chart with 21 horizontal age bars. Males (blue) extend left, females (pink) right. Two clear bulges visible: one at age 70-74 (the first baby-boom cohort, born 1947-49) and one at 45-49 (the echo boom, born 1971-75). The footer reads

🌐 Demo: https://sen.ltd/portfolio/jp-population-pyramid/
📦 GitHub: https://github.com/sen-ltd/jp-population-pyramid

Hit the ▶ button and watch the chart morph at 120 ms per year. The first baby-boomers (born 1947-49) start as the broad base of a true triangle in 1950, become a fat bulge that walks up the chart through the decades, hit the very top of the projection in the 2030s, and disappear off the top by 2050. The two-bulge shape of 2020 turns into the inverted lopsided shape of 2070. Median age goes from 20 to 56, share aged 65+ from 7% to 38%.

Why this is harder than it looks

Drawing a single population pyramid in Plotly or D3 is a 30-line job. The interesting questions are upstream:

  1. Where do the numbers come from, and how do you cover both 70 years of historical data and 50 years of projection in one consistent dataset?
  2. How do you keep the shape evolving smoothly as a user drags the slider, when the source data is naturally 5- or 10-year snapshots?

Both of those have non-obvious answers, and one of them I got wrong on the first pass.

The data: emit it from a function, then nail the totals

The dataset that ships in data.json is generated by generate-data.py — a small Python script that exposes the demographic model as four functions:

  • annual_births(year) — single-year births in thousands, 1850 → 2070. Two Gaussian bumps for the first and second baby booms, plus a piecewise-linear trend that drops through the late 20th century.
  • survival(age, sex, birth_year) — share of a cohort still alive at the given exact age. More on this below.
  • cohort_size(birth_year, age, sex) — multiply the two together with a sex-split factor at birth.
  • bin_population(year, bin_idx, sex) — sum five single-age cohorts to make a 5-year bin.

Once those are in place, building a snapshot for any calendar year is just calling bin_population 21 times for each sex.

The last thing the script does is calibrate:

def snapshot(year):
    raw_male   = [bin_population(year, i, "M") for i in range(N_BINS)]
    raw_female = [bin_population(year, i, "F") for i in range(N_BINS)]
    raw_total  = sum(raw_male) + sum(raw_female)
    target     = TARGET_TOTALS[year]   # IPSS / UN WPP value
    scale      = target / raw_total
    male   = [round(m * scale) for m in raw_male]
    female = [round(f * scale) for f in raw_female]
    return {"year": year, "male": male, "female": female}

Enter fullscreen mode Exit fullscreen mode

Even with carefully tuned birth and survival functions, the unscaled total comes out 92-105% of the actual figure. Rather than fight the model into perfect alignment, I let it generate the shape and then scale each year's totals to the published numbers (1950 = 83.2 M, 2020 = 126.3 M, 2070 = 87.0 M, etc.). The shape lives in the model, the size is anchored to reality.

Where I got it wrong: 1950 wasn't a pyramid

The first version of survival() took only two arguments — age and sex — and used a stylized contemporary Japanese life table:

def survival(age, sex):
    if sex == "F":
        return math.exp(-((age / 90) ** 7))
    return math.exp(-((age / 85) ** 7))

Enter fullscreen mode Exit fullscreen mode

Plug this into the 1950 generator. Anyone in the chart who's age 75 in 1950 was born in 1875, and the function predicts that 42% of their cohort is still alive: exp(-(75/85)^7) ≈ 0.42. That's roughly correct for someone born in 1945, but for someone born in 1875 it's wildly optimistic. Tuberculosis, infant mortality, two wars — real cohort-survival to age 75 for 1875-born Japanese was something like 5-10%.

The result is a 1950 pyramid that looks like a slightly-tapered trapezoid, with a median age of 36.9 and an aging ratio of 18.6%. Both numbers are way off from reality (median age in 1950 Japan was about 22; aging ratio about 5%). The shape isn't a pyramid at all.

The fix is to make survival take birth_year as a parameter, and attenuate the modern curve for older cohorts:

def cohort_factor(birth_year):
    if birth_year >= 1945: return 1.0
    if birth_year >= 1925: return 0.55 + 0.45 * (birth_year - 1925) / 20
    if birth_year >= 1890: return 0.25 + 0.30 * (birth_year - 1890) / 35
    return 0.20

def survival(age, sex, birth_year):
    base = math.exp(-((age / 90 if sex == "F" else 85) ** 7))
    return base * cohort_factor(birth_year)

Enter fullscreen mode Exit fullscreen mode

Now the 1875-born cohort's survival to 75 drops to 0.42 × 0.20 = 8.4%, which is in the right neighbourhood. Median age in 1950 is 20.4, aging ratio 7.2%. The pyramid actually looks like a pyramid.

The lesson here is one any demographer would tell you immediately: mortality is cohort-specific, not just age-specific. If your survival function takes only (age, sex), you're applying today's life table to 19th-century births. The correction is one extra parameter and a piecewise-linear adjustment factor.

Linear interpolation between snapshots

The dataset only carries 13 snapshots — 1950, 1960, ..., 2070. When the user drags the slider to 2005, we blend the 2000 and 2010 snapshots 50/50:

export function interpolateSnapshots(a, b, year) {
  const t = (year - a.year) / (b.year - a.year);
  return {
    year,
    male:   interpolateArrays(a.male,   b.male,   t),
    female: interpolateArrays(a.female, b.female, t),
  };
}

export function getSnapshot(snapshots, year) {
  if (year <= snapshots[0].year)        return clone(snapshots[0]);
  if (year >= snapshots.at(-1).year)    return clone(snapshots.at(-1));
  for (let i = 0; i < snapshots.length - 1; i++) {
    const a = snapshots[i], b = snapshots[i + 1];
    if (year >= a.year && year <= b.year) return interpolateSnapshots(a, b, year);
  }
}

Enter fullscreen mode Exit fullscreen mode

Linear blending of bin counts is not what real demographic dynamics do — cohorts move discretely between bins as they age, with deaths and births perturbing the totals. But for a dragable visualization at one-year resolution, the lie is small enough not to matter; nothing on screen jumps. If you wanted to show actual cohort flow you'd need a continuous-time integrator, which is a different tool with a different scope.

SVG diverging bars with one global scale

The chart is a vertical stack of 21 horizontal bars, with a centre column for the age labels. Males extend leftward from the centre, females rightward.

function renderBars(snapshot, globalMax) {
  const halfPlotW = (VIEW_W - PAD_LEFT - PAD_RIGHT - CENTER_GAP) / 2;
  const cx = VIEW_W / 2;
  for (let i = 0; i < snapshot.male.length; i++) {
    const m = snapshot.male[i], f = snapshot.female[i];
    const mw = (m / globalMax) * halfPlotW;
    const fw = (f / globalMax) * halfPlotW;
    barCache.male[i].setAttribute("x", cx - CENTER_GAP / 2 - mw);
    barCache.male[i].setAttribute("width", mw);
    barCache.female[i].setAttribute("width", fw);
  }
}

Enter fullscreen mode Exit fullscreen mode

Two design choices worth calling out:

  1. globalMax is the largest single bin across all snapshots, not per-frame. If you re-normalise per-frame, the boomer bulge appears stationary in the chart while everything around it grows and shrinks; the eye-catching effect — the bulge visibly rising up the pyramid as cohorts age — disappears. With a fixed scale you keep the right answer.
  2. CSS transitions on <rect> width and x. The setAttribute calls are direct, no animation library, but .bar-male { transition: x 0.15s, width 0.15s; } makes every per-year update interpolate smoothly. Drag the slider and the bars glide. Hit play and you get a film.

The <rect> elements are pooled at first render and reused on every year update. No DOM churn, no React.

Computing stats live

Median age, aging ratio, and working-age ratio are recomputed in JS on every render. With 21 bins and 13 snapshots there's nothing to optimise — just walk the cumulative sum.

export function medianAge(snapshot, binWidth = 5) {
  const total = totalPopulation(snapshot);
  const half = total / 2;
  let cumulative = 0;
  for (let i = 0; i < snapshot.male.length; i++) {
    const binSize = snapshot.male[i] + snapshot.female[i];
    const next = cumulative + binSize;
    if (next >= half) {
      const fraction = binSize === 0 ? 0 : (half - cumulative) / binSize;
      return i * binWidth + fraction * binWidth;
    }
    cumulative = next;
  }
  return (snapshot.male.length - 1) * binWidth;
}

Enter fullscreen mode Exit fullscreen mode

The unit tests pin a tiny synthetic dataset that lets you verify the median by hand:

const TINY = [
  { year: 2000, male: [400, 300, 200, 100], female: [400, 300, 200, 100] },
  ...
];
// Bin sizes (M+F): 800, 600, 400, 200. Cumulative: 800, 1400, 1800, 2000.
// Half-total = 1000 → falls in bin 1. Need 200 more out of 600 → 1/3 of the bin.
// median ≈ 5 + (1/3)*5 = 6.667 years.
assert.ok(Math.abs(medianAge(TINY[0]) - 6.667) < 0.01);

Enter fullscreen mode Exit fullscreen mode

The Japanese number formatting trap

Population in this codebase is in thousands, because that's what the source data looks like. Rendering "1.26億" or "8,320万" requires getting the unit conversions exactly right, and I shipped two different bugs before settling:

  • 1万 = 10 千, so man = thousands / 10. I once wrote Math.round(thousands / 10) followed by "0万", which appended an extra zero and rendered 83,202 千 (= 83.2 M people = 8,320 万) as "83200万" (= 832 億, 832,000 M, off by a factor of 100).
  • 1億 = 1万 × 1万 = 100,000 千. I once divided by 10_000 instead of 100_000 and rendered 128,097 千 as "12.81億" (off by a factor of 10).

The fix is one careful function with three branches and boundary-value tests for all three:

export function formatJpPopulation(thousands) {
  if (thousands >= 100_000) return `${(thousands / 100_000).toFixed(2)}億`;
  if (thousands >= 10)      return `${Math.round(thousands / 10).toLocaleString("en-US")}万`;
  return `${thousands}千`;
}

Enter fullscreen mode Exit fullscreen mode

assert.equal(formatJpPopulation(83_202),  "8,320万");
assert.equal(formatJpPopulation(128_097), "1.28億");
assert.equal(formatJpPopulation(5),       "5千");

Enter fullscreen mode Exit fullscreen mode

The asymmetric scaling (× 10 between 千 and 万, × 10,000 between 万 and 億) makes this one of those functions where boundary-value tests pay off enormously.

Try it

Hit ▶ once and let it cycle. Even if you already know the headline numbers — Japan ages, Japan shrinks — watching the boomer bulge walk up the chart while the base thins out is a different way of having that fact in your head.

The data is a stylized model. To swap in real numbers from UN WPP, IPSS, or e-Stat, you only need to replace data.json — the schema ({ageBins, snapshots: [{year, male[], female[]}]}) is the simplest plausible JSON shape, and the renderer doesn't care where the numbers came from.

MIT, ~250 lines of JS, ~120 lines of Python generator, 16 unit tests, no build step.


🛠 Built by SEN LLC as part of an ongoing series of small, focused developer tools. Browse the full portfolio for more.