← MAAI Study Hub

MAAI802 · two papers per week. Code boxes run real Python in your browser: edit the code, then press Run.

Week 1 · Programming Foundations

MAAI802 · Problem solving, values, variables and output
Paper 1
of 2

1. Programming as problem solving

Programming = giving a computer precise instructions to solve a problem. It does exactly what the instructions say, not what we meant. Human problem → logical steps → computer instructions.

Scripting = short programs that automate tasks. AI: prepare data, check values, simple statistics. Security: search logs, count failed events, prepare a report.

Input → processing → output: almost every program follows this pattern.

An algorithm is a clear sequence of steps, written before code: get the mark → compare with 50 → choose Pass or Fail.

Learning method: concept → command → example → practice.

2. Python building blocks

Python is the language/runtime that runs instructions; an editor, IDE or notebook is where we write them. Week 1 uses built-in Python only (no imports).

A statement is one instruction on a line; Python runs statements top to bottom.

Comments start with #; Python ignores them. Explain purpose, not every obvious line.

TypeHoldsExample
strtext (in quotes)"Ali", 'Dubai'
intwhole numbers25, 100
floatdecimals3.5, 99.95
boolTrue / FalseTrue

3. Variables and assignment

A variable is a name that stores a value for later use. = means "gets the value", not "is equal to".

Naming rules: letters, numbers, underscores; not starting with a number; no spaces or hyphens; case-sensitive (age ≠ Age). Prefer meaningful names: student_name, failed_logins, not x, thing.

Allowed: age2, total_price. Not allowed: 2age, student name, total-price.

4. Output with print()

print() shows one or more values; commas separate arguments and insert a space; each print() starts a new line. Commas can mix strings and numbers.

+ joins strings (concatenation): "Hello " + name. A string + a number fails unless the number becomes a string. * repeats a string: "-" * 20.

Run it: variables, print, + and *

Valid variable name?

Remember: think in input → processing → output, write the algorithm first, then store values in well-named variables and print them.
MAAI802 · Week 1Problem solving → types → variables → print

Input, Casting, Decisions and Errors

From typed text to numbers, True/False questions and if statements
Paper 2
of 2

5. Input and casting

input("prompt") reads what the user types and always returns a string: typing 25 gives "25".

Casting converts types: int("25") → 25, float("3.5") → 3.5, str(25) → "25".

Full chain: input text → int → calculation → str → output.

6. Arithmetic and precedence

+ − * / and ( ). Order: parentheses first, then * and /, then + and −. 10 + 2 * 3 = 16; (10 + 2) * 3 = 36.

Run it: input → cast → calculate

7. Comparisons and Boolean logic

A comparison asks a question and gives True or False: == != > < >= <=. = stores, == compares.

login_success = answer == "yes" turns text into a Boolean.

and: both True. or: at least one True. not: reverses.

8. if statements

Condition + colon; the action is indented (indentation is syntax).

  • if: run only when True. if / else: two paths, only one runs.
  • elif: several paths, checked top to bottom, stops at the first True.
  • Compound: mark >= 50 and attendance >= 75.
  • Nested: an if inside an if (password checked only if the username matches).
Run it: grade with elif

9. Errors and debugging

TypeMeaningExample
Syntaxnot valid Python, cannot be parsedmissing ), colon or indentation
Runtimevalid code fails while runningint("hello") ValueError; 10 / 0 ZeroDivisionError
Logicruns, but the answer is wrongprice + discount instead of −

For syntax errors check brackets, quotes, colons, indentation first. Logic errors show no message, so test the results.

Which error type?

Same Python, two fields: average two values (AI) or alert when failed_logins >= 5 or critical_account == "yes" (security). Later this scales to datasets, Pandas, NumPy and log files.

One line: input() gives text, cast it, calculate, compare to get True/False, branch with if/elif/else, and debug syntax, runtime and logic errors calmly.
MAAI802 · Week 1Input → casting → operators → if → errors

Week 2 · Data Types, Strings and Operators

MAAI802 · Python data, input, operators, conditions and loops (no imports, files or functions yet)
Paper 1
of 2

1. Every value has a type

The type says what a value is and what it can do: str "Dubai", int 25, float 19.5, bool True. "25" looks like a number but is text.

type(x) is a built-in function (a command Python already provides) that reports the type: <class 'int'>. Use it when unsure whether you have text or a number.

2. Output and strings

print(a, b) inserts spaces between arguments; each call starts a new line. + joins strings ("Data" + " " + "Science"); * repeats ("-" * 10, "Go" * 3 → GoGoGo).

3. Simple string manipulation

ToolKind" LOGIN Failed "
len(text)built-in function16
text.strip()method: remove edge spaces"LOGIN Failed"
text.lower() / .upper()method: change case" login failed "
"fail" in text.lower()membership testTrue

Clean input before comparing: answer.strip().lower() == "yes" accepts " YES " too.

4. Input and casting

input() returns a string, always. Cast with int(), float(), str() when the value can meaningfully convert; int("hello") → ValueError.

input → cast → calculate → print; str(next_age) because + cannot join str and int.

Run it: types, cleaning and membership

5. Arithmetic operators

OpMeaning10 ? 3
+ − *add, subtract, multiply13, 7, 30
/division (float)3.333…
//integer division3
%remainder1
**power1000

Order: ( ) → ** → * / // % → + −. 2 ** 3 * 4 = 32. When in doubt, use parentheses.

Comparisons give True/False: == != > >= < <=. = stores; == asks. mark = 72 → mark >= 50 True, mark == 100 False.

Remember: check the type before you calculate, clean text with strip() and lower(), and use // for whole division, % for the remainder, ** for powers.
MAAI802 · Week 2Types → strings → casting → operators

Conditions, Loops and Debugging

Programs that decide and repeat
Paper 2
of 2

6. Boolean operators

and: True only if both are True. or: True if at least one is. not: flips. With age = 20, member = True: age >= 18 and member True, age < 18 or member True, not member False.

Truth table: tap A and B.

7. Conditionals

A True/False question decides whether the indented block runs. if → colon → indented block; else for the alternative; elif for more paths (first match wins). Compound: age >= 18 and score >= 50. Nested: if logged_in: then if is_admin: → Admin page / User page; else "Please log in".

8. Loops

A loop repeats logic without copying lines.

for + range(): a known number of repeats. range(3) → 0, 1, 2; range(1, 4) → 1, 2, 3. The stop value is not included.

while: repeat while a condition is True; tested before each repeat. Something inside must move it toward False, or it runs forever.

Use for when…Use while when…
you know how many repeatsyou repeat while a condition holds
exactly three attemptskeep asking until input is valid

range() explorer

1 4
Run it: for and while

Predict before you run (lecture checkpoints)

9. Integrated examples and debugging

AI-style rule (not ML yet): temperature > 35 and humidity > 60 → high heat risk; elif temperature > 35 → hot; else normal.

Security-style login: username.strip().lower() == "admin" and role == "admin" → admin login detected.

Errors: syntax (missing colon), runtime (int("hello"), 10 / 0), logic (price + discount gives 110 instead of 90). Debug: read the error → find the line → check type and logic → test again.

Workshop: (1) read name, age, mark, cast and print a summary; (2) clean a yes/no answer and decide; (3) a for/range loop and a while loop with a stop condition; comment your code.

Operator lab (section 5)

10 3
One line: combine conditions with and/or/not, use for with range() when you know the count and while when a condition decides, and remember range stops before its end.
MAAI802 · Week 2Boolean logic → if/elif → for, while → debugging

Week 3 · Control Logic and Pattern Matching

MAAI802 · Decisions, text scanning, safe loops and trace tables
Paper 1
of 2

1. Decisions recap

A condition is a question with a True/False answer. The condition is tested first; the colon starts the block; indented lines belong to it; only one path runs.

Compound: and (both), or (at least one), not (reverse). age >= 18 and paid == True → "Access allowed". Use parentheses when a condition gets hard to read.

2. Pattern matching (simple text checks)

Check whether useful text appears inside a larger text with in, after cleaning with strip().lower(). Not Python's match/case.

" Login FAILED for admin " → "failed" in clean_event → Failed login found.

Scanning logic: test the most specific case first. "failed" and "admin" → High; "failed" → Medium; else Normal. Testing "failed" first would never reach High.

Try the event scanner

3. Loop anatomy

  1. Initial value before the loop.
  2. Condition: should it continue?
  3. Body: the indented repeated part.
  4. Update: change something so it can stop.

Sentinel pattern: read a value, while value != "q": process it, then read again. No update → infinite loop.

4. for vs while, and common mistakes

for + range when you know the count (range(1, 4) → 1, 2, 3, stop excluded). while when a condition decides (until "q"). Don't use while when a simple for is clearer.

Mistakes: (1) forgetting the update in a while loop; (2) testing the wrong condition (== instead of !=); (3) code accidentally outside the indented block.

Predict: value = "yes"; count = 0; while value != "q": count += 1, value = "q" → prints 1 (the loop changes value to "q" once).

5. Trace tables

Record how variables change each step. Tap through:

total = 0 → for number in range(1, 4): total = total + number → print(total)

Run it: sentinel loop scanning events until q
Remember: clean text before matching, test the most specific case first, and give every loop an initial value, a condition, a body and an update.
MAAI802 · Week 3Decisions → pattern matching → loops → tracing

Functions and Modular Programming

Name, reuse, test and organise logic
Paper 2
of 2

6. Function vocabulary

Functiona named reusable block of instructions
Definecreate it with def (does not run it)
Callrun it: name()
Parameterplaceholder name inside the definition
Argumentactual value sent in the call
Return valueresult sent back to the caller

Why: write logic once, call it many times; easier to read, test, debug, reuse. Mental model: input → process → output.

Anatomy: def show_total(total):: keyword, descriptive name, parameter, colon, indented body.

Call flow: main reaches the call → body runs → call finishes → main continues ("Hello" then "Done").

7. Parameters, arguments and return

In def greet(name) … greet("Sara"): name is the parameter, "Sara" the argument. With several parameters, order matters: show_user("Ali", 25).

return sends a value back and ends the call. calculate_total(20, 3) → 60, stored in answer.

print vs return: print displays; return gives a result to use later: add_tax(100) → 105.0, + 10 → 115.0.

Local variables: total created inside a function belongs to it; outside, use the returned value.

No return → None: square(4) without return prints None.

Input still gives text: read → clean → cast → pass to the function.

Function quiz

8. Designing a good function

(1) Name the job (calculate_average); (2) decide inputs; (3) decide the result (calculations usually return); (4) test with one easy example; (5) keep it focused: one clear job.

Common mistakes: forgot to call it; missing return (None); wrong indentation.

Run it: modular average

9. Integrated functions and debugging

normalize(text) returns text.strip().lower(); classify_event(event) returns High / Medium / Normal (security); classify_temperature(temp): ≥ 38 High, ≥ 35 Normal, else Low (rule-based, not ML); access_decision(age, paid) nests if statements: Allowed / Payment required / Too young.

Debug: did Python understand it (syntax: def add_one(number) missing colon), did it run (runtime: float("abc")), did it do the intended thing (logic: discount adds 10)? Workshop: larger-of-two function, text cleaner, event loop until q, move the average into a function, trace a call.

One line: conditions choose, loops repeat, text checks match, and functions package that logic into small, named, testable pieces that return results.
MAAI802 · Week 3def → parameters → return → None → modular design

Week 4 · Strings as Sequences, Lists, Dictionaries

MAAI802 · Indexing, slicing, parsing and organising structured data
Paper 1
of 2

1. Strings are sequences

A string is an ordered sequence of characters. Positions (indexes) start at 0. a = "abcdab": a[0] a, a[1] b, a[4] a. Indexing does not change the string.

Slicing text[start:stop]: start included, stop excluded; omit start = from the beginning, omit stop = to the end. a[:2] ab, a[1:] bcdab, a[0:2] ab.

text.find(s) returns the first index of s, or −1 if missing: a.find("ab") 0, a.find("zz") −1.

Position scanning: for i in range(len(a)): visits 0…5; a[i] reads each character (e.g. print 1 whenever it is "b").

Placeholders: "{0}: {1}".format(name, status) → server01: online. {0} gets the first value, {1} the second; the rest is literal.

Slice explorer on a = "abcdab"

1 4

Before you run it: a = "abcdef"

2. Lists

A list stores several values in order in one variable: scores = [72, 81, 69] instead of score1, score2, score3. Same index/slice rules as strings; len(scores) 3.

Mutable: scores[0] = 75 changes an item. scores.append(69) adds to the end (changes the existing list).

Loop directly with for score in scores: when positions don't matter; use range(len(...)) when they do.

average(values) sums in a loop and returns total / len(values) → [10, 20, 30] gives 20.0.

3. Dictionaries

Store values by meaningful keys, not positions: {"ip": "10.0.0.5", "status": "failed", "count": 5}. Access event["ip"].

Assign to a new key to add (event["severity"] = "high"), to an existing key to update. "severity" in event checks keys.

A function can take a dictionary: classify_event(event) returns "review" if count ≥ 5, else "normal".

4. Parsing: raw text → structured record

raw line → split into parts → convert types → store in a dictionary. A delimiter separates fields; line.split(",") returns a list of strings (it doesn't guess meaning). Logs and tool output arrive as text; parsing turns them into fields you can check and count.

Run it: parse_event()
Remember: index from 0, slices exclude the stop, find() gives −1 when missing; lists hold ordered values, dictionaries hold named fields, and split() is the first step of parsing.
MAAI802 · Week 4Indexing → slicing → format → lists → dicts → parsing

Modules, Math, Random and NumPy

Arrays, vectorised operations and broadcasting
Paper 2
of 2

5. Modules and import

A module is reusable code that adds names and functions. import math makes it available; use dot notation: math.sqrt(81) 9.0, math.floor(3.8) 3, math.ceil(3.2) 4. Distance math.sqrt(3*3 + 4*4) = 5.0.

import random: random.randint(1, 6) (both ends inclusive), random.choice(["web", "db", "backup"]). Results vary, so don't predict an exact value.

math and random are standard library; NumPy is an external library: import numpy as np (np is the conventional alias).

6. NumPy arrays

Built for numeric data: element-wise operations and explicit shape. AI data (samples, features, images, parameters) are arrays.

np.array([10, 20, 30]) → [10 20 30]. Same indexing and slicing rules.

Attributes (no parentheses): .shape (3,) = 3 elements; .dtype element type.

np.arange(1, 5) [1 2 3 4] (stop excluded), np.zeros(3), np.ones(3).

2D: np.array([[1,2,3],[4,5,6]]), shape 2 × 3; matrix[row, column]: [0, 0] 1, [1, 2] 6.

7. Vectorised operations

One operation applied to every element, with no Python loop: values + 5 → [15 25 35], * 2 → [20 40 60], / 10 → [1. 2. 3.].

List vs array: [1, 2, 3] * 2 → [1, 2, 3, 1, 2, 3] (repeat); np.array([1, 2, 3]) * 2 → [2 4 6]. Know your type.

Summaries: np.sum 60, np.mean 20.0, np.min 10, np.max 30. np.sqrt([1, 4, 9, 16]) → [1. 2. 3. 4.] (math.sqrt takes one value).

8. Broadcasting

NumPy combines compatible shapes by conceptually stretching the smaller one. A scalar applies to every element (scores + 5 → [65 75 85]); a 3-value row applies to each row of a 2 × 3 matrix. [1, 2, 3] + [10, 20] fails: 3 vs 2 can't align.

Run it: NumPy (downloads NumPy on first run)

Workshop: (1) slice and find() an input string, then scan it by position; (2) split a comma-separated event into a dict, add severity, print with .format(); (3) NumPy [10, 20, 30]: + 5, × 2, mean; extensions with math.sqrt and random.

One line: import modules for reuse, use NumPy arrays for numbers, let vectorised operations replace loops, and broadcast only when shapes line up.
MAAI802 · Week 4import → math, random → arrays → vectorisation → broadcasting

Week 5 · File Handling and Log Processing

MAAI802 · Open, read, filter, parse, count and write plain-text files
Paper 1
of 2

1. Why files

Variables live in memory and vanish when the program stops; files keep data on disk for the next run. Logs usually store one event per line.

A filename is just a string: "security.log" (same folder) or "logs/security.log" (relative path). Opening it is a separate action.

Open → use → close. The with statement closes the file automatically when the block ends:

with open("security.log", "r") as file: → open(name, mode); "r" = read; as file names the file object. (Missing-file errors come with exception handling.)

2. Three ways to read

CommandReturnsUse when
file.read()all content as one stringsmall files
file.readline()the next lineone line at a time
file.readlines()a list of linesall lines in memory

For logs, loop directly: for line in file: gives the next line each iteration. Clean it with line.strip() (removes the line ending) before testing.

3. Filter, count and parse

Filter = keep records meeting a condition: if "failed" in line.strip().lower(): print(line).

Count: start at 0, add 1 per match → "Failed events: 2".

Parse: "2026-10-24,admin,5".split(",") → date, user, attempts. split gives strings; int(parts[2]) + 1 → admin 6. Store fields in a dictionary (record["user"]) to use names, not positions.

4. Writing: choose the mode deliberately

file.write(text) does not add a line break: include \n. Save results with .format(): "Failed events: {0}\n".format(failed_count).

Mistakes: "w" by accident (wipes the file), forgetting \n, comparing unclean lines.

Run it: a complete log summary script (files live in the browser's virtual disk)
Remember: open with "with", read logs line by line, strip and lower before testing, use "w" for a fresh report and "a" to keep history, and add \n yourself.
MAAI802 · Week 5open → read → filter → count → parse → write

Working with Pandas

DataFrames, selecting, filtering and aggregation
Paper 2
of 2

5. Series and DataFrames

Lists hold one ordered collection; dictionaries name fields; Pandas is built for tables. import pandas as pd (external, alias pd).

A Series is one labelled column: pd.Series([82, 67, 91, 74]) (index 0–3).

A DataFrame holds related columns, one row per record: pd.DataFrame(data) where the dictionary keys are column names and each list is a column.

Inspect first: df.head(2) (preview, no change), df.shape (4, 3), df.columns, df.dtypes: attributes, no parentheses.

6. Selecting and filtering

df["score"] → a Series; df[["name", "score"]] (a list) → a DataFrame.

A condition on a column gives a Boolean mask, one True/False per row: df["score"] >= 75 → True, False, True, False. df[mask] keeps the True rows.

Combine with & and parentheses: (df["score"] >= 75) & (df["group"] == "A"). Not Python's and.

New column, no loop: df["adjusted"] = df["score"] + 5.

DataFrame lab: df[df["score"] >= t]

75

7. Aggregation and grouping

Many values → one summary: .sum() 314, .mean() 78.5, .min(), .max(), .count() (non-missing).

Grouped: split by category → choose a column → aggregate: df.groupby("group")["score"].mean() → A 86.5, B 70.5.

Mistakes: wrong column name ("Score" ≠ "score"), and instead of &, mixing up Series and DataFrame. Read from the inside out.

Run it: Pandas (downloads Pandas on first run, ~10 s)

Predict: df2 = pd.DataFrame({"x": [10, 20, 30]}); df2[df2["x"] >= 20]["x"].sum() → keeps 20 and 30 → 50. Workshops: MACS: count failed and admin lines and write both to summary.txt; MAAI: DataFrame of name/score/group, head(2), filter ≥ 70, mean, group means (no read_csv or cleaning yet: Week 6).

Quick check (files, paper 1)

One line: a DataFrame is a table of Series; select columns, filter rows with a Boolean mask (combine with &), then summarise with mean() or groupby().mean().
MAAI802 · Week 5Series → DataFrame → select → mask → aggregate → groupby

Week 6 · Reading, Cleaning and Visualising Data

MAAI802 · CSV, data quality, exploratory analysis and Matplotlib charts
Paper 1
of 2

1. Why raw data needs cleaning

Common problems: missing values, duplicate rows, inconsistent text ("OK", "ok", " ok "), wrong type (numbers as text). Workflow: read → inspect → act → recheck. Never treat zero as a universal replacement for missing.

CSV: comma-separated, first row = column names. pd.read_csv("model_runs.csv") → DataFrame; empty numbers → NaN. Inspect: head(), shape, dtypes.

2. Cleaning commands

ProblemDetectAct
Missingdf.isna().sum()dropna() or fillna(v)
Duplicatesdf.duplicated()drop_duplicates()
Inconsistent textvalue_counts().str.strip(), .str.lower()
Wrong typedf.dtypes.astype(int)

Assign results (clean_df = df.dropna()). fillna(0) is a data decision; a repeat isn't automatically wrong.

Cleaning pipeline: step through model_runs.csv

3. Exploratory data analysis (EDA)

Summaries and charts to understand data before modelling.

df[["latency"]].describe(): count, mean, std, min, quartiles, max. df["status"].value_counts(): ok 2, warning 1 (clean text first).

4. Choose the chart from the question

QuestionChartCommand
Change in order (epochs, time)?Lineplt.plot(x, y, marker="o")
Compare categories (long labels → horizontal)?Bar / barhplt.bar(cat, v), plt.barh(cat, v)
Distribution of numbers?Histogramplt.hist(v, bins=6)
Share of one whole (few categories)?Pieplt.pie(counts, labels=labels)
Two numbers related?Scatterplt.scatter(x, y)
Spread and outliers?Box plotplt.boxplot(v)

import matplotlib.pyplot as plt; xlabel, ylabel, title, plt.show(). Several views: plt.subplot(rows, cols, pos) + plt.tight_layout().

Run it: CSV → clean → summarise → 2 × 2 figure (downloads Pandas + Matplotlib once)
Remember: inspect before cleaning, justify every fix, recheck afterwards, and pick the chart that answers the question.
MAAI802 · Week 6read_csv → isna, duplicates, .str, astype → describe → charts

Exception Handling and Debugging

Scripts that fail in ways we can understand and manage
Paper 2
of 2

5. Common runtime exceptions

Syntax: can't parse. Runtime exception: fails while running (this week). Logic: runs, wrong result.

ValueErrorright kind, bad value: int("hello")
TypeError · IndexError · KeyErrorwrong type · no such position · no such key
FileNotFoundErrorpath does not exist
ZeroDivisionErrordivide or modulo by zero

Hierarchy: BaseException → SystemExit, KeyboardInterrupt, Exception → ValueError, TypeError, ArithmeticError → ZeroDivisionError, LookupError → IndexError/KeyError, OSError → FileNotFoundError.

try risky code · except X matching failure · else only on success · finally at the end either way (cleanup).

except blocks are checked top to bottom: specific first, except Exception as error last. Avoid bare except:.

6. try / except / else / finally

Flow simulator: number = int(value); result = 100 / number

7. Capture, log and raise

except ValueError as error: stores the exception; str(error) → "invalid literal for int() with base 10: 'hello'". Read it as evidence.

Error logging (unattended scripts): append str(error) to errors.log with mode "a", then tell the user "Error recorded".

raise your own rule: raise ValueError("score cannot be negative"). Goal: controlled recovery, not hiding errors.

8. Debugging

Traceback: read from the bottom (type + message), find your line, inspect values. Cycle: reproduce → read → locate → inspect → retest. One justified change at a time. Temporary print() of values explains logic bugs (attempts 5 < threshold 10, so no Alert).

Run it: the complete security handling flow (delete the setup lines to see the missing-file path)
One line: catch the specific exceptions you expect first, keep success work in else and cleanup in finally, log the message, and debug from the bottom of the traceback up.
MAAI802 · Week 6Exceptions → hierarchy → try/except/else/finally → log → debug

Week 7 · Intro to Scikit-learn and ML Concepts

MAAI802 · Features, target, fit and predict (train/test split and metrics come in Week 8)
Paper 1
of 2

1. Machine learning in one sentence

Rules: we write the decision. ML: we give examples with known answers and the model learns a pattern. Supervised = examples include the answer.

Classification → a category (pass/fail). Regression → a number (price).

2. Features X and target y

Features = input columns (X); target = the known answer (y).

X = df[["hours", "practice"]]: double brackets keep a 2D table (rows = examples, columns = features). y = df["passed"]: one Series.

Lecture data: tap a column to make it the target

3. The Scikit-learn workflow

An estimator learns from examples, then outputs predictions. Today: DecisionTreeClassifier.

  1. Import one item: from sklearn.tree import DecisionTreeClassifier.
  2. Create an untrained model: model = DecisionTreeClassifier().
  3. Fit = training: model.fit(X, y) studies X with its answers y and changes the model.
  4. Predict: model.predict(X) returns a class per row → [0 0 0 1 1 1].
  5. Compare actual vs predicted (sanity check).
Run it: the complete Week 7 example (downloads scikit-learn once, ~15 s)

4. Common first-model mistakes

  • Target inside X: the model is handed the answer.
  • Predicting before fitting: nothing learned yet.
  • Dirty data breaks or weakens the workflow.
  • Training predictions as final evidence: matching seen rows ≠ working on new data (Week 8).

Workshop: identify features and target, fit a DecisionTreeClassifier, compare predictions side by side, and explain fit() vs predict().

Remember: choose the target, separate X (table) from y (column), create the estimator, fit, then predict; a prediction is the model's output, not proof it is right.
MAAI802 · Week 7Supervised → X, y → import → create → fit → predict

Bash Basics and Shell Automation

Combine small command-line tools into repeatable workflows
Paper 2
of 2

5. Terminal, shell and Bash

Terminal: where you type. Shell: reads commands and starts tools. Bash: a common shell with its own scripting syntax (Linux, macOS, WSL). Bash is not Python.

Structure: command + arguments (file, pattern) + options starting with -.

pwdprint working directory
lslist contents
cd path / cd ..change directory / one level up
mkdir namecreate a directory (doesn't enter it)
touch filecreate an empty file
cat / head / tailwhole file / beginning / end
grep "ERROR" fprint matching lines (file unchanged)
wc -l filecount lines
echo "text"print text

6. Pipes and redirection

Pipe | sends one command's output into the next: grep "ERROR" app.log | wc -l filters, then counts.

> writes output to a file, replacing it: grep "ERROR" app.log > errors.txt. >> appends: echo "Scan completed" >> audit.txt. Same idea as Python "w" vs "a".

7. Variables and scripts

log_file="app.log": no spaces around =; read it with "$log_file" (quotes are safe for paths with spaces).

A script is a text file of commands. Line 1 shebang #!/bin/bash; # comments. Run with bash check_errors.sh, or chmod +x check_errors.sh then ./check_errors.sh.

#!/bin/bash
# Save ERROR lines and count them
log_file="app.log"
echo "Checking $log_file"
grep "ERROR" "$log_file" > errors.txt
wc -l errors.txt
Practice terminal (simulated Bash: pwd, ls, cd, mkdir, touch, cat, head, tail, grep, wc -l, echo, |, >, >>, variables, bash script.sh)
$

8. Common Bash mistakes

Mixing Python and Bash (print(), indentation); spaces around = (log_file = "app.log" fails); > overwriting when you meant >>; the wrong working directory for a relative filename. When a command fails, check the exact command, path and current directory. Workshop: navigate (pwd, ls, cd), inspect (head/tail) and filter (grep), count with a pipe and save with >, then automate in a script with a filename variable.

Put the ML workflow in order (paper 1)

One line: small tools do one job; pipes connect them, > and >> save their output, and a script with a shebang repeats the whole chain on demand.
MAAI802 · Week 7Navigate → inspect → grep → wc → | → > >> → script

Week 8 · Training and Testing ML Models

MAAI802 · Train/test split, stratification, accuracy and the confusion matrix
Paper 1
of 2

1. Why training predictions are not enough

Scoring rows the model learned from may only show it remembered them. Generalisation = good predictions on unseen data.

Training set: rows used in fit(). Test set: rows held aside to check predictions. Never fit using test answers.

Workflow: X, y → split → fit (X_train, y_train) → predict (X_test) → compare with y_test. Think train = learn, test = check.

2. train_test_split

from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30, random_state=42): ~30% held out; outputs stay aligned; it doesn't train.

random_state makes the split repeatable; it does not make it representative.

Rare classes: a random split may leave 0 attacks to test; stratify=y keeps class proportions (still unstable with 1 attack). Time-ordered logs: train on earlier, test on later.

Split simulator: 1,000 normal ● + 3 attacks ●, test_size = 0.20

3. Accuracy and its trap

from sklearn.metrics import accuracy_score → accuracy_score(y_test, predictions): fraction correct, 0 to 1 (8 of 10 → 0.80). It describes this test set, not every future case.

4. Confusion matrix, leakage and mistakes

Rows = actual classes, columns = predicted. Diagonal = correct; off-diagonal = mistakes. confusion_matrix(y_test, predictions) → [[1 0] [0 2]]: all 3 correct. For rare classes also check precision, recall and F1.

Data leakage: test information reaching training makes results look better than they are; split first, fit only on training data. Mistakes: fitting on all data; predicting before fit; comparing with y_train; one score as proof.

Run it: complete train/test example (downloads scikit-learn once)
Remember: split before fitting, fit only on training rows, evaluate on the test rows, stratify rare classes, and look past accuracy to the confusion matrix.
MAAI802 · Week 8Split → stratify → fit → predict → accuracy → confusion matrix

Parsing Network Data and Simple Scanning Tools

Network records, sockets and an authorised TCP port check
Paper 2
of 2

5. What network data looks like

Addresses (source and destination IP) identify hosts; a port identifies a service endpoint; protocol TCP or UDP; plus timestamp/status. This week: simple text records, not raw packets.

record = "10:15,10.0.0.5,10.0.0.20,443,TCP" → parts = record.split(",") → name the fields (time, source_ip, destination_ip, port = int(parts[3]), protocol). Know the field order first; convert the port to int.

Filter by port (22 or 443), protocol (TCP) or host, with ordinary loops and conditions. New data, same Python.

Run it: parse and count HTTPS

6. Host, port and socket

A socket is a Python object for talking through the network stack. A port check asks one narrow question: can a TCP connection be made to this host and port?

  • import socket (standard library).
  • socket.socket(socket.AF_INET, socket.SOCK_STREAM): AF_INET = IPv4, SOCK_STREAM = TCP. Creating it contacts nobody.
  • sock.settimeout(0.5): never wait forever.
  • sock.connect_ex((host, port)) returns 0 on success, non-zero otherwise.
  • Always sock.close().
def check_port(host, port):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.settimeout(0.5)
    result = sock.connect_ex((host, port))
    sock.close()
    return result == 0

Lab scanner (simulated): for port in ports: check_port("127.0.0.1", port)

target: localhost only

7. Authorisation boundary

Allowed: your own computer, localhost, a provided lab VM, or a host you have explicit permission for. Not acceptable: public systems, classmates' devices, university infrastructure, anything unauthorised. The same action can be legitimate or not depending on permission and scope.

8. Report, handle errors, avoid mistakes

Report: write "{0} open\n".format(port) or closed to scan_results.txt (Week 5 files + Week 8 networking). Errors: except socket.gaierror: "Invalid host"; except OSError as error: "Network error". Mistakes: no timeout, socket not closed, port left as text, unauthorised target. Start with a tiny controlled test. Workshop: parse records into named fields, count by port or protocol, check a short port list on localhost, write results to a file, and explain timeout and authorisation.

Accuracy trap (paper 1): the "always predict normal" model on 1,000 normal + 3 attacks

0
One line: split network records into named fields, filter them with ordinary Python, and check only a short list of ports on an authorised host, with a timeout, closing each socket.
MAAI802 · Week 8Records → split → filter → socket → check_port → report

Week 9 · Model Comparison and Pipeline Automation

MAAI802 · Several classifiers, validation-based choice, ties and error-resistant experiments
Paper 1
of 2

1. Five classifiers, one API

Decision Tree (rule splits, can overfit) · Random Forest (trees vote; strong baseline) · Logistic Regression (linear baseline) · SVM/SVC (separating boundary, RBF by default) · KNN (nearest examples; needs scaling). Only the estimator changes; create → fit → predict stays.

2. Train, validate, test (60/20/20)

Train: fit every candidate. Validation: compare and choose. Test: untouched until the choice is fixed, used once. Two splits: 80/20, then 75/25 of the rest, both stratified.

Fair: same rows and metric, scaling from training data, no test peeking; make_pipeline(StandardScaler(), SVC()).

Wine dataset (178 rows, 13 features, 3 classes): validation accuracy

3. Ties and small validation sets

36 validation rows: one row = 2.78 points, so small gaps are weak evidence (cross-validation is more stable).

max(scores, key=scores.get) returns the first tied item, by dictionary order. List all leaders; break ties with a second metric.

Refit SVM on train + validation, test once: validation 100% → test 97.2%. The test is the honest check.

Supported: SVM led on this split. Not: "SVM is always best". Report seed, sizes, metric, preprocessing, tie rule.

Run it: the automated comparison (downloads scikit-learn once)

4. Error-resistant automation

Load → X/y → splits → models → compare → select → refit → final test. Put risky steps inside try: FileNotFoundError, KeyError (missing column), ValueError (bad data, stratify fails). Convergence is a warning, not an exception. Log timestamp, seed, sizes, scores, leader/tie, test score, error. Mistakes: choosing on test, inconsistent preprocessing, copy-paste blocks, overclaiming.

Remember: compare fairly on validation data, list ties instead of letting max() pick, test once, automate with logging.
MAAI802 · Week 95 classifiers → 60/20/20 → compare → ties → refit → automate

Classes, Modules and Reusable Tools

Basic OOP and turning security scripts into importable building blocks
Paper 2
of 2

5. Classes and objects (basic OOP)

Functions suit one reusable action; a class suits one entity whose data and behaviour belong together (a model result has a name, a score, and can display itself).

Class = blueprint; object = one concrete instance ("SVM", 1.00 and "Random Forest", 0.972 from the same class).

  • class ModelResult: defines it.
  • __init__ runs when an object is created.
  • self is the current object; self.name, self.accuracy are attributes.
  • A method is a function inside the class: def show(self):.

Use a class when several values describe one thing and operations belong to it. Not now: inheritance, polymorphism, abstract classes, decorators.

Run it: ModelResult and LogAnalyzer

6. Functions and modules

One-off script → reusable tool → integrated tool. A reusable function receives what it needs as parameters (no hidden globals): count_errors(filename).

A module is a .py file of functions/classes another file can import. Put count_errors in log_tools.py, then from log_tools import count_errors (same pattern as sklearn). Move Week 8's tested check_port into network_tools.py instead of copying socket code.

Standard libraries: os (paths), socket (network), datetime (timestamps). Don't rewrite what a library does reliably.

Handle errors directly: try: print(count_errors(filename)) except FileNotFoundError:, rather than checking existence first.

7. A small reusable architecture

main.py            # user workflow
log_tools.py       # log functions / LogAnalyzer
network_tools.py   # authorised check_port()
reports/           # output files
from log_tools import count_errors
from network_tools import check_port
def main():
    print("Errors:", count_errors("app.log"))
    print("Port 80 open:", check_port("127.0.0.1", 80))
if __name__ == "__main__":   # not when imported
    main()

Function, module or class?

8. Reusability mistakes

Copy-paste functions (fix in many places); hidden global state; circular imports (A imports B imports A: move shared code to a third module); a class for everything. Prefer small, explicit dependencies. Workshop: move a log function into log_tools.py, call it from main with try/except, import the port checker, write a basic LogAnalyzer.

One line: functions for actions, modules for sharing them, classes when data and behaviour belong together; keep everything small, tested and imported rather than copied.
MAAI802 · Week 9class → __init__ → self → methods → modules → import → main

Week 10 · Capstone Planning and an AI Application

MAAI802 · From experiment to a tested command-line classifier (Iris)
Paper 1
of 2

1. More than a working function

Useful: state user, input, output; say what the result means and can't establish; keep version 1 small. Evidence: normal, invalid and boundary cases; versions; a README.

Plan: a learner enters four flower measurements (cm) and gets a class or a clear error; one fixed classifier, held-out evaluation, command line.

2. Python bridges

Truthiness: "", [], {} are False; non-empty is True; not [] → True. if not timestamp: checks for an empty field.

break ends the nearest loop (user types q); continue skips to the next iteration (reject a row). while True: runs until break.

math.isfinite(x) is False for NaN and ±inf, and float("nan") raises no error, so check it. assert is for tests only (Python -O removes it); validate input with if + raise.

3. Input contract

Four comma-separated numbers: sepal length, sepal width, petal length, petal width, in cm, each finite and > 0; q quits. It does not promise plausibility.

Contract tester: parse_measurements(text)

4. Fixed design, honest evaluation

load_iris(as_frame=True): 150 rows (50 per class), 4 features, classes 0 setosa, 1 versicolor, 2 virginica. The class is the target: putting it in X leaks the answer.

Fix it before scoring: DecisionTreeClassifier(max_depth=3, random_state=20), stratified 80/20 (120/30). Tuning? Use Week 9 validation. Re-rolling seeds invalidates the score.

Result: held-out accuracy 100% (30/30), diagonal matrix. Always-setosa baseline: 33.3%. One prediction = 3.33 points, so a small perfect test is limited evidence.

Run it: ai_app.py (scroll the box for the whole file)
Remember: state the contract, fix the design before scoring, train once outside the loop, keep the training schema for prediction, and present limits honestly (no "unknown species" option, no range check).
MAAI802 · Week 10Plan → contract → fixed evaluation → modular app → tests

Scripted Security Use Case: Log Alerting

Parse, count, select, report, then test and hand off
Paper 2
of 2

5. Rule and format

Rule: read one local file; count FAIL events per account over the whole file; one REVIEW line per account with count ≥ 3; sorted output; report rejected rows. A review is a signal to investigate, not proof; no time window, no blocking; SUCCESS does not reset the count. Synthetic data only, no network.

Format timestamp|account|source|event. Accepted: exactly 4 fields; timestamp, account and source non-empty; event exactly FAIL or SUCCESS. Rejected rows are counted, never reinterpreted.

parse_record(line) splits on |, strips, checks, raises ValueError or returns a dict. read_failures(path) loops lines; a bad row → rejected += 1; continue; FAIL → counts[a] = counts.get(a, 0) + 1. get gives 0 for a new key.

make_alerts(counts, threshold=3) rejects a threshold that isn't a positive int (type(t) != int also rejects True); sorted(counts) gives a stable order; >= includes the boundary.

The fixture (sample_auth.log) and the rule

3
Run it: log_tools + security_app (scroll for the whole file; edit and re-run)

6. Errors at the right level

A malformed row → ValueError → counted as rejected, continue. A missing or unreadable file is not "zero alerts": it stops the run and must be reported. Catch (OSError, UnicodeError, ValueError) at the application boundary; never catch everything and write "no alerts". Write to alerts.txt ("w"), never the input log.

Thresholds: 2 → lab01, lab02; 3 → lab01; 4 → none. Lower flags more, not "better detection".

7. Test, document, demonstrate

Acceptance (AI): inputs and units stated, training schema reused, evaluation separate, useful errors, reproducible score. (Security): format and scope stated, accepted/rejected/boundary tested, threshold and rejections reported, missing file ≠ no alerts, stable order.

Reproducible: record data, seed, settings, versions and the run command; no absolute paths, credentials or copied scores. README: purpose, input, files, install, run, example output, checks, limits. Demo: problem → contract → normal run → a failure or boundary → key function → interpretation → a limitation.

One line: define the record format and rule, parse and count with small tested functions, treat bad rows and missing files differently, test the ≥ boundary, and report scope and limits clearly.
MAAI802 · Week 10Format → parse → count → threshold → report → test → README