Files
2026-08-01 15:00:14 +00:00

2 lines
41 KiB
JavaScript

(self.webpackChunkWebComponents=self.webpackChunkWebComponents||[]).push([[49,250],{29119:(t,e,s)=>{"use strict";(0,s(54250).Hh)({"sr-Cyrl":{msg_parson_check_me:"Провери",msg_parson_reset:"Поништи",msg_parson_help:"Помоћ",msg_parson_too_short:"Искористи све блокове у решењу",msg_parson_drag_from_here:"Превуци одавде",msg_parson_drag_to_here:"Превуци овде",msg_parson_correct_first_try:"Одлично! Успео си из првог покушаја!",msg_parson_correct:"Одлично! Решио си у само $1 покушаја. Одабери Поништи ако желиш да решиш из првог покушаја.",msg_parson_wrong_indent:"Овај блок није тачно увучен. Превуци га лево или десно да пронађеш прави ниво.",msg_parson_wrong_indents:"Ови блокви нису тачно увучени. Превуци их лево или десно да им пронађеш прави ниво.",msg_parson_wrong_order:"Означени блокови у твом програму су нетачни или у погрешном редоследу. Промени редослед или избаци блок из решења.",msg_parson_arrow_navigate:"Користи стрелице за кретње а Спејс да означииш блок који помераш.",msg_parson_help_info:"Одабери Помоћ ако желиш да олакшаш задатак",msg_parson_not_solution:"Одстранили смо блок који није део решења.",msg_parson_provided_indent:"Увукли смо блок.",msg_parson_combined_blocks:"Спојили смо два блока.",msg_parson_remove_incorrect:"Уклонићемо нетачне блокове из одговора.",msg_parson_will_combine:"Спојићемо два блока.",msg_parson_atleast_three_attempts:"Мораш пробати бар 3 могућа решења пре него што погледаш помоћ.",msg_parson_three_blocks_left:"Остало је још 3 тачна блока. Пронађи им редослед.",msg_parson_will_provide_indent:"Увућићемо блок."}})},35358:(t,e,s)=>{var r={"./af":25177,"./af.js":25177,"./ar":61509,"./ar-dz":41488,"./ar-dz.js":41488,"./ar-kw":58676,"./ar-kw.js":58676,"./ar-ly":42353,"./ar-ly.js":42353,"./ar-ma":24496,"./ar-ma.js":24496,"./ar-sa":82682,"./ar-sa.js":82682,"./ar-tn":89756,"./ar-tn.js":89756,"./ar.js":61509,"./az":95533,"./az.js":95533,"./be":28959,"./be.js":28959,"./bg":47777,"./bg.js":47777,"./bm":54903,"./bm.js":54903,"./bn":61290,"./bn.js":61290,"./bo":31545,"./bo.js":31545,"./br":11470,"./br.js":11470,"./bs":44429,"./bs.js":44429,"./ca":7306,"./ca.js":7306,"./cs":56464,"./cs.js":56464,"./cv":73635,"./cv.js":73635,"./cy":64226,"./cy.js":64226,"./da":93601,"./da.js":93601,"./de":77853,"./de-at":26111,"./de-at.js":26111,"./de-ch":54697,"./de-ch.js":54697,"./de.js":77853,"./dv":60708,"./dv.js":60708,"./el":54691,"./el.js":54691,"./en-au":53872,"./en-au.js":53872,"./en-ca":28298,"./en-ca.js":28298,"./en-gb":56195,"./en-gb.js":56195,"./en-ie":66584,"./en-ie.js":66584,"./en-nz":79402,"./en-nz.js":79402,"./eo":32934,"./eo.js":32934,"./es":97650,"./es-do":20838,"./es-do.js":20838,"./es-us":56575,"./es-us.js":56575,"./es.js":97650,"./et":3035,"./et.js":3035,"./eu":3508,"./eu.js":3508,"./fa":119,"./fa.js":119,"./fi":90527,"./fi.js":90527,"./fo":52477,"./fo.js":52477,"./fr":85498,"./fr-ca":26435,"./fr-ca.js":26435,"./fr-ch":37892,"./fr-ch.js":37892,"./fr.js":85498,"./fy":37071,"./fy.js":37071,"./gd":70217,"./gd.js":70217,"./gl":77329,"./gl.js":77329,"./gom-latn":93383,"./gom-latn.js":93383,"./gu":95050,"./gu.js":95050,"./he":11713,"./he.js":11713,"./hi":43861,"./hi.js":43861,"./hr":26308,"./hr.js":26308,"./hu":90609,"./hu.js":90609,"./hy-am":17160,"./hy-am.js":17160,"./id":74063,"./id.js":74063,"./is":89374,"./is.js":89374,"./it":88383,"./it.js":88383,"./ja":23827,"./ja.js":23827,"./jv":89722,"./jv.js":89722,"./ka":41794,"./ka.js":41794,"./kk":27088,"./kk.js":27088,"./km":96870,"./km.js":96870,"./kn":84451,"./kn.js":84451,"./ko":63164,"./ko.js":63164,"./ky":78474,"./ky.js":78474,"./lb":79680,"./lb.js":79680,"./lo":15867,"./lo.js":15867,"./lt":45766,"./lt.js":45766,"./lv":69532,"./lv.js":69532,"./me":58076,"./me.js":58076,"./mi":41848,"./mi.js":41848,"./mk":30306,"./mk.js":30306,"./ml":73739,"./ml.js":73739,"./mr":86169,"./mr.js":86169,"./ms":73386,"./ms-my":92297,"./ms-my.js":92297,"./ms.js":73386,"./mt":77075,"./mt.js":77075,"./my":72264,"./my.js":72264,"./nb":22274,"./nb.js":22274,"./ne":8235,"./ne.js":8235,"./nl":92572,"./nl-be":43784,"./nl-be.js":43784,"./nl.js":92572,"./nn":54566,"./nn.js":54566,"./pa-in":29849,"./pa-in.js":29849,"./pl":94418,"./pl.js":94418,"./pt":79834,"./pt-br":48303,"./pt-br.js":48303,"./pt.js":79834,"./ro":24457,"./ro.js":24457,"./ru":82271,"./ru.js":82271,"./sd":1221,"./sd.js":1221,"./se":33478,"./se.js":33478,"./si":17538,"./si.js":17538,"./sk":5784,"./sk.js":5784,"./sl":46637,"./sl.js":46637,"./sq":86794,"./sq.js":86794,"./sr":45719,"./sr-cyrl":3322,"./sr-cyrl.js":3322,"./sr.js":45719,"./ss":56e3,"./ss.js":56e3,"./sv":41011,"./sv.js":41011,"./sw":40748,"./sw.js":40748,"./ta":11025,"./ta.js":11025,"./te":11885,"./te.js":11885,"./tet":28861,"./tet.js":28861,"./th":55802,"./th.js":55802,"./tl-ph":29231,"./tl-ph.js":29231,"./tlh":31052,"./tlh.js":31052,"./tr":85096,"./tr.js":85096,"./tzl":79846,"./tzl.js":79846,"./tzm":81765,"./tzm-latn":97711,"./tzm-latn.js":97711,"./tzm.js":81765,"./uk":16618,"./uk.js":16618,"./ur":57777,"./ur.js":57777,"./uz":57609,"./uz-latn":72475,"./uz-latn.js":72475,"./uz.js":57609,"./vi":21135,"./vi.js":21135,"./x-pseudo":64051,"./x-pseudo.js":64051,"./yo":82218,"./yo.js":82218,"./zh-cn":52648,"./zh-cn.js":52648,"./zh-hk":1632,"./zh-hk.js":1632,"./zh-tw":50304,"./zh-tw.js":50304};function n(t){var e=o(t);return s(e)}function o(t){if(!s.o(r,t)){var e=new Error("Cannot find module '"+t+"'");throw e.code="MODULE_NOT_FOUND",e}return r[t]}n.keys=function(){return Object.keys(r)},n.resolve=o,t.exports=n,n.id=35358},39234:()=>{},46490:()=>{},54250:(t,e,s)=>{"use strict";s.d(e,{Hh:()=>a,t:()=>l});const r="en",n={};function o(t){return String(t||"").toLowerCase()}let i=o("undefined"!=typeof document&&document.documentElement.lang||"undefined"!=typeof navigator&&navigator.language||r);function a(t){for(const[e,s]of Object.entries(t)){const t=o(e);n[t]=Object.assign(n[t]||{},s)}}function l(t,...e){const s=function(t){for(const e of function(t){const e=[];if(t){e.push(t);const s=t.split("-")[0];s&&s!==t&&e.push(s)}return-1===e.indexOf(r)&&e.push(r),e}(i)){const s=n[e];if(s&&void 0!==s[t])return s[t]}}(t);return void 0===s?t:s.replace(/\$(\d+)/g,((t,s)=>{const r=e[Number(s)-1];return void 0===r?t:String(r)}))}},56906:(t,e,s)=>{"use strict";(0,s(54250).Hh)({"pt-br":{msg_parson_check_me:"Verificar",msg_parson_reset:"Resetar",msg_parson_help:"Ajuda",msg_parson_too_short:"Seu programa é muito curto. Adicione mais blocos.",msg_parson_drag_from_here:"Arraste daqui",msg_parson_drag_to_here:"Largue os blocos aqui",msg_parson_correct_first_try:"Perfeito! Você levou apenas uma tentativa para resolver. Bom trabalho!",msg_parson_correct:"Perfeito! Você levou $1 tentativas para resolver. Clique em Resetar para tentar resolver em uma tentativa.",msg_parson_wrong_indent:"Este bloco não está indentado corretamente. Indente mais arrastando-o para a direita ou reduza a indentação arrastando para a esquerda.",msg_parson_wrong_indents:"Estes blocos não estão indentados corretamente. Para indentar mais, arraste o bloco para a direita. Para reduzir a indentação, arraste para a esquerda.",msg_parson_wrong_order:"Blocos destacados no seu programa estão errados ou estão na ordem errada. Isso pode ser resolvido movendo, excluindo ou substituindo os blocos destacados.",msg_parson_arrow_navigate:"Use as teclas de setas para navegar. Espaço para selecionar/ desmarcar blocos para mover.",msg_parson_help_info:"Clique no botão Ajuda se você quiser facilitar o problema",msg_parson_not_solution:"Foi desabilitado um bloco de código desnecessário (que não faz parte da solução).",msg_parson_provided_indent:"Foi fornecida a indentação.",msg_parson_combined_blocks:"Dois blocos de códigos foram combinados em um.",msg_parson_remove_incorrect:"Será removido um bloco de código incorreto da área de resposta",msg_parson_will_combine:"Serão combinados dois blocos",msg_parson_atleast_three_attempts:"Você deve tentar pelo menos três vezes antes de pedir ajuda",msg_parson_three_blocks_left:"Restam apenas 3 blocos corretos. Você deve colocá-los em ordem",msg_parson_will_provide_indent:"Será fornecida a indentação"}})},67920:()=>{},75794:(t,e,s)=>{"use strict";(0,s(54250).Hh)({en:{msg_parson_check_me:"Check",msg_parson_reset:"Reset",msg_parson_help:"Help me",msg_parson_too_short:"Your answer is too short. Add more blocks.",msg_parson_drag_from_here:"Drag from here",msg_parson_drag_to_here:"Drop blocks here",msg_parson_correct_first_try:"Perfect! It took you only one try to solve this. Great job!",msg_parson_correct:"Perfect! It took you $1 tries to solve this. Click Reset to try to solve it in one attempt.",msg_parson_correct_runnable:"Click Run below to test out your solution.",msg_parson_wrong_indent:"This block is not indented correctly. Either indent it more by dragging it right or reduce the indention by dragging it left.",msg_parson_wrong_indents:"These blocks are not indented correctly. To indent a block more, drag it to the right. To reduce the indention, drag it to the left.",msg_parson_wrong_order:"Highlighted blocks in your answer are wrong or are in the wrong order. This can be fixed by moving, removing, or replacing highlighted blocks.",msg_parson_arrow_navigate:"Arrow keys to navigate. Space to select / deselect block to move.",msg_parson_help_info:"Click on the Help Me button if you want to make the problem easier",msg_parson_not_solution:"Disabled an unneeded code block (one that is not part of the solution).",msg_parson_provided_indent:"Provided the indentation.",msg_parson_combined_blocks:"Combined two code blocks into one.",msg_parson_remove_incorrect:"Will remove an incorrect code block from answer area",msg_parson_will_combine:"Will combine two blocks",msg_parson_atleast_three_attempts:"You must make at least three distinct full attempts at a solution before you can get help",msg_parson_three_blocks_left:"There are only 3 correct blocks left. You should be able to put them in order",msg_parson_will_provide_indent:"Will provide indentation"}})},97401:(t,e,s)=>{"use strict";s.r(e),s.d(e,{default:()=>x,hpList:()=>f});var r=s(78673);class n{constructor(t){this.hparsons=t,this.percent=0}createOutput(){console.log("createOutput method not implemented in feedback!")}async runButtonHandler(){console.log("runButtonClicked method not implemented in feedback!")}customizeUI(){}init(){}clearFeedback(){console.log("clearFeedback method not implemented in feedback!")}reset(){console.log("reset method not implemented in feedback!")}}var o=s(54250);class i{constructor(t){this.problem=t,this.percent=0}inverseLISIndices(t){for(var e=[],s=0;s<t.length;s++){for(var r=[t[s]],n=0;n<s;n++)t[n]<t[s]&&e[n].length+1>r.length&&(r=e[n].concat(t[s]));e.push(r)}var o,i=-1;for(let t in e){var a=e[t];a.length>i&&(i=a.length,o=a)}var l=[],h=0;for(let e=0;e<t.length;e++)h>o.length?l.push(e):t[e]==o[h]?h+=1:l.push(e);return l}grade(){this.correctLines=0,this.percentLines=0;var t,e,s=this.solution,r=this.answer;this.percentLines=Math.min(r.length,s.length)/Math.max(r.length,s.length),r.length<s.length?(e="incorrectTooShort",this.correctLength=!1):r.length==s.length?this.correctLength=!0:this.correctLength=!1;let n=!0;this.correctLines=0,this.solutionLength=s.length;let o=Math.min(s.length,r.length);for(t=0;t<o;t++)r[t]!==s[t]?n=!1:this.correctLines+=1;return n&&this.correctLength?e="correct":(n||"incorrectTooShort"==e)&&(this.correctLength||"incorrectTooShort"==e)||(e="incorrectMoveBlocks"),this.calculatePercent(),this.graderState=e,e}calculatePercent(){let t=.2*this.percentLines,e=this.answer.length,s=this.correctLines/e*.8;this.percent=t+s}}s(75794),s(56906),s(29119);class a extends n{createOutput(){this.messageDiv=document.createElement("div"),this.hparsons.outerDiv.appendChild(this.messageDiv)}customizeUI(){this.hparsons.runButton.textContent="Check Me"}init(){this.checkCount=0,this.solved=!1,this.grader=new i,this.solution=this.hparsons.blockAnswer.map((t=>this.blockContent(t))),this.grader.solution=this.solution,this.answerArea=this.hparsons.hparsonsInput.querySelector(".drop-area")}blockContent(t){const e=(this.hparsons.originalBlocks||[])[Number(t)];return void 0===e?`\0unknown-block-${t}`:e}currentAnswerContent(){return this.hparsons.hparsonsInput.getBlockIndices().map((t=>this.blockContent(t)))}async runButtonHandler(){this.checkCurrentAnswer(),this.logCurrentAnswer(),this.renderFeedback()}async logCurrentAnswer(){let t={scheme:"block",correct:"correct"==this.grader.graderState?"T":"F",answer:this.hparsons.hparsonsInput.getBlockIndices(),percent:this.grader.percent},e={event:"hparsonsAnswer",div_id:this.hparsons.divid,act:JSON.stringify(t),answer:JSON.stringify({blocks:t.answer}),percent:this.grader.percent,correct:t.correct};await this.hparsons.logBookEvent(e)}checkCurrentAnswer(){this.solved||(this.checkCount++,this.clearFeedback(),this.grader.answer=this.currentAnswerContent(),this.grade=this.grader.grade(),"correct"==this.grade&&(this.hparsons.runButton.disabled=!0,this.solved=!0))}renderFeedback(){var t;this.grade=this.grader.graderState;var e=this.answerArea;if(t=this.messageDiv,"correct"===this.grade&&(e.classList.add("correct"),t.style.display="",t.className="hp_feedback alert alert-info",this.checkCount>1?t.innerHTML=(0,o.t)("msg_parson_correct",this.checkCount):t.innerHTML=(0,o.t)("msg_parson_correct_first_try"),this.checkCount=0),"incorrectTooShort"===this.grade&&(e.classList.add("incorrect"),t.style.display="",t.className="hp_feedback alert alert-danger",t.innerHTML=(0,o.t)("msg_parson_too_short")),"incorrectMoveBlocks"===this.grade){var s=this.answerArea.children,r=[],n=[],i=[],a=new Set;for(let t=0;t<s.length;t++){var l=s[t],h=this.blockContent(l.dataset.index),c=-1;for(let t=0;t<this.solution.length;t++)if(!a.has(t)&&this.solution[t]===h){c=t,a.add(t);break}-1==c?i.push(l):(r.push(l),n.push(c))}var d=this.grader.inverseLISIndices(n);for(let t=0;t<d.length;t++)i.push(r[d[t]]);e.classList.add("incorrect"),t.style.display="",t.className="alert alert-danger";for(let t=0;t<i.length;t++)i[t].classList.add("incorrectPosition");t.innerHTML=(0,o.t)("msg_parson_wrong_order")}}clearFeedback(){this.answerArea.classList.remove("incorrect","correct");for(var t=this.answerArea.childNodes,e=0;e<t.length;e++)t[e].classList.remove("correctPosition","incorrectPosition");this.messageDiv.style.display="none"}reset(){this.solved&&(this.checkCount=0,this.hparsons.runButton.disabled=!1,this.solved=!1),this.clearFeedback()}}var l=s(15826),h=s.n(l),c=s(12307),d={};class u extends n{createOutput(){var t=document.createElement("div");t.classList.add("hp_output"),this.outDiv=t,this.output=document.createElement("pre"),this.output.id=this.hparsons.divid+"_stdout",this.output.style.visibility="hidden";var e=document.createElement("div");e.style.clear="both",this.hparsons.outerDiv.appendChild(e),t.appendChild(this.output),this.hparsons.outerDiv.appendChild(t),(e=document.createElement("div")).style.clear="both",this.hparsons.outerDiv.appendChild(e)}renderFeedback(){this.testResult&&(this.output.textContent=this.testResult,this.output.style.visibility="visible"),this.outDiv.style.display=""}clearFeedback(){this.outDiv.style.display="none"}reset(){this.clearFeedback()}init(){var t,e;eBookConfig.useRunestoneServices||window.location.search.includes("mode=browsing")?(t=`/books/published/${eBookConfig.basecourse}`,e=t+"/_static"):(t="",e="/_static");let s={locateFile:t=>`${e}/${t}`};var r=this.hparsons;h()(s).then((function(e){if(r.dburl){r.dburl.startsWith("/_static")&&(r.dburl=`${t}${r.dburl}`),r.runButton.setAttribute("disabled","disabled");let n=r.runButton.textContent;if(r.runButton.textContent="Loading database...",r.dburl in d)return"loading"==d[r.dburl].status?void d[r.dburl].xWaitFor.promise.then((function(){r.db=d[r.dburl].dbObject,r.runButton.removeAttribute("disabled"),r.runButton.textContent=n})):(r.db=d[r.dburl].dbObject,r.runButton.removeAttribute("disabled"),void(r.runButton.textContent=n));{let t;const e=new Promise((e=>{t=e}));d[r.dburl]={status:"loading",xWaitFor:{promise:e,resolve:t}}}var s=new XMLHttpRequest;s.open("GET",r.dburl,!0),s.responseType="arraybuffer",s.onload=t=>{var o=new Uint8Array(s.response);r.db=new e.Database(o),d[r.dburl].dbObject=r.db,r.runButton.textContent=n,r.runButton.removeAttribute("disabled"),d[r.dburl].db=o,d[r.dburl].status="ready",d[r.dburl].xWaitFor.resolve()},s.send()}else r.db=new e.Database}))}async runButtonHandler(){this.hparsons.runButton.disabled=!0;try{await this.runProg()}catch(t){console.log(`there was an error ${t} running the code`)}this.logCurrentAnswer(),this.renderFeedback(),this.hparsons.runButton.disabled=!1}async runProg(){let t=this.hparsons.divid+"_sql_out",e=document.getElementById(t);e&&e.parentElement.removeChild(e),this.output.textContent="",e=document.createElement("div"),e.id=t,this.outDiv.appendChild(e),this.outDiv.style.display="";let s=await this.buildProg();if(!this.hparsons.db)return void(this.output.textContent=`Error: Database not initialized! DBURL: ${this.hparsons.dburl}`);let r=!0;return s.prefix&&(this.prefixresults=this.executeIteratedStatements(this.hparsons.db.iterateStatements(s.prefix)),"failure"==this.prefixresults.at(-1).status&&(this.visualizeResults(e,this.prefixresults,"Error executing hidden code in prefix"),r=!1)),r&&(this.results=this.executeIteratedStatements(this.hparsons.db.iterateStatements(s.input)),"failure"==this.results.at(-1).status?(this.visualizeResults(e,this.results),r=!1):s.suffix||this.visualizeResults(e,this.results)),r&&s.suffix&&(this.suffixresults=this.executeIteratedStatements(this.hparsons.db.iterateStatements(s.suffix)),"failure"==this.suffixresults.at(-1).status?(this.visualizeResults(e,this.suffixresults,"Error executing hidden code in suffix"),r=!1):this.visualizeResults(e,this.suffixresults)),this.hparsons.unittest?r?this.suffixresults?this.testResult=this.autograde(this.suffixresults[this.suffixresults.length-1]):this.testResult=this.autograde(this.results[this.results.length-1]):(this.passed=0,this.failed=0,this.percent=NaN,this.unit_results=`percent:${this.percent}:passed:${this.passed}:failed:${this.failed}`,this.output.style.visibility="hidden"):this.output.style.visibility="hidden",Promise.resolve("done")}executeIteratedStatements(t){let e=[];try{for(let s of t){let t=s.getColumnNames();if(t.length>0){let r=[];for(;s.step();)r.push(s.get());e.push({status:"success",columns:t,values:r,rowcount:r.length})}else{let t=s.getNormalizedSQL().substr(0,6).toLowerCase();s.step(),"insert"===t||"update"===t||"delete"===t?e.push({status:"success",operation:t,rowcount:this.hparsons.db.getRowsModified()}):e.push({status:"success"})}}}catch(s){e.push({status:"failure",message:s.toString(),sql:t.getRemainingSQL()})}return 0===e.length&&e.push({status:"failure",message:"No queries submitted."}),e}visualizeResults(t,e,s){if(s){let e=document.createElement("div");e.setAttribute("class","hp_sql_result"),t.appendChild(e);let r=document.createElement("pre");r.textContent=s,r.setAttribute("class","hp_sql_result_failure"),e.appendChild(r)}for(let s of e){let r=document.createElement("div");if(r.setAttribute("class","hp_sql_result"),t.appendChild(r),"success"===s.status)if(s.columns){let t=document.createElement("div");r.appendChild(t);let n=350;e.length>1&&(n=200),p(s,t,n);let o=document.createElement("pre"),i=1!==s.rowcount?" rows ":" row ",a=""+s.rowcount+i+"returned";s.rowcount>100&&(a+=" (only first 100 rows displayed)"),a+=".",o.textContent=a,o.setAttribute("class","hp_sql_result_success"),r.appendChild(o)}else if(s.rowcount){let t=document.createElement("pre"),e=s.operation;e+="e"===e.charAt(e.length-1)?"d.":"ed.";let n=1!==s.rowcount?" rows ":" row ";t.textContent=""+s.rowcount+n+e,t.setAttribute("class","hp_sql_result_success"),r.appendChild(t)}else{let t=document.createElement("pre");t.textContent="Operation succeeded.",t.setAttribute("class","hp_sql_result_success"),r.appendChild(t)}else{let t=document.createElement("pre");t.textContent=s.message,t.setAttribute("class","hp_sql_result_failure"),r.appendChild(t)}}}async buildProg(){let t={};return this.hparsons.hiddenPrefix&&(t.prefix=this.hparsons.hiddenPrefix),t.input=this.hparsons.hparsonsInput.getParsonsTextArray().join(" ")+"\n",this.hparsons.hiddenSuffix&&(t.suffix=this.hparsons.hiddenSuffix),Promise.resolve(t)}async logCurrentAnswer(){if(this.unit_results){let t={scheme:"execution",correct:0==this.failed&&0!=this.passed?"T":"F",answer:this.hparsons.hparsonsInput.getParsonsTextArray(),percent:this.percent},e={event:"hparsonsAnswer",div_id:this.hparsons.divid,act:JSON.stringify(t),percent:this.percent||0,correct:t.correct,answer:JSON.stringify({blocks:t.answer})};await this.hparsons.logBookEvent(e)}}autograde(t){var e=this.hparsons.unittest.split(/\n/);this.passed=0,this.failed=0;var s="";e=e.filter((function(t){return t.indexOf("assert")>-1}));for(let r of e){let e=r.split(/\s+/);e.shift();let n=e.shift(),o=e.shift(),i=e.join(" "),[a,l]=n.split(",");s+=this.testOneAssert(a,l,o,i,t),s+="\n"}let r=100*this.passed/(this.passed+this.failed);return this.percent=r,r=r.toLocaleString(void 0,{maximumFractionDigits:2}),s+=`You passed ${this.passed} out of ${this.passed+this.failed} tests for ${r}%`,this.unit_results=`percent:${r}:passed:${this.passed}:failed:${this.failed}`,s}testOneAssert(t,e,s,r,n){let o,i="";try{o=n.values[t][e]}catch(s){return"NO_DATA"==r?(this.passed++,i=`Passed: No data in row ${t}, column ${e}`,i):(i=`Failed: Not enough data to check row ${t} or column ${e}`,i)}return{"==":function(t,e){return t==e},"!=":function(t,e){return t!=e},">":function(t,e){return t>e},"<":function(t,e){return t>e}}[s](o,r)?(i=`Pass: ${o} ${s} ${r} in row ${t} column ${n.columns[e]}`,this.passed++):(i=`Failed ${o} ${s} ${r} in row ${t} column ${n.columns[e]}`,this.failed++),i}}function p(t,e,s){let r,n=t.values;0===n.length&&(n=[t.columns.map((t=>null))],r=[0]);var o=new c.A(e,{data:n,trimRows:r,width:"100%",height:s,autoRowSize:!0,autoColumnSize:{useHeaders:!0},rowHeaders:!1,colHeaders:t.columns,editor:!1,maxRows:100,filters:!1,dropdownMenu:!1,licenseKey:"non-commercial-and-evaluation"});let i=40;if(t.values.length>0)for(let t=0;t<n.length&&(i+=o.getRowHeight(t),!(i>s));t++);return o.updateSettings({height:i}),o}var g,m=s(10246);!function(t){let e;!function(t){t.ADD="add",t.MOVE="move",t.REMOVE="remove"}(e=t.InputAction||(t.InputAction={}))}(g||(g={}));var _=s(50011);class b{constructor(t,e,s){this.getText=t=>{let e="";if(this._dropArea.hasChildNodes()){let s=this._dropArea.firstChild;for(e+=this._getTextFromBlock(s);s.nextSibling;)s=s.nextSibling,e+=t?" ":"",e+=this._getTextFromBlock(s);return e}return e},this.getBlockIndices=()=>{const t=this._dropArea.querySelectorAll(".parsons-block");return Array.from(t).map((t=>parseInt(t.dataset.index||"-1")))},this._getTextFromBlock=t=>{var e;if("raw"==this.parentElement.language)return t.innerHTML;if(!t.lastChild||t.lastChild.nodeType!=Node.ELEMENT_NODE)return t.textContent||"";const s=t.lastChild.classList.contains("parsons-tooltip")&&(null===(e=t.lastChild.textContent)||void 0===e?void 0:e.length)||0;return s>0?(t.textContent||"").slice(0,-s):t.textContent||""},this.setSourceBlocks=(t,e)=>{this.blockOrder=[];for(let e=0;e<t.length;++e)this.blockOrder.push(e);if(this.randomize){let t=JSON.stringify(this.blockOrder);for(this.shuffleArray(this.blockOrder);JSON.stringify(this.blockOrder)==t;)this.shuffleArray(this.blockOrder)}this.storedSourceBlocks=t,this.storedSourceBlockExplanations=e,this._resetInput()},this._resetInput=()=>{for(;this._dragArea.firstChild;)this._dragArea.removeChild(this._dragArea.firstChild);for(;this._dropArea.firstChild;)this._dropArea.removeChild(this._dropArea.firstChild);for(let t=0;t<this.blockOrder.length;++t){const e=document.createElement("div");if(e.dataset.index=this.blockOrder[t].toString(),this._dragArea.appendChild(e)," "===this.storedSourceBlocks[this.blockOrder[t]]?e.innerHTML="&nbsp;":this.parentElement.hljsLanguage?e.innerHTML=_.A.highlight(this.storedSourceBlocks[this.blockOrder[t]],{language:this.parentElement.hljsLanguage,ignoreIllegals:!0}).value:"raw"==this.parentElement.language?e.innerHTML=this.storedSourceBlocks[this.blockOrder[t]]:e.innerText=this.storedSourceBlocks[this.blockOrder[t]],e.style.display="inline-block",e.classList.add("parsons-block"),e.onclick=t=>{this._onBlockClicked(e,t)},this.storedSourceBlockExplanations&&this.storedSourceBlockExplanations[this.blockOrder[t]]){const s=document.createElement("div");s.innerText=this.storedSourceBlockExplanations[this.blockOrder[t]],s.classList.add("parsons-tooltip"),e.appendChild(s)}}this._updateBlockAria()},this._onBlockClicked=(t,e)=>{const s=this._getTextFromBlock(t).trim();if(t.parentElement==this._dragArea){let r;if(this.reusable){const e=t.cloneNode(!0);e.onclick=t=>this._onBlockClicked(e,t),this._dropArea.appendChild(e),r=this._getBlockPosition(e)}else this._dropArea.appendChild(t),r=this._getBlockPosition(t);const n={type:"input",action:g.InputAction.ADD,position:[-1,r],answer:this._getTextArray()};e.isTrusted&&this.parentElement.logEvent(n),this._updateBlockAria(),this._announce(`${s} moved to answer area`)}else{const e=this._getBlockPosition(t);this.reusable?this._dropArea.removeChild(t):this._dragArea.appendChild(t);const r={type:"input",action:g.InputAction.REMOVE,position:[e,-1],answer:this._getTextArray()};this.parentElement.logEvent(r),this._updateBlockAria(),this._announce(`${s} moved to available blocks`)}},this._initSortable=()=>{this.reusable?(this._dragSortable=new m.Ay(this._dragArea,{group:{name:"shared",pull:"clone",put:!1},sort:!1,direction:"horizontal",animation:150,draggable:".parsons-block",onClone:t=>{const e=t.clone;e.onclick=t=>this._onBlockClicked(e,t)}}),this._dropSortable=new m.Ay(this._dropArea,{group:"shared",direction:"horizontal",animation:150,draggable:".parsons-block",onAdd:t=>{const e={type:"input",action:g.InputAction.ADD,position:[-1,this._getBlockPosition(t.item)],answer:this._getTextArray()};this.parentElement.logEvent(e),this._updateBlockAria()},onStart:t=>{this._prevPosition=this._getBlockPosition(t.item)},onEnd:t=>{let e,s=g.InputAction.MOVE;const r=this._dropArea.getBoundingClientRect().top,n=this._dropArea.getBoundingClientRect().bottom;if(t.originalEvent.clientY>n||t.originalEvent.clientY<r){const r=t.item;r.parentNode&&r.parentNode.removeChild(r),e=-1,s=g.InputAction.REMOVE}else e=this._getBlockPosition(t.item);const o={type:"input",action:s,position:[this._prevPosition,e],answer:this._getTextArray()};this.parentElement.logEvent(o),this._updateBlockAria()}})):(this._dragSortable=new m.Ay(this._dragArea,{group:{name:"shared"},direction:"horizontal",animation:150,draggable:".parsons-block"}),this._dropSortable=new m.Ay(this._dropArea,{group:"shared",direction:"horizontal",animation:150,draggable:".parsons-block",onAdd:t=>{const e={type:"input",action:g.InputAction.ADD,position:[-1,this._getBlockPosition(t.item)],answer:this._getTextArray()};this.parentElement.logEvent(e),this._updateBlockAria()},onStart:t=>{this._prevPosition=this._getBlockPosition(t.item)},onEnd:t=>{let e=this._getBlockPosition(t.item);const s={type:"input",action:-1==e?g.InputAction.REMOVE:g.InputAction.MOVE,position:[this._prevPosition,e],answer:this._getTextArray()};this.parentElement.logEvent(s),this._updateBlockAria()}}))},this.updateTestStatus=t=>{this._dropArea.classList.contains(t)||(this._dropArea.classList.contains("Pass")?this._dropArea.classList.remove("Pass"):this._dropArea.classList.contains("Fail")?this._dropArea.classList.remove("Fail"):this._dropArea.classList.contains("Error")&&this._dropArea.classList.remove("Error"),this._dropArea.classList.add(t))},this._updateBlockAria=()=>{const t=(t,e)=>{t.querySelectorAll(".parsons-block").forEach(((t,s)=>{t.setAttribute("role","option"),t.setAttribute("aria-selected",e?"true":"false"),t.setAttribute("tabindex",0===s?"0":"-1")}))};t(this._dragArea,!1),t(this._dropArea,!0)},this._focusBlock=(t,e)=>{e.querySelectorAll(".parsons-block").forEach((t=>{t.setAttribute("tabindex","-1")})),t.setAttribute("tabindex","0"),t.focus()},this._announce=t=>{this._liveRegion.textContent="",setTimeout((()=>{this._liveRegion.textContent=t}),10)},this._setupKeyboardNav=()=>{this.el.addEventListener("keydown",(t=>{const e=t.target.closest(".parsons-block");if(!e)return;const s=e.parentElement;if(s!==this._dragArea&&s!==this._dropArea)return;const r=Array.from(s.querySelectorAll(".parsons-block")),n=r.indexOf(e);switch(t.key){case"ArrowRight":case"ArrowDown":t.preventDefault(),n<r.length-1&&this._focusBlock(r[n+1],s);break;case"ArrowLeft":case"ArrowUp":t.preventDefault(),n>0&&this._focusBlock(r[n-1],s);break;case" ":case"Enter":{t.preventDefault();const r=s===this._dragArea;this._onBlockClicked(e,t);let n=null;n=r?this.reusable?this._dropArea.lastElementChild:e:this.reusable?this._dropArea.firstElementChild||this._dragArea.firstElementChild:e,n&&this._focusBlock(n,n.parentElement);break}}}))},this._getBlockPosition=t=>{let e=-1;const s=this._dropArea;if(s)for(e=0;e<s.childNodes.length&&s.childNodes[e]!==t;++e);return e},this._getTextArray=()=>{let t=[];if(this._dropArea.hasChildNodes()){let e=this._dropArea.firstChild;for(t.push(this._getTextFromBlock(e));e.nextSibling;)e=e.nextSibling,t.push(this._getTextFromBlock(e))}return t},this.removeFormat=()=>{if(this._dropArea.hasChildNodes()){let t=this._dropArea.firstChild;for(t.style.removeProperty("background-color");t.nextSibling;)t=t.nextSibling,t.style.removeProperty("background-color")}},this.resetInput=()=>{if(this.reusable){for(;this._dropArea.firstChild;)this._dropArea.removeChild(this._dropArea.firstChild);this._updateBlockAria()}else this._resetInput()},this.el=document.createElement("div"),this.el.classList.add("hparsons-input"),this.parentElement=t,this.el.id="hparsonstool-"+this.parentElement.toolNumber+"-parsons-input";const r=document.createElement("div");r.innerText="Drag or click the blocks below to form your code:",r.classList.add("hparsons-tip"),this.el.append(r),this._dragArea=document.createElement("div"),this.el.appendChild(this._dragArea),this._dragArea.classList.add("drag-area"),this._dragArea.setAttribute("role","listbox"),this._dragArea.setAttribute("aria-label","Available blocks");const n=document.createElement("div");n.innerText="Your code (click on a block to remove it):",n.classList.add("hparsons-tip"),this.el.append(n),this._dropArea=document.createElement("div"),this.el.appendChild(this._dropArea),this._dropArea.classList.add("drop-area"),this._dropArea.setAttribute("role","listbox"),this._dropArea.setAttribute("aria-label","Answer area"),this._prevPosition=-1,this._liveRegion=document.createElement("div"),this._liveRegion.setAttribute("aria-live","polite"),this._liveRegion.setAttribute("aria-atomic","true"),this._liveRegion.classList.add("sr-only"),this.el.appendChild(this._liveRegion),this.storedSourceBlocks=[],this.blockOrder=[],this.storedSourceBlockExplanations=null,this.reusable=e,this.randomize=s,this._dragSortable=null,this._dropSortable=null,this._initSortable(),this._setupKeyboardNav(),this.initialized=!1}shuffleArray(t){for(let e=t.length-1;e>0;e--){let s=Math.floor(Math.random()*(e+1)),r=t[e];t[e]=t[s],t[s]=r}}restoreAnswer(t){this.resetInput();const e=/^\s+$/;for(let s=0;s<t.length;++s){let r=e.test(t[s]);if(this._dragArea.hasChildNodes()){let n=this._dragArea.firstChild;for(;n;){if(r){if(e.test(this._getTextFromBlock(n))&&t[s].length==this._getTextFromBlock(n).length){n.click();break}}else if(this._getTextFromBlock(n)==t[s]){n.click();break}n=n.nextSibling}}}const s={type:"restore",answer:t};this.parentElement.logEvent(s)}restoreAnswerByIndices(t){this.resetInput();for(let e=0;e<t.length;++e){const s=String(t[e]);if(this._dragArea.hasChildNodes()){let t=this._dragArea.firstChild;for(;t;){if(t.dataset.index===s){t.click();break}t=t.nextSibling}}}const e={type:"restore",answer:t.map(String)};this.parentElement.logEvent(e)}}var f,v=s(15603),k=s(85262),A=s(83736),y=s(57470),w=s(69359);_.A.registerLanguage("javascript",v.A),_.A.registerLanguage("sql",y.A),_.A.registerLanguage("java",A.A),_.A.registerLanguage("xml",w.A),_.A.registerLanguage("python",k.A);class C extends HTMLElement{constructor(){super(),this.logEvent=t=>{const e=new CustomEvent("micro-parsons",{bubbles:!0,detail:Object.assign({},t)});this.dispatchEvent(e)},C.toolCount+=1,this.toolNumber=C.toolCount,this.root=this;const t=!!this.getAttribute("reuse"),e=!!this.getAttribute("randomize");this.hparsonsInput=new b(this,t,e),this._parsonsData=new Array,this.parsonsExplanation=null,this.inputType="parsons",this.language=this.getAttribute("language")||"none";let s=new Map(Object.entries({html:"xml",python:"python",javascript:"javascript",java:"java",sql:"sql"}));this.hljsLanguage=s.get(this.language),this.initInput(),this.temporaryInputEvent=null,this.codeBefore=null,this.codeAfter=null}set parsonsData(t){this._parsonsData=t,"parsons"==this.inputType&&this.hparsonsInput.setSourceBlocks(t,this.parsonsExplanation)}get parsonsData(){return this._parsonsData}initInput(){this.inputType="parsons",this._parsonsData=new Array,this.parsonsExplanation=null;const t=null!=this.getAttribute("reuse"),e=null!=this.getAttribute("randomize");this.hparsonsInput=new b(this,t,e),this.root.appendChild(this.hparsonsInput.el)}resetInput(){this.hparsonsInput.resetInput(),this.logEvent({type:"reset"})}restoreAnswer(t){this.hparsonsInput.restoreAnswer(t)}restoreAnswerByIndices(t){this.hparsonsInput.restoreAnswerByIndices(t)}getCurrentInput(t){return this.hparsonsInput.getText(t)}getParsonsTextArray(){return this.hparsonsInput._getTextArray()}getBlockIndices(){return this.hparsonsInput.getBlockIndices()}setCodeContext(t){if(t.before){let e;this.codeBefore=t.before,this.querySelector(".context.before")?e=this.querySelector(".context.before"):(e=document.createElement("pre"),e.className="context before",this.querySelector(".hparsons-input").insertBefore(e,this.querySelector(".drop-area"))),e.innerHTML=this.codeBefore,this.hljsLanguage&&(e.className="context before",e.classList.add(this.hljsLanguage),_.A.highlightElement(e))}if(t.after){let e;this.codeAfter=t.after,this.querySelector(".context.after")?e=this.querySelector(".context.after"):(e=document.createElement("pre"),e.className="context after",this.querySelector(".hparsons-input").appendChild(e)),e.innerHTML=this.codeAfter,this.hljsLanguage&&(e.className="context after",e.classList.add(this.hljsLanguage),_.A.highlightElement(e))}}}C.toolCount=0,customElements.define("micro-parsons",C),void 0===f&&(f={});class x extends r.A{constructor(t){super(t);var e=t.orig.querySelector("textarea");this.reuse=this.parseBooleanAttribute(e,"data-reuse"),this.randomize=this.parseBooleanAttribute(e,"data-randomize"),this.isBlockGrading=this.parseBooleanAttribute(e,"data-blockanswer"),this.language=e.getAttribute("data-language"),null==this.language&&e.textContent.includes('span class="process-math"')&&(this.language="math"),this.isBlockGrading&&(this.blockAnswer=e.getAttribute("data-blockanswer").trim().split(/\s+/)),this.divid=t.orig.id,this.containerDiv=t.orig,this.useRunestoneServices=t.useRunestoneServices;var s=super.localStorageKey();this.storageId=s,this.origElem=e;let r=t.orig.querySelector(".hp_question");r&&r.classList.add("exercise-statement"),this.origText=this.origElem.textContent,this.code=e.textContent||"\n\n\n\n\n",this.dburl=e.getAttribute("data-dburl"),this.runButton=null,this.saveButton=null,this.loadButton=null,this.outerDiv=null,this.controlDiv=null,this.processContent(this.code),this.isBlockGrading?this.feedbackController=new a(this):this.feedbackController=new u(this),this.createEditor(),this.createControls(),this.createOutput(),this.feedbackController.customizeUI(),e.getAttribute("data-caption")?this.caption=e.getAttribute("data-caption"):this.caption="MicroParsons",this.addCaption("runestone"),this.indicate_component_ready(),this.feedbackController.init(),this.checkServer("hparsonsAnswer",!0)}processContent(t){this.hiddenPrefix=this.processSingleContent(t,"--hiddenprefix--"),this.originalBlocks=this.processSingleContent(t,"--blocks--").split("\n").slice(1,-1),this.hiddenSuffix=this.processSingleContent(t,"--hiddensuffix--"),this.unittest=this.processSingleContent(t,"--unittest--")}processSingleContent(t,e){let s=t.indexOf(e);if(s>-1){let r=t.substring(s+e.length),n=r.indexOf("\n--");return r=n>-1?r.substring(0,n+1):r,r}}createEditor(){this.outerDiv=document.createElement("div"),this.origElem.replaceWith(this.outerDiv),this.outerDiv.id=`${this.divid}-container`,this.outerDiv.addEventListener("micro-parsons",(t=>{["input","reset"].includes(t.detail.type)&&(this.logHorizontalParsonsEvent(t.detail),this.feedbackController.clearFeedback())})),(t=>{let e;try{e=document.querySelector(t.selector)}catch(t){throw"micro-parsons: init: selector error"}if(null==e||"DIV"!=e.tagName)throw"micro-parsons: element not a div";const s=-1==["javascript","sql","java","html","python","raw"].indexOf(t.language||"")?"":`language='${t.language}'`,r=`<micro-parsons ${t.reuse?"reuse":""} ${!1===t.randomize?"":"randomize"} ${s} ${t.id?`id='${t.id}'`:""}></micro-parsons>`;e.innerHTML=r;const n=e.firstChild;n.parsonsExplanation=t.parsonsTooltips,n.parsonsData=t.parsonsBlocks,t.context&&n.setCodeContext(t.context)})({selector:`#${this.divid}-container`,id:`${this.divid}-hparsons`,reuse:this.reuse,randomize:this.randomize,parsonsBlocks:[...this.originalBlocks],language:this.language}),this.hparsonsInput=this.outerDiv.querySelector("micro-parsons"),this.renderMathInBlocks(),null!=this.language&&"math"!==this.language||this.outerDiv.querySelectorAll(".hparsons-tip").forEach((t=>{t.textContent.includes("our code")&&(t.textContent=t.textContent.replace("our code","our answer"))}))}createOutput(){this.feedbackController.createOutput()}createControls(){var t=document.createElement("div");t.classList.add("hp_actions"),this.runButton=document.createElement("button"),this.runButton.classList.add("btn","btn-success","run-button"),t.appendChild(this.runButton),this.runButton.setAttribute("type","button"),this.runButton.textContent="Run";var e,s=this;this.runButton.onclick=()=>{s.feedbackController.runButtonHandler(),s.setLocalStorage()},(e=document.createElement("button")).textContent="Reset",e.classList.add("btn","btn-warning","run-button"),t.appendChild(e),this.resetButton=e,this.resetButton.onclick=()=>{s.hparsonsInput.resetInput(),s.setLocalStorage(),s.feedbackController.reset(),s.renderMathInBlocks()},e.setAttribute("type","button"),this.outerDiv.appendChild(t),this.controlDiv=t}decodeHTMLEntities(t){const e=document.createElement("textarea");return e.innerHTML=t,e.value}renderMathInBlocks(){"math"===this.language&&setTimeout((()=>{document.querySelectorAll(`#${this.divid}-container .parsons-block`).forEach((t=>{t.innerHTML=this.decodeHTMLEntities(t.innerHTML),-1!==t.innerHTML.indexOf("process-math")&&(t.innerHTML=t.innerHTML.replace(/<span class="process-math">|<\/span>/g,"")),this.queueMathJax(t)}))}),10)}localData(){var t=localStorage.getItem(this.storageId);return null!==t&&"{"==t.charAt(0)?JSON.parse(t):{}}restoreAnswers(t){if(t.answer){const e=t.answer.blocks??t.answer;if(Array.isArray(e)&&e.length>0){const t=e[0];("number"==typeof t||/^\d+$/.test(String(t)))&&this.hparsonsInput.restoreAnswerByIndices?this.hparsonsInput.restoreAnswerByIndices(e.map(Number)):this.hparsonsInput.restoreAnswer(e)}}t.count&&(this.feedbackController.checkCount=t.count)}checkLocalStorage(){if(this.graderactive)return;let t=this.localData();if(t.timestamp&&t.timestamp<eBookConfig.termStartDate)localStorage.removeItem(this.storageId);else{if(t.answerIndices&&this.hparsonsInput.restoreAnswerByIndices)this.hparsonsInput.restoreAnswerByIndices(t.answerIndices.map(Number));else if(t.answer&&(this.hparsonsInput.restoreAnswer(t.answer),this.isBlockGrading)){const e=this.hparsonsInput.getBlockIndices();t.answerIndices=e,localStorage.setItem(this.storageId,JSON.stringify(t))}t.count&&(this.feedbackController.checkCount=t.count)}}setLocalStorage(t){let e={};null==t?(this.isBlockGrading?(e={answerIndices:this.hparsonsInput.getBlockIndices()},e.count=this.feedbackController.checkCount):e={answer:this.hparsonsInput.getParsonsTextArray()},e.timestamp=new Date):e=t,localStorage.setItem(this.storageId,JSON.stringify(e))}logHorizontalParsonsEvent(t){let e={event:"hparsons",div_id:this.divid,act:JSON.stringify(t)};this.logBookEvent(e)}}document.addEventListener("runestone:login-complete",(function(){document.querySelectorAll("[data-component=hparsons]").forEach((function(t){t.closest("[data-component=timedAssessment]")||(f[t.id]=new x({orig:t,useRunestoneServices:eBookConfig.useRunestoneServices}))}))})),void 0===window.component_factory&&(window.component_factory={}),window.component_factory.hparsons=function(t){return new x(t)}}}]);
//# sourceMappingURL=49.ec404219b760dc60.js.map