From 64ca1d456d234deaf8fb050a5f31b9dedd29e7b8 Mon Sep 17 00:00:00 2001 From: srivibhavpadakandla Date: Sat, 10 Oct 2026 15:54:59 -0700 Subject: [PATCH 01/26] Support hand-written quick checks per track src/lib/quizzes/.ts maps chapter slugs to authored questions; a chapter listed there uses them (with seeded option shuffling) instead of the auto-drafted quiz, whose distractors come from other courses' headings. Co-Authored-By: Claude Opus 5.5 --- src/lib/quiz.ts | 17 +++++++++++++++++ src/lib/quizzes/computer-vision.ts | 9 +++++++++ src/lib/quizzes/financial-literacy.ts | 9 +++++++++ src/lib/quizzes/github.ts | 9 +++++++++ src/lib/quizzes/health-in-tech.ts | 9 +++++++++ src/lib/quizzes/html-css.ts | 9 +++++++++ src/lib/quizzes/index.ts | 24 ++++++++++++++++++++++++ src/lib/quizzes/ml.ts | 9 +++++++++ src/lib/quizzes/python.ts | 9 +++++++++ src/lib/quizzes/roblox.ts | 9 +++++++++ src/lib/quizzes/types.ts | 8 ++++++++ src/lib/quizzes/vibecoding.ts | 9 +++++++++ 12 files changed, 130 insertions(+) create mode 100644 src/lib/quizzes/computer-vision.ts create mode 100644 src/lib/quizzes/financial-literacy.ts create mode 100644 src/lib/quizzes/github.ts create mode 100644 src/lib/quizzes/health-in-tech.ts create mode 100644 src/lib/quizzes/html-css.ts create mode 100644 src/lib/quizzes/index.ts create mode 100644 src/lib/quizzes/ml.ts create mode 100644 src/lib/quizzes/python.ts create mode 100644 src/lib/quizzes/roblox.ts create mode 100644 src/lib/quizzes/types.ts create mode 100644 src/lib/quizzes/vibecoding.ts diff --git a/src/lib/quiz.ts b/src/lib/quiz.ts index d2f61061..a231ae71 100644 --- a/src/lib/quiz.ts +++ b/src/lib/quiz.ts @@ -10,11 +10,14 @@ * Everything is deterministic (seeded from the slug), so the server and client * render the exact same options in the exact same order — no hydration drift. * These are DRAFTS meant for a human review pass, per the team's choice. + * A chapter with hand-written questions in src/lib/quizzes/.ts uses + * those instead; the drafts only fill chapters nobody has written yet. */ import { getChapters } from "@/lib/learn-nav"; import type { LearnTrackId } from "@/lib/learn-types"; import { mulberry32, shuffled } from "@/lib/ml/random"; +import { AUTHORED_QUIZZES } from "@/lib/quizzes"; const TRACKS: LearnTrackId[] = [ "python", @@ -60,6 +63,20 @@ const OPTIONS_PER_Q = 4; export function getQuiz(track: LearnTrackId, slug: string): Quiz | null { const chapter = getChapters(track).find((c) => c.slug === slug); if (!chapter) return null; + + const authored = AUTHORED_QUIZZES[track]?.[slug]; + if (authored && authored.length > 0) { + // Shuffle option order per chapter (seeded, so server and client agree) + // so the right answer isn't always in the position it was written in. + const rand = mulberry32(seedFrom(`${track}/${slug}/authored`)); + const questions: QuizQuestion[] = authored.map((item) => { + const correct = item.options[item.answer]; + const options = shuffled([...item.options], rand); + return { q: item.q, options, answer: options.indexOf(correct) }; + }); + return { questions, passMark: Math.max(1, Math.ceil(questions.length * 0.67)) }; + } + const claims = chapter.headings.map((h) => h.text); if (claims.length === 0) return null; diff --git a/src/lib/quizzes/computer-vision.ts b/src/lib/quizzes/computer-vision.ts new file mode 100644 index 00000000..94ed2b45 --- /dev/null +++ b/src/lib/quizzes/computer-vision.ts @@ -0,0 +1,9 @@ +import type { AuthoredQuestion } from "@/lib/quizzes/types"; + +/** + * Hand-written quick checks for the computer-vision track, keyed by chapter slug. + * A chapter listed here uses these questions instead of the auto-drafted + * quiz in src/lib/quiz.ts. Each question tests something the chapter + * actually teaches; `answer` is the zero-based index of the correct option. + */ +export const QUIZZES: Record = {}; diff --git a/src/lib/quizzes/financial-literacy.ts b/src/lib/quizzes/financial-literacy.ts new file mode 100644 index 00000000..06d44f09 --- /dev/null +++ b/src/lib/quizzes/financial-literacy.ts @@ -0,0 +1,9 @@ +import type { AuthoredQuestion } from "@/lib/quizzes/types"; + +/** + * Hand-written quick checks for the financial-literacy track, keyed by chapter slug. + * A chapter listed here uses these questions instead of the auto-drafted + * quiz in src/lib/quiz.ts. Each question tests something the chapter + * actually teaches; `answer` is the zero-based index of the correct option. + */ +export const QUIZZES: Record = {}; diff --git a/src/lib/quizzes/github.ts b/src/lib/quizzes/github.ts new file mode 100644 index 00000000..e7af8fa3 --- /dev/null +++ b/src/lib/quizzes/github.ts @@ -0,0 +1,9 @@ +import type { AuthoredQuestion } from "@/lib/quizzes/types"; + +/** + * Hand-written quick checks for the github track, keyed by chapter slug. + * A chapter listed here uses these questions instead of the auto-drafted + * quiz in src/lib/quiz.ts. Each question tests something the chapter + * actually teaches; `answer` is the zero-based index of the correct option. + */ +export const QUIZZES: Record = {}; diff --git a/src/lib/quizzes/health-in-tech.ts b/src/lib/quizzes/health-in-tech.ts new file mode 100644 index 00000000..c8a3960a --- /dev/null +++ b/src/lib/quizzes/health-in-tech.ts @@ -0,0 +1,9 @@ +import type { AuthoredQuestion } from "@/lib/quizzes/types"; + +/** + * Hand-written quick checks for the health-in-tech track, keyed by chapter slug. + * A chapter listed here uses these questions instead of the auto-drafted + * quiz in src/lib/quiz.ts. Each question tests something the chapter + * actually teaches; `answer` is the zero-based index of the correct option. + */ +export const QUIZZES: Record = {}; diff --git a/src/lib/quizzes/html-css.ts b/src/lib/quizzes/html-css.ts new file mode 100644 index 00000000..44ce37d4 --- /dev/null +++ b/src/lib/quizzes/html-css.ts @@ -0,0 +1,9 @@ +import type { AuthoredQuestion } from "@/lib/quizzes/types"; + +/** + * Hand-written quick checks for the html-css track, keyed by chapter slug. + * A chapter listed here uses these questions instead of the auto-drafted + * quiz in src/lib/quiz.ts. Each question tests something the chapter + * actually teaches; `answer` is the zero-based index of the correct option. + */ +export const QUIZZES: Record = {}; diff --git a/src/lib/quizzes/index.ts b/src/lib/quizzes/index.ts new file mode 100644 index 00000000..4341edba --- /dev/null +++ b/src/lib/quizzes/index.ts @@ -0,0 +1,24 @@ +import type { LearnTrackId } from "@/lib/learn-types"; +import type { AuthoredQuestion } from "@/lib/quizzes/types"; +import { QUIZZES as computerVision } from "@/lib/quizzes/computer-vision"; +import { QUIZZES as financialLiteracy } from "@/lib/quizzes/financial-literacy"; +import { QUIZZES as github } from "@/lib/quizzes/github"; +import { QUIZZES as healthInTech } from "@/lib/quizzes/health-in-tech"; +import { QUIZZES as htmlCss } from "@/lib/quizzes/html-css"; +import { QUIZZES as ml } from "@/lib/quizzes/ml"; +import { QUIZZES as python } from "@/lib/quizzes/python"; +import { QUIZZES as roblox } from "@/lib/quizzes/roblox"; +import { QUIZZES as vibecoding } from "@/lib/quizzes/vibecoding"; + +/** Hand-written quick checks, one file per track so tracks can be edited independently. */ +export const AUTHORED_QUIZZES: Record> = { + python, + ml, + vibecoding, + "html-css": htmlCss, + github, + "computer-vision": computerVision, + "financial-literacy": financialLiteracy, + "health-in-tech": healthInTech, + roblox, +}; diff --git a/src/lib/quizzes/ml.ts b/src/lib/quizzes/ml.ts new file mode 100644 index 00000000..15cd9959 --- /dev/null +++ b/src/lib/quizzes/ml.ts @@ -0,0 +1,9 @@ +import type { AuthoredQuestion } from "@/lib/quizzes/types"; + +/** + * Hand-written quick checks for the ml track, keyed by chapter slug. + * A chapter listed here uses these questions instead of the auto-drafted + * quiz in src/lib/quiz.ts. Each question tests something the chapter + * actually teaches; `answer` is the zero-based index of the correct option. + */ +export const QUIZZES: Record = {}; diff --git a/src/lib/quizzes/python.ts b/src/lib/quizzes/python.ts new file mode 100644 index 00000000..87366b93 --- /dev/null +++ b/src/lib/quizzes/python.ts @@ -0,0 +1,9 @@ +import type { AuthoredQuestion } from "@/lib/quizzes/types"; + +/** + * Hand-written quick checks for the python track, keyed by chapter slug. + * A chapter listed here uses these questions instead of the auto-drafted + * quiz in src/lib/quiz.ts. Each question tests something the chapter + * actually teaches; `answer` is the zero-based index of the correct option. + */ +export const QUIZZES: Record = {}; diff --git a/src/lib/quizzes/roblox.ts b/src/lib/quizzes/roblox.ts new file mode 100644 index 00000000..99727bb2 --- /dev/null +++ b/src/lib/quizzes/roblox.ts @@ -0,0 +1,9 @@ +import type { AuthoredQuestion } from "@/lib/quizzes/types"; + +/** + * Hand-written quick checks for the roblox track, keyed by chapter slug. + * A chapter listed here uses these questions instead of the auto-drafted + * quiz in src/lib/quiz.ts. Each question tests something the chapter + * actually teaches; `answer` is the zero-based index of the correct option. + */ +export const QUIZZES: Record = {}; diff --git a/src/lib/quizzes/types.ts b/src/lib/quizzes/types.ts new file mode 100644 index 00000000..143153c2 --- /dev/null +++ b/src/lib/quizzes/types.ts @@ -0,0 +1,8 @@ +/** One hand-written quick-check question. */ +export interface AuthoredQuestion { + q: string; + /** Three or four options; keep them similar in length and all plausible. */ + options: readonly string[]; + /** Zero-based index of the correct option. */ + answer: number; +} diff --git a/src/lib/quizzes/vibecoding.ts b/src/lib/quizzes/vibecoding.ts new file mode 100644 index 00000000..3cc071bc --- /dev/null +++ b/src/lib/quizzes/vibecoding.ts @@ -0,0 +1,9 @@ +import type { AuthoredQuestion } from "@/lib/quizzes/types"; + +/** + * Hand-written quick checks for the vibecoding track, keyed by chapter slug. + * A chapter listed here uses these questions instead of the auto-drafted + * quiz in src/lib/quiz.ts. Each question tests something the chapter + * actually teaches; `answer` is the zero-based index of the correct option. + */ +export const QUIZZES: Record = {}; From fb9d2aab8ea45a843bfef48b023b46833bdc17e0 Mon Sep 17 00:00:00 2001 From: srivibhavpadakandla Date: Sat, 10 Oct 2026 16:17:03 -0700 Subject: [PATCH 02/26] Python course: hand-written quick checks and lesson fixes All 31 chapters get authored questions (mostly predict-the-output). Fixes include the grade-chain example (separate ifs gave 95 a C), a traceback with wrong line numbers, a fibonacci stepper missing 13, defaultdict(list()) raising TypeError, the sys.path search order, KeyError behaviour, and chapter counts; adds predict-the-output exercises. Co-Authored-By: Claude Opus 5.5 --- .../python/ChoosingAStructureLesson.tsx | 5 +- .../python/ClassesAndObjectsLesson.tsx | 9 +- .../python/ComprehensionsLesson.tsx | 4 +- src/components/python/ConditionalsLesson.tsx | 31 +- src/components/python/DictionariesLesson.tsx | 28 +- src/components/python/ErrorsLesson.tsx | 20 +- src/components/python/FilesAndPathsLesson.tsx | 15 +- src/components/python/FinalProjectLesson.tsx | 11 +- src/components/python/FunctionsLesson.tsx | 25 + src/components/python/GeneratorStepper.tsx | 2 +- .../python/IteratorsAndGeneratorsLesson.tsx | 4 +- src/components/python/JsonAndApisLesson.tsx | 6 +- src/components/python/LookupSafety.tsx | 2 +- src/components/python/LoopsLesson.tsx | 25 + .../python/ModulesAndPackagesLesson.tsx | 16 +- .../python/NestedStructuresLesson.tsx | 2 +- .../python/NumbersAndOperatorsLesson.tsx | 5 +- src/components/python/OsSetup.tsx | 7 +- .../python/SetsAndTruthinessLesson.tsx | 4 +- src/components/python/StringsLesson.tsx | 28 +- .../python/TestingYourCodeLesson.tsx | 8 +- .../python/TheCollectionsModuleLesson.tsx | 5 +- src/components/python/WhatIsPythonLesson.tsx | 2 +- .../python/WorkingWithLibrariesLesson.tsx | 4 +- src/lib/quizzes/python.ts | 1070 ++++++++++++++++- 25 files changed, 1283 insertions(+), 55 deletions(-) diff --git a/src/components/python/ChoosingAStructureLesson.tsx b/src/components/python/ChoosingAStructureLesson.tsx index d748e8b9..16e8fab2 100644 --- a/src/components/python/ChoosingAStructureLesson.tsx +++ b/src/components/python/ChoosingAStructureLesson.tsx @@ -163,8 +163,9 @@ by_name["Amara"]["chapters"] # one hash, no scan`}

Everything above describes how the work grows, not how long it takes. On small collections a list frequently beats a set outright, because building the set costs - more than the scan it saves — and "small" here can mean a few hundred items, - not a few. + more than the scan it saves — especially when you only look something up once or + twice. Where the crossover sits depends on your data and how many lookups you do, + which is exactly why you measure.

The standard library will tell you rather than leave you guessing. diff --git a/src/components/python/ClassesAndObjectsLesson.tsx b/src/components/python/ClassesAndObjectsLesson.tsx index 4438f570..016a14de 100644 --- a/src/components/python/ClassesAndObjectsLesson.tsx +++ b/src/components/python/ClassesAndObjectsLesson.tsx @@ -83,9 +83,12 @@ export function ClassesAndObjectsLesson() { True`} /> - {'{"name": "Ada", "grade": 92}'} holds the same data, but a typo - like {'student["gade"]'} fails silently at the point of use. A class - gives every instance the same fixed shape and lets you attach behaviour, like{" "} + {'{"name": "Ada", "grade": 92}'} holds the same data, but nothing + guarantees the next dictionary has the same keys, and a typo when writing —{" "} + {'student["gade"] = 95'} — quietly adds a second key instead of + updating the grade. A class's __init__ requires every field + for every instance, an editor can flag ada.gade as an attribute + that was never defined, and you can attach behaviour, like{" "} passed(), directly to the data it acts on.

diff --git a/src/components/python/ComprehensionsLesson.tsx b/src/components/python/ComprehensionsLesson.tsx index b0aa7eac..f98ca715 100644 --- a/src/components/python/ComprehensionsLesson.tsx +++ b/src/components/python/ComprehensionsLesson.tsx @@ -144,7 +144,9 @@ for row in rows: outer loop — for row in rows — comes first, then the inner one —{" "} for value in row. Reverse them and Python raises a{" "} NameError, because row has to exist before{" "} - for value in row makes sense. + for value in row makes sense — or, worse, if a{" "} + row is still lying around from an earlier loop, it quietly loops + over that stale row and hands back the wrong list.

A single nested comprehension for flattening is common and reads fine. Three levels, diff --git a/src/components/python/ConditionalsLesson.tsx b/src/components/python/ConditionalsLesson.tsx index 2a64470d..d59ea888 100644 --- a/src/components/python/ConditionalsLesson.tsx +++ b/src/components/python/ConditionalsLesson.tsx @@ -79,11 +79,30 @@ else:

A score of 95 matches the first condition and stops there — the{" "} {"score >= 80"} check never runs, because it does not need to. - Write this as four separate if statements instead and a score of 95 - would still pass the second and third tests too, which does no harm here only - because each branch happens to overwrite grade rather than act on - it. + Write it with plain if statements instead of elif{" "} + and a score of 95 passes the second and third tests too. Each one overwrites{" "} + grade in turn, so it ends as "C" — a + wrong answer with no error to warn you.

+ = 90: + grade = "A" +if score >= 80: + grade = "B" +if score >= 70: + grade = "C" + +print(grade) +# C`} + lineTones={{ 9: "err" }} + /> + + Even with elif, order matters. Put {"score >= 70"}{" "} + first and a 95 matches it, stops there, and gets a C. Check the narrowest condition + first, so the broader ones only see what is left over. + @@ -228,8 +247,8 @@ empty`} Both read the same way you would say the condition out loud.

- Another piece of syntax is the walrus operator{" "} - := lets you assign a value and test it in the same expression, + One more piece of syntax you will meet: the walrus operator,{" "} + :=, lets you assign a value and test it in the same expression, instead of on the line before.

Strings, numbers, and tuples qualify, because none of them can be edited in place. - A tuple of coordinates makes a perfectly good key for exactly that reason. + A tuple of coordinates makes a perfectly good key for exactly that reason — as long + as everything inside the tuple is immutable too. A tuple holding a list is still + unhashable.

.get() in that situation does not fix the bug — it just moves the failure somewhere harder to find.

+ + + {"{'apple': 5, 'pear': 1}"}. The existing key is overwritten with + its new total, and {'stock.get("pear", 0)'} supplies a starting 0 + for the key that did not exist yet. Writing{" "} + {'stock["pear"] += 1'} instead would have raised{" "} + {"KeyError: 'pear'"}. + + } + openLabel="Reveal the answer" + closeLabel="Hide the answer" + /> diff --git a/src/components/python/ErrorsLesson.tsx b/src/components/python/ErrorsLesson.tsx index d51d6f58..9d3844dd 100644 --- a/src/components/python/ErrorsLesson.tsx +++ b/src/components/python/ErrorsLesson.tsx @@ -63,7 +63,10 @@ def price_for(item): return CATALOGUE[item] def total(cart): - return sum(price_for(item) for item in cart) + running = 0 + for item in cart: + running += price_for(item) + return running total(["bread", "eggs", "kombucha"])`} /> @@ -71,22 +74,23 @@ total(["bread", "eggs", "kombucha"])`} label="Terminal" variant="terminal" code={`Traceback (most recent call last): - File "shop.py", line 9, in + File "shop.py", line 12, in total(["bread", "eggs", "kombucha"]) - File "shop.py", line 6, in total - return sum(price_for(item) for item in cart) - File "shop.py", line 3, in price_for + File "shop.py", line 9, in total + running += price_for(item) + ^^^^^^^^^^^^^^^ + File "shop.py", line 4, in price_for return CATALOGUE[item] ~~~~~~~~~^^^^^^ KeyError: 'kombucha'`} - lineTones={{ 8: "err", 5: "accent" }} + lineTones={{ 9: "err", 6: "accent" }} />

Start at the bottom: KeyError: 'kombucha'. Move up one frame: the crash happened inside price_for, on the line that looks up CATALOGUE[item]. Move up again: price_for was - called from total, which was itself called from line 9, at the - bottom of the file. Reading top to bottom instead tells you the same thing backwards + called from line 9 inside total, which was itself called from line + 12, at the bottom of the file. Reading top to bottom instead tells you the same thing backwards — you would wade through two frames you do not need yet before reaching the one line that actually matters.

diff --git a/src/components/python/FilesAndPathsLesson.tsx b/src/components/python/FilesAndPathsLesson.tsx index 77b95be9..0faff373 100644 --- a/src/components/python/FilesAndPathsLesson.tsx +++ b/src/components/python/FilesAndPathsLesson.tsx @@ -25,7 +25,8 @@ export function FilesAndPathsLesson() { {'open("notes.txt", "w")'} creates the file if it does not exist yet, or empties it if it does — the "w" means write mode.{" "} write() returns the number of characters written, which is easy to - ignore and easy to forget you are ignoring. + ignore and easy to forget you are ignoring. To add to the end of an existing file + instead of wiping it, open it with "a", append mode.

Nothing is guaranteed to actually reach the disk until close() runs. @@ -169,8 +170,9 @@ b'\\x89PNG\\r\\n\\x1a\\n'`} tone: "caution", children: ( <> - {'"data" + "/" + "notes.txt"'} hardcodes a forward slash, - which is wrong on Windows, and breaks the moment a folder name changes. + {'"data" + "/" + "notes.txt"'} glues the separator in by + hand. Doubled or missing slashes creep in as soon as the pieces come from + variables, and the result is a plain string with no path methods at all. ), }, @@ -204,6 +206,13 @@ PosixPath('/Users/you/project/notes.txt') >>> Path("notes.txt").exists() True`} /> +

+ When a data file lives next to your script, build its path from the script's + own location instead of the folder you happened to run it from.{" "} + __file__ is the path of the current .py file, so{" "} + {'Path(__file__).parent / "notes.txt"'} finds the same file no + matter where the program is started. +

pathlib.Path builds and checks paths without string-gluing slashes by hand — resolve() shows exactly which file a relative path points diff --git a/src/components/python/FinalProjectLesson.tsx b/src/components/python/FinalProjectLesson.tsx index a85a397d..6e68bcd2 100644 --- a/src/components/python/FinalProjectLesson.tsx +++ b/src/components/python/FinalProjectLesson.tsx @@ -177,7 +177,10 @@ def word_counts(text): returns{" "} {"{'the': 2, 'cat': 2, 'calm': 1, 'sat': 1, 'ran': 1, 'fast': 1}"} — six keys instead of seven, and 'cat' correctly counted - twice. It is a genuine improvement, and also a reminder that "finished" + twice. One edge to watch: a "word" made only of punctuation, like a lone{" "} + -, strips down to an empty string and gets counted under the key{" "} + ''. Adding if word: before the count + line skips it. It is a genuine improvement, and also a reminder that "finished" for a real program is a judgement call, not a fixed line: the version without this fix was complete enough to call done a section ago, and this version is more correct without either one being the objectively right answer for every use. @@ -187,7 +190,9 @@ def word_counts(text): the most common word. {"max(counts, key=counts.get)"} finds the key whose value is largest without writing a loop yourself — the same{" "} key= argument idea the sorting built-ins in Python use throughout - the standard library. + the standard library. On an empty dictionary it raises ValueError, + exactly as the records chapter warned, so pass default=None if + empty input is allowed.

Whenever the plan is "find the biggest thing by some rule," check first @@ -202,7 +207,7 @@ def word_counts(text):

Nothing about this program is specific to counting words — the same shape, a loop filling a dictionary, is the core of a shopping cart total, a vote tally, or a log - file summary. The twenty-four chapters behind this one are not separate tools; they + file summary. The thirty chapters behind this one are not separate tools; they are the vocabulary this one program was written in.

diff --git a/src/components/python/FunctionsLesson.tsx b/src/components/python/FunctionsLesson.tsx index 8691cd42..16f204be 100644 --- a/src/components/python/FunctionsLesson.tsx +++ b/src/components/python/FunctionsLesson.tsx @@ -2,6 +2,7 @@ import { Lead, LessonSection, P, Strong } from "@/components/learn/primitives/Le import { Callout } from "@/components/learn/primitives/Callout"; import { CodeBlock } from "@/components/learn/primitives/CodeBlock"; import { CompareGrid, TakeawayCard } from "@/components/learn/primitives/Cards"; +import { RevealCard } from "@/components/learn/primitives/RevealCard"; import { FunctionMachine } from "@/components/python/FunctionMachine"; export function FunctionsLesson() { @@ -236,6 +237,30 @@ None`} return. Reaching the end of a function body falls off the end and returns None exactly as if that had been the last line.

+ + + It prints 10, then crashes with{" "} + {"TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'"} + , because double only printed its result and handed back{" "} + None. Change print to return{" "} + inside the function and the last line prints 11. + + } + openLabel="Reveal the answer" + closeLabel="Hide the answer" + />

+ The exact byte counts vary between Python versions, but the gap never closes. That is not a rounding difference — it is the difference between a container that already holds a million pointers and an object that holds only the instruction for how to make the next number, plus a note on where it stopped. The list has to exist @@ -144,7 +145,8 @@ StopIteration`}

- An open file is an iterator, the same as the list example above — for line + An open file is an iterator, like the one iter(numbers) handed back + at the start of this chapter — for line in f: calls next() on it once per line, and each call reads only as far as the next newline character before handing that one line back.

diff --git a/src/components/python/JsonAndApisLesson.tsx b/src/components/python/JsonAndApisLesson.tsx index 886ccb40..b99b6c87 100644 --- a/src/components/python/JsonAndApisLesson.tsx +++ b/src/components/python/JsonAndApisLesson.tsx @@ -81,7 +81,9 @@ export function JsonAndApisLesson() { reads directly from it, which matters because it is the difference between{" "} {'json.load(f)'} and the far more common mistake,{" "} {'json.loads(f)'}, which fails: loads expects text, - and a file object is not text, it is something you read text from. + and a file object is not text, it is something you read text from. The error says + so in its own words: the JSON object must be str, bytes or bytearray, not + TextIOWrapper.

+ + + 4. The loop adds 1, skips 2 with continue, adds 3, skips 4, then + hits break at 5 — so 6 is never even looked at, and only 1 + 3 was added. + + } + openLabel="Reveal the answer" + closeLabel="Hide the answer" + /> diff --git a/src/components/python/ModulesAndPackagesLesson.tsx b/src/components/python/ModulesAndPackagesLesson.tsx index 8cf9cfc4..7fa4fb7c 100644 --- a/src/components/python/ModulesAndPackagesLesson.tsx +++ b/src/components/python/ModulesAndPackagesLesson.tsx @@ -149,7 +149,8 @@ if __name__ == "__main__":

A package is just a folder of modules, with one marker file,{" "} __init__.py, that tells Python to treat the folder as a single - importable unit rather than an ordinary directory. + importable unit rather than an ordinary directory. The file can be completely + empty; its presence is the signal.

import shapes works because Python searches a specific list of locations, in order, called sys.path: the folder the running script - lives in first, then any installed packages, then the standard library. That is also + lives in first, then the standard library, then installed third-party packages. That is also why a typo like import shpaes fails immediately with{" "} ModuleNotFoundError instead of finding something similar — the search is exact, not fuzzy.

+ + Because the script's own folder is searched first, a file you saved as{" "} + random.py or json.py hides the standard-library + module of the same name. import random then imports your file, + and random.randint fails with an AttributeError{" "} + that seems to make no sense. Renaming your file fixes it. +

Inside a package, an import can be written two ways. An{" "} absolute import spells out the full path from the top of the @@ -198,7 +206,7 @@ from .shapes import area_of_circle`}

Run a file containing {"from .shapes import area_of_circle"}{" "} - directly with python angles.py and it fails with{" "} + directly with python3 angles.py and it fails with{" "} ImportError: attempted relative import with no known parent package. Relative imports only resolve inside a package that was itself imported, not a file executed on its own. @@ -210,7 +218,7 @@ from .shapes import area_of_circle`} "A module is one file; a package is a folder of modules with an __init__.py; a library is the general word for published code that might be shipped as either.", "A module's file runs top to bottom exactly once per program, the first time it is imported, then the result is cached.", 'if __name__ == "__main__": guards code so it only runs when the file is executed directly, not when something else imports it — __name__ is just an ordinary variable Python sets differently depending on how the file started.', - "Python searches sys.path, in order, to resolve an import — the running script's own folder first, then installed packages, then the standard library.", + "Python searches sys.path, in order, to resolve an import — the running script's own folder first, then the standard library, then installed packages — so a file named random.py can hide the real random module.", "A relative import (from .shapes import ...) only works inside a package; a plain script run directly needs an absolute one.", ]} /> diff --git a/src/components/python/NestedStructuresLesson.tsx b/src/components/python/NestedStructuresLesson.tsx index 048f6bff..6a391d1b 100644 --- a/src/components/python/NestedStructuresLesson.tsx +++ b/src/components/python/NestedStructuresLesson.tsx @@ -182,7 +182,7 @@ print(first_member["badges"][1].upper())`} "Read an access path left to right: each bracket takes what you are holding and asks it for exactly one thing.", "The bracket you write follows from what you are holding — a quoted name for a dictionary, an integer for a list.", "Nested loops mirror the shape of nested data. Name the loop variables after what they hold, not after the collection.", - "KeyError, IndexError, and TypeError each name a different way a path can run out, and each quotes the thing that was missing.", + "KeyError, IndexError, and TypeError each name a different way a path can run out — and a KeyError quotes the exact key that was missing.", "Python creates a key you assign to, never one you read through. Build each level before filling the one below it.", "You have nested too deep when you cannot say what a level holds without checking. Name an intermediate variable, or promote the shape to a class.", ]} diff --git a/src/components/python/NumbersAndOperatorsLesson.tsx b/src/components/python/NumbersAndOperatorsLesson.tsx index dd608418..30b9af82 100644 --- a/src/components/python/NumbersAndOperatorsLesson.tsx +++ b/src/components/python/NumbersAndOperatorsLesson.tsx @@ -129,8 +129,9 @@ export function NumbersAndOperatorsLesson() { {"0.1 + 0.2 == 0.3"} is False. Round both sides to a sensible number of decimal places before comparing —{" "} {"round(0.1 + 0.2, 2) == 0.3"} is True — or check - that the difference between them is smaller than a tiny tolerance, instead of - checking for exact equality. + that the difference between them is smaller than a tiny tolerance — which is what{" "} + math.isclose(0.1 + 0.2, 0.3) does for you — instead of checking + for exact equality.
diff --git a/src/components/python/OsSetup.tsx b/src/components/python/OsSetup.tsx index a1d93c90..2e8d6a58 100644 --- a/src/components/python/OsSetup.tsx +++ b/src/components/python/OsSetup.tsx @@ -30,7 +30,7 @@ py`, browser: { label: "No install", code: `# Open python.org/shell, or any site offering a Python REPL. -# You get the same interpreter, running on a server instead of your machine.`, +# You get the same language, running on a server or in the browser itself.`, }, }; @@ -44,8 +44,9 @@ export function OsSetup() { Check what you already have

- Most Mac and Linux machines ship with Python already installed. Pick what you are - sitting at. + Most Linux machines ship with Python already installed. On a Mac, the first{" "} + python3 may offer to install Apple's command-line developer tools, + which include it. Pick what you are sitting at.

diff --git a/src/components/python/SetsAndTruthinessLesson.tsx b/src/components/python/SetsAndTruthinessLesson.tsx index 66913d0d..0e96830e 100644 --- a/src/components/python/SetsAndTruthinessLesson.tsx +++ b/src/components/python/SetsAndTruthinessLesson.tsx @@ -33,8 +33,8 @@ export function SetsAndTruthinessLesson() { {'""'} — the empty string, and only the empty string. , <> - [], {"{}"}, and set() — an - empty list, dictionary, or set. + [], {"{}"}, (), and{" "} + set() — an empty list, dictionary, tuple, or set. , <> None — Python's stand-in for "no value at all". diff --git a/src/components/python/StringsLesson.tsx b/src/components/python/StringsLesson.tsx index 2a72eb97..9dae8d08 100644 --- a/src/components/python/StringsLesson.tsx +++ b/src/components/python/StringsLesson.tsx @@ -64,6 +64,32 @@ export function StringsLesson() { A slice, text[start:end], pulls out a whole range at once. The part everyone gets wrong at least once: end is not included.

+ >> word = "python" +>>> word[0:2] +'py' +>>> word[2:6] +'thon' +>>> word[:3] +'pyt' +>>> word[-3:] +'hon'`} + /> +

+ word[0:2] stops before position 2, so it hands back two + characters, not three. Leave out start and the slice begins at the + front; leave out end and it runs to the finish. Because the end is + excluded, word[:3] + word[3:] always rebuilds the whole string with + nothing doubled and nothing lost. +

+ + Before you look at the widget below, predict what text[4:8] gives + for "codewithpurpose", counting from 0. The widget starts + on exactly that slice, so you can check straight away — and the answer is four + characters long, because 8 minus 4 is 4. + @@ -234,7 +260,7 @@ UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 3: ordinal

pytest is what turns a scattering of asserts into a suite you run - with one command. It looks for files named test_*.py and functions + with one command (-v asks it to list each test by name). It looks for files named test_*.py and functions inside them named test_*, runs every one it finds, and reports which passed and which raised — no test runner of your own to write.

@@ -222,7 +222,7 @@ def test_average_of_sample_scores(sample_scores):

{'assert largest([3, 1, 4]) == largest([3, 1, 4])'} from earlier - runs every line inside largest — it counts as full coverage, while + can run every line inside largest — it counts toward full coverage, while proving nothing about whether the function is correct. A coverage percentage answers "did we run this line," never "did we check the right values against it." A green number is a floor worth having, not a ceiling worth trusting. diff --git a/src/components/python/TheCollectionsModuleLesson.tsx b/src/components/python/TheCollectionsModuleLesson.tsx index 1cc7f96c..fdca5952 100644 --- a/src/components/python/TheCollectionsModuleLesson.tsx +++ b/src/components/python/TheCollectionsModuleLesson.tsx @@ -67,8 +67,9 @@ for student in students:

You pass list, not list() — the type itself, so the dictionary can call it fresh for each new key. Passing list() would - hand over one already-built list, and every key would end up sharing it, which is the - aliasing trap from the previous chapter in one of its least obvious costumes. + hand over one already-built empty list instead of something callable, and{" "} + defaultdict refuses it outright with{" "} + TypeError: first argument must be callable or None.

This is the surprise. by_track["chemistry"] on a{" "} diff --git a/src/components/python/WhatIsPythonLesson.tsx b/src/components/python/WhatIsPythonLesson.tsx index 15007fd3..e298ec3c 100644 --- a/src/components/python/WhatIsPythonLesson.tsx +++ b/src/components/python/WhatIsPythonLesson.tsx @@ -138,7 +138,7 @@ TypeError: unsupported operand type(s) for +: 'int' and 'str'`} lineTones={{ 6: "err" }} />

- One of the four prices was typed as text — {"\"20\""} instead of{" "} + One of the two prices was typed as text — {"\"20\""} instead of{" "} 20 — probably because it came from a form field or a spreadsheet column that nobody checked. Nothing about the program looked wrong until Python tried to add an int and a string together and had no idea how. diff --git a/src/components/python/WorkingWithLibrariesLesson.tsx b/src/components/python/WorkingWithLibrariesLesson.tsx index bd54b99d..e18a5702 100644 --- a/src/components/python/WorkingWithLibrariesLesson.tsx +++ b/src/components/python/WorkingWithLibrariesLesson.tsx @@ -53,12 +53,12 @@ Successfully installed requests-2.31.0`}

- python -m venv .venv creates an isolated folder with its own copy of + python3 -m venv .venv creates an isolated folder with its own copy of Python and its own package list.{" "} source .venv/bin/activate switches the current terminal to use that copy, so anything installed afterward stays scoped to this one project. The{" "} diff --git a/src/lib/quizzes/python.ts b/src/lib/quizzes/python.ts index 87366b93..2fd14ed1 100644 --- a/src/lib/quizzes/python.ts +++ b/src/lib/quizzes/python.ts @@ -6,4 +6,1072 @@ import type { AuthoredQuestion } from "@/lib/quizzes/types"; * quiz in src/lib/quiz.ts. Each question tests something the chapter * actually teaches; `answer` is the zero-based index of the correct option. */ -export const QUIZZES: Record = {}; +export const QUIZZES: Record = { + "what-is-python": [ + { + q: "In Python, what tells the interpreter which lines belong inside an if or else block?", + options: [ + "The indentation of the lines", + "Curly braces around the block", + "A semicolon after each line", + "An end keyword after the block", + ], + answer: 0, + }, + { + q: "What does CPython do with your .py file when you run it?", + options: [ + "Compiles it to bytecode, then interprets that bytecode", + "Compiles it straight to machine code ahead of time", + "Sends it to a server that runs it remotely", + "Reads the source text one character at a time", + ], + answer: 0, + }, + { + q: "total_price([{\"price\": 10}, {\"price\": \"20\"}]) adds up the prices. When does Python report the problem?", + options: [ + "Only when that line runs and tries to add an int to a str", + "Before the program starts, while checking the types", + "Never: Python quietly converts \"20\" to the number 20", + "When the file is saved in a Python-aware editor", + ], + answer: 0, + }, + { + q: "Your Python program needs to do heavy number crunching quickly. What does the chapter say fast Python code usually does?", + options: [ + "Calls into libraries written in C underneath", + "Avoids functions so there is less overhead", + "Switches to Python 2, which ran loops faster", + "Puts all the code on a single line", + ], + answer: 0, + }, + ], + "setting-up": [ + { + q: "On macOS or Linux, which command is the safe one to type to start Python 3?", + options: ["python3", "python", "py3", "run python"], + answer: 0, + }, + { + q: "In the REPL you type x = 5 and press return. What does the REPL print?", + options: [ + "Nothing, because an assignment runs silently", + "5", + "x = 5", + "None", + ], + answer: 0, + }, + { + q: "You run python3 hello.py and get \"can't open file 'hello.py': No such file or directory\". What is the likely fix?", + options: [ + "Run it from the folder the file is in, or give its path", + "Fix the syntax error on the first line of hello.py", + "Reinstall Python, because the interpreter is broken", + "Rename the file to hello.txt and run it again", + ], + answer: 0, + }, + { + q: "Why create a virtual environment for each project?", + options: [ + "So each project's packages stay separate and cannot conflict", + "So your code runs faster than with the system Python", + "So the project folder can be committed with every package", + "So Python 2 and Python 3 code can be mixed in one file", + ], + answer: 0, + }, + ], + variables: [ + { + q: "You run a = [1, 2, 3], then b = a, then b.append(4). What does print(a) show?", + options: ["[1, 2, 3, 4]", "[1, 2, 3]", "[4]", "An error, because a was not changed"], + answer: 0, + }, + { + q: "You run a = 3, then b = a, then a = 5. What does print(b) show?", + options: ["3", "5", "8", "None"], + answer: 0, + }, + { + q: "a = [1, 2, 3] and b = [1, 2, 3] are built on separate lines. What are a == b and a is b?", + options: [ + "a == b is True, a is b is False", + "a == b is True, a is b is True", + "a == b is False, a is b is False", + "a == b is False, a is b is True", + ], + answer: 0, + }, + { + q: "Which of these is a valid Python variable name?", + options: ["total_score", "2nd_place", "class", "total-score"], + answer: 0, + }, + ], + "numbers-and-operators": [ + { + q: "What do 7 / 2 and 7 // 2 return?", + options: ["3.5 and 3", "3.5 and 3.5", "3 and 3.5", "3 and 1"], + answer: 0, + }, + { + q: "What does 2 ** 3 ** 2 evaluate to?", + options: ["512", "64", "36", "18"], + answer: 0, + }, + { + q: "0.1 + 0.2 == 0.3 is False. What is the right way to compare these floats?", + options: [ + "Check they are close, e.g. round both or use math.isclose", + "Use is instead of == for floats", + "Convert both sides to int first", + "Add 0.0 to both sides before comparing", + ], + answer: 0, + }, + { + q: "What does int(9.9) return?", + options: ["9", "10", "9.9", "An error, because 9.9 is not whole"], + answer: 0, + }, + ], + strings: [ + { + q: "With name = \"python\", what is name[-1]?", + options: ["'n'", "'p'", "'o'", "An IndexError"], + answer: 0, + }, + { + q: "With word = \"python\", what does word[0:2] return?", + options: ["'py'", "'pyt'", "'yt'", "'p'"], + answer: 0, + }, + { + q: "name = \"python\", then you run name.upper() on its own line. What is name now?", + options: [ + "'python', because strings never change in place", + "'PYTHON', because upper() edits the string", + "None, because upper() returns nothing", + "'Python', because only the first letter changes", + ], + answer: 0, + }, + { + q: "price = 19.5. What does f\"Total: {price * 2:.2f}\" produce?", + options: ["'Total: 39.00'", "'Total: 39.0'", "'Total: 39'", "'Total: {price * 2:.2f}'"], + answer: 0, + }, + ], + "lists-and-tuples": [ + { + q: "Which of these is a tuple holding exactly one item?", + options: ["(1,)", "(1)", "[1]", "tuple 1"], + answer: 0, + }, + { + q: "numbers = [3, 1, 2], then numbers = numbers.sort(). What is numbers now?", + options: ["None", "[1, 2, 3]", "[3, 1, 2]", "[3, 2, 1]"], + answer: 0, + }, + { + q: "Which line gives you a separate copy of the list original?", + options: [ + "safe = original.copy()", + "safe = original", + "safe == original", + "safe = (original)", + ], + answer: 0, + }, + { + q: "A function receives a list and calls scores.append(100). What happens to the caller's list?", + options: [ + "It gains 100 too, because it is the same list", + "Nothing, because the function got a private copy", + "It is replaced with a new list holding only 100", + "Python raises an error for changing an argument", + ], + answer: 0, + }, + ], + dictionaries: [ + { + q: "prices = {\"apple\": 0.6}. What does prices[\"fig\"] do?", + options: ["Raises KeyError: 'fig'", "Returns None", "Returns 0", "Adds \"fig\" with no value"], + answer: 0, + }, + { + q: "Which of these can be used as a dictionary key?", + options: ["(0, 1)", "[0, 1]", "{0: 1}", "{0, 1}"], + answer: 0, + }, + { + q: "You want a price, or 0 when the item is missing, without an error. Which do you write?", + options: [ + "prices.get(\"fig\", 0)", + "prices[\"fig\"] or 0", + "prices.find(\"fig\", 0)", + "prices[\"fig\", 0]", + ], + answer: 0, + }, + { + q: "Which loop gives you each key and its value together?", + options: [ + "for name, price in prices.items():", + "for name, price in prices:", + "for name, price in prices.keys():", + "for name, price in prices.values():", + ], + answer: 0, + }, + ], + "sets-and-truthiness": [ + { + q: "Which of these values is truthy?", + options: ["\"False\"", "0", "[]", "None"], + answer: 0, + }, + { + q: "A function gets votes=[] for a round with zero votes and votes=None before voting starts. Which check tells the two apart?", + options: ["if votes is not None:", "if votes:", "if not votes:", "if votes == []:"], + answer: 0, + }, + { + q: "admins = {\"ada\", \"grace\"} and editors = {\"grace\", \"alan\"}. What is admins & editors?", + options: ["{'grace'}", "{'ada', 'grace', 'alan'}", "{'ada'}", "{'ada', 'alan'}"], + answer: 0, + }, + { + q: "Your loop checks thousands of times whether a name is in a large collection. Which structure makes that check fastest?", + options: ["A set", "A list", "A tuple", "A string of names"], + answer: 0, + }, + ], + conditionals: [ + { + q: "score = 95. An if/elif/else chain checks score >= 90 (grade A), then score >= 80 (grade B), else grade F. What is grade?", + options: ["\"A\"", "\"B\"", "\"F\"", "\"A\", then \"B\""], + answer: 0, + }, + { + q: "score = 95. Three separate if statements (no elif) set grade to A if score >= 90, B if >= 80, C if >= 70. What is grade?", + options: ["\"C\"", "\"A\"", "\"B\"", "An error for reassigning grade"], + answer: 0, + }, + { + q: "With age = 16, what does 13 <= age < 20 evaluate to?", + options: ["True", "False", "16", "A SyntaxError"], + answer: 0, + }, + { + q: "In a match statement, what does case _: do?", + options: [ + "Catches anything no earlier case matched", + "Matches only an empty value", + "Skips the match statement entirely", + "Matches a variable literally named _", + ], + answer: 0, + }, + ], + loops: [ + { + q: "What does list(range(2, 10, 3)) return?", + options: ["[2, 5, 8]", "[2, 5, 8, 11]", "[3, 6, 9]", "[2, 4, 6, 8]"], + answer: 0, + }, + { + q: "names has 4 items and scores has 3. How many times does for name, score in zip(names, scores): run?", + options: ["3", "4", "7", "It raises an error"], + answer: 0, + }, + { + q: "When does the else block attached to a for loop run?", + options: [ + "When the loop finishes without hitting break", + "When the loop body raised an error", + "On every iteration where the if was false", + "Only when the list being looped over is empty", + ], + answer: 0, + }, + { + q: "numbers = [2, 4, 6, 7, 8]. A loop over numbers removes every even n from numbers. What is left?", + options: ["[4, 7]", "[7]", "[2, 4, 6, 7, 8]", "[]"], + answer: 0, + }, + ], + functions: [ + { + q: "def show_total(a, b): print(a + b). What is stored in result after result = show_total(3, 4)?", + options: ["None", "7", "\"7\"", "The function itself"], + answer: 0, + }, + { + q: "def add_item(item, basket=[]) appends item and returns basket. What does a second call, add_item(\"banana\"), return after add_item(\"apple\")?", + options: ["['apple', 'banana']", "['banana']", "['apple']", "[]"], + answer: 0, + }, + { + q: "What does *numbers collect in def total(*numbers):?", + options: [ + "Any extra positional arguments, as a tuple", + "Any keyword arguments, as a dictionary", + "Exactly one argument, multiplied", + "Only arguments that are numbers", + ], + answer: 0, + }, + { + q: "Where does help(greet) get the description it prints?", + options: [ + "The docstring on the first line of the function body", + "A comment written above the def line", + "The name of the function's first parameter", + "The last print call inside the function", + ], + answer: 0, + }, + ], + "scope-and-arguments": [ + { + q: "A function runs total = 100, then returns. What happens if you read total outside it?", + options: [ + "NameError, because total was local to the function", + "It prints 100, because the function already ran", + "It prints None, because the function returned nothing", + "It prints 0, the default value for a new name", + ], + answer: 0, + }, + { + q: "count = 0 at module level. def increment(): count = count + 1. What does calling increment() raise?", + options: ["UnboundLocalError", "NameError", "TypeError", "Nothing; count becomes 1"], + answer: 0, + }, + { + q: "A nested function needs to update a variable of the function it sits inside. Which keyword does it use?", + options: ["nonlocal", "global", "outer", "static"], + answer: 0, + }, + { + q: "def add_score(scores): scores = scores + [100]. After add_score(my_scores), what happens to my_scores?", + options: [ + "Nothing, because only the local name was rebound", + "It gains 100 at the end", + "It becomes a new list holding only 100", + "It becomes None", + ], + answer: 0, + }, + ], + errors: [ + { + q: "Where in a traceback do you find the exception that actually happened?", + options: [ + "On the last line", + "On the first line", + "In the middle frame", + "In a separate log file", + ], + answer: 0, + }, + { + q: "Why can't a try/except in your script catch a SyntaxError in that same file?", + options: [ + "Python refuses to run the file at all, so the except never runs", + "SyntaxError is not an exception type in Python", + "SyntaxError can only be caught with a bare except:", + "The except clause must be placed before the try", + ], + answer: 0, + }, + { + q: "In try / except / else / finally, when does the else block run?", + options: [ + "Only when the try block raised nothing", + "Only when the except block ran", + "Always, after finally", + "Only when the error was re-raised", + ], + answer: 0, + }, + { + q: "Why is a bare except: a bad idea?", + options: [ + "It also hides errors you never expected, like a typo", + "It makes the program noticeably slower to run", + "It only catches SyntaxError, nothing else", + "Python 3 no longer allows it", + ], + answer: 0, + }, + ], + "modules-and-packages": [ + { + q: "main.py does import shapes twice, in two different places. How many times does the code in shapes.py run?", + options: ["Once", "Twice", "Never, until a function is called", "Once per function in it"], + answer: 0, + }, + { + q: "What is __name__ inside weather.py when you run python3 weather.py directly?", + options: ["\"__main__\"", "\"weather\"", "\"weather.py\"", "None"], + answer: 0, + }, + { + q: "You save a file as random.py, and now import random; random.randint(1, 6) fails. Why?", + options: [ + "Your file is found first and hides the real random module", + "randint was removed from the random module", + "Files named after modules cannot contain imports", + "random must be installed with pip first", + ], + answer: 0, + }, + { + q: "Running python3 angles.py, which contains from .shapes import area_of_circle, fails. Why?", + options: [ + "Relative imports only work inside an imported package", + "Dots are not allowed in an import statement", + "shapes.py must be renamed to .shapes.py", + "area_of_circle must be imported before shapes", + ], + answer: 0, + }, + ], + "classes-and-objects": [ + { + q: "Why does every method in a class take self as its first parameter?", + options: [ + "Python passes in the object the method was called on", + "It is a keyword that makes the method public", + "It stores a copy of the class on each method", + "It is only a convention and can be left out freely", + ], + answer: 0, + }, + { + q: "class Student: clubs = [] (in the class body). ada.clubs.append(\"Chess\"). What is grace.clubs?", + options: ["['Chess']", "[]", "An AttributeError", "None"], + answer: 0, + }, + { + q: "What does __init__ actually do?", + options: [ + "Sets starting values on an object that already exists", + "Allocates the memory for a brand-new object", + "Deletes the object when it is no longer used", + "Prints the object in a readable way", + ], + answer: 0, + }, + { + q: "print(ada) shows <__main__.Student object at 0x...>. What do you add to show something readable?", + options: ["A __repr__ method", "A __print__ method", "A to_string method", "A second __init__"], + answer: 0, + }, + ], + inheritance: [ + { + q: "class Dog(Animal): pass, and rex = Dog(\"Rex\"). What is isinstance(rex, Animal)?", + options: [ + "True, because every Dog is also an Animal", + "False, because rex was built as a Dog", + "An error, because Dog defines no methods", + "True only if Animal defines __init__", + ], + answer: 0, + }, + { + q: "Dog adds a breed field. Which line inside Dog.__init__ lets Animal set up name as usual?", + options: [ + "super().__init__(name)", + "Animal = super(name)", + "self.super(name)", + "parent.__init__(self)", + ], + answer: 0, + }, + { + q: "A Car has an Engine. How should you model that?", + options: [ + "Store an Engine object as an attribute of Car", + "Make Car a subclass of Engine", + "Make Engine a subclass of Car", + "Copy every Engine method into Car", + ], + answer: 0, + }, + { + q: "Dog defines its own describe(). What happens to Animal.describe?", + options: [ + "Nothing; only Dog uses the new version", + "It is replaced for every class", + "It is deleted from Animal", + "Both versions run on every call", + ], + answer: 0, + }, + ], + "files-and-paths": [ + { + q: "What does open(\"notes.txt\", \"w\") do if notes.txt already has content?", + options: [ + "Empties it before writing", + "Adds new text after the old text", + "Raises an error because it exists", + "Opens it read-only", + ], + answer: 0, + }, + { + q: "Inside a with open(...) as f: block, an exception is raised. What is f.closed afterwards?", + options: [ + "True, because with closes the file anyway", + "False, because the error skipped the close", + "None, because the file was never opened", + "It depends on the operating system", + ], + answer: 0, + }, + { + q: "You need to scan a 2 GB log file without loading it all into memory. Which do you write?", + options: ["for line in f:", "f.read()", "f.readlines()", "list(f)"], + answer: 0, + }, + { + q: "Your script opens \"notes.txt\", but it fails when run from another folder. Which path finds the file next to the script?", + options: [ + "Path(__file__).parent / \"notes.txt\"", + "Path(\"notes.txt\")", + "\"./\" + \"notes.txt\"", + "Path.cwd() / \"notes.txt\"", + ], + answer: 0, + }, + ], + comprehensions: [ + { + q: "numbers = [1, 2, 3, 4, 5, 6]. What is [n * n for n in numbers if n % 2 == 0]?", + options: ["[4, 16, 36]", "[1, 9, 25]", "[1, 4, 9, 16, 25, 36]", "[2, 4, 6]"], + answer: 0, + }, + { + q: "What does {len(name) for name in [\"Ada\", \"Grace\", \"Alan\"]} build?", + options: [ + "A set: {3, 4, 5}", + "A dict: {'Ada': 3, 'Grace': 5, 'Alan': 4}", + "A list: [3, 5, 4]", + "A tuple: (3, 5, 4)", + ], + answer: 0, + }, + { + q: "rows = [[1, 2], [3]]. Which comprehension flattens it to [1, 2, 3]?", + options: [ + "[v for row in rows for v in row]", + "[v for v in row for row in rows]", + "[row for v in rows]", + "[[v] for row in rows]", + ], + answer: 0, + }, + { + q: "What does {} on its own create?", + options: ["An empty dict", "An empty set", "An empty list", "A SyntaxError"], + answer: 0, + }, + ], + "iterators-and-generators": [ + { + q: "it = iter([10, 20]). After next(it) twice, what does a third next(it) do?", + options: ["Raises StopIteration", "Returns None", "Returns 10 again", "Returns 20 again"], + answer: 0, + }, + { + q: "gen = fibonacci_below(20) for a generator function. How much of the function body has run?", + options: [ + "None of it yet", + "All of it, with values stored", + "Up to the first yield", + "Only the first line", + ], + answer: 0, + }, + { + q: "squares = (n * n for n in range(5)). What does a second list(squares) return?", + options: ["[]", "[0, 1, 4, 9, 16]", "None", "An error"], + answer: 0, + }, + { + q: "Why does sum(n * n for n in range(1_000_000)) use so little memory?", + options: [ + "Each square is made only when sum asks for it", + "Python stores the million squares compressed", + "sum works on the first thousand values only", + "range turns the numbers into a string first", + ], + answer: 0, + }, + ], + decorators: [ + { + q: "What is @log_calls written above def add(a, b): shorthand for?", + options: [ + "add = log_calls(add)", + "log_calls = add(log_calls)", + "add(log_calls)", + "log_calls.add()", + ], + answer: 0, + }, + { + q: "@a is written above @b, which is above def f():. What is f replaced with?", + options: ["a(b(f))", "b(a(f))", "a(f) and b(f)", "f(a(b))"], + answer: 0, + }, + { + q: "After decorating add with a plain wrapper, add.__name__ is 'wrapper'. What fixes that?", + options: [ + "Put @functools.wraps(func) on the inner wrapper", + "Rename wrapper to add inside the decorator", + "Call add.__name__ = add before decorating", + "Remove *args from the wrapper's parameters", + ], + answer: 0, + }, + { + q: "In @repeat(3), what runs first?", + options: [ + "repeat(3), which returns the real decorator", + "The decorated function, three times", + "The wrapper, with 3 as its argument", + "Nothing, until the function is called", + ], + answer: 0, + }, + ], + "list-methods-in-depth": [ + { + q: "What does sorted([\"bo\", \"Zoe\", \"ada\"]) return?", + options: [ + "['Zoe', 'ada', 'bo']", + "['ada', 'bo', 'Zoe']", + "['bo', 'Zoe', 'ada']", + "['Zoe', 'bo', 'ada']", + ], + answer: 0, + }, + { + q: "letters = [\"a\", \"b\", \"c\", \"d\"], then letters[1:3] = [\"X\"]. What is letters?", + options: [ + "['a', 'X', 'd']", + "['a', 'X', 'c', 'd']", + "['a', 'X', 'X', 'd']", + "['X', 'b', 'c', 'd']", + ], + answer: 0, + }, + { + q: "a = [1, 2], then a.append([3, 4]). What is len(a)?", + options: ["3", "4", "2", "1"], + answer: 0, + }, + { + q: "grid = [[0] * 3] * 3, then grid[0][0] = 1. What is grid?", + options: [ + "[[1, 0, 0], [1, 0, 0], [1, 0, 0]]", + "[[1, 0, 0], [0, 0, 0], [0, 0, 0]]", + "[[1, 1, 1], [0, 0, 0], [0, 0, 0]]", + "An error, because grid cannot be changed", + ], + answer: 0, + }, + ], + "records-and-tables": [ + { + q: "Why store a student as {\"name\": ..., \"chapters\": 18} rather than (\"Amara\", 18)?", + options: [ + "The fields have names, so the code still makes sense later", + "Dictionaries use less memory than tuples", + "Tuples cannot hold strings and numbers together", + "Only dictionaries can be put in a list", + ], + answer: 0, + }, + { + q: "Which key sorts students by track, then by most chapters first within each track?", + options: [ + "key=lambda s: (s[\"track\"], -s[\"chapters\"])", + "key=lambda s: (s[\"track\"], s[\"chapters\"])", + "key=lambda s: s[\"track\"] - s[\"chapters\"]", + "key=lambda s: (-s[\"track\"], s[\"chapters\"])", + ], + answer: 0, + }, + { + q: "You filter students into finished, then change a field on a row of finished. What happens to students?", + options: [ + "It changes too, because both lists hold the same dicts", + "Nothing, because filtering copied each dictionary", + "The row is removed from students", + "Python raises an error for editing a filtered row", + ], + answer: 0, + }, + { + q: "What does max(students, key=lambda s: s[\"minutes\"]) do when students is empty?", + options: [ + "Raises ValueError, unless you pass default=", + "Returns None", + "Returns 0", + "Returns an empty dictionary", + ], + answer: 0, + }, + ], + "nested-structures": [ + { + q: "club = {\"members\": [{\"name\": \"Amara\", \"badges\": [\"solder\", \"cad\"]}]}. What is club[\"members\"][0][\"badges\"][1]?", + options: ["'cad'", "'solder'", "'Amara'", "An IndexError"], + answer: 0, + }, + { + q: "club[\"members\"] is a list. What does club[\"members\"][\"0\"] raise?", + options: [ + "TypeError: list indices must be integers", + "KeyError: '0'", + "IndexError: list index out of range", + "Nothing; it returns the first member", + ], + answer: 0, + }, + { + q: "club = {\"name\": \"Robotics\"}. What does club[\"members\"].append(\"Amara\") do?", + options: [ + "Raises KeyError: 'members'", + "Creates a members list holding \"Amara\"", + "Returns None and changes nothing", + "Raises AttributeError on append", + ], + answer: 0, + }, + { + q: "Which error tells you that you tried to go down a level from a string?", + options: ["TypeError", "KeyError", "IndexError", "ValueError"], + answer: 0, + }, + ], + "copying-and-aliasing": [ + { + q: "a = [[1, 2], [3, 4]], b = a.copy(), then b[0].append(9). What is a?", + options: [ + "[[1, 2, 9], [3, 4]]", + "[[1, 2], [3, 4]]", + "[[1, 2], [3, 4], 9]", + "[[9], [3, 4]]", + ], + answer: 0, + }, + { + q: "Which change can tell b = a apart from b = a.copy()?", + options: [ + "Appending to the outer list b", + "Appending to the inner list b[0]", + "Printing b", + "Checking len(b[0])", + ], + answer: 0, + }, + { + q: "Which copy shares nothing with the original nested list?", + options: ["copy.deepcopy(a)", "a.copy()", "list(a)", "a[:]"], + answer: 0, + }, + { + q: "A list holds only numbers and strings. Is a shallow copy enough?", + options: [ + "Yes, because numbers and strings cannot be changed in place", + "No, you always need deepcopy for lists", + "No, numbers are shared and will change together", + "Only if the list has fewer than ten items", + ], + answer: 0, + }, + ], + "errors-in-data": [ + { + q: "scores = {\"amara\": 18}. What does scores.get(\"dara\") return?", + options: ["None", "0", "KeyError: 'dara'", "\"dara\""], + answer: 0, + }, + { + q: "by_track = {}. What does by_track.setdefault(\"ml\", []).append(\"Ben\") leave in by_track?", + options: [ + "{'ml': ['Ben']}", + "{}", + "{'ml': []}", + "A KeyError, because \"ml\" was missing", + ], + answer: 0, + }, + { + q: "minutes = record.get(\"minutes\") is None, and a later line divides by it. What do you see?", + options: [ + "A TypeError at the division, far from the real cause", + "A KeyError naming the missing \"minutes\" key", + "The division quietly treats None as zero", + "A ValueError at the get() call", + ], + answer: 0, + }, + { + q: "A lookup misses nine times out of ten. Which approach does the chapter recommend?", + options: [ + "Check with in first, because raising is costly", + "Use try/except, because it is always faster", + "Use a bare except: to catch every miss", + "Wrap the whole program in one try block", + ], + answer: 0, + }, + ], + "the-collections-module": [ + { + q: "counts = Counter([\"red\", \"red\", \"blue\"]). What is counts[\"green\"]?", + options: ["0", "None", "KeyError: 'green'", "1"], + answer: 0, + }, + { + q: "Which line creates a dictionary that starts every new key with its own empty list?", + options: [ + "defaultdict(list)", + "defaultdict(list())", + "defaultdict([])", + "dict(list)", + ], + answer: 0, + }, + { + q: "On a defaultdict(list), you only read by_track[\"chemistry\"]. What changes?", + options: [ + "The key is added with an empty list", + "Nothing; reading never changes a dict", + "It raises KeyError: 'chemistry'", + "The defaultdict turns into a plain dict", + ], + answer: 0, + }, + { + q: "You process a large queue by removing items from the front. Which structure suits this?", + options: ["deque, using popleft()", "list, using pop(0)", "namedtuple", "Counter"], + answer: 0, + }, + ], + "choosing-a-structure": [ + { + q: "\"dara\" in names, where names is a list of 10,000 names without \"dara\". How many items get compared?", + options: ["All 10,000", "Just 1", "About 100", "None, a list is hashed"], + answer: 0, + }, + { + q: "Why can't a list go inside a set?", + options: [ + "A list can change, so it cannot be hashed", + "Sets can only hold strings", + "A list is too large to store in a set", + "Sets keep order and lists do not", + ], + answer: 0, + }, + { + q: "Your code keeps scanning students to find one by name. What is the better fix?", + options: [ + "Build a dict keyed by name once, then look up", + "Sort the list before every search", + "Convert to a set inside the loop each time", + "Switch the list to a tuple", + ], + answer: 0, + }, + { + q: "You think a set would speed up a small lookup. What should you do before changing the code?", + options: [ + "Measure both versions, for example with timeit", + "Always switch, because sets are always faster", + "Never switch, because lists are always faster", + "Add more items so the difference shows", + ], + answer: 0, + }, + ], + "working-with-libraries": [ + { + q: "What does pip freeze > requirements.txt record?", + options: [ + "The exact version of every installed package", + "Only the packages you typed in pip install", + "The newest version available of each package", + "The source code of every installed package", + ], + answer: 0, + }, + { + q: "Your friend has your requirements.txt. Which command installs the same versions?", + options: [ + "pip install -r requirements.txt", + "pip freeze requirements.txt", + "python3 requirements.txt", + "pip upgrade requirements.txt", + ], + answer: 0, + }, + { + q: "Why does the .venv folder belong in .gitignore?", + options: [ + "It can be rebuilt from the requirements and is very large", + "Git cannot store files that start with a dot", + "It contains your passwords", + "Committing it deletes your installed packages", + ], + answer: 0, + }, + { + q: "Which is a warning sign before you depend on a package?", + options: [ + "It has had no release in several years", + "Its licence is MIT", + "It has only a couple of dependencies", + "Its documentation lists every argument", + ], + answer: 0, + }, + ], + "json-and-apis": [ + { + q: "What does json.loads('{\"ok\": true, \"note\": null}') return?", + options: [ + "{'ok': True, 'note': None}", + "{'ok': 'true', 'note': 'null'}", + "{'ok': true, 'note': null}", + "A JSONDecodeError", + ], + answer: 0, + }, + { + q: "You have an open file f holding JSON. Which call reads it?", + options: ["json.load(f)", "json.loads(f)", "json.dumps(f)", "json.read(f)"], + answer: 0, + }, + { + q: "A request returned status 500 with an HTML body. What should you do before calling .json()?", + options: [ + "Check status_code or call raise_for_status()", + "Retry .json() until it succeeds", + "Wrap it in a bare except:", + "Add a longer timeout", + ], + answer: 0, + }, + { + q: "Where should your API key live?", + options: [ + "In an environment variable, read with os.environ", + "Typed directly into the source file", + "In a comment at the top of the script", + "In the URL of every request you make", + ], + answer: 0, + }, + ], + "testing-your-code": [ + { + q: "What does assert add(2, 3) == 5 do when add is correct?", + options: [ + "Nothing at all", + "Prints True", + "Prints 5", + "Returns the value 5", + ], + answer: 0, + }, + { + q: "Which of these is not a real test?", + options: [ + "assert largest([3, 1, 4]) == largest([3, 1, 4])", + "assert largest([3, 1, 4]) == 4", + "assert largest([]) is None", + "assert largest([-5, -2]) == -2", + ], + answer: 0, + }, + { + q: "How does pytest know to pass sample_scores into test_average(sample_scores)?", + options: [ + "It matches the parameter name to a fixture's name", + "It guesses from the type of the argument", + "It reads the comment above the test", + "You must pass it yourself when calling the test", + ], + answer: 0, + }, + { + q: "Your suite reports 100% coverage. What does that prove?", + options: [ + "Every line ran at least once during the tests", + "Every line gives the correct answer", + "The code has no bugs left", + "Every edge case has a test", + ], + answer: 0, + }, + ], + "final-project": [ + { + q: "What does word_counts(\"the cat the\") return in the minimum version?", + options: [ + "{'the': 2, 'cat': 1}", + "{'the': 1, 'cat': 1}", + "{'cat': 1}", + "['the', 'cat', 'the']", + ], + answer: 0, + }, + { + q: "Why does counts[word] = counts.get(word, 0) + 1 never raise KeyError?", + options: [ + "get supplies 0 the first time a word appears", + "Assigning to a key always checks it first", + "The loop skips words it has not seen", + "counts starts with every word set to 0", + ], + answer: 0, + }, + { + q: "The minimum version counts \"cat,\" and \"cat\" separately. What fixes it?", + options: [ + "word.strip(string.punctuation) before counting", + "text.split(\",\") instead of text.split()", + "Using a set instead of a dictionary", + "Calling word.upper() before counting", + ], + answer: 0, + }, + { + q: "Which finds the most common word in counts?", + options: [ + "max(counts, key=counts.get)", + "max(counts)", + "counts.max()", + "sorted(counts)[0]", + ], + answer: 0, + }, + ], +}; From c646986fa5dae9b5a43073bd4f64db95d77422f7 Mon Sep 17 00:00:00 2001 From: srivibhavpadakandla Date: Sat, 10 Oct 2026 16:17:03 -0700 Subject: [PATCH 03/26] ML and computer vision: hand-written quick checks and lesson fixes All 44 chapters get authored questions with hand-checked arithmetic. Fixes the mean-average-precision widget's AP formula, the husky/wolf example, backwards coefficient-size logic in feature scaling and regularisation, the gradient-descent convergence claim, EU AI Act wording, and colour-receptor claims; adds try-it exercises and common-mistake notes. Co-Authored-By: Claude Opus 5.5 --- .../BoundingBoxesAndIouLesson.tsx | 13 +- .../ColourAndChannelsLesson.tsx | 27 +- .../ConfusionMatrixForVisionLesson.tsx | 9 +- .../computer-vision/ConvolutionLesson.tsx | 17 + .../ConvolutionalNeuralNetworksLesson.tsx | 8 +- .../computer-vision/DatasetBiasLesson.tsx | 6 +- .../FaceDetectionAndPrivacyLesson.tsx | 29 +- .../FeatureDetectorsLesson.tsx | 17 + .../FromPrototypeToProductionLesson.tsx | 6 +- .../ImageClassificationLesson.tsx | 20 +- .../ImagePreprocessingLesson.tsx | 14 +- .../computer-vision/ImagesAsNumbersLesson.tsx | 2 +- .../MeanAveragePrecisionLesson.tsx | 9 +- .../NonMaxSuppressionLesson.tsx | 8 +- .../computer-vision/ObjectDetectionLesson.tsx | 5 +- .../OverfittingInVisionLesson.tsx | 5 +- .../computer-vision/ThresholdCurve.tsx | 12 +- .../TransferLearningLesson.tsx | 8 + .../VisionInSelfDrivingCarsLesson.tsx | 11 +- src/components/ml/BaselinesLesson.tsx | 11 +- src/components/ml/ClusteringLesson.tsx | 6 +- src/components/ml/DataLeakageLesson.tsx | 5 +- src/components/ml/DecisionTreesLesson.tsx | 17 +- .../ml/DimensionalityReductionLesson.tsx | 2 +- src/components/ml/FeatureScalingLesson.tsx | 27 +- src/components/ml/GradientDescentLesson.tsx | 50 +- .../ml/KNearestNeighboursLesson.tsx | 9 +- src/components/ml/NeuralNetworksLesson.tsx | 5 +- src/components/ml/PrecisionRecallLesson.tsx | 14 +- src/components/ml/RandomForestsLesson.tsx | 6 +- src/components/ml/RegularisationLesson.tsx | 8 +- src/lib/quizzes/computer-vision.ts | 808 +++++++++++++++- src/lib/quizzes/ml.ts | 878 +++++++++++++++++- 33 files changed, 1957 insertions(+), 115 deletions(-) diff --git a/src/components/computer-vision/BoundingBoxesAndIouLesson.tsx b/src/components/computer-vision/BoundingBoxesAndIouLesson.tsx index 61808d02..78a9384b 100644 --- a/src/components/computer-vision/BoundingBoxesAndIouLesson.tsx +++ b/src/components/computer-vision/BoundingBoxesAndIouLesson.tsx @@ -1,6 +1,7 @@ import { TakeawayCard } from "@/components/learn/primitives/Cards"; import { Lead, LessonSection, P, Strong } from "@/components/learn/primitives/LessonSection"; import { IouDragger } from "@/components/computer-vision/IouDragger"; +import { RevealCard } from "@/components/learn/primitives/RevealCard"; export function BoundingBoxesAndIouLesson() { return ( @@ -40,6 +41,16 @@ export function BoundingBoxesAndIouLesson() { all score 0. Everything a detector actually produces lands somewhere in between, and the interactive below lets you watch that number move.

+
+ +
@@ -65,7 +76,7 @@ export function BoundingBoxesAndIouLesson() {

0.5 is the threshold you will see quoted most often, but it is a convention, not a property of geometry. A benchmark can and does choose differently — some standard - evaluations report accuracy at 0.75, a noticeably stricter bar, and some report a whole + evaluations report results at 0.75, a noticeably stricter bar, and some report a whole curve of scores across every threshold from 0.5 to 0.95 rather than commit to one.

diff --git a/src/components/computer-vision/ColourAndChannelsLesson.tsx b/src/components/computer-vision/ColourAndChannelsLesson.tsx index 97300d95..a8b87150 100644 --- a/src/components/computer-vision/ColourAndChannelsLesson.tsx +++ b/src/components/computer-vision/ColourAndChannelsLesson.tsx @@ -2,6 +2,7 @@ import { Callout } from "@/components/learn/primitives/Callout"; import { CompareGrid, TakeawayCard } from "@/components/learn/primitives/Cards"; import { InlineCode } from "@/components/learn/primitives/CodeBlock"; import { Lead, LessonSection, P, Strong } from "@/components/learn/primitives/LessonSection"; +import { RevealCard } from "@/components/learn/primitives/RevealCard"; export function ColourAndChannelsLesson() { return ( @@ -27,7 +28,7 @@ export function ColourAndChannelsLesson() { channel until you ask a specific question about a specific image.

- + combined @@ -41,9 +42,9 @@ export function ColourAndChannelsLesson() { G = 206 - + + B = 235 - B = 235
@@ -59,9 +60,11 @@ export function ColourAndChannelsLesson() { 0.299R + 0.587G + 0.114B, not a plain average of the three.

- Green gets nearly five times the weight of blue because human vision is - far more sensitive to green light — your eye has more receptors tuned to that part of - the spectrum than to red or blue. A grayscale conversion that used equal weights would + Green gets about five times the weight of blue because human brightness + perception peaks in the green part of the spectrum: the cones that respond to red and to + green both respond strongly there, while blue-sensitive cones are comparatively few and + contribute little to how bright something looks. A grayscale conversion that used equal + weights would produce a technically valid image that looked wrong to every person who looked at it, because it would not match how brightness actually registers for a human observer.

@@ -71,6 +74,16 @@ export function ColourAndChannelsLesson() { convert to the same grey. The weighting is tuned to human perception, not to the raw light hitting the sensor.
+
+ +
@@ -142,7 +155,7 @@ export function ColourAndChannelsLesson() {

- Click through the matrix above and one pair dominates. Cats, dogs and foxes are each - confused with something else once or twice out of fifty — noise, essentially. Wolves and + Click through the matrix above and one pair dominates. Cats, dogs and foxes each lose + only three or four photos out of fifty, scattered one or two at a time across the other + classes — noise, essentially. Wolves and coyotes are a different story: 19 wolves called coyotes, 21 coyotes called wolves, out of 50 of each. That is 40 of the 54 total errors in the entire matrix, from one pair of classes out of five.

That number changes what you would do next. Improving every class’s accuracy by a - point each is 5 points of work for a few points of overall gain. Fixing the wolf/coyote + point each is five separate pieces of work for one point of overall gain. Fixing the wolf/coyote confusion alone — better ear and muzzle features, more training photos of exactly this pair side by side — recovers up to 40 of the 54 errors on its own, which would push - accuracy from 78.4% into the low-to-mid 90s. The matrix tells you where to spend + accuracy from 78.4% to as high as 94.4%. The matrix tells you where to spend the next month, and the single number never could.

diff --git a/src/components/computer-vision/ConvolutionLesson.tsx b/src/components/computer-vision/ConvolutionLesson.tsx index a0bca882..939248d1 100644 --- a/src/components/computer-vision/ConvolutionLesson.tsx +++ b/src/components/computer-vision/ConvolutionLesson.tsx @@ -3,6 +3,7 @@ import { TakeawayCard } from "@/components/learn/primitives/Cards"; import { InlineCode } from "@/components/learn/primitives/CodeBlock"; import { Lead, LessonSection, P, Strong } from "@/components/learn/primitives/LessonSection"; import { KernelSlider } from "@/components/computer-vision/KernelSlider"; +import { RevealCard } from "@/components/learn/primitives/RevealCard"; export function ConvolutionLesson() { return ( @@ -71,6 +72,22 @@ export function ConvolutionLesson() { to roughly the same value. Where the centre is a genuine anomaly, the subtraction exaggerates it instead of averaging it away.

+
+ +
+ + Strictly, the textbook definition of convolution flips the kernel before sliding it. + Image libraries and neural networks almost always skip the flip — the operation they + run is technically called cross-correlation — and for symmetric kernels like blur and + sharpen the two give identical results. + Edge detection, sharpening, blurring and the very first layer of a neural network’s convolution are all this same slide-multiply-sum procedure. What changes between all of diff --git a/src/components/computer-vision/ConvolutionalNeuralNetworksLesson.tsx b/src/components/computer-vision/ConvolutionalNeuralNetworksLesson.tsx index f25b2dff..7403c914 100644 --- a/src/components/computer-vision/ConvolutionalNeuralNetworksLesson.tsx +++ b/src/components/computer-vision/ConvolutionalNeuralNetworksLesson.tsx @@ -51,7 +51,7 @@ export function ConvolutionalNeuralNetworksLesson() { simply what a network with a 3×3 window and one layer of depth is capable of noticing, and so edges are what it converges on.

- + This is not a claim you have to take on faith. Feature visualisation techniques let you render exactly what pattern makes each first-layer kernel fire most strongly, and across published networks the result looks the same: a bank of oriented edges and colour @@ -92,8 +92,10 @@ export function ConvolutionalNeuralNetworksLesson() { The second is reach. A single 3×3 kernel in the first layer only ever looks at nine pixels. Stack five layers of 3×3 kernels and the fifth layer’s output at any position is influenced by roughly an 11×11 patch of the original image — its{" "} - receptive field. Stack thirty and that patch can cover most of the - photo. Depth is how a network built from small, local operations ends up seeing + receptive field. Each 3×3 layer adds two pixels to the width, so n + layers see a patch 2n + 1 pixels across. Real networks also shrink the grid between + layers with pooling or larger strides, which makes the patch grow much faster, so by + thirty layers it can cover most of the photo. Depth is how a network built from small, local operations ends up seeing something global.

diff --git a/src/components/computer-vision/DatasetBiasLesson.tsx b/src/components/computer-vision/DatasetBiasLesson.tsx index 0e7242d9..084fde07 100644 --- a/src/components/computer-vision/DatasetBiasLesson.tsx +++ b/src/components/computer-vision/DatasetBiasLesson.tsx @@ -45,9 +45,9 @@ export function DatasetBiasLesson() {

This is not hypothetical. Joy Buolamwini and Timnit Gebru’s 2018 “Gender - Shades” study tested three commercial facial-analysis systems and found error rates - on darker-skinned women running as high as 34%, against under 1% for lighter-skinned men - on the same systems. The gap was not a mysterious algorithmic quirk — it traced directly + Shades” study tested three commercial systems that classify the gender of a face and + found error rates on darker-skinned women running as high as 34%, against under 1% for + lighter-skinned men on the same systems. The gap was not a mysterious algorithmic quirk — it traced directly back to benchmark and training datasets that were overwhelmingly lighter-skinned and male.

diff --git a/src/components/computer-vision/FaceDetectionAndPrivacyLesson.tsx b/src/components/computer-vision/FaceDetectionAndPrivacyLesson.tsx index c964c4ad..269519c0 100644 --- a/src/components/computer-vision/FaceDetectionAndPrivacyLesson.tsx +++ b/src/components/computer-vision/FaceDetectionAndPrivacyLesson.tsx @@ -55,9 +55,12 @@ export function FaceDetectionAndPrivacyLesson() { title="Error rates that are not even across faces" >

- The previous chapter’s Gender Shades findings apply directly here, and soberly: that + The Gender Shades findings from the dataset bias chapter apply here, and soberly: that research measured commercial facial-analysis error rates as high as 34% for darker-skinned - women against under 1% for lighter-skinned men, on systems already deployed commercially. + women against under 1% for lighter-skinned men, on systems already sold commercially. + Gender Shades tested gender classification rather than identity matching, but the U.S. + government’s own testing of face recognition algorithms in 2019 also found error + rates that varied across demographic groups for many of the systems it evaluated. A wrongful match from a recognition system is not an abstract inconvenience — it can mean being stopped, questioned, or investigated for something you did not do.

@@ -71,19 +74,19 @@ export function FaceDetectionAndPrivacyLesson() {

- None of this stayed theoretical. Several cities and police departments in the United - States have restricted or banned police use of facial recognition outright, after - documented wrongful arrests traced back to recognition errors. A number of large - companies paused or ended sales of facial recognition to law enforcement following the - same evidence. + None of this stayed theoretical. Several U.S. cities have restricted or banned police + use of facial recognition outright, and documented wrongful arrests traced back to false + matches have since strengthened the case for limits. In 2020, amid public scrutiny that + included independent audits of uneven error rates, a number of large companies paused or + ended sales of facial recognition to police.

@@ -97,8 +100,8 @@ export function FaceDetectionAndPrivacyLesson() { items={[ "Face detection answers 'is there a face here'; face recognition additionally matches that face against a known identity — two different technical steps routinely described as one.", "Unlocking your own phone is recognition you consented to, for a database of one; a public camera matching strangers against a database they never joined is the same technology under an opposite consent situation.", - "Documented research found facial-recognition error rates far higher for darker-skinned women than for lighter-skinned men, meaning the harm of a wrongful match falls unevenly.", - "Real, documented wrongful arrests led multiple cities and companies to restrict or end police use of facial recognition.", + "Documented research found facial-analysis error rates far higher for darker-skinned women than for lighter-skinned men, so the harm of a wrong answer falls unevenly.", + "Multiple cities and companies have restricted or ended police use of facial recognition, and documented wrongful arrests from false matches have strengthened the case for limits.", "The EU's GDPR and AI Act specifically single out biometric identification for stricter rules — this is already shaped policy, not a hypothetical concern.", ]} /> diff --git a/src/components/computer-vision/FeatureDetectorsLesson.tsx b/src/components/computer-vision/FeatureDetectorsLesson.tsx index a167759a..d1b0716f 100644 --- a/src/components/computer-vision/FeatureDetectorsLesson.tsx +++ b/src/components/computer-vision/FeatureDetectorsLesson.tsx @@ -43,7 +43,14 @@ export function FeatureDetectorsLesson() { not the sharpness of the angle, is what a corner detector is actually testing for, and it is exactly what makes a corner locatable again in a second photo.

+

+ An edge sits in between. Slide the window across an edge and the view changes sharply; + slide it along the edge and it barely changes at all. That makes an edge locatable in one + direction and ambiguous in the other, which is why detectors prefer corners, where no + direction is ambiguous. +

), }, + { + title: "Edge", + tone: "neutral", + children: ( +

+ Shift across the edge and the pixels change; shift along it and they do not. You + can pin down one direction, never both. +

+ ), + }, { title: "Corner", tone: "positive", diff --git a/src/components/computer-vision/FromPrototypeToProductionLesson.tsx b/src/components/computer-vision/FromPrototypeToProductionLesson.tsx index 6d281b4e..c287628c 100644 --- a/src/components/computer-vision/FromPrototypeToProductionLesson.tsx +++ b/src/components/computer-vision/FromPrototypeToProductionLesson.tsx @@ -59,7 +59,9 @@ export function FromPrototypeToProductionLesson() { A live video feed at 30 frames per second hands the model a new frame every 33 milliseconds, whether or not it has finished with the last one. A large, highly accurate model that takes 200 milliseconds per frame is not a slower version of a usable system — - it is unusable at that frame rate, full stop, regardless of how it scored offline. + it cannot keep up with that frame rate, regardless of how it scored offline. The only way + to run it is to skip five frames in every six, and whatever happens in those gaps goes + unseen.

This is a genuine trade-off against accuracy, not an implementation footnote to solve @@ -108,7 +110,7 @@ export function FromPrototypeToProductionLesson() { items={[ "A benchmark score is a fact about a static test set measured once; it is not a promise about a continuous, real-time production camera feed.", "Deployed cameras drift from what the model trained on through scratched lenses, seasonal white-balance shifts, and newer sensor generations, and the decline is usually gradual, not dramatic.", - "At 30 frames per second a model has roughly 33 milliseconds per frame; a 200-millisecond model is unusable at that rate regardless of its offline accuracy.", + "At 30 frames per second a model has roughly 33 milliseconds per frame; a 200-millisecond model can only keep up by skipping most frames, regardless of its offline accuracy.", "Choosing a smaller, faster, slightly less accurate model to fit the latency budget is a genuine engineering trade-off, not a footnote to accept reluctantly.", "Production traffic has no automatic ground truth, so monitoring means watching proxy signals — confidence-score drift, spikes in low-confidence predictions, user corrections — rather than a clean accuracy number.", ]} diff --git a/src/components/computer-vision/ImageClassificationLesson.tsx b/src/components/computer-vision/ImageClassificationLesson.tsx index 00947b46..5d9d5485 100644 --- a/src/components/computer-vision/ImageClassificationLesson.tsx +++ b/src/components/computer-vision/ImageClassificationLesson.tsx @@ -22,7 +22,7 @@ export function ImageClassificationLesson() {

That narrowness is the whole design, not a limitation someone forgot to - fix. Detection and segmentation, two chapters ahead, exist specifically to + fix. Detection and segmentation, later in this track, exist specifically to answer the questions classification refuses to.

@@ -52,13 +52,13 @@ export function ImageClassificationLesson() { title="What a confident wrong answer looks like" >

- A well-known example: a model trained to tell huskies from wolves reported 97% - confidence on a photo of a wolf standing in a grassy field — correctly, this time, - identifying it as a wolf, but for the wrong reason entirely. In earlier tests the same - model had called wolves “husky” whenever the photo had snow in the - background, because most of its husky training photos happened to have snow in them - and most of its wolf photos did not. The model had learned to detect snow, not dogs, - and reported startling confidence while doing it. + A well-known demonstration from research on explaining classifiers: a model was + trained to tell huskies from wolves on photos where the wolves were nearly always + pictured against snow. It then labelled a husky standing in snow as a wolf. When the + researchers asked which parts of the image drove the decision, the answer was mostly + the snow, not the animal. The model had learned to detect snow, not wolves, and on + most of its test photos that shortcut happened to give the right answer — which is + exactly why nobody would have noticed from the accuracy alone.

A confidence score describes how sure the model is, not how right it @@ -100,8 +100,8 @@ export function ImageClassificationLesson() { tone: "neutral", children: (

- Right if the true label is anywhere in the model’s five best guesses. Always - the higher number, and quietly a lower bar. + Right if the true label is anywhere in the model’s five best guesses. Never + lower than top-1, and quietly a lower bar.

), }, diff --git a/src/components/computer-vision/ImagePreprocessingLesson.tsx b/src/components/computer-vision/ImagePreprocessingLesson.tsx index d0fde7dd..97a5012c 100644 --- a/src/components/computer-vision/ImagePreprocessingLesson.tsx +++ b/src/components/computer-vision/ImagePreprocessingLesson.tsx @@ -69,7 +69,9 @@ export function ImagePreprocessingLesson() { Normalising fixes the scale rather than the content: divide every pixel by 255 to land in the 0–1 range, or subtract the dataset’s mean and divide by its standard deviation so brightness differences between photos stop swamping the differences that actually - matter — edges, shapes, colour. + matter — edges, shapes, colour. If you use a dataset mean and standard deviation, + compute them from the training photos only, and reuse those same two numbers on every + validation, test and live image.

@@ -101,6 +103,15 @@ export function ImagePreprocessingLesson() { place.
+ + First, an augmentation must not change the right answer. Rotate a handwritten 6 by 180 + degrees and it becomes a 9 that is still labelled 6; flip a photo of text left to right + and it stops being text. Pick only the transformations your real inputs could plausibly + go through. Second, augment the training set only. Validation and test photos should look + like the real inputs the model will meet, so they get resized and normalised, never + randomly rotated or relit. + +
diff --git a/src/components/computer-vision/ImagesAsNumbersLesson.tsx b/src/components/computer-vision/ImagesAsNumbersLesson.tsx index 0233857d..c81a8392 100644 --- a/src/components/computer-vision/ImagesAsNumbersLesson.tsx +++ b/src/components/computer-vision/ImagesAsNumbersLesson.tsx @@ -35,7 +35,7 @@ export function ImagesAsNumbersLesson() { Click any square in the grid above and the value it shows is the entire content of that pixel — one integer, from 0 to 255, for a grayscale image. Nothing else is stored there. 0 is black, 255 is white, and everything between is a shade of grey with - no unit finer than a whole number: 255 possible steps and not one more. + no unit finer than a whole number: 256 possible values and not one more.

A colour pixel is not one number, it is three — one each for red, green and blue, diff --git a/src/components/computer-vision/MeanAveragePrecisionLesson.tsx b/src/components/computer-vision/MeanAveragePrecisionLesson.tsx index 15b3ad47..049d60da 100644 --- a/src/components/computer-vision/MeanAveragePrecisionLesson.tsx +++ b/src/components/computer-vision/MeanAveragePrecisionLesson.tsx @@ -61,8 +61,11 @@ export function MeanAveragePrecisionLesson() { jagged curve to stand.

- Average precision sidesteps the choice: instead of one threshold, take - the precision value at every point along the sweep and average them. It is a way of + Average precision sidesteps the choice: instead of one threshold, walk + down the sorted list and note the precision each time another real object is caught. + Add those up and divide by the number of real objects in the scene — so an object the + detector never found contributes zero. In the panel above that is (1 + 1 + 1 + 0.8 + + 0.83 + 0.75) / 8 ≈ 0.67. It is a way of scoring the whole trade-off curve with one number instead of committing to a threshold nobody agreed on in advance. Mean average precision then averages that score again, across every object class the detector was tested on — one AP for @@ -82,7 +85,7 @@ export function MeanAveragePrecisionLesson() {

It also treats every miss as equally costly, which is never true in practice. A detector that misses a parked car and one that misses a pedestrian stepping into the road produce - the same one-point deduction to AP, and only one of those two failures matters at + the same deduction from AP, and only one of those two failures matters at highway speed. A single mAP number is a fair summary of overall detection quality and a poor guide to which failures you can actually tolerate.

diff --git a/src/components/computer-vision/NonMaxSuppressionLesson.tsx b/src/components/computer-vision/NonMaxSuppressionLesson.tsx index 8b1e6a2f..f971482f 100644 --- a/src/components/computer-vision/NonMaxSuppressionLesson.tsx +++ b/src/components/computer-vision/NonMaxSuppressionLesson.tsx @@ -48,6 +48,11 @@ export function NonMaxSuppressionLesson() { It is one dog, described twice. Suppressing the extra box loses nothing; keeping it would double-count the same animal in the final result.

+

+ In practice this runs separately for each class. A box labelled “dog” never + suppresses a box labelled “person”, however much they overlap — someone + holding a puppy is two objects, not one described twice. +

@@ -67,7 +72,8 @@ export function NonMaxSuppressionLesson() { survive, because none of them overlap each other by quite enough to trip the threshold, and your final output still reports several dogs where there is one.{" "} There is no threshold that is safe for every photo; it is tuned against - a validation set, the same way the IoU threshold in the last lesson was. + a validation set that looks like the scenes you expect. Crowded scenes, where real + objects genuinely overlap, usually want a higher threshold than sparse ones.

diff --git a/src/components/computer-vision/ObjectDetectionLesson.tsx b/src/components/computer-vision/ObjectDetectionLesson.tsx index 1932130c..8d05fc01 100644 --- a/src/components/computer-vision/ObjectDetectionLesson.tsx +++ b/src/components/computer-vision/ObjectDetectionLesson.tsx @@ -54,9 +54,8 @@ export function ObjectDetectionLesson() { The next idea is to run the classifier again and again, on every possible rectangle the image could contain — every position, every width, every height. A modest 224×224 photo has tens of thousands of plausible box positions at just a handful of sizes; check every - size at every position and you are into the millions. That is a combinatorial explosion, - not a plan, and it is exactly the problem the next two lessons exist to avoid solving the - brute-force way. + size at every position and you are into the hundreds of millions. That is a combinatorial + explosion, not a plan, and it is why real detectors take a different route.

diff --git a/src/components/computer-vision/OverfittingInVisionLesson.tsx b/src/components/computer-vision/OverfittingInVisionLesson.tsx index 90997eea..63caad92 100644 --- a/src/components/computer-vision/OverfittingInVisionLesson.tsx +++ b/src/components/computer-vision/OverfittingInVisionLesson.tsx @@ -88,8 +88,9 @@ export function OverfittingInVisionLesson() { being a defence against the actual signal in the photo.

- “More augmentation is always better” is false in exactly the way “more - training data is always better” usually is not. Past the point where validation + More real training data rarely hurts. More augmentation can, because every extra unit + of strength moves the images further from anything the model will really see. Past the + point where validation accuracy peaks, every additional unit of augmentation strength is pure cost. Find that peak on validation data specifically — not on training accuracy, which will look fine right up until the augmentation is destroying the images. diff --git a/src/components/computer-vision/ThresholdCurve.tsx b/src/components/computer-vision/ThresholdCurve.tsx index 82bae3df..b91597e8 100644 --- a/src/components/computer-vision/ThresholdCurve.tsx +++ b/src/components/computer-vision/ThresholdCurve.tsx @@ -51,8 +51,18 @@ const CURVE: readonly CurvePoint[] = Array.from({ length: DETECTIONS.length + 1 }; }); +/** + * Standard (non-interpolated) average precision: the precision at each rank + * where a correct detection is added, summed and divided by the number of + * real objects. Objects that were never detected contribute zero, so the two + * missed objects pull AP down — averaging precision over every cut-off, + * correct or not, would ignore them. + */ const AVERAGE_PRECISION = - CURVE.slice(1).reduce((sum, point) => sum + (point.precision ?? 0), 0) / DETECTIONS.length; + CURVE.slice(1).reduce( + (sum, point, index) => (DETECTIONS[index].correct ? sum + (point.precision ?? 0) : sum), + 0, + ) / TOTAL_GROUND_TRUTH; /** The recall ceiling: even flagging every detection never recovers the two * ground-truth objects nothing was ever proposed for. */ diff --git a/src/components/computer-vision/TransferLearningLesson.tsx b/src/components/computer-vision/TransferLearningLesson.tsx index a9109a0b..591c6cd1 100644 --- a/src/components/computer-vision/TransferLearningLesson.tsx +++ b/src/components/computer-vision/TransferLearningLesson.tsx @@ -69,6 +69,14 @@ export function TransferLearningLesson() { up to the last, doing the seeing; the head is the final layer, doing the naming. Transfer learning keeps the body and swaps the head. +

+ Freezing everything is the cautious end of a dial. With a few thousand photos rather + than a few hundred, a common next step is fine-tuning: once the new + head has trained, unfreeze the last few layers of the body as well and keep training + with a small learning rate, so the later, more specific features can adjust to your + images without wiping out what the early layers already know. With very little data, + leave the body frozen; there is not enough to adjust it without overfitting. +

- A car moving at highway speed covers roughly 30 metres every second. Convert that to + A car moving at highway speed — about 110 km/h — covers roughly 30 metres every + second. Convert that to something more concrete: a vision pipeline that takes 200 milliseconds to decide “object ahead, brake” has already let the car travel about 6 metres before the decision even exists, before the brakes have engaged at all. @@ -39,10 +40,10 @@ export function VisionInSelfDrivingCarsLesson() { it is measuring the same thing your eyes measure: visible light bouncing off surfaces.

- That is why no production self-driving system trusts a camera by itself. Radar keeps + That is why most self-driving systems do not trust a camera by itself. Radar keeps working in rain, fog and darkness that would blind a camera, and measures distance and closing speed directly and precisely — but it is weak at telling you what kind of object - it found, a plastic bag and a small dog can look similar to it. Lidar gives precise 3D + it found, and a stationary car and an overhead sign can be hard for it to tell apart. Lidar gives precise 3D distance to every surface it hits regardless of lighting, at real hardware cost, and can struggle with dark or reflective surfaces that absorb or scatter its laser pulses.

@@ -118,8 +119,8 @@ export function VisionInSelfDrivingCarsLesson() { - + Run the tree on its own and you get 76.0%, on a problem where chance is about 50%. Written in a slide with no baseline beside it, that reads as a working model. It is a working model that is worse than one line of code, and only the baseline says so. @@ -123,10 +123,11 @@ export function BaselinesLesson() { /> - You have reached the end of the track. You know what a model is, how one learns, three - ways to build one, and — through five chapters of Part 4 — most of the ways a score can - lie to you. That last part is the difference between running a library and doing the - work, and it is not what most introductions spend their time on. + That is the end of the fundamentals. You know what a model is, how one learns, three + ways to build one, and — across Parts 2 and 4 — most of the ways a score can lie to + you. That last part is the difference between running a library and doing the work. + Parts 5 and 6 go further: learning without labels, and what the optimiser is actually + doing under the fit.
diff --git a/src/components/ml/ClusteringLesson.tsx b/src/components/ml/ClusteringLesson.tsx index 05886958..22ea178f 100644 --- a/src/components/ml/ClusteringLesson.tsx +++ b/src/components/ml/ClusteringLesson.tsx @@ -18,8 +18,8 @@ export function ClusteringLesson() {

- Look back at Part 4. Train/test splitting, cross-validation, precision and recall — all - of it assumed somebody had already written down the right answer for every example, so + Look back at Parts 2 and 4. Train/test splitting, cross-validation, precision and + recall — all of it assumed somebody had already written down the right answer for every example, so the model’s answer could be compared against it. That comparison is the entire honesty toolbox. Take away the right answers and every tool in it stops working, not because the problem got harder, but because the ingredient they all need is gone. @@ -172,7 +172,7 @@ export function ClusteringLesson() { Notice that this single careless line commits two leaks at once. It ignores time{" "} and puts the reapplications back on both sides. That is the normal case. Real - pipelines rarely have one clean flaw; they have a default `train_test_split` call and - a table nobody interrogated. + pipelines rarely have one clean flaw; they have a default{" "} + train_test_split call and a table nobody interrogated.

diff --git a/src/components/ml/DecisionTreesLesson.tsx b/src/components/ml/DecisionTreesLesson.tsx index 24d660a4..5953cb40 100644 --- a/src/components/ml/DecisionTreesLesson.tsx +++ b/src/components/ml/DecisionTreesLesson.tsx @@ -2,6 +2,7 @@ import { Callout } from "@/components/learn/primitives/Callout"; import { TakeawayCard } from "@/components/learn/primitives/Cards"; import { Lead, LessonSection, P, Strong } from "@/components/learn/primitives/LessonSection"; import { TreeSplitter } from "@/components/ml/TreeSplitter"; +import { RevealCard } from "@/components/learn/primitives/RevealCard"; export function DecisionTreesLesson() { return ( @@ -41,8 +42,10 @@ export function DecisionTreesLesson() {

That mess has a number. Gini impurity asks: if you picked a flat from this group at random and guessed its outcome using nothing but the group's own - proportions, how often would you be wrong? An even 50/50 split scores 0.5, the worst - possible. A group where every flat agrees scores 0. + proportions, how often would you be wrong? With two outcomes, an even 50/50 split + scores 0.5, the worst possible. A group where every flat agrees scores 0. The formula + is one minus the sum of each outcome's share squared, so a group that is 80/20 scores + 1 − (0.8² + 0.2²) = 0.32.

To score a candidate split, measure the impurity of both sides, weight each by how many @@ -51,6 +54,16 @@ export function DecisionTreesLesson() { keeps the largest gain. On this data the winner is rent at £697, worth 0.185 — close to the £700 the flats were actually generated around.

+
+ +
diff --git a/src/components/ml/DimensionalityReductionLesson.tsx b/src/components/ml/DimensionalityReductionLesson.tsx index 07f2b764..abce15f1 100644 --- a/src/components/ml/DimensionalityReductionLesson.tsx +++ b/src/components/ml/DimensionalityReductionLesson.tsx @@ -9,7 +9,7 @@ export function DimensionalityReductionLesson() {
You would expect forty columns of data to teach a model forty times what one column - does. It teaches something closer to four or five times as much, once the columns start + does. It usually teaches far less than that, once the columns start repeating each other and the space between points stops meaning what you think it means. This lesson is about the gap between the columns you were handed and the information actually sitting inside them. diff --git a/src/components/ml/FeatureScalingLesson.tsx b/src/components/ml/FeatureScalingLesson.tsx index 5890dee5..b251abb4 100644 --- a/src/components/ml/FeatureScalingLesson.tsx +++ b/src/components/ml/FeatureScalingLesson.tsx @@ -66,6 +66,13 @@ export function FeatureScalingLesson() { Min-max earns its place when the bounds are known and fixed, such as a pixel value that is always 0 to 255.

+

+ A worked example makes both concrete. Take an income column whose training values run + from $18,000 to $240,000, with a mean of $60,000 and a standard deviation of $30,000. + An applicant earning $45,000 becomes (45,000 − 18,000) / 222,000 ≈ 0.12 under min-max, + and (45,000 − 60,000) / 30,000 = −0.5 under standardisation: half a standard deviation + below the average earner. +

@@ -94,10 +101,10 @@ export function FeatureScalingLesson() { entire prediction, or the entire grouping, is a distance calculation.

- SVMs, and anything with a gradient-based penalty on its coefficients — a - column with a huge range needs a huge coefficient to matter, and the penalty - punishes huge coefficients specifically, regardless of whether the size is - doing real work. + SVMs, and any model with a penalty on the size of its coefficients, such as + ridge or lasso — a column with a tiny range needs a huge coefficient to + matter, and the penalty punishes huge coefficients specifically, regardless of + whether the size is doing real work.

PCA — it finds the directions of largest variance, and a column measured in @@ -105,8 +112,8 @@ export function FeatureScalingLesson() { not it carries more signal.

- Neural networks are scale-invariant in principle and slow in practice — - unscaled inputs drag convergence out for far longer than it needs to take. + Neural networks can in principle learn to compensate for any scale, but in + practice unscaled inputs make training slow and unstable.

), @@ -124,8 +131,8 @@ export function FeatureScalingLesson() { A split like income > 50,000 asks a yes-or-no question about order, not magnitude. Multiply every income by a thousand, or subtract off the mean, and the same applicants land on the same side of the - same split. Any monotonic rescaling leaves a tree-based model byte-for-byte - unchanged. + same split. Any order-preserving rescaling moves the cut-off values but leaves + every prediction exactly as it was.

), @@ -187,8 +194,8 @@ train, test = random_split(features_scaled, 0.33)`} items={[ "Euclidean distance adds squared differences in whatever units it is handed, so a column with a wide range dominates before anybody decided it should.", "Min-max squashes a column onto [0, 1] and is at the mercy of a single outlier; standardisation centres on the mean and divides by the standard deviation, and shrugs one off.", - "k-NN, k-means, SVMs, PCA, anything with a gradient-based penalty, and neural networks all care about scale.", - "Decision trees and the ensembles built from them do not — a split like “income > 50,000” survives any monotonic rescaling untouched.", + "k-NN, k-means, SVMs, PCA, penalised models like ridge and lasso, and neural networks all care about scale.", + "Decision trees and the ensembles built from them do not — a split like “income > 50,000” gives the same answers after any order-preserving rescaling.", "Fit the scaler on the training fold only, and carry its saved numbers into the test fold. Computing them over the whole dataset leaks test information into training.", ]} /> diff --git a/src/components/ml/GradientDescentLesson.tsx b/src/components/ml/GradientDescentLesson.tsx index 17bae59c..ecf27b38 100644 --- a/src/components/ml/GradientDescentLesson.tsx +++ b/src/components/ml/GradientDescentLesson.tsx @@ -3,13 +3,14 @@ import { LabelRows, TakeawayCard } from "@/components/learn/primitives/Cards"; import { CodeBlock, InlineCode } from "@/components/learn/primitives/CodeBlock"; import { Lead, LessonSection, P, Strong } from "@/components/learn/primitives/LessonSection"; import { DescentStepper } from "@/components/ml/DescentStepper"; +import { RevealCard } from "@/components/learn/primitives/RevealCard"; export function GradientDescentLesson() { return (
- You just found the bottom of a bowl by hand — one slider, thirty-six trips, an eyeball - for which direction felt better. That worked because there was exactly one number to + Back in chapter three you found the bottom of a bowl by hand — one slider, thirty-six + trips, an eyeball for which direction felt better. That worked because there was exactly one number to move. This lesson is about the moment there is more than one, and why the search has to change shape entirely once eyeballing it stops being an option. @@ -17,7 +18,7 @@ export function GradientDescentLesson() {

Try every value of one number at a resolution of a hundred steps and that is a hundred - tries — an afternoon, and more or less what the last lesson’s bowl already was: a + tries — an afternoon, and more or less what chapter three’s bowl already was: a curve you could have plotted point by point and read the bottom off with your eyes.

@@ -27,7 +28,8 @@ export function GradientDescentLesson() { the tenth power tries. A small neural network has on the order of a million numbers to set, which puts the count at a hundred raised to the millionth power — a figure with no name worth learning, because the point is not the size of the number, it is that grid - search does not slow down as parameters increase. It stops being an option at all. + search does not merely slow down as parameters increase. It stops being an option at + all.

The shape of the search has to change. Instead of trying values, you need a way to be @@ -44,10 +46,10 @@ export function GradientDescentLesson() { are standing, nothing more, and nothing about the rest of the curve required.

- The last lesson’s widget already computed this every time you dragged its slider. - A badge told you which way to nudge the number, and that badge was reading the{" "} + Chapter three’s widget already computed this every time you dragged its slider. + Its “which way is downhill?” panel told you which way to nudge the number, and that panel was reading the{" "} sign of the derivative — positive or negative, downhill left or downhill - right. Gradient descent is that badge with nobody left to read it: the sign alone + right. Gradient descent is that panel with nobody left to read it: the sign alone chooses a direction, and once there is more than one number to move, the same idea applied to all of them at once gets a new name, the gradient.

@@ -63,8 +65,21 @@ export function GradientDescentLesson() { line, once each, every step.

- Set a rate below and press Step. Nobody is dragging anything - this time — watch what the loop does on its own. + Before you try the widget, run one step by hand. +

+
+ +
+

+ Now set a rate below and press Step. Nobody is dragging + anything this time — watch what the loop does on its own.

@@ -76,7 +91,9 @@ export function GradientDescentLesson() { suggests. At 0.001 the direction is right every single step and the pace is not: after fifty steps the parameter has crept from 0.5 to 4.54, a little over half the distance to the target of 7.8, with the error still sitting at 85.37 against a - floor of 0.4. Fifty more steps would close less than half of what is left. + floor of 0.4. Each step closes the same small fraction of whatever gap remains, so + fifty more steps would close only about the same share again — the gap shrinks, but + never in a hurry.

At 0.03 the same loop reaches 7.761 — within the widget’s own @@ -124,9 +141,9 @@ export function GradientDescentLesson() { card, never handed the wheel.

- You will meet five more words attached to this exact loop before the next chapter is - through. Each one changes a single part of it and none of them replace the update rule - above: + You will meet five more words attached to this exact loop as soon as you read about + training real models. Each one changes a single part of it and none of them replace the + update rule above:

- Every one of those is a variation on the four-word line you already have. The next - lesson stacks that same loop underneath something with vastly more numbers to move — a - neural network — and the loop itself does not change. Only the size of the bowl does. + Every one of those is a variation on the one-line rule you already have. Two chapters + from now, the neural networks lesson stacks that same loop underneath something with + vastly more numbers to move, and the loop itself does not change. Only the size of the + bowl does.

diff --git a/src/components/ml/KNearestNeighboursLesson.tsx b/src/components/ml/KNearestNeighboursLesson.tsx index a14875c2..97cbece1 100644 --- a/src/components/ml/KNearestNeighboursLesson.tsx +++ b/src/components/ml/KNearestNeighboursLesson.tsx @@ -71,8 +71,9 @@ export function KNearestNeighboursLesson() { With two classes and an even k, a vote can tie, and then the model needs a tie-break rule that has nothing to do with the data. Using odd k sidesteps the problem - entirely. With three or more classes ties come back regardless, and most libraries - break them by falling back to the single nearest neighbour. + entirely. With three or more classes ties come back regardless, and the library then + settles them by a fixed rule — often simply whichever class it happens to list first — + which is a choice about code, not evidence from the data. @@ -85,8 +86,8 @@ export function KNearestNeighboursLesson() { “Nearest” means nearest by some measurement, and the obvious measurement is straight-line distance. Revision hours run from 0 to 12. Previous scores run from 20 to 100. A gap of ten points on the previous exam and a gap of ten hours of revision count - the same in that sum — and since the score axis is roughly eight times wider, it - contributes roughly eight times as much. The model is not weighing your features. Your + the same in that sum — and since the score axis is nearly seven times wider, a typical + gap along it is nearly seven times bigger, and it dominates the distance. The model is not weighing your features. Your units are.

diff --git a/src/components/ml/NeuralNetworksLesson.tsx b/src/components/ml/NeuralNetworksLesson.tsx index 91a46b1a..4dc73e34 100644 --- a/src/components/ml/NeuralNetworksLesson.tsx +++ b/src/components/ml/NeuralNetworksLesson.tsx @@ -89,8 +89,9 @@ export function NeuralNetworksLesson() { At zero hidden units the widget above is exactly the straight-line model from the first section, and it shows: 62.5% on the points it trained on, 61.7% on the ones it did not — barely past guessing, because half of each ring sits on either side of any line you - could draw. One or two units bend that line slightly and buy almost nothing (69.2%, - then 85.0% training accuracy, with validation trailing well behind at 63.3% and 68.3%). + could draw. One or two units bend that line and help on the training points (69.2%, + then 85.0%), but validation trails well behind at 63.3% and 68.3% — the folds are not + yet in the right places to trace a ring. By three units the fold count catches up with the shape: 99.2% training accuracy, 93.3% held back. Five is where this particular ring stops needing help — 98.3% on data it never trained on, the best any width reaches here. Pushing on to eight buys nothing diff --git a/src/components/ml/PrecisionRecallLesson.tsx b/src/components/ml/PrecisionRecallLesson.tsx index 8aef7fef..4dc8015f 100644 --- a/src/components/ml/PrecisionRecallLesson.tsx +++ b/src/components/ml/PrecisionRecallLesson.tsx @@ -1,4 +1,5 @@ import { Reveal } from "@/components/Reveal"; +import { RevealCard } from "@/components/learn/primitives/RevealCard"; import { ThresholdExplorer } from "@/components/ml/ThresholdExplorer"; const SCENARIOS = [ @@ -127,7 +128,7 @@ export function PrecisionRecallLesson() { Arranged in a grid, these four counts are called a{" "} confusion matrix. It is not a thing to memorise — it is just these four numbers in a box. Precision and recall are each - built from three of them. + built from two of them, and they share one: the true positives.

@@ -235,6 +236,17 @@ export function PrecisionRecallLesson() { lopsidedness. Take the extreme case — precision 1.0, recall 0.0. A normal average reports 0.5. F1 reports 0.

+ +
+ +
diff --git a/src/components/ml/RandomForestsLesson.tsx b/src/components/ml/RandomForestsLesson.tsx index 204af2d9..47b056c0 100644 --- a/src/components/ml/RandomForestsLesson.tsx +++ b/src/components/ml/RandomForestsLesson.tsx @@ -93,8 +93,8 @@ export function RandomForestsLesson() {

Notice where the gain stops. Between 32 and 120 trees the score moves by half a point. - More trees never makes a forest worse — the average just gets less noisy — but the - returns flatten early. Practitioners pick a few hundred and stop thinking about it, + Past the first handful, more trees do not make a forest worse — the average just gets + less noisy — but the returns flatten early. Practitioners pick a few hundred and stop thinking about it, because the parameter that matters is how the trees are made, not how many.

@@ -135,7 +135,7 @@ export function RandomForestsLesson() { "Feature subsetting limits each split to a random handful of features, which is what stops one strong feature dominating every root.", "Here the forest reached 82.5% against 72.5% for one unrestricted tree and 76.0% for the best pruned one.", "120 trees drew a clean diagonal boundary that no individual member could express.", - "Returns flatten fast — most of the gain arrives by about 30 trees, and more trees never hurt.", + "Returns flatten fast — most of the gain arrives by about 30 trees, and past the first handful more trees do not hurt.", "You lose readability entirely. Feature importances tell you what mattered overall, never why one particular prediction came out as it did.", ]} /> diff --git a/src/components/ml/RegularisationLesson.tsx b/src/components/ml/RegularisationLesson.tsx index a4eb4d5a..226c26d8 100644 --- a/src/components/ml/RegularisationLesson.tsx +++ b/src/components/ml/RegularisationLesson.tsx @@ -166,10 +166,10 @@ export function RegularisationLesson() { /> A penalty on raw coefficient size only makes sense if the coefficients are comparable - in the first place. A rent measured in minutes of walk time and a rent measured in - square metres are not on the same scale, so an unscaled penalty punishes whichever - column happened to be measured in small units, for no reason connected to how much it - actually matters. Standardise every predictor before fitting, exactly as the widget + in the first place. A predictor measured in minutes of walk time and one measured in + square metres are not on the same scale. A column whose numbers are small needs a large + coefficient to have the same effect, so an unscaled penalty punishes that column hardest, + for no reason connected to how much it actually matters. Standardise every predictor before fitting, exactly as the widget above does, and fit that standardiser on the training rows only. diff --git a/src/lib/quizzes/computer-vision.ts b/src/lib/quizzes/computer-vision.ts index 94ed2b45..f8835c14 100644 --- a/src/lib/quizzes/computer-vision.ts +++ b/src/lib/quizzes/computer-vision.ts @@ -6,4 +6,810 @@ import type { AuthoredQuestion } from "@/lib/quizzes/types"; * quiz in src/lib/quiz.ts. Each question tests something the chapter * actually teaches; `answer` is the zero-based index of the correct option. */ -export const QUIZZES: Record = {}; +export const QUIZZES: Record = { + "what-is-computer-vision": [ + { + q: "You need to know exactly which pixels in a photo belong to the dog. Which of the three jobs is that?", + options: ["Segmentation", "Classification", "Detection", "Edge detection"], + answer: 0, + }, + { + q: "A photo contains two dogs and you need a separate box around each one. Which job is that?", + options: ["Classification", "Detection", "Segmentation", "Grayscale conversion"], + answer: 1, + }, + { + q: "Why did hand-written rules like \"two dark ovals above a line\" fail to find faces?", + options: [ + "Computers of the time could not store enough pixels", + "Faces have too few distinctive features to describe", + "Lighting, angle, occlusion and scale change the pixels without changing the scene", + "Rules about shapes cannot be written in program code", + ], + answer: 2, + }, + { + q: "A 4032 × 3024 colour photo stores three numbers per pixel. Roughly how many numbers is that?", + options: ["About 12 million", "About 7,000", "About 3 million", "About 36 million"], + answer: 3, + }, + ], + + "images-as-numbers": [ + { + q: "What does a single pixel in a grayscale image store?", + options: [ + "One integer from 0 to 255", + "Three integers, one per colour", + "A label naming what it shows", + "Its distance to the neighbouring pixels", + ], + answer: 0, + }, + { + q: "How many numbers make up a 28 × 28 grayscale image?", + options: ["56", "784", "2,352", "28"], + answer: 1, + }, + { + q: "You double an image's width and its height. What happens to the number of pixels?", + options: ["It doubles", "It stays the same", "It becomes four times as many", "It becomes eight times as many"], + answer: 2, + }, + { + q: "You zoom far into a photo until it turns into flat squares. What has happened?", + options: [ + "The file has been corrupted by zooming", + "The camera's sensor failed at that spot", + "The viewer is hiding a finer layer of detail", + "You have reached the resolution it was captured at", + ], + answer: 3, + }, + ], + + "colour-and-channels": [ + { + q: "Using grayscale = 0.299R + 0.587G + 0.114B, roughly what grey does pure green (0, 255, 0) become?", + options: ["About 150", "About 85", "About 255", "About 29"], + answer: 0, + }, + { + q: "You load a photo with cv2.imread, show it with Matplotlib, and the blue sky looks orange. What fixes it?", + options: [ + "Divide every pixel value by 255 before plotting", + "Convert it with cv2.cvtColor(img, cv2.COLOR_BGR2RGB) first", + "Convert the photo to grayscale before plotting", + "Resize the photo to a square before plotting", + ], + answer: 1, + }, + { + q: "Which extra channel records how transparent each pixel is?", + options: ["Depth", "Infrared", "Alpha", "Blue"], + answer: 2, + }, + { + q: "Why does green get the largest weight in the usual grayscale formula?", + options: [ + "Green values are usually the largest numbers in a photo", + "Green is stored first in most image files", + "Green carries detail that red and blue lack", + "Human brightness perception is most sensitive to green light", + ], + answer: 3, + }, + ], + + convolution: [ + { + q: "A 3 × 3 kernel visits every position where it fits fully inside an 8 × 8 image. What size is the output?", + options: ["6 × 6", "8 × 8", "5 × 5", "3 × 3"], + answer: 0, + }, + { + q: "A blur kernel with nine values of 1/9 sits over a patch of eight 0s with a 90 in the centre. What is the output?", + options: ["90", "10", "0", "45"], + answer: 1, + }, + { + q: "A sharpen kernel has 5 in the centre, −1 on its four direct neighbours and 0 in the corners. What does it output on a flat patch of 50s?", + options: ["0", "250", "50", "200"], + answer: 2, + }, + { + q: "What actually differs between a blur filter and a sharpen filter?", + options: [ + "How many positions the kernel visits", + "Whether the products are summed or multiplied", + "How far the kernel moves between positions", + "Only the numbers inside the kernel", + ], + answer: 3, + }, + ], + + "edge-detection": [ + { + q: "Which pair of neighbouring pixel values most likely sits on an edge?", + options: ["30 and 210", "118 and 121", "200 and 205", "64 and 70"], + answer: 0, + }, + { + q: "You lower the edge threshold. What happens to the edge map?", + options: [ + "Fewer edges appear, and faint real ones vanish", + "More edges appear, including noise and texture", + "The same edges appear, just drawn thicker", + "Nothing, because the threshold only affects colour", + ], + answer: 1, + }, + { + q: "What is the gradient magnitude across the inside of a flat, evenly painted wall?", + options: [ + "At its maximum", + "Equal to the pixel value", + "Close to zero", + "Undefined", + ], + answer: 2, + }, + { + q: "Which of these can an edge map NOT tell you?", + options: [ + "Where brightness changes quickly", + "How steep each brightness change is", + "Which way brightness is rising", + "What object sits on either side of a line", + ], + answer: 3, + }, + ], + + "feature-detectors": [ + { + q: "Why is a patch of clear blue sky a poor point to try to find again in a second photo?", + options: [ + "It looks the same wherever you shift the window, so it cannot be located", + "Its pixels are too bright to measure reliably", + "Sky always changes colour between two photos", + "It contains too many edges to describe", + ], + answer: 0, + }, + { + q: "You slide a small window along a straight edge, parallel to it. What does the window see?", + options: [ + "A sharp change, just as it would at a corner", + "Almost no change, so its position along the edge is ambiguous", + "A change in every direction at once", + "Nothing at all, because edges have no gradient", + ], + answer: 1, + }, + { + q: "What is a descriptor?", + options: [ + "The keypoint's exact pixel coordinates", + "The label of the object the keypoint belongs to", + "A numeric fingerprint of the patch, built to survive rotation and lighting", + "A raw copy of the pixels around the keypoint", + ], + answer: 2, + }, + { + q: "How are two photos matched once keypoints have descriptors?", + options: [ + "Compare the pixels at the same coordinates", + "Pair up keypoints with the same brightness", + "Match the longest edges in each photo first", + "Pair each keypoint with the one whose descriptor is closest", + ], + answer: 3, + }, + ], + + "image-preprocessing": [ + { + q: "You stretch a 400 × 200 photo straight to 224 × 224. What goes wrong?", + options: [ + "Shapes distort, so a round clock becomes an oval", + "The colours shift towards blue", + "Pixel values climb above 255", + "Nothing, because stretching keeps proportions", + ], + answer: 0, + }, + { + q: "You normalise by dividing each pixel by 255. What does a pixel value of 204 become?", + options: ["0.2", "0.8", "204", "1.25"], + answer: 1, + }, + { + q: "Four independent on/off augmentations are applied to one photo. How many different versions can you get, counting the original?", + options: ["4", "5", "16", "8"], + answer: 2, + }, + { + q: "Which augmentation would be a mistake for a handwritten-digit classifier?", + options: [ + "Shifting each digit a few pixels sideways", + "Slightly brightening or darkening each image", + "Rotating each digit by a few degrees", + "Rotating each digit a full 180 degrees", + ], + answer: 3, + }, + ], + + "image-classification": [ + { + q: "A photo shows three dogs and a cat, and the classifier says \"dog\". By its own contract, is that correct?", + options: [ + "Yes, it only promises one label for the whole image", + "No, it should have said \"three dogs\"", + "No, it should have mentioned the cat", + "Only if it also returns where the dogs are", + ], + answer: 0, + }, + { + q: "A husky-versus-wolf model labels a husky standing in snow as a wolf. What most likely happened?", + options: [ + "Huskies and wolves produce identical pixel values", + "Most of its training wolves were photographed in snow, so it learned snow", + "Its confidence threshold was set too low", + "The photo was too small for the model to classify", + ], + answer: 1, + }, + { + q: "A classifier scores 76% top-1 and 93% top-5. What does the 93% mean?", + options: [ + "Its single best guess is right 93% of the time", + "It is 93% confident on average", + "The true label is among its five best guesses 93% of the time", + "It is right on 93% of the five hardest classes", + ], + answer: 2, + }, + { + q: "A model reports 99% confidence on a photo. What does that number tell you?", + options: [ + "It will be right on 99% of similar photos", + "Its training labels were 99% accurate", + "The photo matches a training photo exactly", + "How sure the model is, not whether it is right", + ], + answer: 3, + }, + ], + + "pixels-to-predictions": [ + { + q: "Top-left weight is 2 and top-right weight is −1. A 2 × 2 square of bright cells (value 1 each) scores 8 in the top-left. Shifted one cell right, two of its cells fall in the top-right. What is the new score?", + options: ["2", "8", "6", "4"], + answer: 0, + }, + { + q: "Why does the per-pixel-weight model fail when an identical shape moves?", + options: [ + "The shape gets dimmer when it moves", + "Each position has its own weight, so a moved shape is a new pattern", + "The threshold changes depending on position", + "The model was never trained on any shapes", + ], + answer: 1, + }, + { + q: "What does a convolution kernel change about this model?", + options: [ + "It gives every pixel two weights instead of one", + "It removes the threshold entirely", + "It reuses one small set of weights at every position", + "It adds more layers of independent weights", + ], + answer: 2, + }, + { + q: "How many weights does a per-pixel model need for a 6 × 6 image, compared with one 3 × 3 kernel?", + options: ["6 versus 3", "36 versus 36", "9 versus 36", "36 versus 9"], + answer: 3, + }, + ], + + "convolutional-neural-networks": [ + { + q: "What do the first-layer kernels of a trained image network typically detect?", + options: [ + "Edges at several angles, and colour contrasts", + "Whole objects such as faces and cars", + "Object parts such as wheels and eyes", + "Random noise that never settles", + ], + answer: 0, + }, + { + q: "Four 3 × 3 layers are stacked with no pooling or striding. How big is the receptive field of the fourth layer?", + options: ["12 × 12", "9 × 9", "7 × 7", "3 × 3"], + answer: 1, + }, + { + q: "A layer of 64 kernels receives the 32 output grids from the layer before. What does each kernel look at?", + options: [ + "Only one of the 32 grids", + "Only the original photo's pixels", + "All 32 grids at once", + "Two of the 32 grids, chosen at random", + ], + answer: 2, + }, + { + q: "What is the main cost of adding depth?", + options: [ + "The receptive field gets smaller", + "The network can no longer detect edges", + "Kernels can no longer share their weights", + "More parameters and computation, and far more data to train from scratch", + ], + answer: 3, + }, + ], + + "transfer-learning": [ + { + q: "You have 400 labelled photos of a product defect. What is the sensible starting point?", + options: [ + "Take a pretrained network, freeze its body, and train a new head", + "Train a deep convolutional network from scratch on the 400 photos", + "Fit one independent weight per pixel and threshold the score", + "Wait until you have a million photos before starting", + ], + answer: 0, + }, + { + q: "In transfer learning, what is \"the head\"?", + options: [ + "The first layer, which detects edges", + "The final layer, which maps features onto your labels", + "The large dataset the network was first trained on", + "The middle layers, which detect textures and parts", + ], + answer: 1, + }, + { + q: "Where does a network pretrained on everyday photos transfer least well?", + options: [ + "Photos of kitchen utensils", + "Photos of different dog breeds", + "Chest X-rays and satellite images", + "Photos of cars on city streets", + ], + answer: 2, + }, + { + q: "Why do the early layers of a pretrained network transfer to new tasks so well?", + options: [ + "They memorised the original 1,000 labels", + "They are retrained from scratch on your photos", + "They hold most of the network's parameters", + "Edges and textures are useful in almost any photo", + ], + answer: 3, + }, + ], + + "object-detection": [ + { + q: "What does a detector return for each object it finds?", + options: [ + "A box, a class label and a confidence score", + "One label for the whole photo", + "A label for every pixel in the photo", + "A single confidence score with no box", + ], + answer: 0, + }, + { + q: "A photo contains three cars and two pedestrians. How many (box, label, confidence) tuples should a good detector return?", + options: ["1", "5", "2", "3"], + answer: 1, + }, + { + q: "Why not simply run a classifier on every possible rectangle in the image?", + options: [ + "Classifiers cannot read cropped images", + "Every box must be a perfect square", + "There are millions of rectangles, far too many to check", + "It would only ever find one object", + ], + answer: 2, + }, + { + q: "Which statement about the two families of detector is right?", + options: [ + "Two-stage detectors are always faster", + "Single-stage detectors propose regions first", + "Two-stage detectors skip classification", + "Single-stage detectors predict in one pass and are usually faster", + ], + answer: 3, + }, + ], + + "bounding-boxes-and-iou": [ + { + q: "The true box is 100 × 100. The predicted box is the same size, shifted 50 pixels to the right. What is the IoU?", + options: ["About 0.33", "0.5", "0.25", "About 0.67"], + answer: 0, + }, + { + q: "Boxes of 12,000 and 10,000 square pixels overlap by 8,000. What is the area of their union?", + options: ["22,000", "14,000", "30,000", "20,000"], + answer: 1, + }, + { + q: "What is the IoU of two boxes that do not touch at all?", + options: ["0.5", "1.0", "0", "Undefined"], + answer: 2, + }, + { + q: "A detection with IoU 0.6 counts as correct at a threshold of 0.5. What happens at a threshold of 0.75?", + options: [ + "It stays correct, because the box has not moved", + "It gets partial credit of 0.8", + "Its IoU rises to meet the new threshold", + "It becomes a miss, although the box has not moved", + ], + answer: 3, + }, + ], + + "non-max-suppression": [ + { + q: "What is the first thing non-max suppression does?", + options: [ + "Keeps the box with the highest confidence", + "Discards the box with the lowest confidence", + "Averages all the boxes into one", + "Sorts the boxes by their size", + ], + answer: 0, + }, + { + q: "Box A has been kept. Box B overlaps it with IoU 0.8, and the threshold is 0.5. What happens to B?", + options: [ + "It is kept as a second object", + "It is discarded as a duplicate", + "It is merged into A by averaging", + "It is set aside and checked again at the end", + ], + answer: 1, + }, + { + q: "Two people stand shoulder to shoulder, and only one of them ends up with a box. What is the likely cause?", + options: [ + "The NMS threshold is set too high", + "The confidence scores are too high", + "The NMS threshold is set too low", + "IoU was computed against the wrong box", + ], + answer: 2, + }, + { + q: "The NMS threshold is set to 0.95. What goes wrong?", + options: [ + "Separate nearby objects get merged into one", + "The highest-confidence box gets discarded", + "Every box in the image is suppressed", + "Duplicate boxes survive around the same object", + ], + answer: 3, + }, + ], + + "image-segmentation": [ + { + q: "How many labels does segmentation produce for a 640 × 480 photo?", + options: ["307,200", "4", "1,120", "640"], + answer: 0, + }, + { + q: "You need to count the cars in a car park, each with its own outline. Which kind of segmentation do you need?", + options: ["Semantic segmentation", "Instance segmentation", "Image classification", "Edge detection"], + answer: 1, + }, + { + q: "Two dogs stand side by side. What does semantic segmentation produce?", + options: [ + "A separate mask for each dog", + "A mask for the larger dog only", + "One shared \"dog\" label, with no idea there are two", + "A box around each dog", + ], + answer: 2, + }, + { + q: "What is the main extra cost of segmentation compared with boxes?", + options: [ + "Masks cannot be graded at all", + "It only works on square images", + "It cannot use colour photos", + "Tracing every outline takes far longer to label", + ], + answer: 3, + }, + ], + + "confusion-matrix-for-vision": [ + { + q: "Rows are the truth and columns are the prediction. The cell at row \"wolf\", column \"coyote\" holds 19. What does that mean?", + options: [ + "19 wolf photos were predicted as coyote", + "19 coyote photos were predicted as wolf", + "19 wolf photos were classified correctly", + "19% of all the predictions were wrong", + ], + answer: 0, + }, + { + q: "A test set has 250 photos and the matrix shows 54 errors in total. What is the accuracy?", + options: ["21.6%", "78.4%", "80%", "54%"], + answer: 1, + }, + { + q: "Wolf/coyote mix-ups cause 40 of those 54 errors. If you fixed that pair completely, what would accuracy become?", + options: ["82.4%", "100%", "94.4%", "88.0%"], + answer: 2, + }, + { + q: "A cats, dogs and birds test set scores 98%. What does that prove?", + options: [ + "The model will also separate wolves from coyotes", + "The model has learned to see in general", + "The model will score 98% in deployment", + "Little, because the test had no easily confused pairs", + ], + answer: 3, + }, + ], + + "mean-average-precision": [ + { + q: "Why does plain accuracy not work for a detector?", + options: [ + "The number of predictions per image varies and has no fixed match to the objects", + "Detectors never output a class label", + "Accuracy can only be computed on grayscale images", + "Every detection is either fully right or fully wrong", + ], + answer: 0, + }, + { + q: "Sorted by confidence, four detections are correct, correct, wrong, correct. The scene has 5 real objects. With all four flagged, what are precision and recall?", + options: [ + "Precision 0.6, recall 0.75", + "Precision 0.75, recall 0.6", + "Precision 0.75, recall 0.75", + "Precision 1.0, recall 0.6", + ], + answer: 1, + }, + { + q: "One report gives mAP@0.5 = 62 and another gives mAP@0.5:0.95 = 41. What can you say?", + options: [ + "The first detector is clearly better", + "One of the two reports must contain an error", + "They could describe the same detector, graded at different IoU bars", + "The second detector found fewer classes", + ], + answer: 2, + }, + { + q: "In mean average precision, what is the \"mean\" taken across?", + options: [ + "The confidence scores of every box", + "The images in the test set", + "The pixels inside each box", + "The average precision of each object class", + ], + answer: 3, + }, + ], + + "dataset-bias": [ + { + q: "A subgroup makes up 4% of the test set. At most, how much can its errors move overall accuracy?", + options: ["4 percentage points", "96 percentage points", "40 percentage points", "0.4 percentage points"], + answer: 0, + }, + { + q: "What is the most reliable way to catch a model failing on one group of people?", + options: [ + "Train a larger model on the same data", + "Report accuracy broken out by subgroup", + "Report the overall accuracy more often", + "Remove small subgroups from the test set", + ], + answer: 1, + }, + { + q: "What did the 2018 Gender Shades study find in commercial facial-analysis systems?", + options: [ + "Error rates were the same for every group tested", + "Errors were highest for lighter-skinned men", + "Errors were far higher for darker-skinned women than lighter-skinned men", + "Errors only appeared on low-resolution photos", + ], + answer: 2, + }, + { + q: "A group is missing from the test set entirely. What does a subgroup breakdown tell you about it?", + options: [ + "That the model works well for that group", + "That the model fails for that group", + "Its accuracy, estimated from similar groups", + "Nothing, so its absence should be stated explicitly", + ], + answer: 3, + }, + ], + + "overfitting-in-vision": [ + { + q: "A network scores 99% on its training photos and 71% on validation photos. What is the diagnosis?", + options: [ + "Overfitting: it has memorised the training photos", + "Underfitting: it is too small for the task", + "A healthy model with a noisy validation set", + "Data leakage from the validation set", + ], + answer: 0, + }, + { + q: "In the augmentation interactive, which strength should you choose?", + options: [ + "Strength 0, where training accuracy is highest", + "Strength 6, where validation accuracy peaks", + "Strength 10, the strongest available", + "Whichever strength gives the highest training accuracy", + ], + answer: 1, + }, + { + q: "Why does augmentation make memorisation harder?", + options: [ + "It shrinks the number of parameters in the network", + "It removes the hardest photos from training", + "The network never sees exactly the same pixels twice", + "It copies validation photos into the training set", + ], + answer: 2, + }, + { + q: "Past the sweet spot, training and validation accuracy fall together. Why?", + options: [ + "The network has started overfitting again", + "The validation set has become too small", + "The learning rate has become too large", + "The images are distorted so much that the real signal is lost", + ], + answer: 3, + }, + ], + + "face-detection-and-privacy": [ + { + q: "A shop camera counts how many faces pass by but never identifies anyone. Which is it doing?", + options: [ + "Face detection", + "Face recognition", + "Face verification against a watchlist", + "Instance segmentation of identities", + ], + answer: 0, + }, + { + q: "What does face recognition add on top of face detection?", + options: [ + "Drawing a box around each face", + "Matching the face against a database of known identities", + "Counting how many faces are in the frame", + "Blurring faces for privacy", + ], + answer: 1, + }, + { + q: "Unlocking your phone and scanning a crowd can run similar code. What is the key ethical difference?", + options: [ + "The phone uses detection, the crowd camera does not", + "The crowd camera is always more accurate", + "Consent: you enrolled yourself in the phone's database of one", + "There is no meaningful difference", + ], + answer: 2, + }, + { + q: "How does the EU AI Act treat real-time remote biometric identification in public spaces for law enforcement?", + options: [ + "It is allowed with no special rules", + "It is allowed only for private companies", + "It is required on all public cameras", + "It is prohibited, apart from narrow listed exceptions", + ], + answer: 3, + }, + ], + + "vision-in-self-driving-cars": [ + { + q: "A car travels at 30 metres per second and its vision pipeline takes 200 ms to decide. How far does it travel before the decision exists?", + options: ["6 metres", "60 metres", "0.6 metres", "15 metres"], + answer: 0, + }, + { + q: "Which sensor keeps measuring distance and closing speed reliably in fog and darkness?", + options: ["Camera", "Radar", "A second camera", "GPS"], + answer: 1, + }, + { + q: "The camera's depth estimate and the radar's distance disagree. What policy does the lesson describe?", + options: [ + "Average the two readings", + "Trust the camera, because it sees more detail", + "Trust radar's direct distance over the camera's estimate", + "Ignore both and brake every time", + ], + answer: 2, + }, + { + q: "Which of these is still a real failure case for deployed systems?", + options: [ + "Reading a standard stop sign in daylight", + "Measuring the distance to a car ahead in clear weather", + "Following clearly painted lane lines on a dry road", + "An overturned trailer unlike anything in the training data", + ], + answer: 3, + }, + ], + + "from-prototype-to-production": [ + { + q: "At 30 frames per second, how long does a model have for each frame?", + options: ["About 33 ms", "About 3.3 ms", "About 300 ms", "About 16.7 ms"], + answer: 0, + }, + { + q: "Confidence scores on one camera drift lower over several weeks, with no crash or error. What does that suggest?", + options: [ + "The model has been retrained by mistake", + "Its input has probably shifted, from the lens, lighting or hardware", + "The model is getting more accurate over time", + "Nothing, because confidence never changes meaningfully", + ], + answer: 1, + }, + { + q: "With no labels on live traffic, what is usually the closest thing to ground truth?", + options: [ + "The model's own confidence scores", + "The original test-set accuracy", + "Corrections reported by users", + "The average brightness of each frame", + ], + answer: 2, + }, + { + q: "A model takes 200 ms per frame on a 30 fps feed. What happens?", + options: [ + "It runs a little slower but sees every frame", + "It speeds up once the feed warms up", + "It is fine, because offline accuracy is what counts", + "It falls behind, unless it skips most of the frames", + ], + answer: 3, + }, + ], +}; diff --git a/src/lib/quizzes/ml.ts b/src/lib/quizzes/ml.ts index 15cd9959..2518cd7d 100644 --- a/src/lib/quizzes/ml.ts +++ b/src/lib/quizzes/ml.ts @@ -6,4 +6,880 @@ import type { AuthoredQuestion } from "@/lib/quizzes/types"; * quiz in src/lib/quiz.ts. Each question tests something the chapter * actually teaches; `answer` is the zero-based index of the correct option. */ -export const QUIZZES: Record = {}; +export const QUIZZES: Record = { + "what-is-ml": [ + { + q: "You need a function that decides whether someone is old enough to vote. What does this lesson recommend?", + options: [ + "Write the rule directly in code, because it can be stated exactly", + "Train a classifier on past voter records so it learns the rule", + "Collect labelled examples first, then decide whether rules are needed", + "Use a learned model, with a hand-written rule as a fallback", + ], + answer: 0, + }, + { + q: "In the rule-stacking interactive, why can hand-written if-statements never match the learned line?", + options: [ + "The rules are chosen at random, so they rarely pick useful thresholds", + "Each rule draws a rectangle, and rectangles can only approximate a diagonal", + "If-statements can only look at one message at a time", + "The learned line was given extra features the rules never saw", + ], + answer: 1, + }, + { + q: "What happens to the accuracy each new hand-written rule buys you?", + options: [ + "Every rule adds about the same amount", + "Later rules add more, because they build on earlier ones", + "Each rule buys less than the last, until extra rules buy nothing", + "Accuracy drops after the third rule, because rules start to conflict", + ], + answer: 2, + }, + { + q: "Which of these is a real cost of switching from written rules to machine learning?", + options: [ + "The model always runs slower than equivalent hand-written code", + "The model must be retrained before every single prediction", + "The model can only handle problems with exactly two features", + "You need many labelled examples, and the result is hard to read", + ], + answer: 3, + }, + ], + + "features-and-labels": [ + { + q: "A model predicts a house's sale price from its floor area and its number of bedrooms. Which is the label?", + options: [ + "The sale price", + "The floor area", + "The number of bedrooms", + "The model's own prediction", + ], + answer: 0, + }, + { + q: "In the bread example, why does a blend of baking time and oven temperature beat either one alone?", + options: [ + "Temperature is measured less precisely, so it needs a partner", + "A loaf can cook through long and cool, or briefly and hot", + "Blending two features halves the error of any model", + "The model cannot read raw minutes, only combined values", + ], + answer: 1, + }, + { + q: "What is feature engineering?", + options: [ + "Choosing which algorithm to train on your data", + "Hand-correcting labels that the model got wrong", + "Inventing new measurements out of the ones you already have", + "Deleting rows that do not fit the expected pattern", + ], + answer: 2, + }, + { + q: "Two bakers judge \"cooked through\" differently while labelling loaves. What does the lesson say happens?", + options: [ + "The model averages their opinions into a more accurate label", + "The model ignores the noisy labels once it has enough data", + "The problem shows up in the features, not in the predictions", + "The model learns their disagreement, and better modelling cannot fix it", + ], + answer: 3, + }, + ], + + "how-models-learn": [ + { + q: "A fuel model's one number is 8 L/100 km. What does it predict for a 150 km trip?", + options: ["12 litres", "8 litres", "18.75 litres", "1.2 litres"], + answer: 0, + }, + { + q: "Why are misses usually squared before they are added up?", + options: [ + "So the total is always a whole number, which is easier to search", + "So misses cannot cancel out, and one big miss outweighs several small ones", + "So small misses count for more than big ones, smoothing out noise", + "So the total error stays in the same units as the prediction", + ], + answer: 1, + }, + { + q: "The best setting's line passes through only two of the thirty-six trips. What does that tell you?", + options: [ + "The model is underfitting and needs a second number", + "The data contains mistakes that should be removed first", + "Best fit means least total error, not touching the most points", + "The slider was not moved far enough to reach the true value", + ], + answer: 2, + }, + { + q: "Why can a machine find the best setting without knowing anything about cars?", + options: [ + "It looks up typical fuel use for each make of car", + "It copies the setting from the most recent trip", + "It keeps whichever setting touches the most dots", + "The total error is a smooth bowl, so it only needs to know which way is downhill", + ], + answer: 3, + }, + ], + + "classification-vs-regression": [ + { + q: "Which of these is a regression problem?", + options: [ + "Predicting how much a customer will spend next month", + "Predicting whether a customer will cancel their plan", + "Predicting which of ten digits a photo shows", + "Predicting whether an email is spam or not", + ], + answer: 0, + }, + { + q: "The same delivery-time model is rounded into 2 categories, then into 20. What happens to the two scores?", + options: [ + "Accuracy rises, and the average miss in minutes also improves", + "Accuracy falls, while the average miss in minutes improves", + "Accuracy and the average miss both stay exactly the same", + "Accuracy falls, and the average miss in minutes gets worse too", + ], + answer: 1, + }, + { + q: "Model A scores 90% on a two-category problem. Model B scores 30% on a twenty-category problem. What can you conclude?", + options: [ + "Model A is three times better than model B", + "Model B is broken and needs to be retrained", + "Nothing yet, because accuracy depends on how many categories there are", + "Model A is better, because only it beats 50%", + ], + answer: 2, + }, + { + q: "A depot manager needs to know how many drivers to schedule tomorrow. Which shape of answer fits best?", + options: [ + "Two categories, busy or quiet, split at the median", + "Ten evenly spaced bands of expected order volume", + "A yes or no on whether extra drivers are needed", + "A number, because they are planning against a quantity", + ], + answer: 3, + }, + ], + + "train-test-split": [ + { + q: "Why does a model's score on its own training data tell you so little?", + options: [ + "It can memorise those examples and score well without learning the pattern", + "Training data is always noisier than the data in the test set", + "The training score is calculated with a different formula", + "Models always score lower on training data than on new data", + ], + answer: 0, + }, + { + q: "You check the test score, tweak the model, and check again, many times over. What is the problem?", + options: [ + "Nothing, because looking more often makes the test score more reliable", + "You are slowly tuning to the test set, so it stops being an honest grade", + "The test set gets a little smaller every time you score it", + "The model forgets some of its training data between checks", + ], + answer: 1, + }, + { + q: "Your test set is tiny, say 5% of the data. What happens to the score you report?", + options: [ + "It is always higher than the model's true score", + "It is always lower than the model's true score", + "It swings a lot depending on which rows landed in the test set", + "It becomes identical to the training score", + ], + answer: 2, + }, + { + q: "What does holding back a larger share of the data mainly buy you?", + options: [ + "A model that trains noticeably faster", + "Higher accuracy on new data", + "A training score you can quote safely", + "A more trustworthy estimate of the score", + ], + answer: 3, + }, + ], + + overfitting: [ + { + q: "Training error is tiny and test error is large. What is happening?", + options: [ + "Overfitting: the model memorised the training examples, noise and all", + "Underfitting: the model is too simple to capture the pattern", + "The model found the true pattern, and the test set is unusually noisy", + "The test set is too large for the model to be graded fairly", + ], + answer: 0, + }, + { + q: "Training error keeps falling as you add bends. If you pick the model by training error alone, what do you get?", + options: [ + "The model with the best test error", + "The most complicated model available, every time", + "The simplest model, a flat line", + "The model with three bends, the sweet spot", + ], + answer: 1, + }, + { + q: "Which signal tells you to stop adding complexity?", + options: [ + "Training error stops falling quickly", + "The fitted curve starts to look smooth", + "Held-back error bottoms out and starts to climb", + "The curve passes through more training points", + ], + answer: 2, + }, + { + q: "A model with zero bends predicts the class average for everyone, and both errors are high. Which description fits?", + options: [ + "Overfitting, hidden from the training numbers", + "Data leakage from the test set", + "A good fit to unusually noisy data", + "Underfitting, which the training numbers show honestly", + ], + answer: 3, + }, + ], + + "precision-recall": [ + { + q: "A fraud model flags 50 transactions and 40 of them really are fraud. There were 80 frauds in total. What are precision and recall?", + options: [ + "Precision 0.8, recall 0.5", + "Precision 0.5, recall 0.8", + "Precision 0.8, recall 0.8", + "Precision 0.4, recall 0.5", + ], + answer: 0, + }, + { + q: "A model always answers \"not fraud\" on data where 3 transactions in 1,000 are fraud. What is its recall?", + options: [ + "0.997, the same as its accuracy", + "0, because it catches none of the fraud", + "0.003, the same as the fraud rate", + "1.0, because it never raises a false alarm", + ], + answer: 1, + }, + { + q: "A flag-everything model has precision 0.32 and recall 1.0. Roughly what is its F1 score?", + options: ["About 0.66", "About 0.32", "About 0.48", "Exactly 1.0"], + answer: 2, + }, + { + q: "Which scenario from the lesson should optimise for recall?", + options: [ + "Filtering spam, where a lost job offer is a disaster", + "Ranking search results, where only the top few matter", + "Any problem where the two classes are evenly balanced", + "Screening for cancer, where a miss costs far more than a false alarm", + ], + answer: 3, + }, + ], + + "k-nearest-neighbours": [ + { + q: "How does k-Nearest Neighbours make a prediction?", + options: [ + "It stores the training data and lets the k closest examples vote", + "It fits a line through the data and reads the answer off it", + "It builds a flowchart of questions from the training data", + "It averages the answers of many small decision trees", + ], + answer: 0, + }, + { + q: "What happens when k = 1?", + options: [ + "Every query returns the majority class, so it underfits", + "Every training point gets its own territory, so it reproduces noise and overfits", + "The model ignores distance and picks a neighbour at random", + "Votes can tie, so the model refuses to give an answer", + ], + answer: 1, + }, + { + q: "Revision hours run 0 to 12 and previous scores run 20 to 100. What goes wrong with raw straight-line distance?", + options: [ + "The hours column dominates, because its numbers are smaller", + "Both columns count equally, which is what you want", + "The score column's wider range dominates every distance", + "Distance cannot be computed when the ranges differ", + ], + answer: 2, + }, + { + q: "Why use an odd value of k when there are two classes?", + options: [ + "So the model trains faster", + "So the boundary is a straight line", + "So the features do not need scaling", + "So the vote can never tie", + ], + answer: 3, + }, + ], + + "decision-trees": [ + { + q: "A group of flats is exactly half \"lets quickly\" and half \"does not\". What is its Gini impurity?", + options: ["0.5", "0", "1.0", "0.25"], + answer: 0, + }, + { + q: "Why does the tree's first split use rent at £697?", + options: [ + "Rent is the first column in the dataset", + "That cut removes more weighted impurity than any other feature and cut point", + "It splits the flats into two groups of exactly equal size", + "Somebody chose it because it is close to a round £700", + ], + answer: 1, + }, + { + q: "Why is every boundary a tree draws a vertical or horizontal line?", + options: [ + "The chart can only draw straight lines", + "Gini impurity only works on straight boundaries", + "Each question asks about one feature at a time", + "Trees rescale every feature before splitting", + ], + answer: 2, + }, + { + q: "At depth 4 the tree scores 100% on training flats, while held-back accuracy has fallen from 82% to 68%. What should you do?", + options: [ + "Grow deeper, since training accuracy is already perfect", + "Remove the held-back flats that the tree gets wrong", + "Keep depth 4 and switch to a different impurity measure", + "Limit the depth to where held-back accuracy peaked", + ], + answer: 3, + }, + ], + + "random-forests": [ + { + q: "Each tree in a random forest trains on a bootstrap sample. What does that mean?", + options: [ + "Rows drawn with replacement to the same size, so some repeat and some are left out", + "A random half of the rows, with no row appearing twice", + "Every row, shuffled into a different random order", + "Only the rows that the previous tree got wrong", + ], + answer: 0, + }, + { + q: "Why does a forest let each split consider only a random subset of the features?", + options: [ + "So each tree trains faster on fewer columns", + "So one dominant feature does not sit at the root of every tree", + "So the forest can cope with missing values", + "So each tree grows deep enough to memorise its sample", + ], + answer: 1, + }, + { + q: "In the interactive, a forest of two trees scored worse than a single tree. Why?", + options: [ + "The second tree was accidentally trained on the test set", + "Adding any tree always lowers accuracy at first", + "With two voters a tie is possible, and the tie-break is not evidence", + "Two trees overfit more than one tree does", + ], + answer: 2, + }, + { + q: "What do you give up when you move from one tree to a forest?", + options: [ + "The ability to draw a diagonal boundary", + "Any way to say which features mattered overall", + "Accuracy on the held-back data", + "A readable flowchart that explains each prediction", + ], + answer: 3, + }, + ], + + "cross-validation": [ + { + q: "In 5-fold cross-validation, how is each row used?", + options: [ + "Tested once and trained on four times", + "Tested four times and trained on once", + "Tested five times and trained on five times", + "Tested once and trained on five times", + ], + answer: 0, + }, + { + q: "Five folds score 3.44, 4.67, 3.89, 3.90 and 5.67. What does the lesson say you should report?", + options: [ + "Only the lowest fold score", + "The average and the spread across the folds", + "Only the average, 4.31", + "Only the worst fold score, to be safe", + ], + answer: 1, + }, + { + q: "Your data is daily sales over two years. How should you build the folds?", + options: [ + "Shuffle the rows randomly before dealing them into folds", + "Put all the Mondays in one fold, all the Tuesdays in the next", + "Use folds that respect time, always testing on later periods", + "Use leave-one-out, so every single day gets tested once", + ], + answer: 2, + }, + { + q: "When is cross-validation least worth its extra cost?", + options: [ + "When data is scarce and every row matters", + "When you need to choose a setting such as k or depth", + "When the model is cheap and quick to train", + "When the dataset is so large that one split is already stable", + ], + answer: 3, + }, + ], + + "data-leakage": [ + { + q: "A loan-default model includes a collectionsCalls column and scores 95%. What is wrong?", + options: [ + "The column is recorded after default, so it would not exist at prediction time", + "The column has too many missing values to be trusted", + "The column needs to be scaled before training", + "Nothing, because a highly predictive column is what you want", + ], + answer: 0, + }, + { + q: "Each patient contributes many rows, and you split the table row by row. What leak does that create?", + options: [ + "Future dates end up in the training set", + "The same patient appears on both sides of the split", + "The label column leaks into the features", + "The scaler is fitted on the test rows", + ], + answer: 1, + }, + { + q: "Which question catches target leakage best?", + options: [ + "Is this column strongly correlated with the label?", + "Does this column have any missing values?", + "Would this value exist at the moment the prediction is needed?", + "Is this column measured in consistent units?", + ], + answer: 2, + }, + { + q: "Why does the lesson call leakage more dangerous than overfitting?", + options: [ + "It makes test scores look bad, so nobody notices it", + "It crashes the pipeline before training finishes", + "It only ever affects very small datasets", + "It makes test scores look good, so the model gets shipped", + ], + answer: 3, + }, + ], + + "class-imbalance": [ + { + q: "75 of 4,000 transactions are fraud. A model that flags nothing scores what accuracy?", + options: ["About 98.1%", "About 1.9%", "About 50%", "About 92.5%"], + answer: 0, + }, + { + q: "For a linear model, what do undersampling, oversampling and class weighting all really change?", + options: [ + "Which features the model treats as important", + "Where the model starts saying yes, by shifting its intercept", + "How much information the fraud examples contain", + "The boundary's shape, from straight to curved", + ], + answer: 1, + }, + { + q: "What cheaper move reproduced the rebalanced result with no retraining?", + options: [ + "Raising the cut-off above 0.5", + "Removing the fraud rows from the test set", + "Lowering the probability cut-off on the original model", + "Training on the test set as well", + ], + answer: 2, + }, + { + q: "Should you rebalance the test set as well as the training set?", + options: [ + "Yes, otherwise precision cannot be computed", + "Yes, the test set must match the training set", + "Only if you used undersampling on training", + "No, it must keep the rare class's real-world rate", + ], + answer: 3, + }, + ], + + baselines: [ + { + q: "60% of students in a dataset passed. What does the \"say the commoner answer\" baseline score?", + options: ["60%", "52%", "50%", "40%"], + answer: 0, + }, + { + q: "On the same data, you predict \"pass\" at random 60% of the time. What accuracy should you expect?", + options: ["60%", "52%", "50%", "48%"], + answer: 1, + }, + { + q: "A depth-4 tree scores 76% and a one-rule stump scores 87.3%. What should you do?", + options: [ + "Ship the tree, because it is a real model", + "Add depth until the tree beats the stump", + "Ship the stump unless a model clearly beats it", + "Report the tree's 76%, since chance is 50%", + ], + answer: 2, + }, + { + q: "Why build the baseline before any real model?", + options: [ + "It usually turns out to be the best model", + "It sets the learning rate for later models", + "It removes the noisy columns from the data", + "It tests loading, splitting and scoring while nothing else can be blamed", + ], + answer: 3, + }, + ], + + clustering: [ + { + q: "Which two moves does k-means repeat until nothing changes?", + options: [ + "Assign each point to its nearest centre, then move each centre to its points' mean", + "Split on the best feature, then repeat the split on each side", + "Add the farthest point as a new centre, then drop the outliers", + "Merge the two closest groups, then recompute every distance", + ], + answer: 0, + }, + { + q: "Why can't you choose k by picking whichever value gives the lowest inertia?", + options: [ + "Inertia is random and changes on every run", + "Inertia keeps falling as k grows, reaching zero with one centre per point", + "Inertia rises as k grows, so k = 1 always wins", + "Inertia only measures the size of the largest cluster", + ], + answer: 1, + }, + { + q: "You run k-means with k = 3 on points scattered completely at random. What happens?", + options: [ + "It reports that no clusters exist", + "It never converges and keeps running", + "It returns three clusters as confidently as it would on real groups", + "It returns a single cluster containing every point", + ], + answer: 2, + }, + { + q: "Two k = 3 runs on the same data finish at inertias of about 88,639 and 255,560. What explains the difference?", + options: [ + "One run used more of the data", + "One run used a different distance measure", + "The second run stopped one round too early", + "The centres started in different places", + ], + answer: 3, + }, + ], + + "dimensionality-reduction": [ + { + q: "What is the first principal component?", + options: [ + "The direction along which the data spreads out the most", + "The original column with the largest values", + "The direction that best separates the labels", + "The plain average of all the columns", + ], + answer: 0, + }, + { + q: "The first component keeps 86% of the variance, but keeping geometry alone keeps 58%. Why does the rotation win?", + options: [ + "It removes the noisiest students from the cloud", + "It blends both columns, so it captures their shared spread", + "It rescales geometry to match the range of algebra", + "It keeps both original columns unchanged", + ], + answer: 1, + }, + { + q: "The flagged students separate best along the direction PCA rated lowest. What does this show?", + options: [ + "PCA was fitted on the wrong part of the data", + "The flag must have been recorded incorrectly", + "PCA never looks at the label, so it can discard the direction that predicts it", + "PCA always keeps the most predictive direction first", + ], + answer: 2, + }, + { + q: "Where should you fit the PCA rotation?", + options: [ + "On the full dataset, before splitting", + "Separately on the training and test sets", + "On the test set, so it matches new data", + "On the training set only, then apply it to the test set", + ], + answer: 3, + }, + ], + + "anomaly-detection": [ + { + q: "Why does training an ordinary classifier on nine fraud examples fail?", + options: [ + "Nine points are far too few to describe what fraud looks like in general", + "Classifiers refuse to run unless the classes are balanced", + "Fraud examples are not allowed to be used as labels", + "Nine examples only overfit when the features are scaled", + ], + answer: 0, + }, + { + q: "What does anomaly detection learn instead?", + options: [ + "The boundary between fraud and normal transactions", + "The shape of normal behaviour, flagging what sits far from it", + "A list of known fraud patterns to match against", + "The average fraudulent transaction", + ], + answer: 1, + }, + { + q: "At one cut-off the detector catches 7 of 9 frauds and raises 64 false alarms. Roughly how many alerts are opened per real fraud found?", + options: ["About 1", "About 7", "About 10", "About 64"], + answer: 2, + }, + { + q: "False alarms have climbed steadily for weeks. What is the likely cause, and the right response?", + options: [ + "Fraud is rising, so loosen the cut-off to cut the alerts", + "The model is overfitting, so collect more fraud examples", + "Nothing is wrong, because false alarms always rise over time", + "Normal has drifted, so refit it on a recent window and recheck the cut-off", + ], + answer: 3, + }, + ], + + "feature-scaling": [ + { + q: "A column runs from 20 to 120. After min-max scaling, what does a value of 70 become?", + options: ["0.5", "0.7", "0.58", "50"], + answer: 0, + }, + { + q: "A column has mean 50 and standard deviation 10. What does 80 become after standardisation?", + options: ["0.8", "3.0", "30", "1.6"], + answer: 1, + }, + { + q: "Which of these models gives the same predictions whether or not you rescale a feature?", + options: ["k-nearest neighbours", "k-means", "A decision tree", "PCA"], + answer: 2, + }, + { + q: "Which order avoids leaking test information through the scaler?", + options: [ + "Fit the scaler on all rows, then split", + "Fit separate scalers on the training and test rows", + "Scale the test set with its own mean and spread", + "Split first, fit on the training rows, then transform both", + ], + answer: 3, + }, + ], + + "gradient-descent": [ + { + q: "A parameter is 5, its gradient is 4, and the learning rate is 0.1. What is the parameter after one update?", + options: ["4.6", "5.4", "4.0", "1.0"], + answer: 0, + }, + { + q: "At one rate, each step jumps past the target and lands further away than the last. What is happening?", + options: [ + "The rate is too small, so the search is crawling", + "The rate is too large, so the search is diverging", + "The search has found a different valley", + "The gradient has the wrong sign", + ], + answer: 1, + }, + { + q: "Why isn't accuracy the number that gradient descent minimises directly?", + options: [ + "It is too slow to compute on large datasets", + "It only works for regression problems", + "It changes in whole steps, so it has no useful slope", + "It always has more than one minimum", + ], + answer: 2, + }, + { + q: "Gradient descent settles at a low point and stops moving. What does that guarantee?", + options: [ + "That it is the lowest point anywhere", + "That the model will not overfit", + "That the learning rate was the best one", + "Only that it is the bottom of the valley it walked into", + ], + answer: 3, + }, + ], + + regularisation: [ + { + q: "What does a regularised fit minimise?", + options: [ + "Training error plus λ times a penalty on coefficient size", + "Training error alone, but measured on fewer rows", + "Test error, measured after every training step", + "The number of features, by deleting columns at random", + ], + answer: 0, + }, + { + q: "Which penalty is willing to set a weak coefficient to exactly zero?", + options: [ + "L2 (ridge)", + "L1 (lasso)", + "Neither, both only shrink coefficients", + "Both, equally often", + ], + answer: 1, + }, + { + q: "With λ near zero, validation error is $668 while training error is $159. What is this?", + options: [ + "Underfitting, from too much penalty", + "Leakage from the validation set", + "Overfitting, because nothing charges for coefficient size", + "The best possible value of λ", + ], + answer: 2, + }, + { + q: "How should you choose λ?", + options: [ + "Pick whichever value gives the best test score", + "Pick whichever value gives the lowest training error", + "Always use λ = 1, the standard default", + "Compare candidates on a validation set or with cross-validation", + ], + answer: 3, + }, + ], + + "neural-networks": [ + { + q: "Two linear layers are stacked with no activation between them. What can the result compute?", + options: [ + "Nothing more than a single weighted sum plus a bias", + "A curved boundary with one bend in it", + "Twice as many patterns as one layer", + "The same as a two-level decision tree", + ], + answer: 0, + }, + { + q: "What does ReLU output for inputs of −3 and 2?", + options: ["−3 and 2", "0 and 2", "0 and 0", "3 and 2"], + answer: 1, + }, + { + q: "What does the universal approximation theorem NOT tell you?", + options: [ + "That a wide enough hidden layer can approximate continuous functions", + "That suitable weights exist for a single hidden layer", + "Whether gradient descent will find those weights, or how much data it needs", + "That one hidden layer can be enough in principle", + ], + answer: 2, + }, + { + q: "On ordinary rows-and-columns data, what does the lesson say routinely beats a neural network?", + options: [ + "A deeper neural network", + "k-nearest neighbours with k = 1", + "A single unpruned decision tree", + "A well-tuned gradient-boosted tree", + ], + answer: 3, + }, + ], + + "from-notebook-to-production": [ + { + q: "After a price rise, new customers look different, but how price predicts churn has not changed. Which kind of drift is this?", + options: ["Input drift", "Concept drift", "Training/serving skew", "Target leakage"], + answer: 0, + }, + { + q: "Missing values are filled with zero in training but left as null in the live service. What is this called?", + options: ["Concept drift", "Training/serving skew", "Input drift", "Class imbalance"], + answer: 1, + }, + { + q: "Labels arrive months after each prediction. What should you monitor in the meantime?", + options: [ + "Live accuracy, recomputed every hour", + "Training loss on the original data", + "Input and prediction distributions, flag rate, latency and errors", + "Nothing, until the labels arrive", + ], + answer: 2, + }, + { + q: "A retrained candidate beats the live model by one point. What should happen next?", + options: [ + "Replace the live model straight away", + "Retrain again until it wins by more", + "Deploy it and delete the old model", + "Check it against the baseline too, then roll out behind a shadow or canary", + ], + answer: 3, + }, + ], +}; From 8fc808d15b84ab7a79d2911001bb438f276c9397 Mon Sep 17 00:00:00 2001 From: srivibhavpadakandla Date: Sat, 10 Oct 2026 16:17:03 -0700 Subject: [PATCH 04/26] HTML/CSS and GitHub: hand-written quick checks and lesson fixes All 45 chapters get authored questions. Fixes a .gitignore with inline comments that would break, unreadable dark-mode links, favicon paths that break on GitHub Pages subfolders, git status --short columns, reflog and git restore behaviour, add -p hunk headers, and colour/specificity claims. Co-Authored-By: Claude Opus 5.5 --- .../github/AnatomyOfARepositoryLesson.tsx | 17 +- .../github/AuthenticationLesson.tsx | 2 +- .../github/ChoosingAWorkflowLesson.tsx | 8 +- src/components/github/IgnoringFilesLesson.tsx | 29 +- src/components/github/InstallingGitLesson.tsx | 8 +- .../github/IssuesAndTrackingLesson.tsx | 4 +- .../github/MergeConflictsLesson.tsx | 4 +- .../github/MergingAPullRequestLesson.tsx | 8 +- .../github/MergingBranchesLesson.tsx | 7 +- .../github/OpeningAPullRequestLesson.tsx | 4 +- .../github/ReadingHistoryLesson.tsx | 4 +- .../github/RebaseAndHistoryLesson.tsx | 5 +- .../RepositoriesAndTheThreeTreesLesson.tsx | 32 +- .../github/StagingAndCommittingLesson.tsx | 8 +- src/components/github/UndoingThingsLesson.tsx | 15 +- src/components/github/WhatABranchIsLesson.tsx | 3 +- .../github/WhyVersionControlLesson.tsx | 4 +- .../html-css/AccessibilityBasicsLesson.tsx | 8 +- .../html-css/ColourAndTypographyLesson.tsx | 16 +- src/components/html-css/DevtoolsLesson.tsx | 7 +- .../html-css/DisplayAndFlowLesson.tsx | 4 +- .../html-css/DocumentStructureLesson.tsx | 6 +- src/components/html-css/DomTree.tsx | 2 +- .../html-css/ElementsAndTagsLesson.tsx | 6 +- src/components/html-css/FlexboxLesson.tsx | 10 + .../html-css/FormsAndInputsLesson.tsx | 2 +- .../html-css/HowCssAttachesLesson.tsx | 11 +- .../html-css/LinksAndImagesLesson.tsx | 10 +- .../html-css/MarkingUpThePageLesson.tsx | 4 +- .../html-css/PublishingYourSiteLesson.tsx | 18 +- .../html-css/ResponsiveDesignLesson.tsx | 13 +- src/components/html-css/SelectorsLesson.tsx | 11 +- .../html-css/StylingThePageLesson.tsx | 14 +- .../html-css/TextAndHeadingsLesson.tsx | 6 +- src/components/html-css/TheBoxModelLesson.tsx | 15 +- .../TheCascadeAndSpecificityLesson.tsx | 12 +- .../html-css/WhatIsAWebsiteLesson.tsx | 4 +- .../html-css/YourFirstPageLesson.tsx | 6 +- src/lib/html-css-lessons.ts | 14 +- src/lib/quizzes/github.ts | 805 +++++++++++++++- src/lib/quizzes/html-css.ts | 896 +++++++++++++++++- 41 files changed, 1920 insertions(+), 142 deletions(-) diff --git a/src/components/github/AnatomyOfARepositoryLesson.tsx b/src/components/github/AnatomyOfARepositoryLesson.tsx index f095fb08..4b21df7d 100644 --- a/src/components/github/AnatomyOfARepositoryLesson.tsx +++ b/src/components/github/AnatomyOfARepositoryLesson.tsx @@ -65,8 +65,8 @@ MIT — see [LICENSE](LICENSE).`} />

A handful of other files get special treatment on GitHub, all of them optional and all of - them ordinary files in the repository — most can live at the root or in a{" "} - .github/ directory to keep the root tidy. + them ordinary files in the repository. LICENSE belongs at the root; most of the others can + live there or in a .github/ directory to keep the root tidy.

This surprises people and it is worth being blunt about. Code on GitHub with no licence file is not open source. Copyright applies by default, and the default is that - nobody may copy, modify, or use it. Making a repository public grants permission to view - it, and only because you agreed to GitHub's terms. + nobody may copy, modify, or use it. Making a repository public lets people view and fork it + on GitHub, because you agreed to GitHub's terms — and nothing more.

A licence is how you grant the rest. There is no need to write one — pick a standard one, @@ -141,8 +141,8 @@ git switch --detach v1.2.0 # look at the code as it was at that release

A release is a GitHub feature built on top of a tag. It adds release - notes, downloadable binaries, and a pre-release flag. Every release has a tag; most tags are - not releases. + notes, downloadable binaries, and a pre-release flag. Every release has a tag; not every tag is + a release.

Network
— a visualisation of every fork and branch that is the fastest way to see whether a fork went somewhere the original did not.{" "} Security holds Dependabot alerts for known-vulnerable dependencies, secret - scanning, and code scanning. On a public repository most of it is free and off by default. + scanning, and code scanning. On a public repository these are free; secret scanning is on by default, and Dependabot + alerts are worth switching on.

- The simplest model that supports review, and by a wide margin the most common on GitHub. One + The simplest model that supports review, and a very common one on GitHub. One permanent branch — main, always deployable — and short-lived branches off it.

;`} develop branch, in particular, is pure overhead when main is deployed the moment something merges.

- - It was adopted almost universally on the strength of one very clear illustration, by an - enormous number of teams who ship continuously and have no supported old versions. If you + + It was adopted widely on the strength of one very clear illustration, including by many + teams who ship continuously and have no supported old versions. If you are using it, be able to say which of its branches solves a problem you actually have. If the answer is none, you are paying for machinery in exchange for nothing. diff --git a/src/components/github/IgnoringFilesLesson.tsx b/src/components/github/IgnoringFilesLesson.tsx index 90227c99..bbd90fc1 100644 --- a/src/components/github/IgnoringFilesLesson.tsx +++ b/src/components/github/IgnoringFilesLesson.tsx @@ -23,13 +23,26 @@ export function IgnoringFilesLesson() {

Three rules do almost all the work, and the third one surprises everybody. @@ -174,7 +187,7 @@ RESEND_API_KEY=`}

- Check first — you may already have it. macOS ships a Git, and most Linux distributions - install one by default. + Check first — you may already have it. macOS offers to install Apple's Git the first + time you type the command, and many Linux distributions include one.

@@ -111,8 +111,8 @@ git config --global core.editor nano`} Press Esc, then type{" "} :wq and press Enter to save and quit, or :q! to - quit without saving. This is one of the most-searched programming questions of - all time. + quit without saving. Being stuck here is a famously common first experience, so do + not feel bad about it. diff --git a/src/components/github/IssuesAndTrackingLesson.tsx b/src/components/github/IssuesAndTrackingLesson.tsx index 4897601e..a76790dd 100644 --- a/src/components/github/IssuesAndTrackingLesson.tsx +++ b/src/components/github/IssuesAndTrackingLesson.tsx @@ -197,8 +197,8 @@ body: {" "} can set{" "} blank_issues_enabled: false{" "} - and add links to Discussions, the docs, or a chat. Most projects find that half their issue - volume was questions, and pointing those somewhere better helps both sides. + and add links to Discussions, the docs, or a chat. On many projects a large share of issues turn + out to be questions, and pointing those somewhere better helps both sides. diff --git a/src/components/github/MergeConflictsLesson.tsx b/src/components/github/MergeConflictsLesson.tsx index 9d718629..7e3a68d5 100644 --- a/src/components/github/MergeConflictsLesson.tsx +++ b/src/components/github/MergeConflictsLesson.tsx @@ -205,8 +205,8 @@ git cherry-pick --abort # a conflicted cherry-pick`} {" "} switches on "reuse recorded resolution". Git records how you resolved each conflict and replays that resolution automatically when it sees the same one again — which - happens constantly if you rebase a long-lived branch repeatedly. It is off by default and - almost everybody who turns it on keeps it on. + happens constantly if you rebase a long-lived branch repeatedly. It is off by default, so + you have to switch it on yourself. diff --git a/src/components/github/MergingAPullRequestLesson.tsx b/src/components/github/MergingAPullRequestLesson.tsx index 2e7edf14..d1589aca 100644 --- a/src/components/github/MergingAPullRequestLesson.tsx +++ b/src/components/github/MergingAPullRequestLesson.tsx @@ -68,8 +68,8 @@ export function MergingAPullRequestLesson() { commits are not merged; they stay on the branch, which is usually then deleted.

- This is the most popular option on GitHub by a wide margin, and the reason is worth stating - plainly: every commit on main builds and passes. Bisect becomes reliable, + Many teams default to this option, and the reason is worth stating plainly: with required + checks, every commit on main builds and passes. Bisect becomes reliable, reverting is one commit with no flags, and the log reads as a list of features rather than a list of afternoons.

@@ -130,7 +130,7 @@ rows and aborted the download. Fixes #482.`} And afterwards: delete the branch. GitHub offers a button and a setting to do it automatically, and the commits are safely in main either way. If you need it back, the - Restore branch button on the pull request works for months. + Restore branch button on the pull request brings it back.

Whether that is good depends on your taste. Some teams want a clean straight line; others - want the record that these three commits were one piece of work reviewed together. Git + want the record that these commits were one piece of work reviewed together. Git lets you insist on the record:

- M is a merge commit, and it is the only kind of commit with two parents. + M is a merge commit, and it is the only kind of commit with more than one + parent. It contains the combined result, it records that these two lines of development joined here, and Git writes its message for you.

@@ -231,7 +232,7 @@ git branch -d fix/login # safe delete: refuses if the work is NOT merged`} "Stand on main and merge the branch to publish work; stand on the branch and merge main to catch up.", "A fast-forward happens when the target has not moved: no commit is created, the label slides.", "--no-ff forces a merge commit anyway; --ff-only refuses to merge unless it can fast-forward.", - "A three-way merge builds a merge commit — the only commit with two parents.", + "A three-way merge builds a merge commit — the only kind of commit with more than one parent.", "The merge base is the most recent shared commit, and it is what lets Git tell an addition from a deletion.", "A line changed on one side is taken silently. A line changed on both sides is a conflict.", "git merge --abort undoes a merge in progress completely.", diff --git a/src/components/github/OpeningAPullRequestLesson.tsx b/src/components/github/OpeningAPullRequestLesson.tsx index c2e7fdcc..ed368066 100644 --- a/src/components/github/OpeningAPullRequestLesson.tsx +++ b/src/components/github/OpeningAPullRequestLesson.tsx @@ -206,7 +206,7 @@ gh pr ready # mark it ready when it is`} }, { label: "The commit tested never existed", - text: "The tested commit is a temporary merge that is not on any branch. This is why a pull request can go red without you pushing anything.", + text: "The tested commit is a temporary merge that is not on any branch. This is why re-running the checks can turn a pull request red without you pushing anything — main moved underneath it.", }, { label: "Required vs optional", @@ -249,7 +249,7 @@ gh pr view --web # open the failing run's logs`} "The description is read by more people than the diff. Say why, and say what you are unsure about.", "A draft pull request cannot be merged and does not request reviewers — good from day one of the work.", "The merge button is gated by required checks, no outstanding changes requested, and enough approvals.", - "Checks run against a temporary merge with the base, not your branch, so a pull request can go red with no push.", + "Checks run against a temporary merge with the base, not your branch, so a re-run can go red with no push from you.", "Small pull requests get reviewed. Large ones get approved.", ]} /> diff --git a/src/components/github/ReadingHistoryLesson.tsx b/src/components/github/ReadingHistoryLesson.tsx index 8038c221..c07536bb 100644 --- a/src/components/github/ReadingHistoryLesson.tsx +++ b/src/components/github/ReadingHistoryLesson.tsx @@ -108,7 +108,7 @@ git log -S "loadUser"`} { label: "git diff", text: "Working tree against the index. What you have changed and NOT staged. Silent if everything is staged." }, { label: "--staged", text: "Index against HEAD. Exactly what your next commit will contain. Read this before every commit." }, { label: "HEAD", text: "Working tree against the last commit. Everything you have done since, staged or not." }, - { label: "a..b", text: "Any two commits, branches, or tags. git diff main..fix/login shows what the branch adds." }, + { label: "a..b", text: "Any two commits, branches, or tags, compared tip to tip. git diff main..fix/login is the same as git diff main fix/login." }, ]} /> diff --git a/src/components/github/RebaseAndHistoryLesson.tsx b/src/components/github/RebaseAndHistoryLesson.tsx index be02f8bd..7f6735b4 100644 --- a/src/components/github/RebaseAndHistoryLesson.tsx +++ b/src/components/github/RebaseAndHistoryLesson.tsx @@ -20,7 +20,7 @@ export function RebaseAndHistoryLesson() {

A rebase takes each of your commits in turn, computes the change it made, and applies that change on top of a different commit. The result is a new commit with the same message, the - same author, the same content — and a different hash, because the parent is different and + same author, the same change — and a different hash, because the parent is different and the hash covers the parent.

@@ -112,7 +112,8 @@ git rebase main lineTones={{ 0: "ok", 1: "ok", 2: "err", 3: "err" }} />

- Every commit is now duplicated. If they merge, both copies land and the diff applies twice. + Every commit is now duplicated. If they merge, both copies end up in the history side by + side, and anything they built on the originals is tangled up with your rewritten ones. Untangling this is unpleasant and it is always somebody else's afternoon, not yours.

diff --git a/src/components/github/RepositoriesAndTheThreeTreesLesson.tsx b/src/components/github/RepositoriesAndTheThreeTreesLesson.tsx index 7ec14861..7435d322 100644 --- a/src/components/github/RepositoriesAndTheThreeTreesLesson.tsx +++ b/src/components/github/RepositoriesAndTheThreeTreesLesson.tsx @@ -180,8 +180,8 @@ Untracked files: variant="terminal" code={`# Same information, one line per file, once you know the letters git status --short -# M src/auth/redirect.ts staged modification -# M src/lib/users.ts modified, not staged +# M src/auth/redirect.ts left column: staged +# M src/lib/users.ts right column: modified, not staged # ?? notes.md untracked`} /> @@ -205,12 +205,13 @@ git status --short code={`git add report.md # index now matches disk # ... you keep typing ... git status --short -# M report.md staged: the version from the git add -# M report.md not staged: everything you typed since`} +# MM report.md +# left M: a staged version, from the git add +# right M: newer edits on disk, not staged`} />

- The same file appears twice, because there are two different versions of it. The - fix is to git add again before committing. This is not a bug and it is not + The file carries two letters, one per column, because there are two different versions of + it — and in the full git status it is listed under both headings. The fix is to git add again before committing. This is not a bug and it is not a trap — it is exactly the behaviour that makes staging useful — but it is the most common source of "I committed it and the change is not there".

@@ -220,6 +221,25 @@ git status --short every commit catches the half-staged file, the stray debug print, and the accidentally pasted password — in that order of frequency.
+

+ Try it yourself. Make a throwaway repository and watch one file move + through the three places. The comments are what each command prints. +

+ notes.txt +git status --short # ?? notes.txt untracked +git add notes.txt +git status --short # A notes.txt staged as a new file +echo "two" >> notes.txt +git status --short # AM notes.txt staged, then changed again +git diff --staged # shows only the line "one" +git add notes.txt +git commit -m "Add notes" +git status --short # (nothing: all three places agree)`} + /> - Almost every leaked credential on GitHub arrived by way of{" "} + A very common way credentials leak onto GitHub is{" "} git add . catching a file the author had forgotten existed. Running{" "} git status first takes @@ -61,7 +61,7 @@ git restore --staged . # unstage everything, keeping every edit`}

This looks like arbitrary pedantry and it is not. Git itself writes messages in the - imperative when it generates them — "Merge branch feature into main", "Revert - Add the caching layer". Your messages sit in the same list, and matching the mood makes + imperative when it generates them — Merge branch 'feature',{" "} + Revert "Add the caching layer". Your messages sit in the same list, and matching the mood makes the log read as one document rather than a pile of styles.

diff --git a/src/components/github/UndoingThingsLesson.tsx b/src/components/github/UndoingThingsLesson.tsx index c6b8ea03..f64781e0 100644 --- a/src/components/github/UndoingThingsLesson.tsx +++ b/src/components/github/UndoingThingsLesson.tsx @@ -19,9 +19,8 @@ export function UndoingThingsLesson() { title="Name what you regret before picking a command" >

- This chapter exists because the top search result for "git undo" is a Stack - Overflow answer with eleven commands and forty thousand upvotes, and running the wrong one - of them destroys work. + This chapter exists because searching for "git undo" turns up long answers + listing many commands side by side, and running the wrong one of them destroys work.

The reliable method is to stop and say out loud what you want to lose. There are only six @@ -32,13 +31,13 @@ export function UndoingThingsLesson() {

- git restore overwrites a file in your working tree with the version from - the last commit. Whatever you had typed is gone — not in the index, not in a commit, not in + git restore overwrites a file in your working tree with the version in + the index — which is the last commit, unless you had staged a newer version. Whatever you had typed is gone — not in the index, not in a commit, not in the reflog. Gone.

@@ -191,7 +190,7 @@ git revert HEAD # undo the very last commit, safely`}

One file per branch, each containing one commit hash and a newline. Forty-one bytes. That diff --git a/src/components/github/WhyVersionControlLesson.tsx b/src/components/github/WhyVersionControlLesson.tsx index 41989e5e..b0cee3a2 100644 --- a/src/components/github/WhyVersionControlLesson.tsx +++ b/src/components/github/WhyVersionControlLesson.tsx @@ -57,8 +57,8 @@ site-final-USE-THIS-ONE (copy)/`} />

Git answers all four, and the price is learning a handful of ideas that are - strange the first time. It is worth it — this is the tool every professional developer on - earth uses, every day, and it has been the standard for twenty years. + strange the first time. It is worth it — this is the tool nearly every software team uses, + every day, and it has been around since 2005.

diff --git a/src/components/html-css/AccessibilityBasicsLesson.tsx b/src/components/html-css/AccessibilityBasicsLesson.tsx index 22b6a994..4b1766d4 100644 --- a/src/components/html-css/AccessibilityBasicsLesson.tsx +++ b/src/components/html-css/AccessibilityBasicsLesson.tsx @@ -43,7 +43,7 @@ export function AccessibilityBasicsLesson() { {" "} with two keyboard handlers is a worse{" "} <button>. Bad - ARIA is measurably worse than no ARIA. + ARIA is worse than no ARIA, because it announces things that are not true.

These are the ARIA attributes most likely to appear on a static site: @@ -172,7 +172,7 @@ export function AccessibilityBasicsLesson() { Removing focus outlines because they look untidy makes a site unusable for anybody navigating by keyboard — there is no longer any way to tell where you are. Style the - outline instead. Chapter 21 does it once, for everything, in four lines with{" "} + outline instead. Chapter 21 does it once, for everything, in a single rule with{" "} :focus-visible.

@@ -213,7 +213,7 @@ export function AccessibilityBasicsLesson() { "Read the page with CSS off. That is roughly the screen reader experience", ]} /> - + Lighthouse and axe are useful and will find missing alt attributes, contrast failures, and unlabelled inputs in seconds. They cannot tell whether your alt text is{" "} good, whether your heading order makes sense, or whether the tab order is logical. @@ -240,7 +240,7 @@ export function AccessibilityBasicsLesson() { "outline: none makes a site unusable by keyboard. Style the outline; never delete it.", "opacity: 0 keeps things focusable, and positive tabindex scrambles the whole page order.", "Alt text describes what the image communicates; functional images describe the action; decorative ones get alt=\"\".", - "Lighthouse catches roughly a third of the problems automatically. Use the keyboard yourself for the rest.", + "Lighthouse catches only some of the problems automatically. Use the keyboard yourself for the rest.", "Almost all of it helps people who are not disabled too — it is one site that works in more conditions.", ]} /> diff --git a/src/components/html-css/ColourAndTypographyLesson.tsx b/src/components/html-css/ColourAndTypographyLesson.tsx index 67da81c6..3981c3b7 100644 --- a/src/components/html-css/ColourAndTypographyLesson.tsx +++ b/src/components/html-css/ColourAndTypographyLesson.tsx @@ -17,14 +17,16 @@ export function ColourAndTypographyLesson() { title="Four ways to write a colour, and when each helps" >

- They all produce the same pixels. The difference is which one you can read and adjust. + Hex, rgb, and hsl can describe exactly the same colour; keywords only cover about 140 named + ones, so the keyword below is the nearest match rather than the same green. The real + difference is which one you can read and adjust.

without a unit. A unitless value is a multiplier that each element applies to its own font size. A value with a unit computes once and then inherits that fixed pixel value to every child, so a large heading inherits a line height meant for - 14-pixel text and its lines overlap. + 16-pixel text and its lines overlap.

- A full-width paragraph on a 27-inch monitor is around 200 characters. Which is why an + A full-width paragraph on a large monitor can run past 200 characters a line. Which is why an unstyled page feels hard to read even though nothing is wrong with it.

With an element selected, the Styles panel on the right lists every rule that matched it — - in cascade order, most specific first, with the file and line number each came from. + in cascade order, with the winning rules at the top and the file and line number each came + from.

- Three things in that list explain most of the panel's behaviour. + Four things in that list explain most of the panel's behaviour.

diff --git a/src/components/html-css/DisplayAndFlowLesson.tsx b/src/components/html-css/DisplayAndFlowLesson.tsx index 9a87bcb4..9f3b6812 100644 --- a/src/components/html-css/DisplayAndFlowLesson.tsx +++ b/src/components/html-css/DisplayAndFlowLesson.tsx @@ -98,7 +98,7 @@ ul ol li form figure blockquote table hr`}

An img is inline, so it sits on the text baseline — and the baseline leaves room for descenders, the tails of{" "} - g and y. That space is the four-pixel gap under an image inside a + g and y. That space is the few-pixel gap under an image inside a container. Two fixes:{" "} img {"{ display: block; }"}{" "} or{" "} diff --git a/src/components/html-css/DocumentStructureLesson.tsx b/src/components/html-css/DocumentStructureLesson.tsx index d2b59d52..3a3c1146 100644 --- a/src/components/html-css/DocumentStructureLesson.tsx +++ b/src/components/html-css/DocumentStructureLesson.tsx @@ -8,7 +8,7 @@ export function DocumentStructureLesson() { return (
- Every page on the internet starts with the same eight lines, and each one is doing a job you + Every page on the internet starts with the same dozen lines, and each one is doing a job you can name. Then see the same markup as a tree, because that is what the browser turns it into and what CSS selects from. @@ -99,7 +99,7 @@ export function DocumentStructureLesson() { }, { label: "viewport", - text: "Without this, a phone renders your page at 980 pixels wide and zooms out, so everything is tiny and no CSS media query ever fires. Chapter 19 explains how to make the layout respond.", + text: "Without this, a phone renders your page at 980 pixels wide and zooms out, so everything is tiny and your small-screen media queries never fire. Chapter 19 explains how to make the layout respond.", }, { label: "title", @@ -176,7 +176,7 @@ export function DocumentStructureLesson() { "html has exactly two children: head, which is about the page, and body, which is the page.", "lang on html tells screen readers how to pronounce your words.", "charset utf-8 goes first, before anything the browser has to decode.", - "The viewport meta tag is what makes a phone render your page at its real width — without it no media query fires.", + "The viewport meta tag is what makes a phone render your page at its real width — without it your small-screen media queries never fire.", "title is the tab, the bookmark, and the search headline. Specific first, site name second.", "The browser turns your markup into a tree called the DOM. Your indentation is ignored.", "Parent, child, descendant, sibling, ancestor — these are CSS selector vocabulary, not jargon.", diff --git a/src/components/html-css/DomTree.tsx b/src/components/html-css/DomTree.tsx index 61578639..b3b49543 100644 --- a/src/components/html-css/DomTree.tsx +++ b/src/components/html-css/DomTree.tsx @@ -31,7 +31,7 @@ const NODES: readonly Node[] = [ { id: "head", depth: 1, source: "", label: "head", kind: "element", note: "Information about the page. Nothing here is drawn — it is the first child of html, and a sibling of body." }, { id: "title", depth: 2, source: "My site", label: "title", kind: "element", note: "A child of head, a grandchild of html. Shown in the browser tab, not on the page." }, { id: "body", depth: 1, source: "", label: "body", kind: "element", note: "Everything visible. A child of html and a SIBLING of head — the two share a parent, which is what sibling means." }, - { id: "h1", depth: 2, source: "

Hello

", label: "h1", kind: "element", note: "A child of body. In CSS, `body h1` and `body > h1` both match it here — but only because it is a direct child." }, + { id: "h1", depth: 2, source: "

Hello

", label: "h1", kind: "element", note: "A child of body. In CSS, `body h1` matches it, and so does `body > h1` — the second only because h1 is a direct child of body." }, { id: "p", depth: 2, source: "

Some text

", label: "p", kind: "element", note: "A sibling of h1. Note it has a child of its own, which is what makes this a tree rather than a list." }, { id: "em", depth: 3, source: " text", label: "em", kind: "element", note: "A child of p, a DESCENDANT of body, and not a child of body. `body > em` matches nothing; `body em` matches this. That distinction is a whole CSS chapter." }, ]; diff --git a/src/components/html-css/ElementsAndTagsLesson.tsx b/src/components/html-css/ElementsAndTagsLesson.tsx index e50cc0b8..0dfe6db4 100644 --- a/src/components/html-css/ElementsAndTagsLesson.tsx +++ b/src/components/html-css/ElementsAndTagsLesson.tsx @@ -91,7 +91,7 @@ export function ElementsAndTagsLesson() { `} />

- There are about fourteen in total and those six are all you will use. Note that{" "} + There are thirteen in total and those six are the ones you will use most. Note that{" "} <link> is void — it points at a stylesheet — while{" "} <a>, the one people call a link, wraps content and definitely closes. @@ -121,8 +121,8 @@ export function ElementsAndTagsLesson() { {" "} and{" "} </br>. - There is no content to wrap and nothing to close. Browsers ignore the stray closing - tag, so it looks like it works. + There is no content to wrap and nothing to close. Browsers patch over both — the + stray closing tag is dropped or reinterpreted — so it looks like it works.

), }, diff --git a/src/components/html-css/FlexboxLesson.tsx b/src/components/html-css/FlexboxLesson.tsx index 278c518f..15e466fd 100644 --- a/src/components/html-css/FlexboxLesson.tsx +++ b/src/components/html-css/FlexboxLesson.tsx @@ -2,6 +2,7 @@ import { Lead, LessonSection, P, Strong } from "@/components/learn/primitives/Le import { Callout } from "@/components/learn/primitives/Callout"; import { CodeBlock } from "@/components/learn/primitives/CodeBlock"; import { CompareGrid, LabelRows, TakeawayCard } from "@/components/learn/primitives/Cards"; +import { RevealCard } from "@/components/learn/primitives/RevealCard"; import { FlexPlayground } from "@/components/html-css/FlexPlayground"; export function FlexboxLesson() { @@ -94,6 +95,15 @@ flex-direction: column-reverse; /* bottom to top */`} main axis is whatever flex-direction says. Toggle direction in the widget above and watch them swap. + diff --git a/src/components/html-css/FormsAndInputsLesson.tsx b/src/components/html-css/FormsAndInputsLesson.tsx index d4f56c3a..425a1c3c 100644 --- a/src/components/html-css/FormsAndInputsLesson.tsx +++ b/src/components/html-css/FormsAndInputsLesson.tsx @@ -160,7 +160,7 @@ export function FormsAndInputsLesson() { <button> with no type is{" "} type="submit". - So a "Add another" button submits the form and reloads the page, which looks like + So an "Add another" button submits the form and reloads the page, which looks like the form randomly resetting itself. Always write{" "} type="button"{" "} on anything that is not the submit. diff --git a/src/components/html-css/HowCssAttachesLesson.tsx b/src/components/html-css/HowCssAttachesLesson.tsx index 647c75f0..6a704125 100644 --- a/src/components/html-css/HowCssAttachesLesson.tsx +++ b/src/components/html-css/HowCssAttachesLesson.tsx @@ -163,8 +163,9 @@ h1 { />

Note that the CSS file contains no HTML, no <style> tags, nothing - but rules. Putting a style tag inside a .css file is a common first-day mistake and it - breaks the whole file — everything after it is treated as invalid. + but rules. Putting a style tag inside a .css file is a common first-day mistake: the browser reads + the tag as part of the next selector, decides that rule is invalid, and throws it away — + with no error anywhere.

Because these defaults differ slightly between browsers, most projects start with a{" "} reset — a few rules that normalise them. A minimal one is three - declarations and covers most of the pain: + rules and covers most of the pain:

- Normalize.css and larger resets exist and are fine. For a hand-written site, those nine - lines cover nearly everything they would, and you can read all of them — which matters more + Normalize.css and larger resets exist and are fine. For a hand-written site, those three + rules cover most of what you need, and you can read all of them — which matters more at this stage than completeness.
diff --git a/src/components/html-css/LinksAndImagesLesson.tsx b/src/components/html-css/LinksAndImagesLesson.tsx index 412c014f..9382dffe 100644 --- a/src/components/html-css/LinksAndImagesLesson.tsx +++ b/src/components/html-css/LinksAndImagesLesson.tsx @@ -38,7 +38,7 @@ export function LinksAndImagesLesson() {

Those are the image's real pixel dimensions and they are not a display size. The - browser uses the ratio to reserve the right shape, then your CSS scales it. This - is the modern advice and it reverses guidance from about 2015. Older tutorials say the - opposite because browsers used to handle images differently. + browser uses the ratio to reserve the right shape, then your CSS scales it. Some + older tutorials say to leave the dimensions off; that advice dates from before browsers + used them this way, and it no longer applies.

- Without those two lines an 4000-pixel photo blows out your layout on a phone and produces + Without those two lines a 4,000-pixel photo blows out your layout on a phone and produces horizontal scrolling. Three more image rules matter:

Not because divs are banned, but because nothing so far has needed one — every region had - an element that described it. Divs will turn up in the next chapter, if a layout - needs a wrapper with no meaning. Notice how far you get before that happens. + an element that described it. A div turns up in the next section, where a group needs + a wrapper with no meaning. Notice how far you get before that happens. diff --git a/src/components/html-css/PublishingYourSiteLesson.tsx b/src/components/html-css/PublishingYourSiteLesson.tsx index a3c1bf99..a2a863ed 100644 --- a/src/components/html-css/PublishingYourSiteLesson.tsx +++ b/src/components/html-css/PublishingYourSiteLesson.tsx @@ -123,14 +123,14 @@ export function PublishingYourSiteLesson() { themselves. That matters because it used to be an annual chore with a fee.

- A custom domain costs roughly £10 a year from any registrar and points at your host with + A custom domain is a small yearly fee from any registrar, and it points at your host with one DNS record. Chapter 1 explains why the change takes a while to appear everywhere.

Two bugs account for nearly every "it worked on my laptop" report, and both are @@ -146,7 +146,7 @@ export function PublishingYourSiteLesson() { macOS and Windows treat{" "} Photo.JPG and{" "} photo.jpg as the - same file. Every Linux web server does not. So a mis-cased path works perfectly + same file. Most Linux web servers do not. So a mis-cased path works perfectly locally and 404s the instant you publish.

), @@ -211,7 +211,7 @@ export function PublishingYourSiteLesson() { }, { label: "Run Lighthouse on the live URL", - detail: "The devtools tab audits performance, accessibility, best practices, and SEO in one click. Read the accessibility and SEO sections in particular; they point to specific fixes.", + detail: "The devtools tab audits performance, accessibility, best practices, and SEO in one click. Read the accessibility and SEO sections in particular; they point to specific fixes.", }, ]} /> @@ -232,11 +232,13 @@ export function PublishingYourSiteLesson() { />