{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "10d7fdd9",
   "metadata": {},
   "source": [
    "# Lab\n",
    "\n",
    "- Use this assignment to practice the chapter's concepts and coding skills in runnable Python code.\n",
    "- Sign in from the account menu before you start working on the assignment.\n",
    "- Write and run your code directly in the coding cells.\n",
    "- Multiple submissions are allowed. The highest score is kept.\n",
    "\n",
    "<div data-lab-answers-release-at=\"2099-12-31T23:59:00-06:00\"></div>\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e120696d",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Question 1: Scaling With Training Statistics\n",
    "#   1. Fit a StandardScaler on X_train only.\n",
    "#   2. Use it to scale the new session below and print both scaled values,\n",
    "#      each rounded to 2 decimals.\n",
    "# Print exactly:\n",
    "# Scaled page value: -0.14\n",
    "# Scaled duration: -0.5\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.preprocessing import StandardScaler\n",
    "\n",
    "# Shopping sessions (made-up numbers for practice): page value in dollars,\n",
    "# seconds spent on product pages, and whether the session ended in a purchase.\n",
    "sessions = pd.DataFrame({\n",
    "    \"page_value\": [0, 12, 0, 35, 0, 4, 28, 0, 0, 19, 0, 41, 0, 7, 0, 22],\n",
    "    \"duration\": [120, 1500, 300, 2400, 60, 900, 1300, 200, 2600, 1700, 150, 3100, 700, 450, 30, 1400],\n",
    "    \"purchase\": [0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1],\n",
    "})\n",
    "X = sessions[[\"page_value\", \"duration\"]]\n",
    "y = sessions[\"purchase\"]\n",
    "X_train, X_test, y_train, y_test = train_test_split(\n",
    "    X, y, test_size=0.25, random_state=24, stratify=y)\n",
    "new_session = pd.DataFrame({\"page_value\": [10], \"duration\": [600]})\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cf6f3233",
   "metadata": {
    "tags": [
     "hide-input",
     "lab-answer"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Scaled page value: -0.14\n",
      "Scaled duration: -0.5\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.preprocessing import StandardScaler\n",
    "\n",
    "# Shopping sessions (made-up numbers for practice): page value in dollars,\n",
    "# seconds spent on product pages, and whether the session ended in a purchase.\n",
    "sessions = pd.DataFrame({\n",
    "    \"page_value\": [0, 12, 0, 35, 0, 4, 28, 0, 0, 19, 0, 41, 0, 7, 0, 22],\n",
    "    \"duration\": [120, 1500, 300, 2400, 60, 900, 1300, 200, 2600, 1700, 150, 3100, 700, 450, 30, 1400],\n",
    "    \"purchase\": [0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1],\n",
    "})\n",
    "X = sessions[[\"page_value\", \"duration\"]]\n",
    "y = sessions[\"purchase\"]\n",
    "X_train, X_test, y_train, y_test = train_test_split(\n",
    "    X, y, test_size=0.25, random_state=24, stratify=y)\n",
    "new_session = pd.DataFrame({\"page_value\": [10], \"duration\": [600]})\n",
    "\n",
    "scaler = StandardScaler().fit(X_train)\n",
    "scaled = scaler.transform(new_session)[0]\n",
    "print(\"Scaled page value:\", round(scaled[0], 2))\n",
    "print(\"Scaled duration:\", round(scaled[1], 2))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d9d80f66",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Question 2: A Pipeline Classifier\n",
    "#   1. Make a pipeline of StandardScaler and KNeighborsClassifier with 3 neighbors.\n",
    "#   2. Fit it on the training set, predict the test set, and print the\n",
    "#      predictions as a list and the test accuracy rounded to 2 decimals.\n",
    "# Print exactly:\n",
    "# Predictions: [1, 0, 0, 0]\n",
    "# Test accuracy: 1.0\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.preprocessing import StandardScaler\n",
    "from sklearn.neighbors import KNeighborsClassifier\n",
    "from sklearn.pipeline import make_pipeline\n",
    "\n",
    "# Shopping sessions (made-up numbers for practice): page value in dollars,\n",
    "# seconds spent on product pages, and whether the session ended in a purchase.\n",
    "sessions = pd.DataFrame({\n",
    "    \"page_value\": [0, 12, 0, 35, 0, 4, 28, 0, 0, 19, 0, 41, 0, 7, 0, 22],\n",
    "    \"duration\": [120, 1500, 300, 2400, 60, 900, 1300, 200, 2600, 1700, 150, 3100, 700, 450, 30, 1400],\n",
    "    \"purchase\": [0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1],\n",
    "})\n",
    "X = sessions[[\"page_value\", \"duration\"]]\n",
    "y = sessions[\"purchase\"]\n",
    "X_train, X_test, y_train, y_test = train_test_split(\n",
    "    X, y, test_size=0.25, random_state=24, stratify=y)\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "868dbf58",
   "metadata": {
    "tags": [
     "hide-input",
     "lab-answer"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Predictions: [1, 0, 0, 0]\n",
      "Test accuracy: 1.0\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.preprocessing import StandardScaler\n",
    "from sklearn.neighbors import KNeighborsClassifier\n",
    "from sklearn.pipeline import make_pipeline\n",
    "\n",
    "# Shopping sessions (made-up numbers for practice): page value in dollars,\n",
    "# seconds spent on product pages, and whether the session ended in a purchase.\n",
    "sessions = pd.DataFrame({\n",
    "    \"page_value\": [0, 12, 0, 35, 0, 4, 28, 0, 0, 19, 0, 41, 0, 7, 0, 22],\n",
    "    \"duration\": [120, 1500, 300, 2400, 60, 900, 1300, 200, 2600, 1700, 150, 3100, 700, 450, 30, 1400],\n",
    "    \"purchase\": [0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1],\n",
    "})\n",
    "X = sessions[[\"page_value\", \"duration\"]]\n",
    "y = sessions[\"purchase\"]\n",
    "X_train, X_test, y_train, y_test = train_test_split(\n",
    "    X, y, test_size=0.25, random_state=24, stratify=y)\n",
    "\n",
    "model = make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=3))\n",
    "model.fit(X_train, y_train)\n",
    "predictions = model.predict(X_test)\n",
    "print(\"Predictions:\", predictions.tolist())\n",
    "print(\"Test accuracy:\", round((predictions == y_test).mean(), 2))\n",
    "# Without StandardScaler, duration (in the thousands of seconds) swamps page\n",
    "# value in the distance, and the classifier gets one of the four test sessions wrong."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "056747a8",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Question 3: The Confusion Matrix\n",
    "#   1. Count the true negatives, false positives, false negatives, and true\n",
    "#      positives, with \"fraud\" as the positive class (confusion_matrix with\n",
    "#      labels=[\"ok\", \"fraud\"] gives them in that order with .ravel()).\n",
    "# Print exactly:\n",
    "# True negatives: 5\n",
    "# False positives: 3\n",
    "# False negatives: 1\n",
    "# True positives: 3\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "from sklearn.metrics import confusion_matrix\n",
    "\n",
    "# Twelve checked orders (made-up data for practice); fraud is the positive class.\n",
    "actual    = [\"fraud\", \"ok\", \"ok\", \"fraud\", \"ok\", \"ok\", \"fraud\", \"ok\", \"ok\", \"ok\", \"fraud\", \"ok\"]\n",
    "predicted = [\"fraud\", \"ok\", \"fraud\", \"fraud\", \"ok\", \"ok\", \"fraud\", \"ok\", \"fraud\", \"ok\", \"ok\", \"fraud\"]\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "14e48ff1",
   "metadata": {
    "tags": [
     "hide-input",
     "lab-answer"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True negatives: 5\n",
      "False positives: 3\n",
      "False negatives: 1\n",
      "True positives: 3\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "from sklearn.metrics import confusion_matrix\n",
    "\n",
    "# Twelve checked orders (made-up data for practice); fraud is the positive class.\n",
    "actual    = [\"fraud\", \"ok\", \"ok\", \"fraud\", \"ok\", \"ok\", \"fraud\", \"ok\", \"ok\", \"ok\", \"fraud\", \"ok\"]\n",
    "predicted = [\"fraud\", \"ok\", \"fraud\", \"fraud\", \"ok\", \"ok\", \"fraud\", \"ok\", \"fraud\", \"ok\", \"ok\", \"fraud\"]\n",
    "\n",
    "tn, fp, fn, tp = confusion_matrix(actual, predicted, labels=[\"ok\", \"fraud\"]).ravel()\n",
    "print(\"True negatives:\", tn)\n",
    "print(\"False positives:\", fp)\n",
    "print(\"False negatives:\", fn)\n",
    "print(\"True positives:\", tp)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c17ab083",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Question 4: Precision, Recall, and F1\n",
    "#   1. Compute precision, recall, and F1 for the fraud classifier, with \"fraud\"\n",
    "#      as the positive class. Round each to 3 decimals.\n",
    "# Print exactly:\n",
    "# Precision: 0.5\n",
    "# Recall: 0.75\n",
    "# F1: 0.6\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "\n",
    "# Twelve checked orders (made-up data for practice); fraud is the positive class.\n",
    "actual    = [\"fraud\", \"ok\", \"ok\", \"fraud\", \"ok\", \"ok\", \"fraud\", \"ok\", \"ok\", \"ok\", \"fraud\", \"ok\"]\n",
    "predicted = [\"fraud\", \"ok\", \"fraud\", \"fraud\", \"ok\", \"ok\", \"fraud\", \"ok\", \"fraud\", \"ok\", \"ok\", \"fraud\"]\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e312db16",
   "metadata": {
    "tags": [
     "hide-input",
     "lab-answer"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Precision: 0.5\n",
      "Recall: 0.75\n",
      "F1: 0.6\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "\n",
    "# Twelve checked orders (made-up data for practice); fraud is the positive class.\n",
    "actual    = [\"fraud\", \"ok\", \"ok\", \"fraud\", \"ok\", \"ok\", \"fraud\", \"ok\", \"ok\", \"ok\", \"fraud\", \"ok\"]\n",
    "predicted = [\"fraud\", \"ok\", \"fraud\", \"fraud\", \"ok\", \"ok\", \"fraud\", \"ok\", \"fraud\", \"ok\", \"ok\", \"fraud\"]\n",
    "\n",
    "tp = sum([a == \"fraud\" and p == \"fraud\" for a, p in zip(actual, predicted)])\n",
    "fp = sum([a == \"ok\" and p == \"fraud\" for a, p in zip(actual, predicted)])\n",
    "fn = sum([a == \"fraud\" and p == \"ok\" for a, p in zip(actual, predicted)])\n",
    "precision = tp / (tp + fp)\n",
    "recall = tp / (tp + fn)\n",
    "f1 = 2 * precision * recall / (precision + recall)\n",
    "print(\"Precision:\", round(precision, 3))\n",
    "print(\"Recall:\", round(recall, 3))\n",
    "print(\"F1:\", round(f1, 3))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a4d32561",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Question 5: Choosing by Cost\n",
    "#   A missed fraud case costs $200 and a false alarm costs $10.\n",
    "#   1. Compute each model's total error cost from its false negatives and\n",
    "#      false positives on the same test orders.\n",
    "#   2. Print each cost and the name of the cheaper model.\n",
    "# Print exactly:\n",
    "# Model A cost: $2800\n",
    "# Model B cost: $2500\n",
    "# Cheaper: Model B\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "\n",
    "COST_FN = 200   # dollars lost for each missed fraud case (an assumption)\n",
    "COST_FP = 10    # dollars spent checking each false alarm (an assumption)\n",
    "errors = pd.DataFrame({\n",
    "    \"model\": [\"Model A\", \"Model B\"],\n",
    "    \"false_negatives\": [12, 5],\n",
    "    \"false_positives\": [40, 150],\n",
    "})\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "acc539ab",
   "metadata": {
    "tags": [
     "hide-input",
     "lab-answer"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Model A cost: $2800\n",
      "Model B cost: $2500\n",
      "Cheaper: Model B\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "\n",
    "COST_FN = 200   # dollars lost for each missed fraud case (an assumption)\n",
    "COST_FP = 10    # dollars spent checking each false alarm (an assumption)\n",
    "errors = pd.DataFrame({\n",
    "    \"model\": [\"Model A\", \"Model B\"],\n",
    "    \"false_negatives\": [12, 5],\n",
    "    \"false_positives\": [40, 150],\n",
    "})\n",
    "\n",
    "errors[\"cost\"] = COST_FN * errors[\"false_negatives\"] + COST_FP * errors[\"false_positives\"]\n",
    "for name, cost in zip(errors[\"model\"], errors[\"cost\"]):\n",
    "    print(name, \"cost: $\" + str(cost))\n",
    "print(\"Cheaper:\", errors.loc[errors[\"cost\"].idxmin(), \"model\"])\n",
    "# Model B is wrong far more often (155 errors against 52), yet cheaper,\n",
    "# because it misses fewer of the costly fraud cases."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "59cbf036",
   "metadata": {},
   "source": [
    "<style>\n",
    ".ch15-lab-grader { max-width: 900px; margin-top: 1rem; }\n",
    ".ch15-lab-feedback-list { display: grid; gap: 0.45rem; margin: 0 0 1rem; }\n",
    ".ch15-lab-feedback-list[hidden] { display: none; }\n",
    ".ch15-lab-feedback-row { border: 1px solid #d8dee4; border-radius: 6px; padding: 0.55rem 0.65rem; }\n",
    ".ch15-lab-feedback-row strong { margin-right: 0.35rem; }\n",
    ".ch15-lab-feedback-row.correct { border-color: #aceebb; background: #dafbe1; color: #116329; }\n",
    ".ch15-lab-feedback-row.incorrect { border-color: #ffcecb; background: #ffebe9; color: #cf222e; }\n",
    ".ch15-lab-actions { display: flex; gap: 0.75rem; align-items: center; margin: 1rem 0 0; flex-wrap: wrap; }\n",
    ".ch15-lab-actions button { border: 1px solid #176de8; border-radius: 6px; background: #176de8; color: white; padding: 0.55rem 0.9rem; cursor: pointer; font-weight: 600; }\n",
    ".ch15-lab-actions button.secondary { background: white; color: #176de8; }\n",
    ".ch15-lab-actions.is-locked { opacity: 0.55; }\n",
    ".ch15-lab-actions button:disabled { cursor: not-allowed; opacity: 0.65; }\n",
    ".ch15-lab-result { font-weight: 700; }\n",
    "</style>\n",
    "\n",
    "<div class='ch15-lab-grader' id='ch15-lab-grader'>\n",
    "  <div class='ch15-lab-feedback-list' aria-live='polite' hidden>\n",
    "    <div class='ch15-lab-feedback-row' data-question='q1'><strong>Question 1</strong><span></span></div>\n",
    "    <div class='ch15-lab-feedback-row' data-question='q2'><strong>Question 2</strong><span></span></div>\n",
    "    <div class='ch15-lab-feedback-row' data-question='q3'><strong>Question 3</strong><span></span></div>\n",
    "    <div class='ch15-lab-feedback-row' data-question='q4'><strong>Question 4</strong><span></span></div>\n",
    "    <div class='ch15-lab-feedback-row' data-question='q5'><strong>Question 5</strong><span></span></div>\n",
    "  </div>\n",
    "  <div class='ch15-lab-actions'>\n",
    "    <button type='button' id='ch15-lab-submit' disabled>Submit</button>\n",
    "    <button type='button' class='secondary' id='ch15-lab-reset'>Clear Results</button>\n",
    "    <span class='ch15-lab-result' id='ch15-lab-result' aria-live='polite'></span>\n",
    "  </div>\n",
    "</div>\n",
    "\n",
    "<script>\n",
    "(function () {\n",
    "  var labId = 'ch15-lab';\n",
    "\n",
    "  function getParams() {\n",
    "    var params = new URLSearchParams(window.location.search);\n",
    "    return {\n",
    "      canvas_course_id: params.get('canvas_course_id') || params.get('course_id') || '',\n",
    "      canvas_assignment_id: params.get('canvas_assignment_id') || params.get('assignment_id') || '',\n",
    "      canvas_user_id: params.get('canvas_user_id') || params.get('user_id') || ''\n",
    "    };\n",
    "  }\n",
    "\n",
    "  function loadSessionIdentity(identity, actions, submit, result) {\n",
    "    submit.disabled = true;\n",
    "    actions.classList.add('is-locked');\n",
    "    result.textContent = 'Sign in from the account menu to submit this assignment.';\n",
    "\n",
    "    return fetch('/api/v1/session.php', { credentials: 'same-origin' })\n",
    "      .then(function (response) { return response.ok ? response.json() : null; })\n",
    "      .then(function (payload) {\n",
    "        if (!payload || !payload.authenticated || !payload.identity) return identity;\n",
    "        identity.canvas_user_id = payload.identity.canvas_user_id || identity.canvas_user_id || '';\n",
    "        identity.student_identifier = payload.identity.student_identifier || '';\n",
    "        submit.disabled = false;\n",
    "        actions.classList.remove('is-locked');\n",
    "        result.textContent = payload.identity.display_name ? 'Signed in as ' + payload.identity.display_name + '.' : 'Signed in.';\n",
    "        return identity;\n",
    "      })\n",
    "      .catch(function () { return identity; });\n",
    "  }\n",
    "\n",
    "  function codeFromCell(cell) {\n",
    "    var cm = cell.querySelector('.CodeMirror');\n",
    "    if (cm && cm.CodeMirror && typeof cm.CodeMirror.getValue === 'function') return cm.CodeMirror.getValue();\n",
    "    var cmContent = cell.querySelector('.cm-content');\n",
    "    if (cmContent && cmContent.cmView && cmContent.cmView.view) return cmContent.cmView.view.state.doc.toString();\n",
    "    var textarea = cell.querySelector('textarea');\n",
    "    if (textarea) return textarea.value;\n",
    "    var pre = cell.querySelector('.cell_input pre');\n",
    "    return pre ? pre.textContent : '';\n",
    "  }\n",
    "\n",
    "  function collectCodeCells() {\n",
    "    var cells = Array.prototype.slice.call(document.querySelectorAll('div.cell.tag_thebe-interactive')).slice(0, 5);\n",
    "    var code = {};\n",
    "    cells.forEach(function (cell, index) {\n",
    "      code['q' + (index + 1)] = codeFromCell(cell);\n",
    "    });\n",
    "    return code;\n",
    "  }\n",
    "\n",
    "  function applyFeedback(grader, feedback) {\n",
    "    var list = grader.querySelector('.ch15-lab-feedback-list');\n",
    "    list.hidden = false;\n",
    "    ['q1', 'q2', 'q3', 'q4', 'q5'].forEach(function (question) {\n",
    "      var row = grader.querySelector('[data-question=' + question + ']');\n",
    "      var message = row.querySelector('span');\n",
    "      var item = feedback[question];\n",
    "      row.className = 'ch15-lab-feedback-row';\n",
    "      if (!item) return;\n",
    "      message.textContent = item.message + ' (' + item.score + ' / ' + item.max_score + ')';\n",
    "      row.classList.add(item.correct ? 'correct' : 'incorrect');\n",
    "    });\n",
    "  }\n",
    "\n",
    "  function clearFeedback(grader) {\n",
    "    var list = grader.querySelector('.ch15-lab-feedback-list');\n",
    "    list.hidden = true;\n",
    "    grader.querySelectorAll('.ch15-lab-feedback-row').forEach(function (row) {\n",
    "      row.className = 'ch15-lab-feedback-row';\n",
    "      var message = row.querySelector('span');\n",
    "      if (message) message.textContent = '';\n",
    "    });\n",
    "  }\n",
    "\n",
    "  function saveAttempt(payload) {\n",
    "    return fetch('/api/v1/lab-attempts.php', {\n",
    "      method: 'POST',\n",
    "      headers: { 'Content-Type': 'application/json' },\n",
    "      credentials: 'same-origin',\n",
    "      body: JSON.stringify(payload)\n",
    "    }).then(function (response) {\n",
    "      return response.text().then(function (text) {\n",
    "        var payload = text ? JSON.parse(text) : null;\n",
    "        if (!payload || !response.ok || !payload.ok) {\n",
    "          throw new Error((payload && (payload.message || payload.error)) || 'Submission API is unavailable.');\n",
    "        }\n",
    "        return payload;\n",
    "      });\n",
    "    });\n",
    "  }\n",
    "\n",
    "  function initLabGrader() {\n",
    "    var grader = document.getElementById('ch15-lab-grader');\n",
    "    if (!grader || grader.dataset.ready === 'true') return;\n",
    "    grader.dataset.ready = 'true';\n",
    "\n",
    "    var identity = getParams();\n",
    "    var actions = grader.querySelector('.ch15-lab-actions');\n",
    "    var result = document.getElementById('ch15-lab-result');\n",
    "    var submit = document.getElementById('ch15-lab-submit');\n",
    "    var reset = document.getElementById('ch15-lab-reset');\n",
    "\n",
    "    loadSessionIdentity(identity, actions, submit, result);\n",
    "\n",
    "    submit.addEventListener('click', function () {\n",
    "      clearFeedback(grader);\n",
    "      submit.disabled = true;\n",
    "      result.textContent = 'Submitting code.';\n",
    "\n",
    "      saveAttempt({\n",
    "        lab_id: labId,\n",
    "        code: collectCodeCells(),\n",
    "        canvas_course_id: identity.canvas_course_id,\n",
    "        canvas_assignment_id: identity.canvas_assignment_id,\n",
    "        canvas_user_id: identity.canvas_user_id\n",
    "      })\n",
    "        .then(function (payload) {\n",
    "          var best = (payload.best_score === null || typeof payload.best_score === 'undefined') ? payload.score : payload.best_score;\n",
    "          var attempt = (payload.attempt_count === null || typeof payload.attempt_count === 'undefined') ? '' : ' Attempt ' + payload.attempt_count + '.';\n",
    "          applyFeedback(grader, payload.feedback || {});\n",
    "          result.textContent = 'Submission saved.' + attempt + ' Score: ' + payload.score + ' / ' + payload.max_score + '. Best score: ' + best + ' / ' + payload.max_score + '. Canvas sync: ' + payload.canvas_sync_status + '.';\n",
    "        })\n",
    "        .catch(function (error) {\n",
    "          result.textContent = 'Could not save this attempt: ' + error.message;\n",
    "        })\n",
    "        .finally(function () {\n",
    "          submit.disabled = false;\n",
    "        });\n",
    "    });\n",
    "\n",
    "    reset.addEventListener('click', function () {\n",
    "      clearFeedback(grader);\n",
    "      result.textContent = '';\n",
    "    });\n",
    "  }\n",
    "\n",
    "  if (document.readyState === 'loading') {\n",
    "    document.addEventListener('DOMContentLoaded', initLabGrader);\n",
    "  } else {\n",
    "    initLabGrader();\n",
    "  }\n",
    "})();\n",
    "</script>\n"
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "cell_metadata_filter": "-all",
   "main_language": "python",
   "notebook_metadata_filter": "-all"
  },
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
