Lawfare Group → Knowledge Institute → Lawfare Academy
Reproduce the worked examples
Copy the complete code below into a UTF-8 file named verify.py and run python verify.py with Python 3. It uses only the standard library and creates disposable in-memory SQLite databases. It does not access a network or learner records. Assertions fail if the expected synthetic results change.
These checks verify the stated arithmetic and query behavior, not independent academic acceptance or production migration safety.
"""Python 3 standard-library fixtures. Synthetic data only; no network or live DB."""
import math,statistics,sqlite3,json
def probability():
cells=[180,20,490,9310];p=180/670;negative=20/9330;rare=.0009/(.0009+.04995)
assert sum(cells)==10000 and abs(p-18/67)<1e-14
assert 100*p>10 and 100*rare<10 and 1000*rare>10
return dict(cells=cells,posterior=p,negative_posterior=negative,rare_posterior=rare,rare_flagged_expected=[9,499.5])
def comparisons():
groups=[[8,9,10],[10,11,12],[12,13,14]];means=list(map(statistics.mean,groups));grand=statistics.mean(sum(groups,[]))
between=sum(len(g)*(m-grand)**2 for g,m in zip(groups,means));within=sum(sum((v-m)**2 for v in g) for g,m in zip(groups,means));total=sum((v-grand)**2 for v in sum(groups,[]))
mse=within/6;se=math.sqrt(mse*(1/3+1/3));critical=2.4469118511449692
assert [between,within,total]==[24,6,30] and between/2/mse==12
return dict(means=means,SS=[between,within,total],df=[2,6,8],F=12,contrast=4,SE=se,t=4/se,CI=[4-critical*se,4+critical*se],second_contrast={'estimate':3,'SE':math.sqrt(.5)})
def normalization():
db=sqlite3.connect(':memory:');db.execute('PRAGMA foreign_keys=ON')
db.executescript('CREATE TABLE original(order_id TEXT NOT NULL,line_no INTEGER NOT NULL,customer_id TEXT NOT NULL,name TEXT NOT NULL,day TEXT NOT NULL,product TEXT NOT NULL,qty INTEGER NOT NULL,price INTEGER NOT NULL,PRIMARY KEY(order_id,line_no)); CREATE TABLE customers(customer_id TEXT PRIMARY KEY NOT NULL,name TEXT NOT NULL); CREATE TABLE orders(order_id TEXT PRIMARY KEY NOT NULL,customer_id TEXT NOT NULL REFERENCES customers(customer_id),day TEXT NOT NULL); CREATE TABLE lines(order_id TEXT NOT NULL REFERENCES orders(order_id),line_no INTEGER NOT NULL,product TEXT NOT NULL,qty INTEGER NOT NULL CHECK(qty>0),price INTEGER NOT NULL CHECK(price>=0),PRIMARY KEY(order_id,line_no));')
rows=[('O1',1,'C1','North','2026-01-05','P1',2,10),('O1',2,'C1','North','2026-01-05','P2',1,30),('O2',1,'C1','North','2026-01-06','P1',3,10)]
db.executemany('INSERT INTO original VALUES(?,?,?,?,?,?,?,?)',rows);db.execute("INSERT INTO customers VALUES('C1','North')");db.executemany('INSERT INTO orders VALUES(?,?,?)',[('O1','C1','2026-01-05'),('O2','C1','2026-01-06')]);db.executemany('INSERT INTO lines VALUES(?,?,?,?,?)',[(v[0],v[1],v[5],v[6],v[7]) for v in rows]);db.commit()
query='SELECT l.order_id,l.line_no,o.customer_id,c.name,o.day,l.product,l.qty,l.price FROM lines l JOIN orders o ON o.order_id=l.order_id JOIN customers c ON c.customer_id=o.customer_id'
restored=db.execute(query+' ORDER BY l.order_id,l.line_no').fetchall();assert restored==rows
assert not db.execute('SELECT * FROM original EXCEPT '+query).fetchall() and not db.execute(query+' EXCEPT SELECT * FROM original').fetchall()
totals=db.execute('SELECT order_id,SUM(qty*price) FROM lines GROUP BY order_id ORDER BY order_id').fetchall();assert totals==[('O1',50),('O2',30)]
try:db.execute("INSERT INTO lines VALUES('O1',1,'P3',1,99)");raise AssertionError('Duplicate line accepted')
except sqlite3.IntegrityError:db.rollback()
hypothetical=[('O1',2*12+30),('O2',3*12)];assert hypothetical==[('O1',54),('O2',36)]
return dict(restored_rows=restored,totals=totals,total=80,hypothetical_catalog_repricing=hypothetical,duplicate_key_rejected=True)
def windows():
db=sqlite3.connect(':memory:');db.executescript('CREATE TABLE sales(id INTEGER PRIMARY KEY,rep TEXT,day TEXT,amount INTEGER);')
db.executemany('INSERT INTO sales VALUES(?,?,?,?)',[(1,'A','2026-01-01',100),(2,'A','2026-02-01',300),(3,'B','2026-01-01',200),(4,'B','2026-02-01',100),(5,'B','2026-02-01',50)])
raw=db.execute('SELECT id,rep,SUM(amount) OVER(PARTITION BY rep ORDER BY day,id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) FROM sales ORDER BY rep,day,id').fetchall();assert raw==[(1,'A',100),(2,'A',400),(3,'B',200),(4,'B',300),(5,'B',350)]
peers=db.execute("SELECT id,SUM(amount) OVER(PARTITION BY rep ORDER BY day) FROM sales WHERE rep='B' ORDER BY day,id").fetchall();assert peers==[(3,200),(4,350),(5,350)]
monthly="SELECT rep,substr(day,1,7) AS month,SUM(amount) AS amount FROM sales GROUP BY rep,substr(day,1,7)"
full=db.execute('WITH monthly AS ('+monthly+'), running AS (SELECT rep,month,SUM(amount) OVER(PARTITION BY rep ORDER BY month ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS cumulative FROM monthly) SELECT rep,cumulative FROM running WHERE month=\'2026-02\' ORDER BY rep').fetchall();assert full==[('A',400),('B',350)]
truncated=db.execute('WITH monthly AS ('+monthly+') SELECT rep,SUM(amount) OVER(PARTITION BY rep ORDER BY month ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) FROM monthly WHERE month=\'2026-02\' ORDER BY rep').fetchall();assert truncated==[('A',300),('B',150)]
return dict(transaction_running=raw,default_peers=peers,full_history_February=full,February_only=truncated)
def adjustment():
rows=[]
for t,e,n,y in [(0,0,2,50),(0,1,8,80),(1,0,8,55),(1,1,2,85)]:rows.extend([(t,e,y)]*n)
means=[statistics.mean(y for t,e,y in rows if t==v) for v in [0,1]];assert means==[74,61]
assert all(y==50+5*t+30*e for t,e,y in rows)
assert all(y==80+5*t-30*(1-e) for t,e,y in rows)
standardized=[(.5*50+.5*80),(.5*55+.5*85)];assert standardized==[65,70]
return dict(pooled_nonparticipant_participant=means,pooled_difference=-13,conditional_difference=5,standardized_nonparticipant_participant=standardized)
def interactions():
x=[1,2,3];a=[12,14,16];b=[19,18,17];coef=[10,2,10,-3];centered=[14,2,4,-3]
for d,ys in [(0,a),(1,b)]:
for u,v in zip(x,ys):
assert v==coef[0]+coef[1]*u+coef[2]*d+coef[3]*u*d
z=u-2;assert v==centered[0]+centered[1]*z+centered[2]*d+centered[3]*z*d
common=sum((v-(13+.5*u+4*d))**2 for d,ys in [(0,a),(1,b)] for u,v in zip(x,ys));assert common==9
assert 10-3*2==4 and 10-3*4==-2
return dict(coefficients=coef,centered_coefficients=centered,common_slope_SSE=common,interaction_SSE=0,contrast_at_2=4,crossover=10/3,contrast_at_4=-2,limits='Exact synthetic fit; no real-world precision or causal claim.')
def run():return dict(probability=probability(),comparisons=comparisons(),normalization=normalization(),windows=windows(),adjustment=adjustment(),interactions=interactions())
if __name__=='__main__':print(json.dumps(run(),indent=2))
Related chapters
- Reverse the condition before making the decision
- Ask which comparison before inspecting the means
- Normalize the facts while preserving their meaning
- Keep the window, the row and the reporting period distinct
- An adjusted coefficient still needs a causal argument
- Make the reference point and the interaction explicit