This repository was archived by the owner on Mar 5, 2025. It is now read-only.
forked from RunestoneInteractive/RunestoneComponents
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathactivecode.js
More file actions
executable file
·1649 lines (1394 loc) · 60.9 KB
/
activecode.js
File metadata and controls
executable file
·1649 lines (1394 loc) · 60.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Created by bmiller on 3/19/15.
*/
var edList = {};
ActiveCode.prototype = new RunestoneBase();
// separate into constructor and init
function ActiveCode(opts) {
if (opts) {
this.init(opts);
}
}
ActiveCode.prototype.init = function(opts) {
RunestoneBase.apply( this, arguments ); // call parent constructor
var suffStart = -1;
var orig = opts.orig;
this.useRunestoneServices = opts.useRunestoneServices;
this.python3 = opts.python3;
this.alignVertical = opts.vertical;
this.origElem = orig;
this.divid = orig.id;
this.code = $(orig).text() || "\n\n\n\n\n";
this.language = $(orig).data('lang');
this.timelimit = $(orig).data('timelimit');
this.includes = $(orig).data('include');
this.hidecode = $(orig).data('hidecode');
this.runButton = null;
this.saveButton = null;
this.loadButton = null;
this.outerDiv = null;
this.output = null; // create pre for output
this.graphics = null; // create div for turtle graphics
this.codecoach = null;
this.codelens = null;
if(this.includes !== undefined) {
this.includes = this.includes.split(/\s+/);
}
suffStart = this.code.indexOf('====');
if (suffStart > -1) {
this.suffix = this.code.substring(suffStart+5);
this.code = this.code.substring(0,suffStart);
}
this.createEditor();
this.createOutput();
this.createControls();
if ($(orig).data('caption')) {
this.caption = $(orig).data('caption');
} else {
this.caption = ""
}
//this.addCaption();
if ($(orig).data('autorun')) {
$(document).ready(this.runProg.bind(this));
}
};
ActiveCode.prototype.createEditor = function (index) {
this.containerDiv = document.createElement('div');
var linkdiv = document.createElement('div')
linkdiv.id = this.divid.replace(/_/g,'-').toLowerCase(); // :ref: changes _ to - so add this as a target
$(this.containerDiv).addClass("ac_section");
var codeDiv = document.createElement("div");
// lc mod
// add this ac_editor_container class so we can apply styles
$(codeDiv).addClass("ac_code_div ac_editor_container");
this.codeDiv = codeDiv;
this.containerDiv.id = this.divid;
this.containerDiv.lang = this.language;
this.outerDiv = this.containerDiv;
$(this.origElem).replaceWith(this.containerDiv);
if (linkdiv.id !== this.divid) { // Don't want the 'extra' target if they match.
this.containerDiv.appendChild(linkdiv);
}
this.containerDiv.appendChild(codeDiv);
var editor = CodeMirror(codeDiv, {value: this.code, lineNumbers: true,
mode: this.containerDiv.lang, indentUnit: 4,
matchBrackets: true, autoMatchParens: true,
extraKeys: {"Tab": "indentMore", "Shift-Tab": "indentLess"}
});
// Make the editor resizable
/*
LC MOD
The resizable UI is janky and we don't need it
$(editor.getWrapperElement()).resizable({
resize: function() {
editor.setSize($(this).width(), $(this).height());
editor.refresh();
}
});
*/
if (this.useRunestoneServices) {
// give the user a visual cue that they have changed but not saved
// but only if it's *possible* to save
editor.on('change', (function () {
if (useRunestoneServiceseditor.acEditEvent == false || editor.acEditEvent === undefined) {
$(editor.getWrapperElement()).css('border-top', '2px solid #b43232');
$(editor.getWrapperElement()).css('border-bottom', '2px solid #b43232');
this.logBookEvent({'event': 'activecode', 'act': 'edit', 'div_id': this.divid});
}
editor.acEditEvent = true;
}).bind(this)); // use bind to preserve *this* inside the on handler.
}
this.editor = editor;
if (this.hidecode) {
// lc mod
// instead of toggling visiblity of codeDiv,
// we toggle visiblity of its child, .CodeMirror
// (because we dont want the ctrl buttons to disappear)
$(this.codeDiv).find(".CodeMirror").css("display","none");
}
};
ActiveCode.prototype.createControls = function () {
var ctrlDiv = document.createElement("div");
$(ctrlDiv).addClass("ac_actions");
// Run
var butt = document.createElement("button");
$(butt).text("Run");
$(butt).addClass("btn btn-success");
ctrlDiv.appendChild(butt);
this.runButton = butt;
$(butt).click(this.runProg.bind(this));
// Save
if (this.useRunestoneServices) {
butt = document.createElement("button");
$(butt).addClass("ac_opt btn btn-default");
$(butt).text("Save");
$(butt).css("margin-left", "10px");
this.saveButton = butt;
this.saveButton.onclick = this.saveEditor.bind(this);
ctrlDiv.appendChild(butt);
if (this.hidecode) {
$(butt).css("display", "none")
}
}
// Load
if (this.useRunestoneServices) {
butt = document.createElement("button");
$(butt).addClass("ac_opt btn btn-default");
$(butt).text("Load");
$(butt).css("margin-left", "10px");
this.loadButton = butt;
this.loadButton.onclick = this.loadEditor.bind(this);
ctrlDiv.appendChild(butt);
if (this.hidecode) {
$(butt).css("display", "none")
}
}
if ($(this.origElem).data('gradebutton')) {
butt = document.createElement("button");
$(butt).addClass("ac_opt btn btn-default");
$(butt).text("Show Feedback");
$(butt).css("margin-left","10px");
this.gradeButton = butt;
ctrlDiv.appendChild(butt);
$(butt).click(this.createGradeSummary.bind(this))
}
// Show/Hide Code
if (this.hidecode) {
butt = document.createElement("button");
$(butt).addClass("ac_opt btn btn-default");
$(butt).text("Show/Hide Code");
$(butt).css("margin-left", "10px");
this.showHideButt = butt;
ctrlDiv.appendChild(butt);
$(butt).click( (function() {
// lc mod
// instead of toggling visiblity of codeDiv,
// we toggle visiblity of its child, .CodeMirror
// (because we dont want the ctrl buttons to disappear)
$(this.codeDiv).find(".CodeMirror").toggle();
$(this.loadButton).toggle();
$(this.saveButton).toggle();
}).bind(this));
}
// CodeLens
if ($(this.origElem).data("codelens")) {
butt = document.createElement("button");
$(butt).addClass("ac_opt btn btn-default");
$(butt).text("Show CodeLens");
$(butt).css("margin-left", "10px");
this.clButton = butt;
ctrlDiv.appendChild(butt);
$(butt).click(this.showCodelens.bind(this));
}
// CodeCoach
if (this.useRunestoneServices && $(this.origElem).data("coach")) {
butt = document.createElement("button");
$(butt).addClass("ac_opt btn btn-default");
$(butt).text("Code Coach");
$(butt).css("margin-left", "10px");
this.coachButton = butt;
ctrlDiv.appendChild(butt);
$(butt).click(this.showCodeCoach.bind(this));
}
// Audio Tour
if ($(this.origElem).data("audio")) {
butt = document.createElement("button");
$(butt).addClass("ac_opt btn btn-default");
$(butt).text("Audio Tour");
$(butt).css("margin-left", "10px");
this.atButton = butt;
ctrlDiv.appendChild(butt);
$(butt).click((function() {new AudioTour(this.divid, this.editor.getValue(), 1, $(this.origElem).data("audio"))}).bind(this));
}
// lc mod
// the control button go inside the container for the code
// rather than outside above it
$(this.codeDiv).prepend(ctrlDiv);
};
ActiveCode.prototype.createOutput = function () {
// Create a parent div with two elements: pre for standard output and a div
// to hold turtle graphics output. We use a div in case the turtle changes from
// using a canvas to using some other element like svg in the future.
var outDiv = document.createElement("div");
$(outDiv).addClass("ac_output col-md-12");
this.outDiv = outDiv;
this.output = document.createElement('pre');
this.graphics = document.createElement('div');
this.graphics.id = this.divid + "_graphics";
$(this.graphics).addClass("ac-canvas");
// This bit of magic adds an event which waits for a canvas child to be created on our
// newly created div. When a canvas child is added we add a new class so that the visible
// canvas can be styled in CSS. Which a the moment means just adding a border.
$(this.graphics).on("DOMNodeInserted", 'canvas', (function(e) {
$(this.graphics).addClass("visible-ac-canvas");
}).bind(this));
outDiv.appendChild(this.output);
outDiv.appendChild(this.graphics);
// lc mod
// Instead of a header outside (above) the ac_output div,
// we use a div inside the ac_output div
var outputLabel = $("<div class='ac_output_label'>Output</div>");
$(outDiv).prepend(outputLabel);
this.outerDiv.appendChild(outDiv);
clearDiv = document.createElement("div");
$(clearDiv).css("clear","both"); // needed to make parent div resize properly
this.outerDiv.appendChild(clearDiv);
var lensDiv = document.createElement("div");
$(lensDiv).addClass("code-lens");
$(lensDiv).css("display","none");
this.codelens = lensDiv;
this.outerDiv.appendChild(lensDiv);
var coachDiv = document.createElement("div")
$(coachDiv).addClass("col-md-12");
$(coachDiv).css("display","none");
this.codecoach = coachDiv;
this.outerDiv.appendChild(coachDiv);
clearDiv = document.createElement("div");
$(clearDiv).css("clear","both"); // needed to make parent div resize properly
this.outerDiv.appendChild(clearDiv);
};
ActiveCode.prototype.disableSaveLoad = function() {
$(this.saveButton).addClass('disabled');
$(this.saveButton).attr('title','Login to save your code');
$(this.loadButton).addClass('disabled');
$(this.loadButton).attr('title','Login to load your code');
};
ActiveCode.prototype.addCaption = function() {
//someElement.parentNode.insertBefore(newElement, someElement.nextSibling);
var capDiv = document.createElement('p');
$(capDiv).html(this.caption + " (" + this.divid + ")");
$(capDiv).addClass("ac_caption");
$(capDiv).addClass("ac_caption_text");
this.outerDiv.parentNode.insertBefore(capDiv, this.outerDiv.nextSibling);
};
ActiveCode.prototype.saveEditor = function () {
var res;
var saveSuccess = function(data, status, whatever) {
if (data.redirect) {
alert("Did not save! It appears you are not logged in properly")
} else if (data == "") {
alert("Error: Program not saved");
}
else {
var acid = eval(data)[0];
if (acid.indexOf("ERROR:") == 0) {
alert(acid);
} else {
// use a tooltip to provide some success feedback
var save_btn = $(this.saveButton);
save_btn.attr('title', 'Saved your code.');
opts = {
'trigger': 'manual',
'placement': 'bottom',
'delay': { show: 100, hide: 500}
};
save_btn.tooltip(opts);
save_btn.tooltip('show');
setTimeout(function () {
save_btn.tooltip('destroy')
}, 4000);
// lc mod
// we want the border to simply disappear after saving
$('#' + acid + ' .CodeMirror').css('border-top', '0');
$('#' + acid + ' .CodeMirror').css('border-bottom', '0');
}
}
}.bind(this);
var data = {acid: this.divid, code: this.editor.getValue()};
data.lang = this.language;
if (data.code.match(/^\s+$/)) {
res = confirm("You are about to save an empty program, this will overwrite a previously saved program. Continue?");
if (! res) {
return;
}
}
$(document).ajaxError(function (e, jqhxr, settings, exception) {
alert("Request Failed for" + settings.url)
});
jQuery.post(eBookConfig.ajaxURL + 'saveprog', data, saveSuccess);
if (this.editor.acEditEvent) {
this.logBookEvent({'event': 'activecode', 'act': 'edit', 'div_id': this.divid}); // Log the run event
this.editor.acEditEvent = false;
}
this.logBookEvent({'event': 'activecode', 'act': 'save', 'div_id': this.divid}); // Log the run event
};
ActiveCode.prototype.loadEditor = function () {
var loadEditor = (function (data, status, whatever) {
// function called when contents of database are returned successfully
var res = eval(data)[0];
if (res.source) {
this.editor.setValue(res.source);
setTimeout(function() {
this.editor.refresh();
}.bind(this),500);
$(this.loadButton).tooltip({'placement': 'bottom',
'title': "Loaded your saved code.",
'trigger': 'manual'
});
} else {
$(this.loadButton).tooltip({'placement': 'bottom',
'title': "No saved code.",
'trigger': 'manual'
});
}
$(this.loadButton).tooltip('show');
setTimeout(function () {
$(this.loadButton).tooltip('destroy')
}.bind(this), 4000);
}).bind(this);
var data = {acid: this.divid};
if (this.sid !== undefined) {
data['sid'] = this.sid;
}
// This function needs to be chainable for when we want to do things like run the activecode
// immediately after loading the previous input (such as in a timed exam)
var dfd = jQuery.Deferred();
this.logBookEvent({'event': 'activecode', 'act': 'load', 'div_id': this.divid}); // Log the run event
jQuery.get(eBookConfig.ajaxURL + 'getprog', data, loadEditor).done(function () {dfd.resolve();});
return dfd;
};
ActiveCode.prototype.createGradeSummary = function () {
// get grade and comments for this assignment
// get summary of all grades for this student
// display grades in modal window
var showGradeSummary = function (data, status, whatever) {
var report = eval(data)[0];
// check for report['message']
if (report) {
body = "<h4>Grade Report</h4>" +
"<p>This assignment: " + report['grade'] + "</p>" +
"<p>" + report['comment'] + "</p>" +
"<p>Number of graded assignments: " + report['count'] + "</p>" +
"<p>Average score: " + report['avg'] + "</p>"
} else {
body = "<h4>The server did not return any grade information</h4>";
}
var html = '<div class="modal fade">' +
' <div class="modal-dialog compare-modal">' +
' <div class="modal-content">' +
' <div class="modal-header">' +
' <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>' +
' <h4 class="modal-title">Assignment Feedback</h4>' +
' </div>' +
' <div class="modal-body">' +
body +
' </div>' +
' </div>' +
' </div>' +
'</div>';
el = $(html);
el.modal();
};
var data = {'div_id': this.divid};
jQuery.get(eBookConfig.ajaxURL + 'getassignmentgrade', data, showGradeSummary);
};
ActiveCode.prototype.hideCodelens = function (button, div_id) {
this.codelens.style.display = 'none'
};
ActiveCode.prototype.showCodelens = function () {
if (this.codelens.style.display == 'none') {
this.codelens.style.display = 'block';
this.clButton.innerText = "Hide Codelens";
} else {
this.codelens.style.display = "none";
this.clButton.innerText = "Show in Codelens";
return;
}
var cl = this.codelens.firstChild;
if (cl) {
this.codelens.removeChild(cl)
}
var code = this.editor.getValue();
var myVars = {};
myVars.code = code;
myVars.origin = "opt-frontend.js";
myVars.cumulative = false;
myVars.heapPrimitives = false;
myVars.drawParentPointers = false;
myVars.textReferences = false;
myVars.showOnlyOutputs = false;
myVars.rawInputLstJSON = JSON.stringify([]);
if (this.python3) {
myVars.py = 3;
} else {
myVars.py = 2;
}
myVars.curInstr = 0;
myVars.codeDivWidth = 350;
myVars.codeDivHeight = 400;
var srcURL = '//pythontutor.com/iframe-embed.html';
var embedUrlStr = $.param.fragment(srcURL, myVars, 2 /* clobber all */);
var myIframe = document.createElement('iframe');
myIframe.setAttribute("id", this.divid + '_codelens');
myIframe.setAttribute("width", "800");
myIframe.setAttribute("height", "500");
myIframe.setAttribute("style", "display:block");
myIframe.style.background = '#fff';
//myIframe.setAttribute("src",srcURL)
myIframe.src = embedUrlStr;
this.codelens.appendChild(myIframe);
this.logBookEvent({
'event': 'codelens',
'act': 'view',
'div_id': this.divid
});
};
// <iframe id="%(divid)s_codelens" width="800" height="500" style="display:block"src="#">
// </iframe>
ActiveCode.prototype.showCodeCoach = function () {
var myIframe;
var srcURL;
var cl;
var div_id = this.divid;
if (this.codecoach === null) {
this.codecoach = document.createElement("div");
this.codecoach.style.display = 'block'
}
cl = this.codecoach.firstChild;
if (cl) {
this.codecoach.removeChild(cl)
}
srcURL = eBookConfig.app + '/admin/diffviewer?divid=' + div_id;
myIframe = document.createElement('iframe');
myIframe.setAttribute("id", div_id + '_coach');
myIframe.setAttribute("width", "800px");
myIframe.setAttribute("height", "500px");
myIframe.setAttribute("style", "display:block");
myIframe.style.background = '#fff';
myIframe.style.width = "100%";
myIframe.src = srcURL;
this.codecoach.appendChild(myIframe);
$(this.codecoach).show()
this.logBookEvent({
'event': 'coach',
'act': 'view',
'div_id': this.divid
});
};
ActiveCode.prototype.toggleEditorVisibility = function () {
};
ActiveCode.prototype.addErrorMessage = function (err) {
//logRunEvent({'div_id': this.divid, 'code': this.prog, 'errinfo': err.toString()}); // Log the run event
var errHead = $('<h3>').html('Error');
this.eContainer = this.outerDiv.appendChild(document.createElement('div'));
this.eContainer.className = 'error alert alert-danger';
this.eContainer.id = this.divid + '_errinfo';
this.eContainer.appendChild(errHead[0]);
var errText = this.eContainer.appendChild(document.createElement('pre'));
var errString = err.toString();
var to = errString.indexOf(":");
var errName = errString.substring(0, to);
errText.innerHTML = errString;
$(this.eContainer).append('<h3>Description</h3>');
var errDesc = this.eContainer.appendChild(document.createElement('p'));
errDesc.innerHTML = errorText[errName];
$(this.eContainer).append('<h3>To Fix</h3>');
var errFix = this.eContainer.appendChild(document.createElement('p'));
errFix.innerHTML = errorText[errName + 'Fix'];
var moreInfo = '../ErrorHelp/' + errName.toLowerCase() + '.html';
//console.log("Runtime Error: " + err.toString());
};
var errorText = {};
errorText.ParseError = "A parse error means that Python does not understand the syntax on the line the error message points out. Common examples are forgetting commas beteween arguments or forgetting a : on a for statement";
errorText.ParseErrorFix = "To fix a parse error you just need to look carefully at the line with the error and possibly the line before it. Make sure it conforms to all of Python's rules.";
errorText.TypeError = "Type errors most often occur when an expression tries to combine two objects with types that should not be combined. Like raising a string to a power";
errorText.TypeErrorFix = "To fix a type error you will most likely need to trace through your code and make sure the variables have the types you expect them to have. It may be helpful to print out each variable along the way to be sure its value is what you think it should be.";
errorText.NameError = "A name error almost always means that you have used a variable before it has a value. Often this may be a simple typo, so check the spelling carefully.";
errorText.NameErrorFix = "Check the right hand side of assignment statements and your function calls, this is the most likely place for a NameError to be found.";
errorText.ValueError = "A ValueError most often occurs when you pass a parameter to a function and the function is expecting one type and you pass another.";
errorText.ValueErrorFix = "The error message gives you a pretty good hint about the name of the function as well as the value that is incorrect. Look at the error message closely and then trace back to the variable containing the problematic value.";
errorText.AttributeError = "This error message is telling you that the object on the left hand side of the dot, does not have the attribute or method on the right hand side.";
errorText.AttributeErrorFix = "The most common variant of this message is that the object undefined does not have attribute X. This tells you that the object on the left hand side of the dot is not what you think. Trace the variable back and print it out in various places until you discover where it becomes undefined. Otherwise check the attribute on the right hand side of the dot for a typo.";
errorText.TokenError = "Most of the time this error indicates that you have forgotten a right parenthesis or have forgotten to close a pair of quotes.";
errorText.TokenErrorFix = "Check each line of your program and make sure that your parenthesis are balanced.";
errorText.TimeLimitError = "Your program is running too long. Most programs in this book should run in less than 10 seconds easily. This probably indicates your program is in an infinite loop.";
errorText.TimeLimitErrorFix = "Add some print statements to figure out if your program is in an infinte loop. If it is not you can increase the run time with sys.setExecutionLimit(msecs)";
errorText.Error = "Your program is running for too long. Most programs in this book should run in less than 30 seconds easily. This probably indicates your program is in an infinite loop.";
errorText.ErrorFix = "Add some print statements to figure out if your program is in an infinte loop. If it is not you can increase the run time with sys.setExecutionLimit(msecs)";
errorText.SyntaxError = "This message indicates that Python can't figure out the syntax of a particular statement. Some examples are assigning to a literal, or a function call";
errorText.SyntaxErrorFix = "Check your assignment statments and make sure that the left hand side of the assignment is a variable, not a literal or a function.";
errorText.IndexError = "This message means that you are trying to index past the end of a string or a list. For example if your list has 3 things in it and you try to access the item at position 3 or more.";
errorText.IndexErrorFix = "Remember that the first item in a list or string is at index position 0, quite often this message comes about because you are off by one. Remember in a list of length 3 the last legal index is 2";
errorText.URIError = "";
errorText.URIErrorFix = "";
errorText.ImportError = "This error message indicates that you are trying to import a module that does not exist";
errorText.ImportErrorFix = "One problem may simply be that you have a typo. It may also be that you are trying to import a module that exists in 'real' Python, but does not exist in this book. If this is the case, please submit a feature request to have the module added.";
errorText.ReferenceError = "This is most likely an internal error, particularly if the message references the console.";
errorText.ReferenceErrorFix = "Try refreshing the webpage, and if the error continues, submit a bug report along with your code";
errorText.ZeroDivisionError = "This tells you that you are trying to divide by 0. Typically this is because the value of the variable in the denominator of a division expression has the value 0";
errorText.ZeroDivisionErrorFix = "You may need to protect against dividing by 0 with an if statment, or you may need to rexamine your assumptions about the legal values of variables, it could be an earlier statment that is unexpectedly assigning a value of zero to the variable in question.";
errorText.RangeError = "This message almost always shows up in the form of Maximum call stack size exceeded.";
errorText.RangeErrorFix = "This always occurs when a function calls itself. Its pretty likely that you are not doing this on purpose. Except in the chapter on recursion. If you are in that chapter then its likely you haven't identified a good base case.";
errorText.InternalError = "An Internal error may mean that you've triggered a bug in our Python";
errorText.InternalErrorFix = "Report this error, along with your code as a bug.";
errorText.IndentationError = "This error occurs when you have not indented your code properly. This is most likely to happen as part of an if, for, while or def statement.";
errorText.IndentationErrorFix = "Check your if, def, for, and while statements to be sure the lines are properly indented beneath them. Another source of this error comes from copying and pasting code where you have accidentally left some bits of code lying around that don't belong there anymore.";
errorText.NotImplementedError = "This error occurs when you try to use a builtin function of Python that has not been implemented in this in-browser version of Python.";
errorText.NotImplementedErrorFix = "For now the only way to fix this is to not use the function. There may be workarounds. If you really need this builtin function then file a bug report and tell us how you are trying to use the function.";
ActiveCode.prototype.setTimeLimit = function (timer) {
var timelimit = this.timelimit;
if (timer !== undefined ) {
timelimit = timer
}
// set execLimit in milliseconds -- for student projects set this to
// 25 seconds -- just less than Chrome's own timer.
if (this.code.indexOf('ontimer') > -1 ||
this.code.indexOf('onclick') > -1 ||
this.code.indexOf('onkey') > -1 ||
this.code.indexOf('setDelay') > -1 ) {
Sk.execLimit = null;
} else {
if (timelimit === "off") {
Sk.execLimit = null;
} else if (timelimit) {
Sk.execLimit = timelimit;
} else {
Sk.execLimit = 25000;
}
}
};
ActiveCode.prototype.builtinRead = function (x) {
if (Sk.builtinFiles === undefined || Sk.builtinFiles["files"][x] === undefined)
throw "File not found: '" + x + "'";
return Sk.builtinFiles["files"][x];
};
ActiveCode.prototype.outputfun = function(text) {
// bnm python 3
pyStr = function(x) {
if (x instanceof Array) {
return '[' + x.join(", ") + ']';
} else {
return x
}
}
var x = text;
if (! this.python3 ) {
if (x.charAt(0) == '(') {
x = x.slice(1, -1);
x = '[' + x + ']';
try {
var xl = eval(x);
xl = xl.map(pyStr);
x = xl.join(' ');
} catch (err) {
}
}
}
$(this.output).css("visibility","visible");
text = x;
text = text.replace(/</g, "<").replace(/>/g, ">").replace(/\n/g, "<br/>");
$(this.output).append(text);
};
ActiveCode.prototype.buildProg = function() {
// assemble code from prefix, suffix, and editor for running.
var pretext;
var prog = this.editor.getValue();
if (this.includes !== undefined) {
// iterate over the includes, in-order prepending to prog
pretext = "";
for (var x=0; x < this.includes.length; x++) {
pretext = pretext + edList[this.includes[x]].editor.getValue();
}
prog = pretext + prog
}
if(this.suffix) {
prog = prog + this.suffix;
}
return prog;
};
ActiveCode.prototype.runProg = function() {
var prog = this.buildProg();
$(this.output).text('');
$(this.eContainer).remove();
Sk.configure({output : this.outputfun.bind(this),
read : this.builtinRead,
python3: this.python3,
imageProxy : 'http://image.runestone.academy:8080/320x'
});
Sk.divid = this.divid;
this.setTimeLimit();
(Sk.TurtleGraphics || (Sk.TurtleGraphics = {})).target = this.graphics;
Sk.canvas = this.graphics.id; //todo: get rid of this here and in image
$(this.runButton).attr('disabled', 'disabled');
//$(this.codeDiv).switchClass("col-md-12","col-md-7",{duration:500,queue:false});
//$(this.outDiv).show({duration:700,queue:false});
var myPromise = Sk.misceval.asyncToPromise(function() {
return Sk.importMainWithBody("<stdin>", false, prog, true);
});
myPromise.then((function(mod) { // success
$(this.runButton).removeAttr('disabled');
this.logRunEvent({'div_id': this.divid, 'code': prog, 'errinfo': 'success'}); // Log the run event
}).bind(this),
(function(err) { // fail
$(this.runButton).removeAttr('disabled');
this.logRunEvent({'div_id': this.divid, 'code': prog, 'errinfo': err.toString()}); // Log the run event
this.addErrorMessage(err)
}).bind(this));
if (typeof(allVisualizers) != "undefined") {
$.each(allVisualizers, function (i, e) {
e.redrawConnectors();
});
}
};
JSActiveCode.prototype = new ActiveCode();
function JSActiveCode(opts) {
if (opts) {
this.init(opts)
}
}
JSActiveCode.prototype.init = function(opts) {
ActiveCode.prototype.init.apply(this,arguments)
}
JSActiveCode.prototype.outputfun = function (a) {
$(this.output).css("visibility","visible");
var str = "[";
if (typeof(a) == "object" && a.length) {
for (var i = 0; i < a.length; i++)
if (typeof(a[i]) == "object" && a[i].length) {
str += (i == 0 ? "" : " ") + "[";
for (var j = 0; j < a[i].length; j++)
str += a[i][j] + (j == a[i].length - 1 ?
"]" + (i == a.length - 1 ? "]" : ",") + "\n" : ", ");
} else str += a[i] + (i == a.length - 1 ? "]" : ", ");
} else {
try {
str = JSON.stringify(a);
} catch (e) {
str = a;
}
}
return str;
};
JSActiveCode.prototype.runProg = function() {
var _this = this;
var prog = this.buildProg();
var write = function(str) {
_this.output.innerHTML += _this.outputfun(str);
};
var writeln = function(str) {
if (!str) str="";
_this.output.innerHTML += _this.outputfun(str)+"<br />";
};
$(this.eContainer).remove();
$(this.output).text('');
//$(this.codeDiv).switchClass("col-md-12","col-md-6",{duration:500,queue:false});
//$(this.outDiv).show({duration:700,queue:false});
try {
eval(prog)
} catch(e) {
this.addErrorMessage(e);
}
};
HTMLActiveCode.prototype = new ActiveCode();
function HTMLActiveCode (opts) {
if (opts) {
this.init(opts);
}
}
HTMLActiveCode.prototype.runProg = function () {
var prog = this.buildProg();
$(this.output).text('');
prog = "<script type=text/javascript>window.onerror = function(msg,url,line) {alert(msg+' on line: '+line);};</script>" + prog;
this.output.srcdoc = prog;
};
HTMLActiveCode.prototype.init = function(opts) {
ActiveCode.prototype.init.apply(this,arguments);
this.code = $('<textarea />').html(this.origElem.innerHTML).text();
$(this.runButton).text('Render');
this.editor.setValue(this.code);
};
HTMLActiveCode.prototype.createOutput = function () {
var outDiv = document.createElement("div");
$(outDiv).addClass("ac_output");
$(outDiv).addClass("col-md-12");
this.outDiv = outDiv;
this.output = document.createElement('iframe');
$(this.output).css("background-color","white");
$(this.output).css("position","relative");
$(this.output).css("height","400px");
$(this.output).css("width","100%");
var outputLabel = $("<h5>Output</h5>");
$(outDiv).append(outputLabel);
outDiv.appendChild(this.output);
this.outerDiv.appendChild(outDiv);
clearDiv = document.createElement("div");
$(clearDiv).css("clear","both"); // needed to make parent div resize properly
this.outerDiv.appendChild(clearDiv);
};
String.prototype.replaceAll = function (target, replacement) {
return this.split(target).join(replacement);
};
AudioTour.prototype = new RunestoneBase();
// function to display the audio tours
function AudioTour (divid, code, bnum, audio_text) {
this.elem = null; // current audio element playing
this.currIndex; // current index
this.len; // current length of audio files for tour
this.buttonCount; // number of audio tour buttons
this.aname; // the audio file name
this.ahash; // hash of the audio file name to the lines to highlight
this.theDivid; // div id
this.afile; // file name for audio
this.playing = false; // flag to say if playing or not
this.tourName;
// Replacing has been done here to make sure special characters in the code are displayed correctly
code = code.replaceAll("*doubleq*", "\"");
code = code.replaceAll("*singleq*", "'");
code = code.replaceAll("*open*", "(");
code = code.replaceAll("*close*", ")");
code = code.replaceAll("*nline*", "<br/>");
var codeArray = code.split("\n");
var audio_hash = new Array();
var bval = new Array();
var atype = audio_text.replaceAll("*doubleq*", "\"");
var audio_type = atype.split("*atype*");
for (var i = 0; i < audio_type.length - 1; i++) {
audio_hash[i] = audio_type[i];
var aword = audio_type[i].split(";");
bval.push(aword[0]);
}
var first = "<pre><div id='" + divid + "_l1'>" + "1. " + codeArray[0] + "</div>";
num_lines = codeArray.length;
for (var i = 1; i < num_lines; i++) {
if (i < 9) {
first = first + "<div id='" + divid + "_l" + (i + 1) + "'>" + (i + 1) + ". " + codeArray[i] + "</div>";
}
else if (i < 99) {
first = first + "<div id='" + divid + "_l" + (i + 1) + "'>" + (i + 1) + ". " + codeArray[i] + "</div>";
}
else {
first = first + "<div id='" + divid + "_l" + (i + 1) + "'>" + (i + 1) + ". " + codeArray[i] + "</div>";
}
}
first = first + "</pre>";
//laying out the HTML content
var bcount = 0;
var html_string = "<div class='modal-lightsout'></div><div class='modal-profile'><h3>Take an audio tour!</h3><div class='modal-close-profile'></div><p id='windowcode'></p><p id='" + divid + "_audiocode'></p>";
html_string += "<p id='status'></p>";
html_string += "<input type='image' src='../_static/first.png' width='25' id='first_audio' name='first_audio' title='Play first audio in tour' alt='Play first audio in tour' onerror=\"this.onerror=null;this.src='_static/first.png'\" disabled/>" +
"<input type='image' src='../_static/prev.png' width='25' id='prev_audio' name='prev_audio' title='Play previous audio in tour' alt='Play previous audio in tour' onerror=\"this.onerror=null;this.src='_static/prev.png'\" disabled/>" +
"<input type='image' src='../_static/pause.png' width='25' id='pause_audio' name='pause_audio' title='Pause current audio' alt='Pause current audio' onerror=\"this.onerror=null;this.src='_static/pause.png'\" disabled/>" + "" +
"<input type='image' src='../_static/next.png' width ='25' id='next_audio' name='next_audio' title='Play next audio in tour' alt='Play next audio in tour' onerror=\"this.onerror=null;this.src='_static/next.png'\" disabled/>" +
"<input type='image' src='../_static/last.png' width ='25' id='last_audio' name='last_audio' title='Play last audio in tour' alt='Play last audio in tour' onerror=\"this.onerror=null;this.src='_static/last.png'\" disabled/><br/>";
for (var i = 0; i < audio_type.length - 1; i++) {
html_string += "<input type='button' style='margin-right:5px;' class='btn btn-default btn-sm' id='button_audio_" + i + "' name='button_audio_" + i + "' value=" + bval[i] + " />";
bcount++;
}
//html_string += "<p id='hightest'></p><p id='hightest1'></p><br/><br/><p id='test'></p><br/><p id='audi'></p></div>";
html_string += "</div>";
var tourdiv = document.createElement('div');
document.body.appendChild(tourdiv);
$(tourdiv).html(html_string);
$('#windowcode').html(first);
// Position modal box
$.fn.center = function () {
this.css("position", "absolute");
// y position
this.css("top", ($(window).scrollTop() + $(navbar).height() + 10 + "px"));
// show window on the left so that you can see the output from the code still
this.css("left", ($(window).scrollLeft() + "px"));
return this;
};
$(".modal-profile").center();
$('.modal-profile').fadeIn("slow");
//$('.modal-lightsout').css("height", $(document).height());
$('.modal-lightsout').fadeTo("slow", .5);
$('.modal-close-profile').show();
// closes modal box once close link is clicked, or if the lights out divis clicked
$('.modal-close-profile, .modal-lightsout').click( (function () {
if (this.playing) {
this.elem.pause();
}
//log change to db
this.logBookEvent({'event': 'Audio', 'act': 'closeWindow', 'div_id': divid});
$('.modal-profile').fadeOut("slow");
$('.modal-lightsout').fadeOut("slow");
document.body.removeChild(tourdiv);
}).bind(this));
// Accommodate buttons for a maximum of five tours
$('#' + 'button_audio_0').click((function () {
this.tour(divid, audio_hash[0], bcount);
}).bind(this));
$('#' + 'button_audio_1').click((function () {
this.tour(divid, audio_hash[1], bcount);
}).bind(this));
$('#' + 'button_audio_2').click((function () {
this.tour(divid, audio_hash[2], bcount);
}).bind(this));
$('#' + 'button_audio_3').click((function () {
this.tour(divid, audio_hash[3], bcount);
}).bind(this));
$('#' + 'button_audio_4').click((function () {
this.tour(divid, audio_hash[4], bcount);
}).bind(this));
// handle the click to go to the next audio
$('#first_audio').click((function () {
this.firstAudio();
}).bind(this));
// handle the click to go to the next audio
$('#prev_audio').click((function () {
this.prevAudio();
}).bind(this));
// handle the click to pause or play the audio
$('#pause_audio').click((function () {
this.pauseAndPlayAudio();
}).bind(this));
// handle the click to go to the next audio
$('#next_audio').click((function () {
this.nextAudio();
}).bind(this));
// handle the click to go to the next audio
$('#last_audio').click((function () {
this.lastAudio();
}).bind(this));
// make the image buttons look disabled
$("#first_audio").css('opacity', 0.25);
$("#prev_audio").css('opacity', 0.25);
$("#pause_audio").css('opacity', 0.25);
$("#next_audio").css('opacity', 0.25);
$("#last_audio").css('opacity', 0.25);
}
AudioTour.prototype.tour = function (divid, audio_type, bcount) {
// set globals
this.buttonCount = bcount;
this.theDivid = divid;
// enable prev, pause/play and next buttons and make visible
$('#first_audio').removeAttr('disabled');
$('#prev_audio').removeAttr('disabled');
$('#pause_audio').removeAttr('disabled');
$('#next_audio').removeAttr('disabled');
$('#last_audio').removeAttr('disabled');
$("#first_audio").css('opacity', 1.0);
$("#prev_audio").css('opacity', 1.0);
$("#pause_audio").css('opacity', 1.0);
$("#next_audio").css('opacity', 1.0);
$("#last_audio").css('opacity', 1.0);
// disable tour buttons
for (var i = 0; i < bcount; i++)
$('#button_audio_' + i).attr('disabled', 'disabled');