-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathkhan-exercise.js
2188 lines (1814 loc) · 81.1 KB
/
khan-exercise.js
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
/* khan-exercise.js
The main entry point here is essentially the onjQueryLoaded method around
line 750. It loads in many of the pre-reqs and then calls, one way or
another, setUserExercise and loadModule for each required module in utils/.
setProblemNum updates some instance vars that get looked at by other
functions.
loadModule will load an individual exercise util module (e.g.,
word-problems.js, etc). It _also_ loads in the Khan Academy site skin and
exercise template via injectSite which runs prepareSite first then
makeProblemBag and makeProblem when it finishes loading dependencies.
prepareSite and makeProblem are both fairly heavyweight functions.
If you are trying to register some behavior when the page loads, you
probably want it to go in either prepareSite here or, if it makes sense, in
problemTemplateRendered in interface.js. By the time prepareSite is called,
jQuery and any core plugins are already available.
If you are trying to do something each time a problem loads, you probably
want to look at makeProblem.
At the end of evaluation, the inner Khan object is returned/exposed as well
as the inner Util object.
Catalog of events fired on the Khan object by khan-exercises:
* newProblem -- when a new problem has completely finished rendering
* hintUsed -- when a hint has been used by the user
* allHintsUsed -- when all possible hints have been used by the user
* checkAnswer -- when the user attempts to check an answer, incorrect or
correct
* problemDone -- when the user has completed a problem which, in this case,
usually means supplying the correct answer. Note the user may have made
multiple attempts to finally get at the correct answer. A summary object
including {attempts: <number>, card: <Object>} is included as an
event parameter.
* attemptError -- when an error occurs during an API attempt
* apiRequestStarted / apiRequestEnded -- when an API request is sent
outbound or completed, respectively. Listeners can keep track of whether
or not khan-exercises is still waiting on API responses.
* updateUserExercise -- when an updated userExercise has been received
and is being used by khan-exercises, either via the result of an API
call or initialization
* showGuess -- when a guess is populated in the answer area in problem
history mode
*/
var Khan = (function() {
// Numbers which are coprime to the number of bins, used for jumping through
// exercises. To quickly test a number in python use code like:
// import fractions
// fractions.gcd( 197, 200)
var primes = [197, 3, 193, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43,
47, 53, 59, 61, 67, 71, 73, 79, 83],
userExercise,
// Check to see if we're in local mode
localMode = typeof Exercises === "undefined",
// Set in prepareSite when Exercises.init() has already been called
assessmentMode,
// The ID, filename, and name of the exercise -- these will only be set here in localMode
exerciseId = ((/([^\/.]+)(?:\.html)?$/.exec(window.location.pathname) || [])[1]) || "",
exerciseFile = exerciseId + ".html",
exerciseName = deslugify(exerciseId),
// Bin users into a certain number of realms so that
// there is some level of reproducability in their questions.
// If you change this, make sure all entries in the array "primes"
// set above are coprime to the new value.
bins = 200,
// Number of past problems to consider when avoiding duplicates
dupWindowSize = 5,
// The seed information
randomSeed,
// Holds the current username
user = null,
userCRC32,
// The current problem and its corresponding exercise
problem,
exercise,
// The number of the current problem that we're on
problemNum = 1,
// Info for constructing the seed
seedOffset = 0,
jumpNum = 1,
problemSeed = 0,
seedsSkipped = 0,
consecutiveSkips = 0,
problemID,
// The current validator function
answerData,
validator,
getAnswer,
hints,
// The exercise elements
exercises,
// Where we are in the shuffled list of problem types
problemBag,
problemBagIndex = 0,
// How many problems are we doing? (For the fair shuffle bag.)
problemCount = 10,
hintsUsed,
// Bug-hunting "undefined" attempt content
debugLogLog = ["start of log"],
debugLog = function(l) {
debugLogLog.push(l);
},
// Dictionary of loading and loaded exercises; keys are exercise IDs,
// values are promises that are resolved when the exercise is loaded
exerciseFilePromises = {},
// A promise for each loaded or loading module, keyed by module filename
// (module.src) -- will be resolved when the module is loaded (on the live
// site, immediately)
modulePromises = {},
// Promise that gets resolved when MathJax is loaded
mathJaxLoaded,
urlBase = typeof urlBaseOverride !== "undefined" ? urlBaseOverride :
localMode ? "../" : "/khan-exercises/",
// In local mode, we use khan-exercises local copy of the /images
// directory. But in production (on www.khanacademy.org), we use
// the canonical location of images, which is under '/'.
imageBase = ((typeof urlBaseOverride !== "undefined" || localMode)
? (urlBase + "images/") : ("/images/"));
lastFocusedSolutionInput = null,
gae_bingo = window.gae_bingo || { bingo: function() {} },
// The ul#examples (keep in a global because we need to modify it even when it's out of the DOM)
examples = null;
// Add in the site stylesheets
if (localMode) {
(function() {
var link = document.createElement("link");
link.rel = "stylesheet";
link.href = urlBase + "css/khan-site.css";
document.getElementsByTagName("head")[0].appendChild(link);
link = document.createElement("link");
link.rel = "stylesheet";
link.href = urlBase + "css/khan-exercise.css";
document.getElementsByTagName("head")[0].appendChild(link);
link = document.createElement("link");
link.rel = "stylesheet";
link.href = urlBase + "css/grids.css";
document.getElementsByTagName("head")[0].appendChild(link);
link = document.createElement("link");
link.rel = "stylesheet";
link.href = urlBase + "local-only/katex/katex.css";
document.getElementsByTagName("head")[0].appendChild(link);
})();
}
// The main Khan Module
var Khan = {
// Set of modules currently in use -- keys are module names, value is
// always true
modules: {},
// Map from exercise ID to a list of required modules (data-require),
// These module names are used in resetModules() and indirectly by
// runModules(), where $.fn["module-name"], $.fn["module-nameLoad"],
// and $.fn["module-nameCleanup"] are called.
exerciseModulesMap: {},
// So modules can use file paths properly
urlBase: urlBase,
imageBase: imageBase,
startLoadingExercise: startLoadingExercise,
moduleDependencies: {
"math": ["raphael"],
// Load Raphael locally because IE8 has a problem with the 1.5.2 minified release
// http://groups.google.com/group/raphaeljs/browse_thread/thread/c34c75ad8d431544
// The normal module dependencies.
"calculus": ["math", "expressions", "polynomials"],
"exponents": ["math", "math-format"],
"kinematics": ["math"],
"math-format": ["math", "expressions"],
"polynomials": ["math", "expressions"],
"stat": ["math"],
"word-problems": ["math"],
"derivative-intuition": ["jquery.mobile.vmouse"],
"unit-circle": ["jquery.mobile.vmouse"],
"interactive": ["graphie", "jquery.mobile.vmouse"],
"mean-and-median": ["stat"],
"math-model": ["ast"],
"simplify": ["math-model", "ast", "expr-helpers", "expr-normal-form", "steps-helpers"],
"congruency": ["angles", "interactive"],
"graphie-3d": ["graphie", "matrix"],
"graphie-geometry": ["graphie", "matrix"],
"graphie-helpers": ["math-format"],
"matrix": ["expressions"],
"matrix-input": ["jquery.cursor-position"],
"chemistry": ["math-format"],
"d3": ["math-format"]
},
warnTimeout: function() {
$(Exercises).trigger("warning", [$._("你的網路連線可能太慢. 請重新整理或" +
"向均一回報問題."),
false]);
// TODO(alpert): This event binding is kind of gross
$("#warn-report").click(function(e) {
e.preventDefault();
$("#report").click();
});
},
warnFont: function() {
var warning;
if ($.browser.msie) {
warning = $._("You should " +
"<a href='http://missmarcialee.com/2011/08/" +
"how-to-enable-font-download-in-internet-explorer-8/' " +
"target='_blank'>enable font download</a> " +
"to improve the appearance of math expressions."
);
} else {
warning = $._("You should enable font download in your " +
"browser to improve the appearance of math expressions");
}
// Show the message to users is confusing. Few people can understand it.
// $(Exercises).trigger("warning", [warning, true]);
},
// TODO(alpert): This doesn't need to be in the Khan object.
getBaseModules: function() {
var mods = [];
// Base modules required for every problem
// MathJax is here because Perseus wants it loaded regardless of if
// we load a khan-exercises problem that needs it. Previously it
// was a dependency of 'math' so this isn't really any different.
mods.push("answer-types", "tmpl", "tex","jquery.adhesion", "calculator",
{
src: urlBase + "utils/MathJax/2.1/MathJax.js?config=KAthJax-da9a7f53e588f3837b045a600e1dc440"
});
return mods;
},
resetModules: function(exerciseId) {
var modules = Khan.getBaseModules().concat(
Khan.exerciseModulesMap[exerciseId]);
var moduleSet = {};
$.each(modules, function(i, mod) {
useModule(mod);
});
Khan.modules = moduleSet;
function useModule(modNameOrObject) {
if (typeof modNameOrObject === "string") {
moduleSet[modNameOrObject] = true;
var deps = Khan.moduleDependencies[modNameOrObject] || [];
$.each(deps, function(i, mod) {
useModule(mod);
});
} else if (modNameOrObject.name) {
moduleSet[modNameOrObject.name] = true;
}
}
},
// Populate this with modules
Util: {
debugLog: debugLog,
// http://burtleburtle.net/bob/hash/integer.html
// This is also used as a PRNG in the V8 benchmark suite
random: function() {
// Robert Jenkins' 32 bit integer hash function.
var seed = randomSeed;
seed = ((seed + 0x7ed55d16) + (seed << 12)) & 0xffffffff;
seed = ((seed ^ 0xc761c23c) ^ (seed >>> 19)) & 0xffffffff;
seed = ((seed + 0x165667b1) + (seed << 5)) & 0xffffffff;
seed = ((seed + 0xd3a2646c) ^ (seed << 9)) & 0xffffffff;
seed = ((seed + 0xfd7046c5) + (seed << 3)) & 0xffffffff;
seed = ((seed ^ 0xb55a4f09) ^ (seed >>> 16)) & 0xffffffff;
return (randomSeed = (seed & 0xfffffff)) / 0x10000000;
}
},
// Load in a collection of scripts, execute callback upon completion
loadScript: function(url, callback) {
var head = document.getElementsByTagName("head")[0];
var isMathJax = url.indexOf("/MathJax/") !== -1;
if (!localMode && url.indexOf("/khan-exercises/") === 0 &&
(!isMathJax || window.MathJax)) {
// Don't bother loading khan-exercises content in non-local
// mode; this content is already packaged up and available
// (*unless* it's MathJax, which is silly and still needs
// to be loaded (if it's not preloaded))
callback();
return;
}
// Adapted from jQuery getScript (ajax/script.js) -- can't use
// jQuery here because we load jQuery using this routine
var script = document.createElement("script");
script.async = "async";
script.src = url;
script.onerror = function() {
// No error in IE, but this is mostly for debugging during
// development so it's probably okay
// http://stackoverflow.com/questions/2027849/how-to-trigger-script-onerror-in-internet-explorer
Khan.error("Error loading script " + script.src);
};
script.onload = script.onreadystatechange = function() {
if (!script.readyState ||
(/loaded|complete/).test(script.readyState)) {
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
// Remove the script
if (script.parentNode) {
script.parentNode.removeChild(script);
}
// Dereference the script
script = undefined;
if (isMathJax) {
// If we're loading MathJax, don't bump up the
// count of loaded scripts until MathJax is done
// loading all of its dependencies.
MathJax.Hub.Queue(mathJaxLoaded.resolve);
mathJaxLoaded.then(callback);
} else {
callback();
}
}
};
head.appendChild(script);
},
// Query String Parser
// Original from:
// http://stackoverflow.com/questions/901115/get-querystring-values-in-javascript/2880929#2880929
queryString: function() {
var urlParams = {},
e,
a = /\+/g, // Regex for replacing addition symbol with a space
r = /([^&=]+)=?([^&]*)/g,
d = function(s) { return decodeURIComponent(s.replace(a, " ")); },
q = window.location.search.substring(1);
while ((e = r.exec(q))) {
urlParams[d(e[1])] = d(e[2]);
}
return urlParams;
},
// Display error messages
error: function() {
if (typeof console !== "undefined") {
$.each(arguments, function(ix, arg) {
console.error(arg);
});
}
},
scratchpad: (function() {
var disabled = false, wasVisible, pad;
var actions = {
disable: function() {
wasVisible = actions.isVisible();
actions.hide();
$("#scratchpad-show").hide();
$("#scratchpad-not-available").show();
disabled = true;
},
enable: function() {
if (wasVisible) {
actions.show();
wasVisible = false;
}
$("#scratchpad-show").show();
$("#scratchpad-not-available").hide();
disabled = false;
},
isVisible: function() {
return $("#scratchpad").is(":visible");
},
show: function() {
if (actions.isVisible()) {
return;
}
var makeVisible = function() {
$("#workarea, #hintsarea").css("padding-top", 50);
$("#scratchpad").show();
$("#scratchpad-show").text("隱藏計算紙");
// If pad has never been created or if it's empty
// because it was removed from the DOM, recreate a new
// scratchpad.
if (!pad || !$("#scratchpad div").children().length) {
pad = new DrawingScratchpad(
$("#scratchpad div")[0]);
// add GA_code to scratchpad svg after drawing #scratchpad svg
$("#scratchpad svg").attr("onclick","Analytics.send_ga_event('exercise', 'click', 'scratchpad_used');");
}
};
loadModule("scratchpad").then(makeVisible);
},
hide: function() {
if (!actions.isVisible()) {
return;
}
$("#workarea, #hintsarea").css("padding-top", 0);
$("#scratchpad").hide();
$("#scratchpad-show").text("顯示計算紙");
},
toggle: function() {
actions.isVisible() ? actions.hide() : actions.show();
},
clear: function() {
if (pad) {
pad = null;
}
$("#scratchpad div").children().remove();
if (actions.isVisible()) { // create a new scratch pad
pad = new DrawingScratchpad($("#scratchpad div")[0]);
}
},
resize: function() {
if (pad) {
pad.resize();
}
}
};
return actions;
})(),
relatedVideos: {
exercise: null,
cache: {},
getVideos: function() {
return this.cache[this.exercise.name] || [];
},
setVideos: function(exercise) {
this.resetRelatedVideoBox();
if (exercise.relatedVideos) {
this.cache[exercise.name] = exercise.relatedVideos;
}
this.exercise = exercise;
this.render();
},
showThumbnail: function(index) {
$("#related-video-list .related-video-list li").each(function(i, el) {
if (i === index) {
$(el)
.find("a.related-video-inline").hide().end()
.find(".thumbnail").show();
}
else {
$(el)
.find("a.related-video-inline").show().end()
.find(".thumbnail").hide();
}
});
},
// make a link to a related video, appending exercise ID.
makeHref: function(video) {
return video.relativeUrl + "?exid=" + this.exercise.name;
},
anchorElement: function(video, needComma) {
var template = Templates.get("video.related-video-link");
return $(template({
href: this.makeHref(video),
video: video,
separator: needComma
})).data("video", video);
},
render: function() {
if (localMode) {
// Templates isn't available locally and we won't have any
// related videos to show anyway
return;
}
var container = $(".related-video-box");
var jel = container.find(".related-video-list");
var self = this;
var template = Templates.get("video.thumbnail");
_.each(self.getVideos(), function(video, i) {
var thumbnailDiv = $(template({
href: self.makeHref(video),
video: video,
isCN: window.config.site == "cn"
})).find("a.related-video")
.data("video", video)
.end();
var inlineLink = self.anchorElement(video)
.addClass("related-video-inline");
var sideBarLi = $("<li>")
.append(inlineLink)
.append(thumbnailDiv);
if (i > 0) {
thumbnailDiv.hide();
} else {
inlineLink.hide();
}
jel.append(sideBarLi);
});
container.toggle(self.getVideos().length > 0);
self._bindEvents();
},
_eventsBound: false,
/**
* Called to initialize related video event handlers.
* Should only be called after video.js package is loaded.
*/
_bindEvents: function() {
if (this._eventsBound) {
return;
}
// make caption slide up over the thumbnail on hover
var captionHeight = 45;
var marginTop = 23;
// queue:false to make sure these run simultaneously
var options = {duration: 150, queue: false};
$(".related-video-box")
.delegate(".thumbnail", "mouseenter mouseleave", function(e) {
var isMouseEnter = e.type === "mouseenter";
$(e.currentTarget).find(".thumbnail_label").animate(
{marginTop: marginTop + (isMouseEnter ? 0 : captionHeight)},
options)
.end()
.find(".thumbnail_teaser").animate(
{height: (isMouseEnter ? captionHeight : 0)},
options);
});
ModalVideo.hookup();
this._eventsBound = true;
},
resetRelatedVideoBox: function(){
var container = $(".related-video-box");
container.hide();
container.find(".related-video-list").empty();
}
},
getSeedInfo: function() {
return {
// A hash representing the exercise version
sha1: typeof userExercise !== "undefined" ?
userExercise.exerciseModel.sha1 : exerciseId,
seed: problemSeed,
problem_type: problemID
};
},
getIssueInfo: function() {
var path = exerciseFile + "?seed=" + problemSeed + "&problem=" +
problemID,
pathlink = "[" + path + (exercise.data("name") !== exerciseId ? " (" + exercise.data("name") + ")" : "") + "](http://sandcastle.khanacademy.org/media/castles/Khan:master/exercises/" + path + "&debug)",
historyLink = "[Answer timeline](" + "http://sandcastle.khanacademy.org/media/castles/Khan:master/exercises/" + path + "&debug&activity=" + encodeURIComponent(JSON.stringify(Exercises.userActivityLog)).replace(/\)/g, "\\)") + ")",
userHash = "User hash: " + KhanUtil.crc32(user),
parts = [pathlink, historyLink,
" " + JSON.stringify(Exercises.guessLog), userHash],
body = $.grep(parts, function(e) { return e != null; }).join("\n\n");
return {
pretitle: exerciseName,
bodyInfo: body
};
},
asc: function(text) { // 全型轉半型的 function
if (typeof text != "string") {
return text
}
var asciiTable = "!\"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
var big5Table = "%uFF01%u201D%uFF03%uFF04%uFF05%uFF06%u2019%uFF08%uFF09%uFF0A%uFF0B%uFF0C%uFF0D%uFF0E%uFF0F%uFF10%uFF11%uFF12%uFF13%uFF14%uFF15%uFF16%uFF17%uFF18%uFF19%uFF1A%uFF1B%uFF1C%uFF1D%uFF1E%uFF1F%uFF20%uFF21%uFF22%uFF23%uFF24%uFF25%uFF26%uFF27%uFF28%uFF29%uFF2A%uFF2B%uFF2C%uFF2D%uFF2E%uFF2F%uFF30%uFF31%uFF32%uFF33%uFF34%uFF35%uFF36%uFF37%uFF38%uFF39%uFF3A%uFF3B%uFF3C%uFF3D%uFF3E%uFF3F%u2018%uFF41%uFF42%uFF43%uFF44%uFF45%uFF46%uFF47%uFF48%uFF49%uFF4A%uFF4B%uFF4C%uFF4D%uFF4E%uFF4F%uFF50%uFF51%uFF52%uFF53%uFF54%uFF55%uFF56%uFF57%uFF58%uFF59%uFF5A%uFF5B%uFF5C%uFF5D%uFF5E";
var result = "";
for (var i = 0; i < text.length; i++) {
var val = escape(text.charAt(i));
var j = big5Table.indexOf(val);
result += (((j > -1) && (val.length == 6)) ? asciiTable.charAt(j / 6) : text.charAt(i));
}
return result;
},
scoreInput: function() {
var guess = getAnswer();
var asc_transform_list = ["text", "number", "decimal", "set", "multiple"];
if (asc_transform_list.indexOf(Khan.answerType) >= 0) {
if (Array.isArray(guess)) {
for (index = 0; index < guess.length; ++index) {
if (Array.isArray(guess[index])) {
for (sub_index = 0; sub_index < guess[index].length;++sub_index) {
guess[index][sub_index] = Khan.asc(guess[index][sub_index]);
}
}
else{
guess[index] = Khan.asc(guess[index]);
}
}
}
else {
guess = Khan.asc(guess);
}
} // 全型轉半型
return validator(guess);
},
cleanupProblem: function() {
$("#workarea, #hintsarea").runModules(problem, "Cleanup");
}
};
// see line 183. this ends the main Khan module
// Load query string params
Khan.query = Khan.queryString();
if (Khan.query.activity !== undefined) {
userExercise = {
current: true,
exerciseModel: {},
readOnly: true,
userActivity: JSON.parse(Khan.query.activity)
};
}
// Seed the random number generator with the user's hash
randomSeed = localMode && parseFloat(Khan.query.seed) || userCRC32 ||
(new Date().getTime() & 0xffffffff);
if (localMode) {
// Load in jQuery and underscore, as well as the interface glue code
// TODO(cbhl): Don't load history.js if we aren't in readOnly mode.
var initScripts = [
urlBase+"local-only/jquery.js",
urlBase+"local-only/jquery-migrate-1.1.1.js",
urlBase+"local-only/jquery-ui-1.9.2.custom.js",
urlBase+"local-only/jquery.qtip.js",
urlBase+"local-only/underscore.js",
urlBase+"local-only/jed.js",
urlBase+"local-only/i18n.js",
// TODO(csilvers): I18N: pick the file based on lang=XX param
urlBase+"local-only/localeplanet/icu.en-US.js",
urlBase+"local-only/i18n.js",
urlBase+"local-only/katex/katex.js",
urlBase+"exercises-stub.js",
urlBase+"history.js",
urlBase+"interface.js"
];
(function loadInitScripts() {
if (initScripts.length) {
var src = initScripts.shift();
Khan.loadScript(src, loadInitScripts);
} else {
onjQueryLoaded();
}
})();
} else {
onjQueryLoaded();
}
function onjQueryLoaded() {
initEvents();
// Initialize to an empty jQuery set
exercises = $();
mathJaxLoaded = $.Deferred();
Khan.mathJaxLoaded = mathJaxLoaded.promise();
$(function() {
var promises = [];
// Load all base modules, and if this is local mode, any specified
// in the data-require on <html>
var mods = Khan.getBaseModules();
if (localMode) {
var modString = document.documentElement.getAttribute(
"data-require") || "";
var exMods = modString.length ? modString.split(" ") : [];
Khan.exerciseModulesMap[exerciseId] = exMods;
mods.push.apply(mods, exMods);
}
$.each(mods, function(i, mod) {
promises.push(loadModule(mod));
});
// Ensure that all local exercises that don't have a data-name
// already get tagged with the current, original data-name.
$("div.exercise").not("[data-name]").data("name", exerciseId);
var remoteExercises = $("div.exercise[data-name]");
remoteExercises.each(function() {
promises.push(loadExercise(this));
});
// All remote exercises (if any) have now been loaded
$.when.apply($, promises).then(function() {
loadTestModeSite();
});
});
$.fn.extend({
// Pick a random element from a set of elements
getRandom: function() {
return this.eq(Math.floor(this.length * KhanUtil.random()));
},
// Run the methods provided by a module against some elements
runModules: function(problem, type) {
type = type || "";
var info = {
localMode: localMode
};
return this.each(function(i, elem) {
elem = $(elem);
// Run the main method of any modules
$.each(Khan.modules, function(mod) {
if ($.fn[mod + type]) {
debugLog("running " + mod + type);
elem[mod + type](problem, info);
debugLog("ran " + mod + type);
} else {
debugLog("(" + mod + type + " not a fn; src " + mod.src + ")");
}
});
});
}
});
// See if an element is detached
$.expr[":"].attached = function(elem) {
return $.contains(elem.ownerDocument.documentElement, elem);
};
}
// Add up how much total weight is in each exercise so we can adjust for
// it later
function weighExercises(problems) {
if (exercises.length > 1) {
$.map(problems, function(elem) {
elem = $(elem);
var exercise = elem.parents("div.exercise").eq(0);
var exerciseTotal = exercise.data("weight-sum");
exerciseTotal = exerciseTotal !== undefined ? exerciseTotal : 0;
var weight = elem.data("weight");
weight = weight !== undefined ? weight : 1;
exercise.data("weight-sum", exerciseTotal + weight);
});
}
}
// Create a set of n problems fairly from the weights - not random; it
// ensures that the proportions come out as fairly as possible with ints
// (still usually a little bit random).
// There has got to be a better way to do this.
function makeProblemBag(problems, n, force_random) {
var bag = [], totalWeight = 0;
if (problems.length > 0) {
// Collect the weights for the problems and find the total weight
var weights = $.map(problems, function(elem, i) {
elem = $(elem);
var exercise = elem.parents("div.exercise").eq(0);
var exerciseWeight = exercise.data("weight");
exerciseWeight = exerciseWeight !== undefined ? exerciseWeight : 1;
var exerciseTotal = exercise.data("weight-sum");
var weight = elem.data("weight");
weight = weight !== undefined ? weight : 1;
if (exerciseTotal !== undefined) {
weight = weight * exerciseWeight / exerciseTotal;
elem.data("weight", weight);
}
// Also write down the index/id for each problem so we can do
// links to problems (?problem=17)
elem.data("id", elem.attr("id") || "" + i);
totalWeight += weight;
return weight;
});
while (n) {
bag.push((function() {
// Figure out which item we're going to pick
if (force_random !== undefined && force_random == true) {
var index = totalWeight * Math.random();
} else {
var index = totalWeight * KhanUtil.random();
}
for (var i = 0; i < problems.length; i++) {
if (index < weights[i] || i === problems.length - 1) {
var w = Math.min(weights[i], totalWeight / (n--));
weights[i] -= w;
totalWeight -= w;
return problems.eq(i);
} else {
index -= weights[i];
}
}
// This will never happen
return Khan.error("makeProblemBag got confused w/ index " + index);
})());
}
}
return bag;
}
// TODO(alpert): Merge with loadExercise
function startLoadingExercise(exerciseId, exerciseName, exerciseFile, exerciseIsQuiz) {
var promise = exerciseFilePromises[exerciseId];
if (promise != null) {
// Already started (or finished) loading this exercise
return promise;
}
// TODO(alpert): Creating an HTML element here makes no sense to me
var exerciseElem = $("<div>")
.data("name", exerciseId)
.data("displayName", exerciseName)
.data("fileName", exerciseFile)
.data("rootName", exerciseId)
.data("isQuiz", exerciseIsQuiz);
// Queue up an exercise load
return loadExercise(exerciseElem);
}
function loadAndRenderExercise(nextUserExercise) {
setUserExercise(nextUserExercise);
var typeOverride = userExercise.problemType,
seedOverride = userExercise.seed;
exerciseId = userExercise.exerciseModel.name;
exerciseName = userExercise.exerciseModel.displayName;
exerciseFile = userExercise.exerciseModel.fileName;
isQuiz = userExercise.exerciseModel.isQuizExercise;
function finishRender() {
// Get all problems of this exercise type...
// TODO(alpert): What happens if multiple summatives in topic mode
// have the same subexercises? (Or if the subexercises appear in
// the topic individually.)
var problems = exercises.filter(function() {
return $.data(this, "rootName") === exerciseId;
}).children(".problems").children();
// ...and create a new problem bag with problems of our new exercise type.
problemBag = makeProblemBag(problems, 10, userExercise.exerciseModel.isQuizExercise);
// Update related videos
Khan.relatedVideos.setVideos(userExercise.exerciseModel);
// Make scratchpad persistent per-user
if (user) {
var lastScratchpad = window.localStorage["scratchpad:" + user];
if (typeof lastScratchpad !== "undefined" && JSON.parse(lastScratchpad)) {
Khan.scratchpad.show();
}
}
$(Exercises).trigger("clearExistingProblem");
// Generate a new problem
makeProblem(0, typeOverride, seedOverride);
}
startLoadingExercise(exerciseId, exerciseName, exerciseFile, isQuiz).then(
function() {
finishRender();
});
}
/**
* Returns whether we should skip the current problem because it's
* a duplicate (or too similar) to a recently done problem in the same
* exercise.
*/
function shouldSkipProblem() {
// We don't need to skip duplicate problems in test mode, which allows
// us to use the LocalStore localStorage abstraction from shared-package
if (typeof LocalStore === "undefined") {
return false;
}
var cacheKey = "prevProblems:" + user + ":" + exerciseName;
var cached = LocalStore.get(cacheKey);
var lastProblemNum = (cached && cached["lastProblemNum"]) || 0;
if (lastProblemNum === problemNum && !userExercise.exerciseModel.isQuizExercise) {
// Getting here means the user refreshed the page or returned to
// this exercise after being away. So, we don't need to and
// shouldn't skip this problem.
return false;
}
var pastHashes = (cached && cached["history"]) || [];
var varsHash = $.tmpl.getVarsHash();