"""Original R008 authoring source. Python 3.10+, standard library only. Reads only exercises.json and the named original pack files; no network. """ from pathlib import Path import hashlib import html import json import re import struct import textwrap import zipfile import zlib SOURCE=Path(__file__).resolve() STANDALONE=(SOURCE.parent/'exercises.json').is_file() ROOT=SOURCE.parents[2] OUT=SOURCE.parent if STANDALONE else ROOT/'website/public/resources/r008-v1' DATA=json.loads((OUT/'exercises.json').read_text(encoding='utf-8')) ITEMS=DATA['exercises'] # Original handwritten-style polylines. A raised 2 intentionally sits between # the end of 'sin' and the x; no original student writing is used. GLYPHS={ 'f':[[(.75,0),(.4,.05),(.25,1.1)],[(0,.4),(.7,.35)]], '(':[[(.65,0),(.2,.25),(0,.6),(.2,.95),(.65,1.15)]], ')':[[(0,0),(.45,.25),(.65,.6),(.45,.95),(0,1.15)]], 'x':[[(0,.2),(.8,1)],[(.85,.15),(0,1)]], '=':[[(0,.4),(.9,.4)],[(0,.7),(.9,.7)]], 's':[[(.8,.3),(.4,.2),(0,.4),(.65,.7),(.8,.85),(.4,1),(0,.9)]], 'i':[[(.4,.38),(.35,1)],[(.4,.1),(.43,.14)]], 'n':[[(0,1),(0,.25),(.1,.4),(.5,.23),(.75,.4),(.8,1)]], '2':[[(0,.2),(.2,0),(.65,0),(.85,.25),(.45,.65),(0,1),(.9,1)]]} def note_paths(): for i,c in enumerate('f(x)=sin'): for path in GLYPHS[c]:yield [(i*19+a*15,25+b*26) for a,b in path] for path in GLYPHS['x']:yield [(174+a*16,25+b*26) for a,b in path] for path in GLYPHS['2']:yield [(154+a*10,7+b*15) for a,b in path] def note_png(): width,height,scale=640,220,3 b=bytearray([255]*(width*height*3)) for path in note_paths(): for (x0,y0),(x1,y1) in zip(path,path[1:]): x0,y0,x1,y1=[v*scale+20 for v in [x0,y0,x1,y1]] steps=max(1,int(max(abs(x1-x0),abs(y1-y0))*2)) for n in range(steps+1): x,y=round(x0+(x1-x0)*n/steps),round(y0+(y1-y0)*n/steps) for dx in range(-2,3): for dy in range(-2,3): if 0<=x+dxI',len(p))+t+p+struct.pack('>I',zlib.crc32(t+p)) rows=b''.join(b'\0'+b[y*width*3:(y+1)*width*3] for y in range(height)) return b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR',struct.pack('>IIBBBBB',width,height,8,2,0,0,0))+chunk(b'IDAT',zlib.compress(rows,9))+chunk(b'IEND',b'') class Page: def __init__(self):self.parts=['0.10 0.13 0.16 rg\n'];self.bound=[] def text(self,value,x,y,size=11,font='F1'): assert all(ord(c)<128 for c in value),value # Courier's exact width is used for equations; conservative bound for prose. width=len(value)*size*(.6 if font=='F3' else .58) assert x>=36 and y>=30 and y<=762,(value,x,y) if font=='F3':assert x+width<=580,(value,width) self.bound.append({'text':value,'x':x,'y':y,'size':size}) t=value.replace('\\','\\\\').replace('(','\\(').replace(')','\\)') self.parts.append(f'BT /{font} {size} Tf {x} {792-y} Td ({t}) Tj ET\n') def para(self,value,x,y,width=89,size=10.5,leading=14): for line in textwrap.wrap(value,width=width):self.text(line,x,y,size);y+=leading return y def line(self,x,y,w):self.parts.append(f'0.65 G 0.45 w {x} {792-y} m {x+w} {792-y} l S\n') def note(self,x,y): self.parts.append('0.10 0.13 0.16 RG 1.5 w 1 J 1 j\n') for path in note_paths(): self.parts.append(f'{x+path[0][0]} {792-y-path[0][1]} m '+' '.join(f'{x+a} {792-y-b} l' for a,b in path[1:])+' S\n') def stream(self):return ''.join(self.parts).encode('ascii') def pdf(pages): objects=[b'<< /Type /Catalog /Pages 2 0 R >>',b'', b'<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>', b'<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold >>', b'<< /Type /Font /Subtype /Type1 /BaseFont /Courier >>'] kids=[] for p in pages: n=len(objects)+1;kids.append(f'{n} 0 R');stream=p.stream() objects.append(f'<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 3 0 R /F2 4 0 R /F3 5 0 R >> >> /Contents {n+1} 0 R >>'.encode()) objects.append(f'<< /Length {len(stream)} >>\nstream\n'.encode()+stream+b'endstream') objects[1]=f'<< /Type /Pages /Kids [{" ".join(kids)}] /Count {len(kids)} >>'.encode() out=bytearray(b'%PDF-1.4\n%\xe2\xe3\xcf\xd3\n');offsets=[0] for n,obj in enumerate(objects,1):offsets.append(len(out));out+=f'{n} 0 obj\n'.encode()+obj+b'\nendobj\n' xref=len(out);out+=f'xref\n0 {len(objects)+1}\n0000000000 65535 f \n'.encode() for offset in offsets[1:]:out+=f'{offset:010d} 00000 n \n'.encode() out+=f'trailer\n<< /Size {len(objects)+1} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n'.encode() return bytes(out) def heading(p,key,page): p.text('CALCULUS / FIND THE FIRST ERROR',42,43,10,'F2') p.text('Instructor key' if key else 'Error-checking worksheet',42,72,22,'F2') p.text(f'{"KEY" if key else "WORKSHEET"} {page} / 2',466,43,10,'F2') p.text('Original R008 v1.0 | (c) 2026 InkDraft. Copy, adapt and share with this notice.',42,738,8.5) p.text('Full reuse terms: inkdraft.org/resources/r008-v1/LICENSE.txt',42,750,8.5) p.text('Paper alone is enough. No app, account or purchase required.',42,762,9) def worksheets(): pages=[] for page in [1,2]: p=Page();heading(p,False,page) if page==1: p.text('Find the first wrong line, or write "no error". Explain and repair the derivative.',42,96,11) p.text('All angles are in radians. x^2 means x squared; * means multiplication.',42,112,10.5) else: p.text('Keep the stated domain. Do not assume every example contains an error.',42,96,11) p.text('For the final note, ask for clarification before selecting a derivative.',42,112,10.5) for slot,e in enumerate(ITEMS[(page-1)*4:page*4]): top=140+slot*145 p.text(f'{e["id"]}. {e["title"]}',42,top,12,'F2') if e['id']!=8: p.text(e['function'],42,top+19,11.3,'F3') p.text('Domain: '+e['domain'],370,top,9) for j,line in enumerate(e['work'],1):p.text(f'{j}. {line}',52,top+36+(j-1)*16,10.4,'F3') p.text('First error (or none): ______ Reason / corrected derivative:',42,top+90,10) p.line(42,top+113,528);p.line(42,top+132,528) else: p.text('The copied exponent placement is unclear.',42,top+19,10.5) p.note(54,top+26) p.text('Ask the writer to clarify. Give both possible readings',282,top+43,10) p.text('and conditional derivatives; do not choose one.',282,top+58,10) p.line(42,top+101,528);p.line(42,top+124,528) pages.append(p) return pages def keys(): pages=[] for page in [1,2]: p=Page();heading(p,True,page) p.text('Use after learners have made their own decisions. Equivalent correct forms are valid.',42,99,10.5) for slot,e in enumerate(ITEMS[(page-1)*4:page*4]): top=132+slot*148 outcome='Clarification required' if e['id']==8 else 'No error' if e['first_error'] is None else f'First error: line {e["first_error"]}' p.text(f'{e["id"]}. {outcome}',42,top,12,'F2') y=p.para(e['reason'],42,top+19,width=94,size=10.5,leading=14) if e['id']==8: clauses=re.split(r'(?<=\.) (?=If )',e['repair']) for i,line in enumerate(clauses):p.text(line,42,y+4+i*17,11,'F3') y+=len(clauses)*17+1 else:p.text(e['repair'],42,y+5,10.8,'F3');y+=20 y=p.para(e['check'],42,y+7,width=100,size=9.5,leading=12) p.text('Domain: '+e['domain'],42,y+3,9.5) assert y+3{title} | InkDraft
InkDraft · Open teaching resources{'Worksheet' if key else 'Separate instructor key'}

CALCULUS · ORIGINAL RESOURCE · R008 v1.0

{'Instructor key' if key else 'Find the first error.'}

{'Decisions, explanations and corrected derivatives for all eight examples.' if key else 'Eight worked examples. Decide what is wrong, what is already correct, and when the source needs clarification.'}

Paper alone is enough. No InkDraft purchase, account, connection or software is needed. Print the worksheet and write your reasoning, or use this HTML version with your own paper.

'''] if key: parts.append('

Use this key after an independent attempt. Accept equivalent algebraic forms on the stated domain. Examples 2 and 6 are correct-work controls; example 8 requires clarification. No student trial or learning outcome is claimed.

A numerical counterexample can disprove a proposed derivative; agreement at one point cannot prove it. The repairs below have also been checked by symbolic differentiation.

') else: parts.append(f'

How to use it

{html.escape(DATA["instructions"])}

{html.escape(DATA["assumptions"])}

This page is the text alternative to the print PDF. It has no answer-entry form and collects no student work. The instructor key is on a separate page.

') for e in ITEMS: parts.append(f'

{e["id"]}. {html.escape(e["title"])}

') if e['id']!=8:parts.append(f'

{html.escape(e["function"])}

') parts.append(f'

Domain: {html.escape(e["domain"])}

') if key: result='Clarification required' if e['id']==8 else 'No error' if e['first_error'] is None else f'First error: line {e["first_error"]}' parts.append(f'

{result}

{html.escape(e["reason"])}

{html.escape(e["repair"])}

{html.escape(e["check"])}

') elif e['id']==8: parts.append(f'
{ALT}
Original generated stroke drawing. The exponent placement is deliberately unclear; this is not a sample of student work.

{html.escape(e["prompt"])}

Write your clarification question and both conditional derivatives on paper.

') else: parts.append('
    '+''.join(f'
  1. {html.escape(line)}
  2. ' for line in e['work'])+'

First error (or no error)? Explain your decision and write a corrected derivative if needed.

') parts.append('
') parts.append(f'''

Reuse and adapt

These original exercises and the generated note may be copied, adapted and distributed under the included reuse license, with its notice. It covers R008 material only. No endorsement or learning gains are implied.

Edit exercises.json and rebuild with the included Python generator, or adapt the included HTML directly. Printing and editing instructions · File checksums.

''') return '\n'.join(parts)+'\n' def write(name,value): if isinstance(value,bytes):(OUT/name).write_bytes(value) else:(OUT/name).write_text(value,encoding='utf-8',newline='\n') def main(): student=worksheets();teacher=keys() write('calculus-first-error-worksheet.pdf',pdf(student)) write('calculus-first-error-instructor-key.pdf',pdf(teacher)) write('ambiguous-note.png',note_png()) write('worksheet.html',webpage());write('instructor-key.html',webpage(True));write('resource.css',CSS+'\n') write('generate.py',SOURCE.read_bytes()) if not STANDALONE: public=ROOT/'website/public' (public/'calculus-first-error.html').write_text(webpage(web=True),encoding='utf-8',newline='\n') (public/'calculus-first-error-key.html').write_text(webpage(True,True),encoding='utf-8',newline='\n') (public/'calculus-first-error.css').write_text(CSS+'\n',encoding='utf-8',newline='\n') names=['exercises.json','generate.py','README.txt','LICENSE.txt','calculus-first-error-worksheet.pdf','calculus-first-error-instructor-key.pdf','ambiguous-note.png','worksheet.html','instructor-key.html','resource.css'] write('SHA256SUMS.txt',''.join(f'{hashlib.sha256((OUT/n).read_bytes()).hexdigest()} {n}\n' for n in sorted(names))) with zipfile.ZipFile(OUT/'inkdraft-r008-v1.zip','w',compression=zipfile.ZIP_DEFLATED,compresslevel=9) as z: for name in sorted(names+['SHA256SUMS.txt']): info=zipfile.ZipInfo('inkdraft-r008-v1/'+name,date_time=(2026,11,18,0,0,0));info.compress_type=zipfile.ZIP_DEFLATED;info.external_attr=0o100644<<16 z.writestr(info,(OUT/name).read_bytes()) print('Generated 2 worksheet + 2 key pages, accessible web/offline HTML and 12-file pack.') if __name__=='__main__':main()