{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Homework\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"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "::::{div} assignment-question-card\n",
    "\n",
    "**1. How Resampling Works**\n",
    "\n",
    "A bootstrap resample is drawn without replacement from the original sample and has the same size as the original sample.\n",
    "\n",
    "<div class=\"tf-options\" role=\"radiogroup\" aria-label=\"Question 1 answer\">\n",
    "  <label><input type=\"radio\" name=\"ch11-hw-q1\" value=\"true\"> True</label>\n",
    "  <label><input type=\"radio\" name=\"ch11-hw-q1\" value=\"false\"> False</label>\n",
    "</div>\n",
    "\n",
    "::::\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "### Solution\n",
    "# False\n",
    "# A bootstrap resample is drawn WITH replacement. Without replacement, a resample of the same size would just be the original sample in a different order.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "::::{div} assignment-question-card\n",
    "\n",
    "**2. Interval for a Mean**\n",
    "\n",
    "A 95% confidence interval for the mean order value is \\$42 to \\$48. This means that 95% of individual orders are between \\$42 and \\$48.\n",
    "\n",
    "<div class=\"tf-options\" role=\"radiogroup\" aria-label=\"Question 2 answer\">\n",
    "  <label><input type=\"radio\" name=\"ch11-hw-q2\" value=\"true\"> True</label>\n",
    "  <label><input type=\"radio\" name=\"ch11-hw-q2\" value=\"false\"> False</label>\n",
    "</div>\n",
    "\n",
    "::::\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "### Solution\n",
    "# False\n",
    "# The interval estimates the average order value. Individual orders vary much more than their average does.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "::::{div} assignment-question-card\n",
    "\n",
    "**3. What \"95% Confidence\" Means**\n",
    "\n",
    "For a reliable approximate procedure under suitable sampling conditions, if we repeated the whole process many times (draw a new random sample, bootstrap it, build a 95% interval), about 95% of those intervals would contain the true parameter.\n",
    "\n",
    "<div class=\"tf-options\" role=\"radiogroup\" aria-label=\"Question 3 answer\">\n",
    "  <label><input type=\"radio\" name=\"ch11-hw-q3\" value=\"true\"> True</label>\n",
    "  <label><input type=\"radio\" name=\"ch11-hw-q3\" value=\"false\"> False</label>\n",
    "</div>\n",
    "\n",
    "::::\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "### Solution\n",
    "# True\n",
    "# The confidence level describes the process, not one particular interval.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "::::{div} assignment-question-card\n",
    "\n",
    "**4. Lower Confidence**\n",
    "\n",
    "From the same bootstrap distribution, the 80% confidence interval is no wider than the 95% confidence interval.\n",
    "\n",
    "<div class=\"tf-options\" role=\"radiogroup\" aria-label=\"Question 4 answer\">\n",
    "  <label><input type=\"radio\" name=\"ch11-hw-q4\" value=\"true\"> True</label>\n",
    "  <label><input type=\"radio\" name=\"ch11-hw-q4\" value=\"false\"> False</label>\n",
    "</div>\n",
    "\n",
    "::::\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "### Solution\n",
    "# True\n",
    "# The 80% interval runs from the 10th to the 90th percentile, which is inside the 2.5th to 97.5th percentile range.\n",
    "# The widths can be equal when percentile endpoints tie.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "::::{div} assignment-question-card\n",
    "\n",
    "**5. Estimating a Maximum**\n",
    "\n",
    "A bootstrap confidence interval works well for estimating the highest salary paid by a large company from a random sample of its employees.\n",
    "\n",
    "<div class=\"tf-options\" role=\"radiogroup\" aria-label=\"Question 5 answer\">\n",
    "  <label><input type=\"radio\" name=\"ch11-hw-q5\" value=\"true\"> True</label>\n",
    "  <label><input type=\"radio\" name=\"ch11-hw-q5\" value=\"false\"> False</label>\n",
    "</div>\n",
    "\n",
    "::::\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "### Solution\n",
    "# False\n",
    "# The bootstrap works poorly for extremes. A resample can never contain a value larger than the sample's maximum, and the sample probably missed the highest salary.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### 6. The Middle Half of Orders\n",
    "# Describe individual order values (in dollars), not uncertainty in a mean.\n",
    "# Use the chapter's nearest convention; this odd-size sample has the same\n",
    "# ordinary median and nearest 50th percentile.\n",
    "#   1. Compute the 25th, 50th, and 75th percentiles with method='nearest'.\n",
    "# Print exactly:\n",
    "# 25th percentile: 45\n",
    "# Median: 49\n",
    "# 75th percentile: 52\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "\n",
    "orders = pd.Series([38, 52, 45, 61, 47, 55, 40, 49, 58, 44, 51, 46, 63, 42, 50])\n",
    "\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "tags": [
     "hide-input",
     "homework-answer"
    ]
   },
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "25th percentile: 45\nMedian: 49\n75th percentile: 52\n"
    }
   ],
   "source": [
    "### Solution\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "\n",
    "orders = pd.Series([38, 52, 45, 61, 47, 55, 40, 49, 58, 44, 51, 46, 63, 42, 50])\n",
    "\n",
    "print(\"25th percentile:\", np.percentile(orders, 25, method='nearest'))\n",
    "print(\"Median:\", np.percentile(orders, 50, method='nearest'))\n",
    "print(\"75th percentile:\", np.percentile(orders, 75, method='nearest'))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### 7. One Bootstrap Resample\n",
    "# Draw one bootstrap resample of orders with .sample(): same size,\n",
    "# replacement, and random_state=7. Then summarize that resample.\n",
    "#   1. Compute the mean of the resample, rounded to 2 decimals.\n",
    "#   2. Count the distinct values in the resample with nunique().\n",
    "# Print exactly:\n",
    "# Resample mean: 50.67\n",
    "# Distinct values: 9 of 15\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "\n",
    "orders = pd.Series([38, 52, 45, 61, 47, 55, 40, 49, 58, 44, 51, 46, 63, 42, 50])\n",
    "\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "tags": [
     "hide-input",
     "homework-answer"
    ]
   },
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "Resample mean: 50.67\nDistinct values: 9 of 15\n"
    }
   ],
   "source": [
    "### Solution\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "\n",
    "orders = pd.Series([38, 52, 45, 61, 47, 55, 40, 49, 58, 44, 51, 46, 63, 42, 50])\n",
    "resample = orders.sample(len(orders), replace=True, random_state=7)\n",
    "\n",
    "print(\"Resample mean:\", round(resample.mean(), 2))\n",
    "print(\"Distinct values:\", resample.nunique(), \"of\", len(resample))\n",
    "# Drawing with replacement repeats some orders and leaves others out.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### 8. Interval for the Mean Order Value\n",
    "# Generate 40 bootstrap means from orders: draw len(orders) values WITH\n",
    "# replacement using rng.choice, and collect each mean in bootstrap_means.\n",
    "# Set up the list before the loop. Keep the seed outside the loop.\n",
    "# Then compute a central 95% interval with method='nearest'.\n",
    "# Round only the displayed endpoints to 2 decimals.\n",
    "# Forty repetitions make this a coarse workflow exercise; use thousands\n",
    "# and check endpoint stability for a real management decision.\n",
    "# Print exactly:\n",
    "# 95% CI: 45.67 to 52.6\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "\n",
    "orders = pd.Series([38, 52, 45, 61, 47, 55, 40, 49, 58, 44, 51, 46, 63, 42, 50])\n",
    "rng = np.random.default_rng(434)\n",
    "\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "tags": [
     "hide-input",
     "homework-answer"
    ]
   },
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "95% CI: 45.67 to 52.6\n"
    }
   ],
   "source": [
    "### Solution\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "\n",
    "orders = pd.Series([38, 52, 45, 61, 47, 55, 40, 49, 58, 44, 51, 46, 63, 42, 50])\n",
    "rng = np.random.default_rng(434)\n",
    "bootstrap_means = []\n",
    "for i in range(40):\n",
    "    resample = rng.choice(orders, size=len(orders), replace=True)\n",
    "    bootstrap_means.append(np.mean(resample))\n",
    "\n",
    "left = np.percentile(bootstrap_means, 2.5, method='nearest')\n",
    "right = np.percentile(bootstrap_means, 97.5, method='nearest')\n",
    "print(\"95% CI:\", round(left, 2), \"to\", round(right, 2))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### 9. Sample Size and Interval Width\n",
    "# Two surveys estimated the share of customers who use the mobile app.\n",
    "# Survey A asked 100 customers; survey B asked 400.\n",
    "#   1. Compute the width of each 95% interval, rounded to 3 decimals.\n",
    "#   2. Compute how many times wider interval A is than interval B, rounded to 1 decimal.\n",
    "# Print exactly:\n",
    "# Width A: 0.18\n",
    "# Width B: 0.09\n",
    "# Ratio: 2.0\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "\n",
    "interval_a = [0.31, 0.49]     # n = 100\n",
    "interval_b = [0.355, 0.445]   # n = 400\n",
    "\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "tags": [
     "hide-input",
     "homework-answer"
    ]
   },
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "Width A: 0.18\nWidth B: 0.09\nRatio: 2.0\n"
    }
   ],
   "source": [
    "### Solution\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "\n",
    "interval_a = [0.31, 0.49]     # n = 100\n",
    "interval_b = [0.355, 0.445]   # n = 400\n",
    "\n",
    "width_a = interval_a[1] - interval_a[0]\n",
    "width_b = interval_b[1] - interval_b[0]\n",
    "\n",
    "print(\"Width A:\", round(width_a, 3))\n",
    "print(\"Width B:\", round(width_b, 3))\n",
    "print(\"Ratio:\", round(width_a / width_b, 1))\n",
    "# With comparable designs and variability, four times n gives roughly\n",
    "# half the width. This is a planning approximation, not a guarantee.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### 10. Checking a Supplier's Claim\n",
    "# A supplier claims a 5% defect rate. In a random sample of 300 parts, 18 (0.06)\n",
    "# were defective. The 40 rounded bootstrap proportions below are supplied\n",
    "# for arithmetic practice, not a complete supplier-approval analysis.\n",
    "#   1. Compute the 95% confidence interval (method='nearest').\n",
    "#   2. Check whether the claimed rate of 0.05 is inside the interval.\n",
    "# Print exactly:\n",
    "# 95% CI: 0.033 to 0.083\n",
    "# Claim inside interval: True\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "\n",
    "claimed = 0.05\n",
    "bootstrap_props = pd.Series([0.043, 0.07, 0.033, 0.05, 0.093, 0.057, 0.063, 0.07, 0.067, 0.06,\n",
    "                             0.033, 0.067, 0.043, 0.05, 0.047, 0.083, 0.04, 0.067, 0.057, 0.083,\n",
    "                             0.057, 0.077, 0.083, 0.05, 0.057, 0.033, 0.06, 0.04, 0.06, 0.057,\n",
    "                             0.067, 0.07, 0.063, 0.05, 0.067, 0.073, 0.05, 0.057, 0.053, 0.073])\n",
    "\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "tags": [
     "hide-input",
     "homework-answer"
    ]
   },
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "95% CI: 0.033 to 0.083\nClaim inside interval: True\n"
    }
   ],
   "source": [
    "### Solution\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "\n",
    "claimed = 0.05\n",
    "bootstrap_props = pd.Series([0.043, 0.07, 0.033, 0.05, 0.093, 0.057, 0.063, 0.07, 0.067, 0.06,\n",
    "                             0.033, 0.067, 0.043, 0.05, 0.047, 0.083, 0.04, 0.067, 0.057, 0.083,\n",
    "                             0.057, 0.077, 0.083, 0.05, 0.057, 0.033, 0.06, 0.04, 0.06, 0.057,\n",
    "                             0.067, 0.07, 0.063, 0.05, 0.067, 0.073, 0.05, 0.057, 0.053, 0.073])\n",
    "\n",
    "left = np.percentile(bootstrap_props, 2.5, method='nearest')\n",
    "right = np.percentile(bootstrap_props, 97.5, method='nearest')\n",
    "\n",
    "print(\"95% CI:\", left, \"to\", right)\n",
    "print(\"Claim inside interval:\", left <= claimed <= right)\n",
    "# This practice interval does not rule out 5%; it does not prove the claim\n",
    "# or show that the supplier meets the buyer's requirements.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<style>\n",
    ".ch11-hw-grader { max-width: 900px; margin-top: 1rem; }\n",
    ".ch11-hw-feedback-list { display: grid; gap: 0.45rem; margin: 0 0 1rem; }\n",
    ".ch11-hw-feedback-list[hidden] { display: none; }\n",
    ".ch11-hw-feedback-row { border: 1px solid #d8dee4; border-radius: 6px; padding: 0.55rem 0.65rem; }\n",
    ".ch11-hw-feedback-row strong { margin-right: 0.35rem; }\n",
    ".ch11-hw-feedback-row.correct { border-color: #aceebb; background: #dafbe1; color: #116329; }\n",
    ".ch11-hw-feedback-row.incorrect { border-color: #ffcecb; background: #ffebe9; color: #cf222e; }\n",
    ".ch11-hw-actions { display: flex; gap: 0.75rem; align-items: center; margin: 1rem 0 0; flex-wrap: wrap; }\n",
    ".ch11-hw-actions button { border: 1px solid #176de8; border-radius: 6px; background: #176de8; color: white; padding: 0.55rem 0.9rem; cursor: pointer; font-weight: 600; }\n",
    ".ch11-hw-actions button.secondary { background: white; color: #176de8; }\n",
    ".ch11-hw-actions.is-locked { opacity: 0.55; }\n",
    ".ch11-hw-actions button:disabled { cursor: not-allowed; opacity: 0.65; }\n",
    ".ch11-hw-result { font-weight: 700; }\n",
    "</style>\n",
    "\n",
    "<div class='ch11-hw-grader' id='ch11-hw-grader'>\n",
    "  <div class='ch11-hw-feedback-list' aria-live='polite' hidden>\n",
    "    <div class='ch11-hw-feedback-row' data-question='q1'><strong>Question 1</strong><span></span></div>\n",
    "    <div class='ch11-hw-feedback-row' data-question='q2'><strong>Question 2</strong><span></span></div>\n",
    "    <div class='ch11-hw-feedback-row' data-question='q3'><strong>Question 3</strong><span></span></div>\n",
    "    <div class='ch11-hw-feedback-row' data-question='q4'><strong>Question 4</strong><span></span></div>\n",
    "    <div class='ch11-hw-feedback-row' data-question='q5'><strong>Question 5</strong><span></span></div>\n",
    "    <div class='ch11-hw-feedback-row' data-question='q6'><strong>Question 6</strong><span></span></div>\n",
    "    <div class='ch11-hw-feedback-row' data-question='q7'><strong>Question 7</strong><span></span></div>\n",
    "    <div class='ch11-hw-feedback-row' data-question='q8'><strong>Question 8</strong><span></span></div>\n",
    "    <div class='ch11-hw-feedback-row' data-question='q9'><strong>Question 9</strong><span></span></div>\n",
    "    <div class='ch11-hw-feedback-row' data-question='q10'><strong>Question 10</strong><span></span></div>\n",
    "  </div>\n",
    "  <div class='ch11-hw-actions'>\n",
    "    <button type='button' id='ch11-hw-submit' disabled>Submit</button>\n",
    "    <button type='button' class='secondary' id='ch11-hw-reset'>Clear Results</button>\n",
    "    <span class='ch11-hw-result' id='ch11-hw-result' aria-live='polite'></span>\n",
    "  </div>\n",
    "</div>\n",
    "\n",
    "<script>\n",
    "(function () {\n",
    "  var homeworkId = 'ch11-homework';\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 + 6)] = codeFromCell(cell);\n",
    "    });\n",
    "    return code;\n",
    "  }\n",
    "\n",
    "  function collectAnswers() {\n",
    "    var answers = {};\n",
    "    ['q1', 'q2', 'q3', 'q4', 'q5'].forEach(function (question) {\n",
    "      var checked = document.querySelector('input[name=\"ch11-hw-' + question + '\"]:checked');\n",
    "      answers[question] = checked ? checked.value : '';\n",
    "    });\n",
    "    return answers;\n",
    "  }\n",
    "\n",
    "  function applyFeedback(grader, feedback) {\n",
    "    var list = grader.querySelector('.ch11-hw-feedback-list');\n",
    "    list.hidden = false;\n",
    "    ['q1', 'q2', 'q3', 'q4', 'q5', 'q6', 'q7', 'q8', 'q9', 'q10'].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 = 'ch11-hw-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('.ch11-hw-feedback-list');\n",
    "    list.hidden = true;\n",
    "    grader.querySelectorAll('.ch11-hw-feedback-row').forEach(function (row) {\n",
    "      row.className = 'ch11-hw-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/homework-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 initHomeworkGrader() {\n",
    "    var grader = document.getElementById('ch11-hw-grader');\n",
    "    if (!grader || grader.dataset.ready === 'true') return;\n",
    "    grader.dataset.ready = 'true';\n",
    "\n",
    "    var identity = getParams();\n",
    "    var actions = grader.querySelector('.ch11-hw-actions');\n",
    "    var result = document.getElementById('ch11-hw-result');\n",
    "    var submit = document.getElementById('ch11-hw-submit');\n",
    "    var reset = document.getElementById('ch11-hw-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 homework.';\n",
    "\n",
    "      saveAttempt({\n",
    "        homework_id: homeworkId,\n",
    "        answers: collectAnswers(),\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', initHomeworkGrader);\n",
    "  } else {\n",
    "    initHomeworkGrader();\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
}
