1: # The LearningOnline Network with CAPA
2: # used by lonxml::xmlparse() as input variable $safeinit to Apache::run::run()
3: #
4: # $Id: default_homework.lcpm,v 1.174 2018/09/12 21:10:44 raeburn Exp $
5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
28: #
29:
30: #init some globals
31: $hidden::RANDOMINIT=0;
32: $pi=atan2(1,1)*4;
33: $rad2deg=180.0/$pi;
34: $deg2rad=$pi/180.0;
35: $"=' ';
36: use strict;
37: {
38: my $n = 0;
39: my $total = 0;
40: my $num_left = 0;
41: my @order;
42: my $type;
43:
44: sub init_permutation {
45: my ($size,$requested_type) = @_;
46: @order = (0..$size-1);
47: $n = $size;
48: $type = $requested_type;
49: if ($type eq 'ordered') {
50: $total = $num_left = 1;
51: } elsif ($type eq 'unordered') {
52: $total = $num_left = &factorial($size);
53: } else {
54: die("Unkown type: $type");
55: }
56: }
57:
58: sub get_next_permutation {
59: if ($num_left == $total) {
60: $num_left--;
61: return \@order;
62: }
63:
64: # Find largest index j with a[j] < a[j+1]
65:
66: my $j = scalar(@order) - 2;
67: while ($order[$j] > $order[$j+1]) {
68: $j--;
69: }
70:
71: # Find index k such that a[k] is smallest integer
72: # greater than a[j] to the right of a[j]
73:
74: my $k = scalar(@order) - 1;
75: while ($order[$j] > $order[$k]) {
76: $k--;
77: }
78:
79: # Interchange a[j] and a[k]
80:
81: @order[($k,$j)] = @order[($j,$k)];
82:
83: # Put tail end of permutation after jth position in increasing order
84:
85: my $r = scalar(@order) - 1;
86: my $s = $j + 1;
87:
88: while ($r > $s) {
89: @order[($s,$r)]=@order[($r,$s)];
90: $r--;
91: $s++;
92: }
93:
94: $num_left--;
95: return(\@order);
96: }
97:
98: sub get_permutations_left {
99: return $num_left;
100: }
101: }
102:
103: sub check_commas {
104: my ($response)=@_;
105: #print("$response ");
106: my @numbers=split(',',$response);
107: #print(" numbers ".join('-',@numbers)." ");
108: if (scalar(@numbers) > 1) {
109: #print(" numbers[0] ".$numbers[0]." ");
110: if (length($numbers[0]) > 3 || length($numbers[0]) == 0) { return -1; }
111: shift(@numbers);
112: #print(" numbers ".scalar(@numbers)." ");
113: while (scalar(@numbers) > 1) {
114: #print(" numbers ".join('-',@numbers)." ");
115: if (length($numbers[0]) != 3) { return -2; }
116: shift(@numbers);
117: }
118: my ($number)=split('\.',$numbers[0]);
119: #print(" number ".$number." ");
120: #print(" numbers[0] ".$numbers[0]." ");
121: if (length($number) != 3) { return -3; }
122: } else {
123: my ($number)=split('\.',$numbers[0]);
124: if (length($number) > 3) { return -4; }
125: }
126: return 1;
127: }
128:
129:
130: sub caparesponse_check {
131: my ($answer,$response)=@_;
132: #not properly used yet: calc
133: #not to be used: $ans_fmt
134: my $type=$LONCAPA::CAPAresponse_args{'type'};
135: my $tol=$LONCAPA::CAPAresponse_args{'tol'};
136: my $sig=$LONCAPA::CAPAresponse_args{'sig'};
137: my $ans_fmt=$LONCAPA::CAPAresponse_args{'format'};
138: my $unit=$LONCAPA::CAPAresponse_args{'unit'};
139: my $calc=$LONCAPA::CAPAresponse_args{'calc'};
140: my $samples=$LONCAPA::CAPAresponse_args{'samples'};
141:
142: my $tol_type=''; # gets it's value from whether tol has a % or not done
143: my $sig_lbound=''; #done
144: my $sig_ubound=''; #done
145:
146: #type's definitons come from capaParser.h
147:
148: #remove leading and trailing whitespace
149: if (!defined($response)) {
150: $response='';
151: }
152: if ($response=~ /^\s|\s$/) {
153: $response=~ s:^\s+|\s+$::g;
154: }
155:
156: if ($type eq 'cs' || $type eq 'ci') {
157: #for string answers make sure all places spaces occur, there is
158: #really only 1 space, in both the answer and the response
159: $answer=~s/ +/ /g;
160: $response=~s/ +/ /g;
161: } elsif ($type eq 'mc') {
162: $answer=~s/[\s,]//g;
163: $response=~s/[\s,]//g;
164: }
165: if ($type eq 'float' && $unit=~/\$/) {
166: if ($response!~/^\$|\$$/) { return ('NO_UNIT', undef); }
167: $response=~s/\$//g;
168: }
169: if ($type eq 'float' && $unit=~/\,/ && (&check_commas($response)<0)) {
170: return "COMMA_FAIL:";
171: }
172: $ans_fmt=~s/\W//g;
173: $unit=~s/[\$,]//g;
174: if ($type eq 'float') { $response=~s/,//g; }
175:
176: if (length($response) > 500) { return ('TOO_LONG',undef); }
177:
178: if ($type eq '' ) {
179: if ( $answer eq ($answer *1.0)) { $type = 2;
180: } else { $type = 3; }
181: } else {
182: if ($type eq 'cs') { $type = 4; }
183: elsif ($type eq 'ci') { $type = 3 }
184: elsif ($type eq 'mc') { $type = 5; }
185: elsif ($type eq 'fml') { $type = 8; }
186: elsif ($type eq 'math') { $type = 9; }
187: elsif ($type eq 'subj') { $type = 7; }
188: elsif ($type eq 'float') { $type = 2; }
189: elsif ($type eq 'int') { $type = 1; }
190: else { return ('ERROR', "Unknown type of answer: $type") }
191: }
192:
193: my $points;
194: my $id_list;
195: #formula type setup the sample points
196: if ($type eq '8') {
197: ($id_list,$points)=split(/@/,$samples);
198: }
199: if ($tol eq '') {
200: $tol=0.0;
201: $tol_type=1; #TOL_ABSOLUTE
202: } else {
203: if ($tol =~ /%$/) {
204: chop $tol;
205: $tol_type=2; #TOL_PERCENTAGE
206: } else {
207: $tol_type=1; #TOL_ABSOLUTE
208: }
209: }
210:
211: ($sig_ubound,$sig_lbound)=&LONCAPA_INTERNAL_get_sigrange($sig);
212:
213: my $reterror="";
214: my $result;
215: if (($type eq '9') || ($type eq '8')) {
216: if ($response=~/\=/) {
217: return ('BAD_FORMULA','Please submit just an expression, not an equation.');
218: } elsif ($response =~ /\,/ and $response !~ /^\s*\{.*\}\s*$/) {
219: return ('BAD_FORMULA');
220: }
221: }
222: if ($type eq '9') {
223: $result = &maxima_check(&maxima_cas_formula_fix($response),&maxima_cas_formula_fix($answer),\$reterror);
224: } else {
225: if ($type eq '8') { # fml type
226: $response = &capa_formula_fix($response);
227: $answer = &capa_formula_fix($answer);
228: }
229: $result = &caparesponse_capa_check_answer($response,$answer,$type,
230: $tol_type,$tol,
231: $sig_lbound,$sig_ubound,
232: $ans_fmt,$unit,$calc,$id_list,
233: $points,$external::randomseed,
234: \$reterror);
235: }
236: if ($result == '1') { $result='EXACT_ANS'; }
237: elsif ($result == '2') { $result='APPROX_ANS'; }
238: elsif ($result == '3') { $result='SIG_FAIL'; }
239: elsif ($result == '4') { $result='UNIT_FAIL'; }
240: elsif ($result == '5') { $result='NO_UNIT'; }
241: elsif ($result == '6') { $result='UNIT_OK'; }
242: elsif ($result == '7') { $result='INCORRECT'; }
243: elsif ($result == '8') { $result='UNIT_NOTNEEDED'; }
244: elsif ($result == '9') { $result='ANS_CNT_NOT_MATCH'; }
245: elsif ($result =='10') { $result='SUB_RECORDED'; }
246: elsif ($result =='11') { $result='BAD_FORMULA'; }
247: elsif ($result =='12' && !$response) { $result='MISSING_ANSWER'; }
248: elsif ($result =='12') { $result='WANTED_NUMERIC'; }
249: elsif ($result =='13') { $result='UNIT_INVALID_INSTRUCTOR'; }
250: elsif ($result =='141') { $result='UNIT_INVALID_STUDENT'; }
251: elsif ($result =='142') { $result='UNIT_INVALID_STUDENT'; }
252: elsif ($result =='143') { $result='UNIT_INVALID_STUDENT'; }
253: elsif ($result =='15') { $result='UNIT_IRRECONCIBLE'; }
254: else {$result = "ERROR: Unknown Result:$result:$@:";}
255:
256: return ($result,$reterror);
257: }
258:
259:
260: sub caparesponse_check_list {
261: my $responses=$LONCAPA::CAPAresponse_args{'response'};
262: &LONCAPA_INTERNAL_DEBUG("args ".join(':',%LONCAPA::CAPAresponse_args));
263: my $type = $LONCAPA::CAPAresponse_args{'type'};
264: my $answerunit=$LONCAPA::CAPAresponse_args{'unit'};
265: &LONCAPA_INTERNAL_DEBUG("Got type :$type: answer unit :$answerunit:\n");
266:
267: my $preprocess=$LONCAPA::CAPAresponse_args{'preprocess'};
268: $preprocess=~s/^\&//;
269:
270: my $num_input_lines =
271: scalar(@{$LONCAPA::CAPAresponse_answer->{'answers'}});
272:
273: if ($type ne '' ) {
274: if (scalar(@$responses) < $num_input_lines) {
275: return 'MISSING_ANSWER';
276: }
277: if (scalar(@$responses) > $num_input_lines) {
278: return 'EXTRA_ANSWER';
279: }
280:
281: }
282:
283: foreach my $which (0..($num_input_lines-1)) {
284: my $answer_size =
285: scalar(@{$LONCAPA::CAPAresponse_answer->{'answers'}[$which]});
286: if ($type ne ''
287: && $answer_size > 1) {
288: $responses->[$which]=[split(/,/,$responses->[$which])];
289: } else {
290: $responses->[$which]=[$responses->[$which]];
291: }
292: }
293: foreach my $which (0..($num_input_lines-1)) {
294: my $answer_size =
295: scalar(@{$LONCAPA::CAPAresponse_answer->{'answers'}[$which]});
296: my $response_size =
297: scalar(@{$responses->[$which]});
298: if ($answer_size > $response_size) {
299: return 'MISSING_ANSWER';
300: }
301: if ($answer_size < $response_size) {
302: return 'EXTRA_ANSWER';
303: }
304: }
305:
306: my $unit;
307: my ($allowalgebra)=($LONCAPA::CAPAresponse_args{'allowalgebra'}=~/^(yes|1|on)$/i);
308: if ($type eq 'float' || $type eq '') {
309: #for numerical problems split off the unit
310: my $part1;
311: my $part2;
312: my $match_algebra = qr{^(.*[^\s])\s+([^\s]+)$};
313: # FIXME: with the above regexp, algebra with spaces will not be evaluated correctly
314: my $match_numerical_units = qr{^([\d\.\,\s\$]*(?:(?:[xX\*]10[\^\*]*|[eE]*)[\+\-]*\d*)*(?:^|\S)\d+)([\$\s\w\^\*\/\(\)\+\-]*[^\d\.\s\,][\$\s\w\^\*\/\(\)\+\-]*)$};
315: if ($allowalgebra) {
316: ($part1,$part2) = ($responses->[0][-1] =~ /$match_algebra/);
317: } else {
318: ($part1,$part2) = ($responses->[0][-1] =~ /$match_numerical_units/);
319: }
320: if (defined($part1) && defined($part2)) {
321: $responses->[0][-1]=$part1;
322: $unit=&capa_formula_fix($part2);
323: my $customunits=$LONCAPA::CAPAresponse_args{'customunits'};
324: if ($customunits =~ /\S/) {
325: foreach my $replacement (split(/\s*\,\s*/,$customunits)) {
326: my ($which,$what)=split(/\s*\=\s*/,$replacement);
327: if ((defined($which)) && (defined($what))) {
328: $what=&capa_formula_fix($what);
329: $unit=~s/$which/\($what\)/g;
330: }
331: }
332: }
333: if (scalar(@$responses) > 0 && defined $answerunit) {
334: # there are several response values, units should be the same for all
335: $part2 =~ s/^\s+|\s+$//g;
336: for (my $i=1; $i<scalar(@$responses); $i++) {
337: my $element = $responses->[$i][-1];
338: my ($part1i, $part2i);
339: if ($allowalgebra) {
340: ($part1i, $part2i) = ($element =~ /$match_algebra/);
341: } else {
342: ($part1i, $part2i) = ($element =~ /$match_numerical_units/);
343: }
344: $part2i =~ s/^\s+|\s+$//g;
345: if (!defined $part2i) {
346: return 'NO_UNIT';
347: } elsif ($part2i ne $part2) {
348: return ('UNIT_FAIL', "$part2 $part2i");
349: } else {
350: $responses->[$i][-1] = $part1i;
351: }
352: }
353: }
354: }
355: }
356: $unit=~s/\s//;
357: my $error;
358: foreach my $response (@$responses) {
359: foreach my $element (@$response) {
360: # See if we have preprocessor
361: if ($preprocess=~/\S/) {
362: if (defined(&$preprocess)) {
363: no strict 'refs';
364: $element=&$preprocess($element,$unit);
365: use strict 'refs';
366: }
367: }
368: if (($type eq 'float') || (($type eq '') && ($unit ne ''))) {
369: $element =~ s/\s//g;
370: }
371: my $appendunit=$unit;
372: # Deal with percentages
373: # unit is unit entered by student, answerunit is unit by author
374: # Deprecated: divide answer by 100 if student entered percent,
375: # but author did not. Too much confusion
376: # if (($unit=~/\%/) && ($answerunit ne '%')) {
377: # $element=$element/100;
378: # $appendunit=~s/\%//;
379: # }
380: # Author entered percent, student did not
381: if (($unit!~/\%/) && ($answerunit=~/\%/)) {
382: $element=$element*100;
383: $appendunit='%'.$appendunit;
384: }
385: # Zero does not need a dimension
386: if (($element =~ /^[0\.]+$/) && ($unit!~/\w/) && ($answerunit=~/\w/)) {
387: $appendunit=$answerunit;
388: }
389: # Do the math for the student if allowed
390: if ($allowalgebra) {
391: $element=&cas('maxima',$element);
392: }
393: if ($appendunit ne '') {
394: $element .= " $appendunit";
395: }
396: &LONCAPA_INTERNAL_DEBUG("Made response element :$element:");
397: }
398: }
399:
400: foreach my $thisanswer (@{ $LONCAPA::CAPAresponse_answer->{'answers'} }) {
401: if (!defined($thisanswer)) {
402: return ('ERROR','answer was undefined');
403: }
404: }
405:
406: my $allow_control_char = 0;
407: my $control_chars_removed = 0;
408: my $ansstring;
409: if ($type eq 'cs' || $type eq 'ci') {
410: if (ref($LONCAPA::CAPAresponse_answer->{'answers'}) eq 'ARRAY') {
411: foreach my $strans (@{$LONCAPA::CAPAresponse_answer->{'answers'}}) {
412: if (ref($strans) eq 'ARRAY') {
413: $ansstring = join("\0",@{$strans});
414: foreach my $item (@{$strans}) {
415: if ($item =~ /[\000-\037]/) {
416: $allow_control_char = 1;
417: }
418: }
419: }
420: }
421: }
422: }
423:
424: # &LONCAPA_INTERNAL_DEBUG(&LONCAPA_INTERNAL_Dumper($responses));
425: my %memoized;
426: if ($LONCAPA::CAPAresponse_answer->{'type'} eq 'ordered') {
427: for (my $i=0; $i<scalar(@$responses);$i++) {
428: my $answer = $LONCAPA::CAPAresponse_answer->{'answers'}[$i];
429: my $response = $responses->[$i];
430: my $key = "$answer\0$response";
431: my (@awards,@msgs);
432: for (my $j=0; $j<scalar(@$response); $j++) {
433: if ($type eq 'cs' || $type eq 'ci') {
434: unless ($allow_control_char) {
435: if ($response->[$j] =~ /[\000-\037]/) {
436: $response->[$j] =~ s/[\000-\037]//g;
437: $control_chars_removed = 1;
438: }
439: }
440: }
441: # See if we have preprocessor for string responses
442: if (($preprocess=~/\S/) && ($type eq 'cs' || $type eq 'ci')) {
443: if (defined(&$preprocess)) {
444: no strict 'refs';
445: $response->[$j]=&$preprocess($response->[$j]);
446: use strict 'refs';
447: }
448: }
449:
450: my ($award,$msg) = &caparesponse_check($answer->[$j],
451: $response->[$j]);
452: if ($type eq 'cs' || $type eq 'ci') {
453: $error = &verify_stringresponse($type,$award,$response->[$j],
454: $answer->[$j]);
455: }
456: push(@awards,$award);
457: push(@msgs, $msg);
458: }
459: my ($award,$msg) =
460: &LONCAPA_INTERNAL_FINALIZEAWARDS(\@awards,\@msgs);
461: $memoized{$key} = [$award,$msg];
462: }
463: } else {
464: #FIXME broken with unorder responses where one is a <value>
465: # and the other is a <vector> (need to delay parse til
466: # inside the loop?)
467: foreach my $response (@$responses) {
468: my $response_size = scalar(@{$response});
469: foreach my $answer (@{ $LONCAPA::CAPAresponse_answer->{'answers'} }) {
470: my $key = "$answer\0$response";
471: my $answer_size = scalar(@{$answer});
472: my ($award,$msg);
473: if ($answer_size > $response_size) {
474: $award = 'MISSING_ANSWER';
475: } elsif ($answer_size < $response_size) {
476: $award = 'EXTRA_ANSWER';
477: } else {
478: my (@awards,@msgs);
479: for (my $j=0; $j<scalar(@$response); $j++) {
480: if ($type eq 'cs' || $type eq 'ci') {
481: unless ($allow_control_char) {
482: if ($response->[$j] =~ /[\000-\037]/) {
483: $response->[$j] =~ s/[\000-\037]//g;
484: $control_chars_removed = 1;
485: }
486: }
487: }
488: # See if we have preprocessor
489: if (($preprocess=~/\S/) && ($type eq 'cs' || $type eq 'ci')) {
490: if (defined(&$preprocess)) {
491: no strict 'refs';
492: $response->[$j]=&$preprocess($response->[$j]);
493: use strict 'refs';
494: }
495: }
496:
497: my ($award,$msg) = &caparesponse_check($answer->[$j],
498: $response->[$j]);
499: if ($type eq 'cs' || $type eq 'ci') {
500: $error = &verify_stringresponse($type,$award,$response->[$j],
501: $answer->[$j]);
502: }
503: push(@awards,$award);
504: push(@msgs, $msg);
505: }
506: ($award,$msg) =
507: &LONCAPA_INTERNAL_FINALIZEAWARDS(\@awards,\@msgs);
508: }
509: $memoized{$key} = [$award,$msg];
510: }
511: }
512: }
513:
514: my ($final_award,$final_msg);
515: &init_permutation(scalar(@$responses),
516: $LONCAPA::CAPAresponse_answer->{'type'});
517:
518: # possible FIXMEs
519: # - significant time is spent calling non-safe space routine
520: # from safe space
521: # - early outs could be possible with classifying awards is to stratas
522: # and stopping as so as hitting the top strata
523: # - some early outs also might be possible with check ing the
524: # memoized hash of results (is correct even possible? etc.)
525:
526: my (@final_awards,@final_msg);
527: while( &get_permutations_left() ) {
528: my $order = &get_next_permutation();
529: my (@awards, @msgs, $i);
530: foreach my $thisanswer (@{ $LONCAPA::CAPAresponse_answer->{'answers'} }) {
531: my $key = "$thisanswer\0".$responses->[$order->[$i]];
532: push(@awards,$memoized{$key}[0]);
533: push(@msgs,$memoized{$key}[1]);
534: $i++;
535:
536: }
537: &LONCAPA_INTERNAL_DEBUG(" all awards ".join(':',@awards));
538:
539: my ($possible_award,$possible_msg) =
540: &LONCAPA_INTERNAL_FINALIZEAWARDS(\@awards,\@msgs);
541: &LONCAPA_INTERNAL_DEBUG(" pos awards ".$possible_award);
542: push(@final_awards,$possible_award);
543: push(@final_msg,$possible_msg);
544: }
545:
546: &LONCAPA_INTERNAL_DEBUG(" all final_awards ".join(':',@final_awards));
547: my ($final_award,$final_msg) =
548: &LONCAPA_INTERNAL_FINALIZEAWARDS(\@final_awards,\@final_msg,undef,1);
549: return ($final_award,$final_msg,$error,$control_chars_removed,$ansstring);
550: }
551:
552: sub verify_stringresponse {
553: my ($type,$award,$resp,$ans) = @_;
554: return if ($award eq 'EXACT_ANS');
555: my $error;
556: if ($resp =~ /^\s|\s$/) {
557: $resp =~ s{^\s+|\s+$}{}g;
558: }
559: if ($ans =~ /^\s|\s$/) {
560: $ans =~ s{^\s+|\s+$}{}g;
561: }
562: if ($type eq 'ci') {
563: $resp = lc($resp);
564: $ans = lc($ans);
565: }
566: if ($resp eq $ans) {
567: if ($award eq 'INCORRECT') {
568: $error = 'MISGRADED';
569: }
570: }
571: return $error;
572: }
573:
574: sub cas {
575: my ($system,$input,$library)=@_;
576: my $output;
577: my $dump;
578: if ($system eq 'maxima') {
579: $output=&maxima_eval($input,$library);
580: } elsif ($system eq 'R') {
581: ($output,$dump)=&r_eval($input,$library,0);
582: } else {
583: $output='Error: unrecognized CAS';
584: }
585: return $output;
586: }
587:
588: sub cas_hashref {
589: my ($system,$input,$library)=@_;
590: if ($system eq 'maxima') {
591: return 'Error: unsupported CAS';
592: } elsif ($system eq 'R') {
593: return &r_eval($input,$library,1);
594: } else {
595: return 'Error: unrecognized CAS';
596: }
597: }
598:
599: #
600: # cas_hashref_entry takes a list of indices and gets the entry in a hash generated by Rreturn.
601: # Call: cas_hashref_entry(Rvalue, index1, index2, ...) where Rvalue is a hash returned by Rreturn.
602: # Rentry will return the first scalar value it encounters (ignoring excess indices).
603: # If an invalid key is given, it returns undef.
604: #
605: sub cas_hashref_entry {
606: return &Rentry(@_);
607: }
608:
609: #
610: # cas_hashref_array takes a list of indices and gets a column array from a hash generated by Rreturn.
611: # Call: cas_hashref_array(Rvalue, index1, index2, ...) where Rvalue is a hash returned by Rreturn.
612: # If an invalid key is given, it returns undef.
613: #
614: sub cas_hashref_array {
615: return &Rarray(@_);
616: }
617:
618: sub tex {
619: if ( $external::target eq "tex" ) {
620: return $_[0];
621: } else {
622: return $_[1];
623: }
624: }
625:
626: sub var_in_tex {
627: if ( $external::target eq "tex" ) {
628: return $_[0];
629: } else {
630: return "";
631: }
632: }
633:
634: sub web {
635: if ( $external::target eq "tex" ) {
636: return $_[1];
637: } else {
638: if ( $external::target eq "web" || $external::target eq "answer") {
639: return $_[2];
640: } else {
641: return $_[0];
642: }
643: }
644: }
645:
646: sub html {
647: if ( $external::target eq "web" ) {
648: return shift;
649: }
650: }
651:
652: sub hinton {
653: return 0;
654: }
655:
656: sub random {
657: my ($start,$end,$step)=@_;
658: if ( ! $hidden::RANDOMINIT ) {
659: if ($external::randomseed == 0) { $external::randomseed=1; }
660: if ($external::randomseed =~/,/) {
661: my ($num1,$num2)=split(/,/,$external::randomseed);
662: &random_set_seed(1,abs($num1));
663: } elsif ($external::randomseed =~/:/) {
664: my ($num1,$num2)=split(/:/,$external::randomseed);
665: &random_set_seed(abs($num1),abs($num2));
666: } else {
667: &random_set_seed(1,int(abs($external::randomseed)));
668: }
669: &math_random_uniform();
670: $hidden::RANDOMINIT=1;
671: }
672: if (!defined($step)) { $step=1; }
673: my $num=1+int(($end-$start)/$step);
674: my $result=$start + int(&math_random_uniform() * $num)*$step;
675: return $result;
676: }
677:
678: sub random_normal {
679: my ($item_cnt,$seed,$av,$std_dev) = @_;
680: my @oldseed=&random_get_seed();
681: my @retArray;
682: &random_set_seed_from_phrase($seed);
683: @retArray=&math_random_normal($item_cnt,$av,$std_dev);
684: &random_set_seed(@oldseed);
685: return @retArray;
686: }
687:
688: sub random_beta {
689: my ($item_cnt,$seed,$aa,$bb) = @_;
690: my @oldseed=&random_get_seed();
691: my @retArray;
692: &random_set_seed_from_phrase($seed);
693: @retArray=&math_random_beta($item_cnt,$aa,$bb);
694: &random_set_seed(@oldseed);
695: return @retArray;
696: }
697:
698: sub random_gamma {
699: my ($item_cnt,$seed,$a,$r) = @_;
700: my @oldseed=&random_get_seed();
701: my @retArray;
702: &random_set_seed_from_phrase($seed);
703: @retArray=&math_random_gamma($item_cnt,$a,$r);
704: &random_set_seed(@oldseed);
705: return @retArray;
706: }
707:
708: sub random_exponential {
709: my ($item_cnt,$seed,$av) = @_;
710: my @oldseed=&random_get_seed();
711: my @retArray;
712: &random_set_seed_from_phrase($seed);
713: @retArray=&math_random_exponential($item_cnt,$av);
714: &random_set_seed(@oldseed);
715: return @retArray;
716: }
717:
718: sub random_poisson {
719: my ($item_cnt,$seed,$mu) = @_;
720: my @oldseed=&random_get_seed();
721: my @retArray;
722: &random_set_seed_from_phrase($seed);
723: @retArray=&math_random_poisson($item_cnt,$mu);
724: &random_set_seed(@oldseed);
725: return @retArray;
726: }
727:
728: sub random_chi {
729: my ($item_cnt,$seed,$df) = @_;
730: my @oldseed=&random_get_seed();
731: my @retArray;
732: &random_set_seed_from_phrase($seed);
733: @retArray=&math_random_chi_square($item_cnt,$df);
734: &random_set_seed(@oldseed);
735: return @retArray;
736: }
737:
738: sub random_noncentral_chi {
739: my ($item_cnt,$seed,$df,$nonc) = @_;
740: my @oldseed=&random_get_seed();
741: my @retArray;
742: &random_set_seed_from_phrase($seed);
743: @retArray=&math_random_noncentral_chi_square($item_cnt,$df,$nonc);
744: &random_set_seed(@oldseed);
745: return @retArray;
746: }
747:
748: sub random_f {
749: my ($item_cnt,$seed,$dfn,$dfd) = @_;
750: my @oldseed=&random_get_seed();
751: my @retArray;
752: &random_set_seed_from_phrase($seed);
753: @retArray=&math_random_f($item_cnt,$dfn,$dfd);
754: &random_set_seed(@oldseed);
755: return @retArray;
756: }
757:
758: sub random_noncentral_f {
759: my ($item_cnt,$seed,$dfn,$dfd,$nonc) = @_;
760: my @oldseed=&random_get_seed();
761: my @retArray;
762: &random_set_seed_from_phrase($seed);
763: @retArray=&math_random_noncentral_f($item_cnt,$dfn,$dfd,$nonc);
764: &random_set_seed(@oldseed);
765: return @retArray;
766: }
767:
768: sub random_multivariate_normal {
769: my ($item_cnt,$seed,$mean,$covar) = @_;
770: my @oldseed=&random_get_seed();
771: &random_set_seed_from_phrase($seed);
772: my @retArray=&math_random_multivariate_normal($item_cnt,@$mean,@$covar);
773: &random_set_seed(@oldseed);
774: return @retArray;
775: }
776:
777: sub random_multinomial {
778: my ($item_cnt,$seed,@p) = @_;
779: my @oldseed=&random_get_seed();
780: my @retArray;
781: &random_set_seed_from_phrase($seed);
782: my @retArray=&math_random_multinomial($item_cnt,@p);
783: &random_set_seed(@oldseed);
784: return @retArray;
785: }
786:
787: sub random_permutation {
788: my ($seed,@inArray) = @_;
789: my @oldseed=&random_get_seed();
790: my @retArray;
791: &random_set_seed_from_phrase($seed);
792: @retArray=&math_random_permutation(@inArray);
793: &random_set_seed(@oldseed);
794: return @retArray;
795: }
796:
797: sub random_uniform {
798: my ($item_cnt,$seed,$low,$high) = @_;
799: my @oldseed=&random_get_seed();
800: my @retArray;
801: &random_set_seed_from_phrase($seed);
802: @retArray=&math_random_uniform($item_cnt,$low,$high);
803: &random_set_seed(@oldseed);
804: return @retArray;
805: }
806:
807: sub random_uniform_integer {
808: my ($item_cnt,$seed,$low,$high) = @_;
809: my @oldseed=&random_get_seed();
810: my @retArray;
811: &random_set_seed_from_phrase($seed);
812: @retArray=&math_random_uniform_integer($item_cnt,$low,$high);
813: &random_set_seed(@oldseed);
814: return @retArray;
815: }
816:
817: sub random_binomial {
818: my ($item_cnt,$seed,$nt,$p) = @_;
819: my @oldseed=&random_get_seed();
820: my @retArray;
821: &random_set_seed_from_phrase($seed);
822: @retArray=&math_random_binomial($item_cnt,$nt,$p);
823: &random_set_seed(@oldseed);
824: return @retArray;
825: }
826:
827: sub random_negative_binomial {
828: my ($item_cnt,$seed,$ne,$p) = @_;
829: my @oldseed=&random_get_seed();
830: my @retArray;
831: &random_set_seed_from_phrase($seed);
832: @retArray=&math_random_negative_binomial($item_cnt,$ne,$p);
833: &random_set_seed(@oldseed);
834: return @retArray;
835: }
836:
837: sub abs { CORE::abs(shift) }
838: sub sin { CORE::sin(shift) }
839: sub cos { CORE::cos(shift) }
840: sub exp { CORE::exp(shift) }
841: sub int { CORE::int(shift) }
842: sub log { CORE::log(shift) }
843: sub ln { CORE::log(shift) }
844: sub atan2 { CORE::atan2($_[0],$_[1]) }
845: sub sqrt { CORE::sqrt(shift) }
846:
847: sub tan { CORE::sin($_[0]) / CORE::cos($_[0]) }
848: #sub atan { atan2($_[0], 1); }
849: #sub acos { atan2(sqrt(1 - $_[0] * $_[0]), $_[0] ); }
850: #sub asin { atan2($_[0], sqrt(1- $_[0] * $_[0]) ); }
851:
852: sub log10 { CORE::log($_[0])/CORE::log(10); }
853:
854: sub factorial {
855: my $input = CORE::int(shift);
856: return "Error - unable to take factorial of an negative number ($input)" if $input < 0;
857: return "Error - factorial result is greater than system limit ($input)" if $input > 170;
858: return 1 if $input == 0;
859: my $result = 1;
860: for (my $i=2; $i<=$input; $i++) { $result *= $i }
861: return $result;
862: }
863:
864: sub sgn {
865: return -1 if $_[0] < 0;
866: return 0 if $_[0] == 0;
867: return 1 if $_[0] > 0;
868: }
869:
870: sub min {
871: my @sorted = sort { $a <=> $b || $a cmp $b } @_;
872: return shift @sorted;
873: }
874:
875: sub max {
876: my @sorted = sort { $a <=> $b || $a cmp $b } @_;
877: return pop @sorted;
878: }
879:
880: sub roundto {
881: my ($input,$n) = @_;
882: return sprintf('%.'.$n.'f',$input);
883: }
884:
885: sub to_string {
886: my ($input,$n) = @_;
887: return sprintf($input) if $n eq "";
888: $n = '.'.$n if $n !~ /^\./;
889: return sprintf('%'.$n,$input) if $n ne "";
890: }
891:
892: sub sub_string {
893: my ($str,$start,$len) = @_;
894: return substr($str,$start-1,$len);
895: }
896:
897: sub pow {return $_[0] ** $_[1]; }
898: sub ceil {return (($_[0]-CORE::int($_[0]))== 0.0) ? $_[0] : (($_[0] > 0) ? (CORE::int($_[0])+ 1) : CORE::int($_[0])); }
899: sub floor {return (($_[0]-CORE::int($_[0]))== 0.0) ? $_[0] : (($_[0] > 0) ? CORE::int($_[0]) : (CORE::int($_[0])-1)); }
900: #sub floor {return int($_[0]); }
901:
902: sub format {
903: my ($value,$fmt)=@_;
904: my ($dollarmode,$commamode,$alwaysperiod,$options);
905: if ($fmt =~ /^([^\d]*)(.*)/) { $options=$1; $fmt=$2; }
906: #if ($options =~ /\$/) { $dollamode=1; }
907: #if ($options =~ /,/) { $commamode=1; }
908: if ($options =~ /\./) { $alwaysperiod=1; }
909: my $result;
910: if ($fmt=~/s$/i) {
911: $result=&format_significant_figures($value,$fmt);
912: } else {
913: $fmt=~s/e/E/g;
914: $result=sprintf('%.'.$fmt,$value);
915: if ($alwaysperiod && $fmt eq '0f') { $result .='.'; }
916: $result=~s/(E[+-]*)0/$1/;
917: }
918: #if ($dollarmode) {$result=&dollarformat($result);}
919: #if ($commamode) {$result=&commaformat($result);}
920: return $result;
921: }
922:
923: sub chemparse {
924: my ($reaction) = @_;
925: my @tokens = split(/(\s\+|\->|<=>|<\-|\.)/,$reaction);
926: my $formula = '';
927: foreach my $token (@tokens) {
928: if ($token eq '->' ) {
929: if ($external::target eq 'web') {
930: $formula .= '→ ';
931: } else {
932: $formula .= '<m>\ensuremath{\rightarrow}</m> ';
933: }
934: next;
935: }
936: if ($token eq '<-' ) {
937: if ($external::target eq 'web') {
938: $formula .= '← ';
939: } else {
940: $formula .= '<m>\ensuremath{\leftarrow}</m> ';
941: }
942: next;
943: }
944: if ($token eq '<=>') {
945: if ($external::target eq 'web' &&
946: &EXT('request.browser.unicode')) {
947: $formula .= '⇌ ';
948: } else {
949: $formula .= &web('<=> ','<m>\ensuremath{\rightleftharpoons}</m> ',
950: '<=> ');
951: }
952: next;
953: }
954: if ($token eq '.') {
955: $formula =~ s/(\ \;| )$//;
956: $formula .= '·';
957: next;
958: }
959: $token =~ /^\s*([\d|\/]*(?:&frac\d\d)?)(.*)/;
960: $formula .= $1 if ($1 ne '1'); # stoichiometric coefficient
961:
962: my $molecule = $2;
963: # subscripts
964: $molecule =~ s|(?<=[a-zA-Z\)\]\s])(\d+)|<sub>$1</sub>|g;
965: # superscripts
966: $molecule =~ s|\^(\d*[+\-]*)|<sup>$1</sup>|g;
967: # strip whitespace
968: $molecule =~ s/\s*//g;
969: # forced space
970: $molecule =~ s/_/ /g;
971: $molecule =~ s/-/−/g;
972: $formula .= $molecule.' ';
973: }
974: # get rid of trailing space
975: $formula =~ s/(\ \;| )$//;
976: return &xmlparse($formula);
977: }
978:
979: sub convert_engineer_format {
980: my ($ans,$baseunit)=@_;
981: my ($value,$answer,$unit);
982: $baseunit =~ s{[^\w/\-\.]}{}g;
983: eval {
984: $value = &number_format_pref($ans);
985: };
986: my ($answer,$prefix) = ($value=~ /^(.+)(\w)$/);
987: my $unit = $prefix.$baseunit;
988: return($answer,$unit);
989: }
990:
991: sub prettyprint {
992: my ($value,$fmt,$target)=@_;
993: my $result;
994: if (!$target) { $target = $external::target; }
995: if ($fmt =~ /chem/i) { return(&chemparse($value)); }
996: my ($dollarmode,$commamode,$alwaysperiod,$options);
997: if ($fmt =~ /^([^\d]*)(.*)/) { $options=$1; $fmt=$2; }
998: if ($options =~ /\$/) { $dollarmode=1; }
999: if ($options =~ /,/) { $commamode=1; }
1000: if ($options =~ /\./) { $alwaysperiod=1; }
1001: if ($fmt=~/s$/i) {
1002: $value=&format_significant_figures($value,$fmt);
1003: } elsif ($fmt) {
1004: $value=sprintf('%.'.$fmt,$value);
1005: }
1006: if ($alwaysperiod && $fmt eq '0f') {
1007: if ($target eq 'tex') {
1008: $value .='\\ensuremath{.}';
1009: } else {
1010: $value .='.';
1011: }
1012: }
1013: if ($value =~ /([0-9\.\-\+]+)E([0-9\-\+]+)/i ) {
1014: my $frac=$1;
1015: if ($dollarmode) { $frac=&dollarformat($frac); }
1016: if ($commamode) { $frac=&commaformat($frac); }
1017: my $exponent=$2;
1018: $exponent=~s/^\+0*//;
1019: $exponent=~s/^-0*/-/;
1020: $exponent=~s/^-0*/-/;
1021: if ($exponent eq '-') { undef($exponent); }
1022: if ($exponent) {
1023: if ($target eq 'web') {
1024: $result=$frac.'×10<sup>'.$exponent.'</sup>';
1025: } elsif ($target eq 'tex') {
1026: $result='\ensuremath{'.$frac.'\times 10^{'.$exponent.'}}';
1027: } else {
1028: $result=$value;
1029: }
1030: } else {
1031: $result=$frac;
1032: }
1033: } else {
1034: $result=$value;
1035: if ($dollarmode) { $result=&dollarformat($result,$target); }
1036: elsif ($commamode) { $result=&commaformat($result,$target); }
1037: }
1038: return $result;
1039: }
1040:
1041: sub commaformat {
1042: my ($number,$target) = @_;
1043: if ($number =~ /\./) {
1044: while ($number =~ /([^0-9]*)([0-9]+)([^\.,][^\.,][^\.,])([,0-9]*\.[0-9]*)$/) {
1045: $number = $1.$2.','.$3.$4;
1046: }
1047: } else {
1048: while ($number =~ /^([^0-9]*)([0-9]+)([^,][^,][^,])([,0-9]*)$/) {
1049: $number = $1.$2.','.$3.$4;
1050: }
1051: }
1052: return $number;
1053: }
1054:
1055: sub dollarformat {
1056: my ($number,$target) = @_;
1057: if (!$target) { $target = $external::target; }
1058: $number=&commaformat($number,$target);
1059: if ($target eq 'tex') {
1060: $number='\$'.$number; #' stupid emacs
1061: } else {
1062: $number='$'.$number; #' stupid emacs
1063: }
1064: return $number;
1065: }
1066:
1067: # format of form ns or nS where n is an integer
1068: sub format_significant_figures {
1069: my ($number,$format) = @_;
1070: return '0' if ($number == 0);
1071: # extract number of significant figures needed
1072: my ($sig) = ($format =~ /(\d+)s/i);
1073: # arbitrary choice - suggestions ?? or throw error message?
1074: $sig = 3 if ($sig eq '');
1075: # save the minus sign
1076: my $sign = ($number < 0) ? '-' : '';
1077: $number = abs($number);
1078: # needed to correct for a number greater than 1 (or
1079: my $power = ($number < 1) ? 0 : 1;
1080: # could round up. Take the integer part of log10.
1081: my $x10 = int(log($number)/log(10));
1082: # find number with values left of decimal pt = # of sign figs.
1083: my $xsig = $number*10**($sig-$x10-$power);
1084: # get just digits left of decimal pt - also rounds off correctly
1085: my $xint = sprintf('%.0f',$xsig);
1086: # save any trailing zero's
1087: my ($zeros) = ($xint =~ /(0+)$/);
1088: # return number to original magnitude
1089: my $numSig = $xint*10**($x10-$sig+$power);
1090: if ($numSig =~ /^(\d+)\.(\d+)/) {
1091: # insert trailing zero's if have decimal point
1092: my @digarray = split('',$1.$2);
1093: my $sigcount;
1094: while (@digarray > 0) {
1095: my $item = shift(@digarray);
1096: if ($item) {
1097: $sigcount = 1 + @digarray;
1098: last;
1099: }
1100: }
1101: if (($sigcount) && ($sig >= $sigcount)) {
1102: $zeros = substr($zeros,0,($sig - $sigcount));
1103: }
1104: $numSig =~ s/^(\d+)\.(\d+)(\e?(.*)?)$/$1\.$2$zeros$3/;
1105: } else {
1106: if ($numSig =~ /^(\d+)e([\+\-]\d+)$/i) {
1107: my $pre_exp = $1;
1108: my $exponent = $2;
1109: $numSig = $pre_exp.'.'.$zeros.'E'.$exponent;
1110: } elsif ($numSig =~ /0$/) {
1111: # add decimal pt for number ending with 0 and length == # of sig figs
1112: if (length($numSig) == $sig) {
1113: $numSig.='.';
1114: } elsif (length($numSig) > $sig) {
1115: # exponential form for number ending with 0 and length > # of sig figs
1116: my $fmtsig = $sig-1;
1117: if ($fmtsig) {
1118: $numSig = sprintf('%.'.$fmtsig.'E',$numSig);
1119: }
1120: } elsif (length($numSig) < $sig) {
1121: $numSig.='.'.substr($zeros,0,($sig-length($numSig)));
1122: }
1123: } else {
1124: if (length($numSig) < $sig) {
1125: $numSig.='.'.substr($zeros,0,($sig-length($numSig)));
1126: }
1127: }
1128: }
1129: # return number with sign
1130: return $sign.$numSig;
1131: }
1132:
1133: sub map {
1134: my ($phrase,$dest,$source)=@_;
1135: my @oldseed=&random_get_seed();
1136: my @seed = &random_seed_from_phrase($phrase);
1137: &random_set_seed(@seed);
1138: my $destct = scalar(@$dest);
1139: if (!$source) {
1140: my @output;
1141: my @idx = &math_random_permuted_index($destct);
1142: my $ctr = 0;
1143: while ($ctr < $destct) {
1144: $output[$ctr] = $$dest[$idx[$ctr]];
1145: $ctr++;
1146: }
1147: &random_set_seed(@oldseed);
1148: return @output;
1149: } else {
1150: my $num = scalar(@$source);
1151: my @idx = &math_random_permuted_index($num);
1152: my $ctr = 0;
1153: my $tot = $num;
1154: $tot = $destct if $destct < $num;
1155: if (ref($$dest[0])) {
1156: while ($ctr < $tot) {
1157: ${$$dest[$ctr]} = $$source[$idx[$ctr]];
1158: $ctr++;
1159: }
1160: } else {
1161: while ($ctr < $tot) {
1162: $$dest[$ctr] = $$source[$idx[$ctr]];
1163: $ctr++;
1164: }
1165: }
1166: }
1167: &random_set_seed(@oldseed);
1168: return '';
1169: }
1170:
1171: sub rmap {
1172: my ($phrase,$dest,$source)=@_;
1173: my @oldseed=&random_get_seed();
1174: my @seed = &random_seed_from_phrase($phrase);
1175: &random_set_seed(@seed);
1176: my $destct = scalar(@$dest);
1177: if (!$source) {
1178: my @idx = &math_random_permuted_index($destct);
1179: my $ctr = 0;
1180: my @r_idx;
1181: while ($ctr < $destct) {
1182: $r_idx[$idx[$ctr]] = $ctr;
1183: $ctr++;
1184: }
1185: my @output;
1186: $ctr = 0;
1187: while ($ctr < $destct) {
1188: $output[$ctr] = $$dest[$r_idx[$ctr]];
1189: $ctr++;
1190: }
1191: &random_set_seed(@oldseed);
1192: return @output;
1193: } else {
1194: my $num = scalar(@$source);
1195: my @idx = &math_random_permuted_index($num);
1196: my $ctr = 0;
1197: my $tot = $num;
1198: $tot = $destct if $destct < $num;
1199: my @r_idx;
1200: while ($ctr < $tot) {
1201: $r_idx[$idx[$ctr]] = $ctr;
1202: $ctr++;
1203: }
1204: $ctr = 0;
1205: if (ref($$dest[0])) {
1206: while ($ctr < $tot) {
1207: ${$$dest[$ctr]} = $$source[$r_idx[$ctr]];
1208: $ctr++;
1209: }
1210: } else {
1211: while ($ctr < $tot) {
1212: $$dest[$ctr] = $$source[$r_idx[$ctr]];
1213: $ctr++;
1214: }
1215: }
1216: }
1217: &random_set_seed(@oldseed);
1218: return '';
1219: }
1220:
1221: sub capa_id { return }
1222:
1223: sub problem { return }
1224:
1225: sub name{
1226: my $fullname = &EXT('environment.lastname').', '.&EXT('environment.firstname').' '.&EXT('environment.middlename');
1227: $fullname = "" if $fullname eq ", ";
1228: $fullname =~ s/\%2d/-/g;
1229: return $fullname;
1230: }
1231:
1232: sub student_number {
1233: my $id = &EXT('environment.id');
1234: $id = '' if $id eq "";
1235: return $id;
1236: }
1237:
1238: sub class {
1239: my $course = &EXT('course.description');
1240: $course = '' if $course eq "";
1241: return $course;
1242: }
1243:
1244: sub classid {
1245: my $courseid = &EXT('request.course.id');
1246: $courseid = '' if $courseid eq "";
1247: return $courseid;
1248: }
1249:
1250: sub firstname {
1251: my $firstname = &EXT('environment.firstname');
1252: $firstname = '' if $firstname eq "";
1253: return $firstname;
1254: }
1255:
1256: sub middlename {
1257: my $middlename = &EXT('environment.middlename');
1258: $middlename = '' if $middlename eq "";
1259: return $middlename;
1260: }
1261:
1262: sub lastname {
1263: my $lastname = &EXT('environment.lastname');
1264: $lastname = '' if $lastname eq "";
1265: return $lastname;
1266: }
1267:
1268: sub sec {
1269: my $sec = &EXT('request.course.sec');
1270: $sec = '' if $sec eq "";
1271: return $sec;
1272: }
1273:
1274: sub submission {
1275: my ($partid,$responseid,$subnumber,$encode,$cleanupnum,$mapalias)=@_;
1276: my $sub='';
1277: if ($subnumber) { $sub=$subnumber.':'; }
1278: my $output =
1279: &EXT('user.resource.'.$sub.'resource.'.$partid.'.'.$responseid.'.submission',$mapalias);
1280: if (ref($output) eq 'ARRAY') {
1281: my @items = @{$output};
1282: if ($encode) {
1283: @items = map { &encode_response($_); } @items;
1284: }
1285: if (ref($cleanupnum) eq 'HASH') {
1286: @items = map { &cleanup_numerical_response($cleanupnum,$_); } @items;
1287: }
1288: return \@items;
1289: } else {
1290: if ($encode) {
1291: $output = &encode_response($output);
1292: }
1293: if (ref($cleanupnum) eq 'HASH') {
1294: $output = &cleanup_numerical_response($cleanupnum,$output);
1295: }
1296: return $output;
1297: }
1298: }
1299:
1300: sub encode_response {
1301: my ($value) = @_;
1302: $value =~ s/&/&/g;
1303: $value =~ s/</</g;
1304: $value =~ s/>/>/g;
1305: $value =~ s/"/"/g;
1306: return $value;
1307: }
1308:
1309: sub cleanup_numerical_response {
1310: my ($cleanupnum,$value) = @_;
1311: if (ref($cleanupnum) eq 'HASH') {
1312: if ($cleanupnum->{exponent}) {
1313: if ($value =~ m{^(.*)[\*xX]\s*10\s*\^\s*(\+|\-)?\s*(\d+)(.*)$}) {
1314: my $pre_exp = $1;
1315: my $sign = $2;
1316: my $exponent = $3;
1317: my $post_exp = $4;
1318: if ($pre_exp !~ /\./) {
1319: $pre_exp .= '.';
1320: }
1321: if ($sign eq '') {
1322: $sign = '+';
1323: }
1324: $value = $pre_exp.'E'.$sign.$exponent.$post_exp;
1325: }
1326: }
1327: if ($cleanupnum->{comma}) {
1328: $value =~ s{(\d+),(\d+)}{$1$2};
1329: }
1330: if ($cleanupnum->{letterforzero}) {
1331: $value =~ s/^\s*o(\.\d+)/0$1/i;
1332: }
1333: if ($cleanupnum->{spaces}) {
1334: $value =~ s{^\s+|\s+$}{}g;
1335: if ($value =~ m{^(.*)\.\s+(\d+)(.*)$}) {
1336: my $pre_pt = $1;
1337: my $decimal = $2;
1338: my $post_dec = $3;
1339: $value = $pre_pt.'.'.$decimal.$post_dec;
1340: }
1341: }
1342: if ($cleanupnum->{format} =~ /^\d+s$/i) {
1343: $value = &format_significant_figures($value,$cleanupnum->{format});
1344: }
1345: }
1346: return $value;
1347: }
1348:
1349: sub currentpart {
1350: return $external::part;
1351: }
1352:
1353: sub eval_time {
1354: my ($timestamp)=@_;
1355: unless ($timestamp) { return ''; }
1356: return &locallocaltime($timestamp);
1357: }
1358:
1359: sub open_date {
1360: my ($partid)=@_;
1361: unless ($partid) { $partid=0; }
1362: return &eval_time(&EXT('resource.'.$partid.'.opendate'));
1363: }
1364:
1365: sub due_date {
1366: my ($partid)=@_;
1367: unless ($partid) { $partid=0; }
1368: return &eval_time(&EXT('resource.'.$partid.'.duedate'));
1369: }
1370:
1371: sub answer_date {
1372: my ($partid)=@_;
1373: unless ($partid) { $partid=0; }
1374: return &eval_time(&EXT('resource.'.$partid.'.answerdate'));
1375: }
1376:
1377: sub open_date_epoch {
1378: my ($partid)=@_;
1379: unless ($partid) { $partid=0; }
1380: return &EXT('resource.'.$partid.'.opendate');
1381: }
1382:
1383: sub due_date_epoch {
1384: my ($partid)=@_;
1385: unless ($partid) { $partid=0; }
1386: return &EXT('resource.'.$partid.'.duedate');
1387: }
1388:
1389: sub answer_date_epoch {
1390: my ($partid)=@_;
1391: unless ($partid) { $partid=0; }
1392: return &EXT('resource.'.$partid.'.answerdate');
1393: }
1394:
1395: sub parameter_setting {
1396: my ($which,$partid)=@_;
1397: unless ($partid) { $partid=0; }
1398: return &EXT('resource.'.$partid.'.'.$which);
1399: }
1400:
1401: sub stored_data {
1402: my ($which,$partid)=@_;
1403: unless ($partid) { $partid=0; }
1404: return &EXT('user.resource.resource.'.$partid.'.'.$which);
1405: }
1406:
1407: sub wrong_bubbles {
1408: my ($correct,$lower,$upper,$step,@given)=@_;
1409: my @array=();
1410: my %hash=();
1411: foreach my $new (@given) {
1412: $hash{$new}=1;
1413: }
1414: my $num=int(¶meter_setting('numbubbles',¤tpart()));
1415: unless ($num) { $num=8; }
1416: if ($num>1) {
1417: for (my $i=0;$i<=500;$i++) {
1418: my $new=&random($lower,$upper,$step);
1419: if ($hash{$new}) { next; }
1420: if (abs($new-$correct)<$step) { next; }
1421: $hash{$new}=1;
1422: @array=keys(%hash);
1423: if ($#array+2>=$num) { last; }
1424: }
1425: }
1426: return @array;
1427: }
1428:
1429: sub array_moments {
1430: my @input=@_;
1431: my (@output,$N);
1432: $N=scalar (@input);
1433: $output[0]=$N;
1434: if ($N <= 1) {
1435: $output[1]=$input[0];
1436: $output[1]="Input array not defined" if ($N == 0);
1437: $output[2]="variance undefined for N<=1";
1438: $output[3]="skewness undefined for N<=1";
1439: $output[4]="kurtosis undefined for N<=1";
1440: return @output;
1441: }
1442: my $sum=0;
1443: foreach my $line (@input) {
1444: $sum+=$line;
1445: }
1446: $output[1] = $sum/$N;
1447: my ($x,$sdev,$var,$skew,$kurt) = 0;
1448: foreach my $line (@input) {
1449: $x=$line-$output[1];
1450: $var+=$x**2;
1451: $skew+=$x**3;
1452: $kurt+=$x**4;
1453: }
1454: $output[2]=$var/($N-1);
1455: $sdev=CORE::sqrt($output[2]);
1456: if ($sdev == 0) {
1457: $output[3]="inf-variance=0";
1458: $output[4]="inf-variance=0";
1459: return @output;
1460: }
1461: $output[3]=$skew/($sdev**3*$N);
1462: $output[4]=$kurt/($sdev**4*$N)-3;
1463: return @output;
1464: }
1465:
1466: sub choose {
1467: my $num = $_[0];
1468: return $_[$num];
1469: }
1470:
1471: #&sum1(1,$x,sub { &sum1($_[0],2*$_[0], sub { fact($_[0])**2 })});
1472: #sub sum1 {
1473: # my ($start,$end,$sub)=@_;
1474: # my $sum=0;
1475: # for (my $i=$start;$i<=$end;$i++) {
1476: # $sum+=&$sub($i);
1477: # }
1478: # return $sum
1479: #}
1480:
1481: #&sum2('a',1,$x,'&sum2(\'b\',$a,2*$a, \'&factorial($b)**2\')');
1482: #sub sum2 {
1483: # my ($varname,$start,$end,$line)=@_;
1484: # my $sum=0;
1485: # for (my $i=$start;$i<=$end;$i++) {
1486: # my $func=sub {
1487: # eval("\$".$varname."=$i");
1488: # eval($line);
1489: # };
1490: # $sum+=&$func($i);
1491: # }
1492: # return $sum
1493: #}
1494:
1495: # expiremental idea
1496: sub proper_path {
1497: my ($path)=@_;
1498: if ( $external::target eq "tex" ) {
1499: return '/home/httpd/html'.$path;
1500: } else {
1501: return $path;
1502: }
1503: }
1504:
1505: sub input_id {
1506: my ($part_id, $response_id, $textline_id) = @_;
1507: return 'HWVAL_'.$part_id.'_'.$response_id.'_'.$textline_id;
1508: }
1509:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>