File:
[LON-CAPA] /
loncom /
homework /
default_homework.lcpm
Revision
1.169:
download - view:
text,
annotated -
select for diffs
Wed Jun 25 16:50:51 2014 UTC (10 years, 2 months ago) by
raeburn
Branches:
MAIN
CVS tags:
version_2_11_0,
HEAD
- Bugs 6609, 6611, 6614
- Optional fifth arg can be provided to &submission() to clean up learner
submitted data (e.g., in a multi-part problem) where learner data from
submissions to a numerical respnse in an earlier part will be used as
variables in the script block when calculating answers for a later part.
- "cleanupnum" arg is a ref to a hash, with one or more of the following
keys => values:
exponent => 1, comma => 1, letterforzero => 1, spaces => 1, format => 'ns'
(where n is an integer, i.e., number of significant digits).
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.169 2014/06/25 16:50:51 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: if ($allowalgebra) {
313: ($part1,$part2)=($responses->[0][-1]=~ /^(.*[^\s])\s+([^\s]+)$/);
314: } else {
315: ($part1,$part2)=($responses->[0][-1]=~ /^([\d\.\,\s\$]*(?:(?:[xX\*]10[\^\*]*|[eE]*)[\+\-]*\d*)*(?:^|\S)\d+)([\$\s\w\^\*\/\(\)\+\-]*[^\d\.\s\,][\$\s\w\^\*\/\(\)\+\-]*)$/);
316: }
317: if (defined($part1) && defined($part2)) {
318: $responses->[0][-1]=$part1;
319: $unit=&capa_formula_fix($part2);
320: my $customunits=$LONCAPA::CAPAresponse_args{'customunits'};
321: if ($customunits =~ /\S/) {
322: foreach my $replacement (split(/\s*\,\s*/,$customunits)) {
323: my ($which,$what)=split(/\s*\=\s*/,$replacement);
324: if ((defined($which)) && (defined($what))) {
325: $what=&capa_formula_fix($what);
326: $unit=~s/$which/\($what\)/g;
327: }
328: }
329: }
330: }
331: }
332: $unit=~s/\s//;
333: my $error;
334: foreach my $response (@$responses) {
335: foreach my $element (@$response) {
336: # See if we have preprocessor
337: if ($preprocess=~/\S/) {
338: if (defined(&$preprocess)) {
339: no strict 'refs';
340: $element=&$preprocess($element,$unit);
341: use strict 'refs';
342: }
343: }
344: if (($type eq 'float') || (($type eq '') && ($unit ne ''))) {
345: $element =~ s/\s//g;
346: }
347: my $appendunit=$unit;
348: # Deal with percentages
349: # unit is unit entered by student, answerunit is unit by author
350: # Deprecated: divide answer by 100 if student entered percent,
351: # but author did not. Too much confusion
352: # if (($unit=~/\%/) && ($answerunit ne '%')) {
353: # $element=$element/100;
354: # $appendunit=~s/\%//;
355: # }
356: # Author entered percent, student did not
357: if (($unit!~/\%/) && ($answerunit=~/\%/)) {
358: $element=$element*100;
359: $appendunit='%'.$appendunit;
360: }
361: # Zero does not need a dimension
362: if (($element =~ /^[0\.]+$/) && ($unit!~/\w/) && ($answerunit=~/\w/)) {
363: $appendunit=$answerunit;
364: }
365: # Do the math for the student if allowed
366: if ($allowalgebra) {
367: $element=&cas('maxima',$element);
368: }
369: if ($appendunit ne '') {
370: $element .= " $appendunit";
371: }
372: &LONCAPA_INTERNAL_DEBUG("Made response element :$element:");
373: }
374: }
375:
376: foreach my $thisanswer (@{ $LONCAPA::CAPAresponse_answer->{'answers'} }) {
377: if (!defined($thisanswer)) {
378: return ('ERROR','answer was undefined');
379: }
380: }
381:
382: my $allow_control_char = 0;
383: my $control_chars_removed = 0;
384: my $ansstring;
385: if ($type eq 'cs' || $type eq 'ci') {
386: if (ref($LONCAPA::CAPAresponse_answer->{'answers'}) eq 'ARRAY') {
387: foreach my $strans (@{$LONCAPA::CAPAresponse_answer->{'answers'}}) {
388: if (ref($strans) eq 'ARRAY') {
389: $ansstring = join("\0",@{$strans});
390: foreach my $item (@{$strans}) {
391: if ($item =~ /[\000-\037]/) {
392: $allow_control_char = 1;
393: }
394: }
395: }
396: }
397: }
398: }
399:
400: # &LONCAPA_INTERNAL_DEBUG(&LONCAPA_INTERNAL_Dumper($responses));
401: my %memoized;
402: if ($LONCAPA::CAPAresponse_answer->{'type'} eq 'ordered') {
403: for (my $i=0; $i<scalar(@$responses);$i++) {
404: my $answer = $LONCAPA::CAPAresponse_answer->{'answers'}[$i];
405: my $response = $responses->[$i];
406: my $key = "$answer\0$response";
407: my (@awards,@msgs);
408: for (my $j=0; $j<scalar(@$response); $j++) {
409: if ($type eq 'cs' || $type eq 'ci') {
410: unless ($allow_control_char) {
411: if ($response->[$j] =~ /[\000-\037]/) {
412: $response->[$j] =~ s/[\000-\037]//g;
413: $control_chars_removed = 1;
414: }
415: }
416: }
417: # See if we have preprocessor for string responses
418: if (($preprocess=~/\S/) && ($type eq 'cs' || $type eq 'ci')) {
419: if (defined(&$preprocess)) {
420: no strict 'refs';
421: $response->[$j]=&$preprocess($response->[$j]);
422: use strict 'refs';
423: }
424: }
425:
426: my ($award,$msg) = &caparesponse_check($answer->[$j],
427: $response->[$j]);
428: if ($type eq 'cs' || $type eq 'ci') {
429: $error = &verify_stringresponse($type,$award,$response->[$j],
430: $answer->[$j]);
431: }
432: push(@awards,$award);
433: push(@msgs, $msg);
434: }
435: my ($award,$msg) =
436: &LONCAPA_INTERNAL_FINALIZEAWARDS(\@awards,\@msgs);
437: $memoized{$key} = [$award,$msg];
438: }
439: } else {
440: #FIXME broken with unorder responses where one is a <value>
441: # and the other is a <vector> (need to delay parse til
442: # inside the loop?)
443: foreach my $response (@$responses) {
444: my $response_size = scalar(@{$response});
445: foreach my $answer (@{ $LONCAPA::CAPAresponse_answer->{'answers'} }) {
446: my $key = "$answer\0$response";
447: my $answer_size = scalar(@{$answer});
448: my ($award,$msg);
449: if ($answer_size > $response_size) {
450: $award = 'MISSING_ANSWER';
451: } elsif ($answer_size < $response_size) {
452: $award = 'EXTRA_ANSWER';
453: } else {
454: my (@awards,@msgs);
455: for (my $j=0; $j<scalar(@$response); $j++) {
456: if ($type eq 'cs' || $type eq 'ci') {
457: unless ($allow_control_char) {
458: if ($response->[$j] =~ /[\000-\037]/) {
459: $response->[$j] =~ s/[\000-\037]//g;
460: $control_chars_removed = 1;
461: }
462: }
463: }
464: # See if we have preprocessor
465: if (($preprocess=~/\S/) && ($type eq 'cs' || $type eq 'ci')) {
466: if (defined(&$preprocess)) {
467: no strict 'refs';
468: $response->[$j]=&$preprocess($response->[$j]);
469: use strict 'refs';
470: }
471: }
472:
473: my ($award,$msg) = &caparesponse_check($answer->[$j],
474: $response->[$j]);
475: if ($type eq 'cs' || $type eq 'ci') {
476: $error = &verify_stringresponse($type,$award,$response->[$j],
477: $answer->[$j]);
478: }
479: push(@awards,$award);
480: push(@msgs, $msg);
481: }
482: ($award,$msg) =
483: &LONCAPA_INTERNAL_FINALIZEAWARDS(\@awards,\@msgs);
484: }
485: $memoized{$key} = [$award,$msg];
486: }
487: }
488: }
489:
490: my ($final_award,$final_msg);
491: &init_permutation(scalar(@$responses),
492: $LONCAPA::CAPAresponse_answer->{'type'});
493:
494: # possible FIXMEs
495: # - significant time is spent calling non-safe space routine
496: # from safe space
497: # - early outs could be possible with classifying awards is to stratas
498: # and stopping as so as hitting the top strata
499: # - some early outs also might be possible with check ing the
500: # memoized hash of results (is correct even possible? etc.)
501:
502: my (@final_awards,@final_msg);
503: while( &get_permutations_left() ) {
504: my $order = &get_next_permutation();
505: my (@awards, @msgs, $i);
506: foreach my $thisanswer (@{ $LONCAPA::CAPAresponse_answer->{'answers'} }) {
507: my $key = "$thisanswer\0".$responses->[$order->[$i]];
508: push(@awards,$memoized{$key}[0]);
509: push(@msgs,$memoized{$key}[1]);
510: $i++;
511:
512: }
513: &LONCAPA_INTERNAL_DEBUG(" all awards ".join(':',@awards));
514:
515: my ($possible_award,$possible_msg) =
516: &LONCAPA_INTERNAL_FINALIZEAWARDS(\@awards,\@msgs);
517: &LONCAPA_INTERNAL_DEBUG(" pos awards ".$possible_award);
518: push(@final_awards,$possible_award);
519: push(@final_msg,$possible_msg);
520: }
521:
522: &LONCAPA_INTERNAL_DEBUG(" all final_awards ".join(':',@final_awards));
523: my ($final_award,$final_msg) =
524: &LONCAPA_INTERNAL_FINALIZEAWARDS(\@final_awards,\@final_msg,undef,1);
525: return ($final_award,$final_msg,$error,$control_chars_removed,$ansstring);
526: }
527:
528: sub verify_stringresponse {
529: my ($type,$award,$resp,$ans) = @_;
530: return if ($award eq 'EXACT_ANS');
531: my $error;
532: if ($resp =~ /^\s|\s$/) {
533: $resp =~ s{^\s+|\s+$}{}g;
534: }
535: if ($ans =~ /^\s|\s$/) {
536: $ans =~ s{^\s+|\s+$}{}g;
537: }
538: if ($type eq 'ci') {
539: $resp = lc($resp);
540: $ans = lc($ans);
541: }
542: if ($resp eq $ans) {
543: if ($award eq 'INCORRECT') {
544: $error = 'MISGRADED';
545: }
546: }
547: return $error;
548: }
549:
550: sub cas {
551: my ($system,$input,$library)=@_;
552: my $output;
553: my $dump;
554: if ($system eq 'maxima') {
555: $output=&maxima_eval($input,$library);
556: } elsif ($system eq 'R') {
557: ($output,$dump)=&r_eval($input,$library,0);
558: } else {
559: $output='Error: unrecognized CAS';
560: }
561: return $output;
562: }
563:
564: sub cas_hashref {
565: my ($system,$input,$library)=@_;
566: if ($system eq 'maxima') {
567: return 'Error: unsupported CAS';
568: } elsif ($system eq 'R') {
569: return &r_eval($input,$library,1);
570: } else {
571: return 'Error: unrecognized CAS';
572: }
573: }
574:
575: #
576: # cas_hashref_entry takes a list of indices and gets the entry in a hash generated by Rreturn.
577: # Call: cas_hashref_entry(Rvalue, index1, index2, ...) where Rvalue is a hash returned by Rreturn.
578: # Rentry will return the first scalar value it encounters (ignoring excess indices).
579: # If an invalid key is given, it returns undef.
580: #
581: sub cas_hashref_entry {
582: return &Rentry(@_);
583: }
584:
585: #
586: # cas_hashref_array takes a list of indices and gets a column array from a hash generated by Rreturn.
587: # Call: cas_hashref_array(Rvalue, index1, index2, ...) where Rvalue is a hash returned by Rreturn.
588: # If an invalid key is given, it returns undef.
589: #
590: sub cas_hashref_array {
591: return &Rarray(@_);
592: }
593:
594: sub tex {
595: if ( $external::target eq "tex" ) {
596: return $_[0];
597: } else {
598: return $_[1];
599: }
600: }
601:
602: sub var_in_tex {
603: if ( $external::target eq "tex" ) {
604: return $_[0];
605: } else {
606: return "";
607: }
608: }
609:
610: sub web {
611: if ( $external::target eq "tex" ) {
612: return $_[1];
613: } else {
614: if ( $external::target eq "web" || $external::target eq "answer") {
615: return $_[2];
616: } else {
617: return $_[0];
618: }
619: }
620: }
621:
622: sub html {
623: if ( $external::target eq "web" ) {
624: return shift;
625: }
626: }
627:
628: sub hinton {
629: return 0;
630: }
631:
632: sub random {
633: my ($start,$end,$step)=@_;
634: if ( ! $hidden::RANDOMINIT ) {
635: if ($external::randomseed == 0) { $external::randomseed=1; }
636: if ($external::randomseed =~/,/) {
637: my ($num1,$num2)=split(/,/,$external::randomseed);
638: &random_set_seed(1,abs($num1));
639: } elsif ($external::randomseed =~/:/) {
640: my ($num1,$num2)=split(/:/,$external::randomseed);
641: &random_set_seed(abs($num1),abs($num2));
642: } else {
643: &random_set_seed(1,int(abs($external::randomseed)));
644: }
645: &math_random_uniform();
646: $hidden::RANDOMINIT=1;
647: }
648: if (!defined($step)) { $step=1; }
649: my $num=1+int(($end-$start)/$step);
650: my $result=$start + int(&math_random_uniform() * $num)*$step;
651: return $result;
652: }
653:
654: sub random_normal {
655: my ($item_cnt,$seed,$av,$std_dev) = @_;
656: my @oldseed=&random_get_seed();
657: my @retArray;
658: &random_set_seed_from_phrase($seed);
659: @retArray=&math_random_normal($item_cnt,$av,$std_dev);
660: &random_set_seed(@oldseed);
661: return @retArray;
662: }
663:
664: sub random_beta {
665: my ($item_cnt,$seed,$aa,$bb) = @_;
666: my @oldseed=&random_get_seed();
667: my @retArray;
668: &random_set_seed_from_phrase($seed);
669: @retArray=&math_random_beta($item_cnt,$aa,$bb);
670: &random_set_seed(@oldseed);
671: return @retArray;
672: }
673:
674: sub random_gamma {
675: my ($item_cnt,$seed,$a,$r) = @_;
676: my @oldseed=&random_get_seed();
677: my @retArray;
678: &random_set_seed_from_phrase($seed);
679: @retArray=&math_random_gamma($item_cnt,$a,$r);
680: &random_set_seed(@oldseed);
681: return @retArray;
682: }
683:
684: sub random_exponential {
685: my ($item_cnt,$seed,$av) = @_;
686: my @oldseed=&random_get_seed();
687: my @retArray;
688: &random_set_seed_from_phrase($seed);
689: @retArray=&math_random_exponential($item_cnt,$av);
690: &random_set_seed(@oldseed);
691: return @retArray;
692: }
693:
694: sub random_poisson {
695: my ($item_cnt,$seed,$mu) = @_;
696: my @oldseed=&random_get_seed();
697: my @retArray;
698: &random_set_seed_from_phrase($seed);
699: @retArray=&math_random_poisson($item_cnt,$mu);
700: &random_set_seed(@oldseed);
701: return @retArray;
702: }
703:
704: sub random_chi {
705: my ($item_cnt,$seed,$df) = @_;
706: my @oldseed=&random_get_seed();
707: my @retArray;
708: &random_set_seed_from_phrase($seed);
709: @retArray=&math_random_chi_square($item_cnt,$df);
710: &random_set_seed(@oldseed);
711: return @retArray;
712: }
713:
714: sub random_noncentral_chi {
715: my ($item_cnt,$seed,$df,$nonc) = @_;
716: my @oldseed=&random_get_seed();
717: my @retArray;
718: &random_set_seed_from_phrase($seed);
719: @retArray=&math_random_noncentral_chi_square($item_cnt,$df,$nonc);
720: &random_set_seed(@oldseed);
721: return @retArray;
722: }
723:
724: sub random_f {
725: my ($item_cnt,$seed,$dfn,$dfd) = @_;
726: my @oldseed=&random_get_seed();
727: my @retArray;
728: &random_set_seed_from_phrase($seed);
729: @retArray=&math_random_f($item_cnt,$dfn,$dfd);
730: &random_set_seed(@oldseed);
731: return @retArray;
732: }
733:
734: sub random_noncentral_f {
735: my ($item_cnt,$seed,$dfn,$dfd,$nonc) = @_;
736: my @oldseed=&random_get_seed();
737: my @retArray;
738: &random_set_seed_from_phrase($seed);
739: @retArray=&math_random_noncentral_f($item_cnt,$dfn,$dfd,$nonc);
740: &random_set_seed(@oldseed);
741: return @retArray;
742: }
743:
744: sub random_multivariate_normal {
745: my ($item_cnt,$seed,$mean,$covar) = @_;
746: my @oldseed=&random_get_seed();
747: &random_set_seed_from_phrase($seed);
748: my @retArray=&math_random_multivariate_normal($item_cnt,@$mean,@$covar);
749: &random_set_seed(@oldseed);
750: return @retArray;
751: }
752:
753: sub random_multinomial {
754: my ($item_cnt,$seed,@p) = @_;
755: my @oldseed=&random_get_seed();
756: my @retArray;
757: &random_set_seed_from_phrase($seed);
758: my @retArray=&math_random_multinomial($item_cnt,@p);
759: &random_set_seed(@oldseed);
760: return @retArray;
761: }
762:
763: sub random_permutation {
764: my ($seed,@inArray) = @_;
765: my @oldseed=&random_get_seed();
766: my @retArray;
767: &random_set_seed_from_phrase($seed);
768: @retArray=&math_random_permutation(@inArray);
769: &random_set_seed(@oldseed);
770: return @retArray;
771: }
772:
773: sub random_uniform {
774: my ($item_cnt,$seed,$low,$high) = @_;
775: my @oldseed=&random_get_seed();
776: my @retArray;
777: &random_set_seed_from_phrase($seed);
778: @retArray=&math_random_uniform($item_cnt,$low,$high);
779: &random_set_seed(@oldseed);
780: return @retArray;
781: }
782:
783: sub random_uniform_integer {
784: my ($item_cnt,$seed,$low,$high) = @_;
785: my @oldseed=&random_get_seed();
786: my @retArray;
787: &random_set_seed_from_phrase($seed);
788: @retArray=&math_random_uniform_integer($item_cnt,$low,$high);
789: &random_set_seed(@oldseed);
790: return @retArray;
791: }
792:
793: sub random_binomial {
794: my ($item_cnt,$seed,$nt,$p) = @_;
795: my @oldseed=&random_get_seed();
796: my @retArray;
797: &random_set_seed_from_phrase($seed);
798: @retArray=&math_random_binomial($item_cnt,$nt,$p);
799: &random_set_seed(@oldseed);
800: return @retArray;
801: }
802:
803: sub random_negative_binomial {
804: my ($item_cnt,$seed,$ne,$p) = @_;
805: my @oldseed=&random_get_seed();
806: my @retArray;
807: &random_set_seed_from_phrase($seed);
808: @retArray=&math_random_negative_binomial($item_cnt,$ne,$p);
809: &random_set_seed(@oldseed);
810: return @retArray;
811: }
812:
813: sub abs { CORE::abs(shift) }
814: sub sin { CORE::sin(shift) }
815: sub cos { CORE::cos(shift) }
816: sub exp { CORE::exp(shift) }
817: sub int { CORE::int(shift) }
818: sub log { CORE::log(shift) }
819: sub ln { CORE::log(shift) }
820: sub atan2 { CORE::atan2($_[0],$_[1]) }
821: sub sqrt { CORE::sqrt(shift) }
822:
823: sub tan { CORE::sin($_[0]) / CORE::cos($_[0]) }
824: #sub atan { atan2($_[0], 1); }
825: #sub acos { atan2(sqrt(1 - $_[0] * $_[0]), $_[0] ); }
826: #sub asin { atan2($_[0], sqrt(1- $_[0] * $_[0]) ); }
827:
828: sub log10 { CORE::log($_[0])/CORE::log(10); }
829:
830: sub factorial {
831: my $input = CORE::int(shift);
832: return "Error - unable to take factorial of an negative number ($input)" if $input < 0;
833: return "Error - factorial result is greater than system limit ($input)" if $input > 170;
834: return 1 if $input == 0;
835: my $result = 1;
836: for (my $i=2; $i<=$input; $i++) { $result *= $i }
837: return $result;
838: }
839:
840: sub sgn {
841: return -1 if $_[0] < 0;
842: return 0 if $_[0] == 0;
843: return 1 if $_[0] > 0;
844: }
845:
846: sub min {
847: my @sorted = sort { $a <=> $b || $a cmp $b } @_;
848: return shift @sorted;
849: }
850:
851: sub max {
852: my @sorted = sort { $a <=> $b || $a cmp $b } @_;
853: return pop @sorted;
854: }
855:
856: sub roundto {
857: my ($input,$n) = @_;
858: return sprintf('%.'.$n.'f',$input);
859: }
860:
861: sub to_string {
862: my ($input,$n) = @_;
863: return sprintf($input) if $n eq "";
864: $n = '.'.$n if $n !~ /^\./;
865: return sprintf('%'.$n,$input) if $n ne "";
866: }
867:
868: sub sub_string {
869: my ($str,$start,$len) = @_;
870: return substr($str,$start-1,$len);
871: }
872:
873: sub pow {return $_[0] ** $_[1]; }
874: sub ceil {return (($_[0]-CORE::int($_[0]))== 0.0) ? $_[0] : (($_[0] > 0) ? (CORE::int($_[0])+ 1) : CORE::int($_[0])); }
875: sub floor {return (($_[0]-CORE::int($_[0]))== 0.0) ? $_[0] : (($_[0] > 0) ? CORE::int($_[0]) : (CORE::int($_[0])-1)); }
876: #sub floor {return int($_[0]); }
877:
878: sub format {
879: my ($value,$fmt)=@_;
880: my ($dollarmode,$commamode,$alwaysperiod,$options);
881: if ($fmt =~ /^([^\d]*)(.*)/) { $options=$1; $fmt=$2; }
882: #if ($options =~ /\$/) { $dollamode=1; }
883: #if ($options =~ /,/) { $commamode=1; }
884: if ($options =~ /\./) { $alwaysperiod=1; }
885: my $result;
886: if ($fmt=~/s$/i) {
887: $result=&format_significant_figures($value,$fmt);
888: } else {
889: $fmt=~s/e/E/g;
890: $result=sprintf('%.'.$fmt,$value);
891: if ($alwaysperiod && $fmt eq '0f') { $result .='.'; }
892: $result=~s/(E[+-]*)0/$1/;
893: }
894: #if ($dollarmode) {$result=&dollarformat($result);}
895: #if ($commamode) {$result=&commaformat($result);}
896: return $result;
897: }
898:
899: sub chemparse {
900: my ($reaction) = @_;
901: my @tokens = split(/(\s\+|\->|<=>|<\-|\.)/,$reaction);
902: my $formula = '';
903: foreach my $token (@tokens) {
904: if ($token eq '->' ) {
905: $formula .= '<m>\ensuremath{\rightarrow}</m> ';
906: next;
907: }
908: if ($token eq '<-' ) {
909: $formula .= '<m>\ensuremath{\leftarrow}</m> ';
910: next;
911: }
912: if ($token eq '<=>') {
913: if ($external::target eq 'web' &&
914: &EXT('request.browser.unicode')) {
915: $formula .= '⇌ ';
916: } else {
917: $formula .= &web('<=> ','<m>\ensuremath{\rightleftharpoons}</m> ',
918: '<=> ');
919: }
920: next;
921: }
922: if ($token eq '.') {
923: $formula =~ s/(\ \;| )$//;
924: $formula .= '·';
925: next;
926: }
927: $token =~ /^\s*([\d|\/]*(?:&frac\d\d)?)(.*)/;
928: $formula .= $1 if ($1 ne '1'); # stoichiometric coefficient
929:
930: my $molecule = $2;
931: # subscripts
932: $molecule =~ s|(?<=[a-zA-Z\)\]\s])(\d+)|<sub>$1</sub>|g;
933: # superscripts
934: $molecule =~ s|\^(\d*[+\-]*)|<sup>$1</sup>|g;
935: # strip whitespace
936: $molecule =~ s/\s*//g;
937: # forced space
938: $molecule =~ s/_/ /g;
939: $molecule =~ s/-/−/g;
940: $formula .= $molecule.' ';
941: }
942: # get rid of trailing space
943: $formula =~ s/(\ \;| )$//;
944: return &xmlparse($formula);
945: }
946:
947: sub prettyprint {
948: my ($value,$fmt,$target)=@_;
949: my $result;
950: if (!$target) { $target = $external::target; }
951: if ($fmt =~ /chem/i) { return(&chemparse($value)); }
952: my ($dollarmode,$commamode,$alwaysperiod,$options);
953: if ($fmt =~ /^([^\d]*)(.*)/) { $options=$1; $fmt=$2; }
954: if ($options =~ /\$/) { $dollarmode=1; }
955: if ($options =~ /,/) { $commamode=1; }
956: if ($options =~ /\./) { $alwaysperiod=1; }
957: if ($fmt=~/s$/i) {
958: $value=&format_significant_figures($value,$fmt);
959: } elsif ($fmt) {
960: $value=sprintf('%.'.$fmt,$value);
961: }
962: if ($alwaysperiod && $fmt eq '0f') {
963: if ($target eq 'tex') {
964: $value .='\\ensuremath{.}';
965: } else {
966: $value .='.';
967: }
968: }
969: if ($value =~ /([0-9\.\-\+]+)E([0-9\-\+]+)/i ) {
970: my $frac=$1;
971: if ($dollarmode) { $frac=&dollarformat($frac); }
972: if ($commamode) { $frac=&commaformat($frac); }
973: my $exponent=$2;
974: $exponent=~s/^\+0*//;
975: $exponent=~s/^-0*/-/;
976: $exponent=~s/^-0*/-/;
977: if ($exponent eq '-') { undef($exponent); }
978: if ($exponent) {
979: if ($target eq 'web') {
980: $result=$frac.'×10<sup>'.$exponent.'</sup>';
981: } elsif ($target eq 'tex') {
982: $result='\ensuremath{'.$frac.'\times 10^{'.$exponent.'}}';
983: } else {
984: $result=$value;
985: }
986: } else {
987: $result=$frac;
988: }
989: } else {
990: $result=$value;
991: if ($dollarmode) { $result=&dollarformat($result,$target); }
992: elsif ($commamode) { $result=&commaformat($result,$target); }
993: }
994: return $result;
995: }
996:
997: sub commaformat {
998: my ($number,$target) = @_;
999: if ($number =~ /\./) {
1000: while ($number =~ /([^0-9]*)([0-9]+)([^\.,][^\.,][^\.,])([,0-9]*\.[0-9]*)$/) {
1001: $number = $1.$2.','.$3.$4;
1002: }
1003: } else {
1004: while ($number =~ /^([^0-9]*)([0-9]+)([^,][^,][^,])([,0-9]*)$/) {
1005: $number = $1.$2.','.$3.$4;
1006: }
1007: }
1008: return $number;
1009: }
1010:
1011: sub dollarformat {
1012: my ($number,$target) = @_;
1013: if (!$target) { $target = $external::target; }
1014: $number=&commaformat($number,$target);
1015: if ($target eq 'tex') {
1016: $number='\$'.$number; #' stupid emacs
1017: } else {
1018: $number='$'.$number; #' stupid emacs
1019: }
1020: return $number;
1021: }
1022:
1023: # format of form ns or nS where n is an integer
1024: sub format_significant_figures {
1025: my ($number,$format) = @_;
1026: return '0' if ($number == 0);
1027: # extract number of significant figures needed
1028: my ($sig) = ($format =~ /(\d+)s/i);
1029: # arbitrary choice - suggestions ?? or throw error message?
1030: $sig = 3 if ($sig eq '');
1031: # save the minus sign
1032: my $sign = ($number < 0) ? '-' : '';
1033: $number = abs($number);
1034: # needed to correct for a number greater than 1 (or
1035: my $power = ($number < 1) ? 0 : 1;
1036: # could round up. Take the integer part of log10.
1037: my $x10 = int(log($number)/log(10));
1038: # find number with values left of decimal pt = # of sign figs.
1039: my $xsig = $number*10**($sig-$x10-$power);
1040: # get just digits left of decimal pt - also rounds off correctly
1041: my $xint = sprintf('%.0f',$xsig);
1042: # save any trailing zero's
1043: my ($zeros) = ($xint =~ /(0+)$/);
1044: # return number to original magnitude
1045: my $numSig = $xint*10**($x10-$sig+$power);
1046: if ($numSig =~ /^(\d+)\.(\d+)/) {
1047: # insert trailing zero's if have decimal point
1048: my @digarray = split('',$1.$2);
1049: my $sigcount;
1050: while (@digarray > 0) {
1051: my $item = shift(@digarray);
1052: if ($item) {
1053: $sigcount = 1 + @digarray;
1054: last;
1055: }
1056: }
1057: if (($sigcount) && ($sig >= $sigcount)) {
1058: $zeros = substr($zeros,0,($sig - $sigcount));
1059: }
1060: $numSig =~ s/^(\d+)\.(\d+)(\e?(.*)?)$/$1\.$2$zeros$3/;
1061: } else {
1062: if ($numSig =~ /^(\d+)e([\+\-]\d+)$/i) {
1063: my $pre_exp = $1;
1064: my $exponent = $2;
1065: $numSig = $pre_exp.'.'.$zeros.'E'.$exponent;
1066: } elsif ($numSig =~ /0$/) {
1067: # add decimal pt for number ending with 0 and length == # of sig figs
1068: if (length($numSig) == $sig) {
1069: $numSig.='.';
1070: } elsif (length($numSig) > $sig) {
1071: # exponential form for number ending with 0 and length > # of sig figs
1072: my $fmtsig = $sig-1;
1073: if ($fmtsig) {
1074: $numSig = sprintf('%.'.$fmtsig.'E',$numSig);
1075: }
1076: } elsif (length($numSig) < $sig) {
1077: $numSig.='.'.substr($zeros,0,($sig-length($numSig)));
1078: }
1079: } else {
1080: if (length($numSig) < $sig) {
1081: $numSig.='.'.substr($zeros,0,($sig-length($numSig)));
1082: }
1083: }
1084: }
1085: # return number with sign
1086: return $sign.$numSig;
1087: }
1088:
1089: sub map {
1090: my ($phrase,$dest,$source)=@_;
1091: my @oldseed=&random_get_seed();
1092: my @seed = &random_seed_from_phrase($phrase);
1093: &random_set_seed(@seed);
1094: my $destct = scalar(@$dest);
1095: if (!$source) {
1096: my @output;
1097: my @idx = &math_random_permuted_index($destct);
1098: my $ctr = 0;
1099: while ($ctr < $destct) {
1100: $output[$ctr] = $$dest[$idx[$ctr]];
1101: $ctr++;
1102: }
1103: &random_set_seed(@oldseed);
1104: return @output;
1105: } else {
1106: my $num = scalar(@$source);
1107: my @idx = &math_random_permuted_index($num);
1108: my $ctr = 0;
1109: my $tot = $num;
1110: $tot = $destct if $destct < $num;
1111: if (ref($$dest[0])) {
1112: while ($ctr < $tot) {
1113: ${$$dest[$ctr]} = $$source[$idx[$ctr]];
1114: $ctr++;
1115: }
1116: } else {
1117: while ($ctr < $tot) {
1118: $$dest[$ctr] = $$source[$idx[$ctr]];
1119: $ctr++;
1120: }
1121: }
1122: }
1123: &random_set_seed(@oldseed);
1124: return '';
1125: }
1126:
1127: sub rmap {
1128: my ($phrase,$dest,$source)=@_;
1129: my @oldseed=&random_get_seed();
1130: my @seed = &random_seed_from_phrase($phrase);
1131: &random_set_seed(@seed);
1132: my $destct = scalar(@$dest);
1133: if (!$source) {
1134: my @idx = &math_random_permuted_index($destct);
1135: my $ctr = 0;
1136: my @r_idx;
1137: while ($ctr < $destct) {
1138: $r_idx[$idx[$ctr]] = $ctr;
1139: $ctr++;
1140: }
1141: my @output;
1142: $ctr = 0;
1143: while ($ctr < $destct) {
1144: $output[$ctr] = $$dest[$r_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: my @r_idx;
1156: while ($ctr < $tot) {
1157: $r_idx[$idx[$ctr]] = $ctr;
1158: $ctr++;
1159: }
1160: $ctr = 0;
1161: if (ref($$dest[0])) {
1162: while ($ctr < $tot) {
1163: ${$$dest[$ctr]} = $$source[$r_idx[$ctr]];
1164: $ctr++;
1165: }
1166: } else {
1167: while ($ctr < $tot) {
1168: $$dest[$ctr] = $$source[$r_idx[$ctr]];
1169: $ctr++;
1170: }
1171: }
1172: }
1173: &random_set_seed(@oldseed);
1174: return '';
1175: }
1176:
1177: sub capa_id { return }
1178:
1179: sub problem { return }
1180:
1181: sub name{
1182: my $fullname = &EXT('environment.lastname').', '.&EXT('environment.firstname').' '.&EXT('environment.middlename');
1183: $fullname = "" if $fullname eq ", ";
1184: $fullname =~ s/\%2d/-/g;
1185: return $fullname;
1186: }
1187:
1188: sub student_number {
1189: my $id = &EXT('environment.id');
1190: $id = '' if $id eq "";
1191: return $id;
1192: }
1193:
1194: sub class {
1195: my $course = &EXT('course.description');
1196: $course = '' if $course eq "";
1197: return $course;
1198: }
1199:
1200: sub classid {
1201: my $courseid = &EXT('request.course.id');
1202: $courseid = '' if $courseid eq "";
1203: return $courseid;
1204: }
1205:
1206: sub firstname {
1207: my $firstname = &EXT('environment.firstname');
1208: $firstname = '' if $firstname eq "";
1209: return $firstname;
1210: }
1211:
1212: sub middlename {
1213: my $middlename = &EXT('environment.middlename');
1214: $middlename = '' if $middlename eq "";
1215: return $middlename;
1216: }
1217:
1218: sub lastname {
1219: my $lastname = &EXT('environment.lastname');
1220: $lastname = '' if $lastname eq "";
1221: return $lastname;
1222: }
1223:
1224: sub sec {
1225: my $sec = &EXT('request.course.sec');
1226: $sec = '' if $sec eq "";
1227: return $sec;
1228: }
1229:
1230: sub submission {
1231: my ($partid,$responseid,$subnumber,$encode,$cleanupnum)=@_;
1232: my $sub='';
1233: if ($subnumber) { $sub=$subnumber.':'; }
1234: my $output =
1235: &EXT('user.resource.'.$sub.'resource.'.$partid.'.'.$responseid.'.submission');
1236: if (ref($output) eq 'ARRAY') {
1237: my @items = @{$output};
1238: if ($encode) {
1239: @items = map { &encode_response($_); } @items;
1240: }
1241: if (ref($cleanupnum) eq 'HASH') {
1242: @items = map { &cleanup_numerical_response($cleanupnum,$_); } @items;
1243: }
1244: return \@items;
1245: } else {
1246: if ($encode) {
1247: $output = &encode_response($output);
1248: }
1249: if (ref($cleanupnum) eq 'HASH') {
1250: $output = &cleanup_numerical_response($cleanupnum,$output);
1251: }
1252: return $output;
1253: }
1254: }
1255:
1256: sub encode_response {
1257: my ($value) = @_;
1258: $value =~ s/&/&/g;
1259: $value =~ s/</</g;
1260: $value =~ s/>/>/g;
1261: $value =~ s/"/"/g;
1262: return $value;
1263: }
1264:
1265: sub cleanup_numerical_response {
1266: my ($cleanupnum,$value) = @_;
1267: if (ref($cleanupnum) eq 'HASH') {
1268: if ($cleanupnum->{exponent}) {
1269: if ($value =~ m{^(.*)[\*xX]\s*10\s*\^\s*(\+|\-)?\s*(\d+)(.*)$}) {
1270: my $pre_exp = $1;
1271: my $sign = $2;
1272: my $exponent = $3;
1273: my $post_exp = $4;
1274: if ($pre_exp !~ /\./) {
1275: $pre_exp .= '.';
1276: }
1277: if ($sign eq '') {
1278: $sign = '+';
1279: }
1280: $value = $pre_exp.'E'.$sign.$exponent.$post_exp;
1281: }
1282: }
1283: if ($cleanupnum->{comma}) {
1284: $value =~ s{(\d+),(\d+)}{$1$2};
1285: }
1286: if ($cleanupnum->{letterforzero}) {
1287: $value =~ s/^\s*o(\.\d+)/0$1/i;
1288: }
1289: if ($cleanupnum->{spaces}) {
1290: $value =~ s{^\s+|\s+$}{}g;
1291: if ($value =~ m{^(.*)\.\s+(\d+)(.*)$}) {
1292: my $pre_pt = $1;
1293: my $decimal = $2;
1294: my $post_dec = $3;
1295: $value = $pre_pt.'.'.$decimal.$post_dec;
1296: }
1297: }
1298: if ($cleanupnum->{format} =~ /^\d+s$/i) {
1299: $value = &format_significant_figures($value,$cleanupnum->{format});
1300: }
1301: }
1302: return $value;
1303: }
1304:
1305: sub currentpart {
1306: return $external::part;
1307: }
1308:
1309: sub eval_time {
1310: my ($timestamp)=@_;
1311: unless ($timestamp) { return ''; }
1312: return &locallocaltime($timestamp);
1313: }
1314:
1315: sub open_date {
1316: my ($partid)=@_;
1317: unless ($partid) { $partid=0; }
1318: return &eval_time(&EXT('resource.'.$partid.'.opendate'));
1319: }
1320:
1321: sub due_date {
1322: my ($partid)=@_;
1323: unless ($partid) { $partid=0; }
1324: return &eval_time(&EXT('resource.'.$partid.'.duedate'));
1325: }
1326:
1327: sub answer_date {
1328: my ($partid)=@_;
1329: unless ($partid) { $partid=0; }
1330: return &eval_time(&EXT('resource.'.$partid.'.answerdate'));
1331: }
1332:
1333: sub open_date_epoch {
1334: my ($partid)=@_;
1335: unless ($partid) { $partid=0; }
1336: return &EXT('resource.'.$partid.'.opendate');
1337: }
1338:
1339: sub due_date_epoch {
1340: my ($partid)=@_;
1341: unless ($partid) { $partid=0; }
1342: return &EXT('resource.'.$partid.'.duedate');
1343: }
1344:
1345: sub answer_date_epoch {
1346: my ($partid)=@_;
1347: unless ($partid) { $partid=0; }
1348: return &EXT('resource.'.$partid.'.answerdate');
1349: }
1350:
1351: sub parameter_setting {
1352: my ($which,$partid)=@_;
1353: unless ($partid) { $partid=0; }
1354: return &EXT('resource.'.$partid.'.'.$which);
1355: }
1356:
1357: sub stored_data {
1358: my ($which,$partid)=@_;
1359: unless ($partid) { $partid=0; }
1360: return &EXT('user.resource.resource.'.$partid.'.'.$which);
1361: }
1362:
1363: sub wrong_bubbles {
1364: my ($correct,$lower,$upper,$step,@given)=@_;
1365: my @array=();
1366: my %hash=();
1367: foreach my $new (@given) {
1368: $hash{$new}=1;
1369: }
1370: my $num=int(¶meter_setting('numbubbles',¤tpart()));
1371: unless ($num) { $num=8; }
1372: if ($num>1) {
1373: for (my $i=0;$i<=500;$i++) {
1374: my $new=&random($lower,$upper,$step);
1375: if ($hash{$new}) { next; }
1376: if (abs($new-$correct)<$step) { next; }
1377: $hash{$new}=1;
1378: @array=keys(%hash);
1379: if ($#array+2>=$num) { last; }
1380: }
1381: }
1382: return @array;
1383: }
1384:
1385: sub array_moments {
1386: my @input=@_;
1387: my (@output,$N);
1388: $N=scalar (@input);
1389: $output[0]=$N;
1390: if ($N <= 1) {
1391: $output[1]=$input[0];
1392: $output[1]="Input array not defined" if ($N == 0);
1393: $output[2]="variance undefined for N<=1";
1394: $output[3]="skewness undefined for N<=1";
1395: $output[4]="kurtosis undefined for N<=1";
1396: return @output;
1397: }
1398: my $sum=0;
1399: foreach my $line (@input) {
1400: $sum+=$line;
1401: }
1402: $output[1] = $sum/$N;
1403: my ($x,$sdev,$var,$skew,$kurt) = 0;
1404: foreach my $line (@input) {
1405: $x=$line-$output[1];
1406: $var+=$x**2;
1407: $skew+=$x**3;
1408: $kurt+=$x**4;
1409: }
1410: $output[2]=$var/($N-1);
1411: $sdev=CORE::sqrt($output[2]);
1412: if ($sdev == 0) {
1413: $output[3]="inf-variance=0";
1414: $output[4]="inf-variance=0";
1415: return @output;
1416: }
1417: $output[3]=$skew/($sdev**3*$N);
1418: $output[4]=$kurt/($sdev**4*$N)-3;
1419: return @output;
1420: }
1421:
1422: sub choose {
1423: my $num = $_[0];
1424: return $_[$num];
1425: }
1426:
1427: #&sum1(1,$x,sub { &sum1($_[0],2*$_[0], sub { fact($_[0])**2 })});
1428: #sub sum1 {
1429: # my ($start,$end,$sub)=@_;
1430: # my $sum=0;
1431: # for (my $i=$start;$i<=$end;$i++) {
1432: # $sum+=&$sub($i);
1433: # }
1434: # return $sum
1435: #}
1436:
1437: #&sum2('a',1,$x,'&sum2(\'b\',$a,2*$a, \'&factorial($b)**2\')');
1438: #sub sum2 {
1439: # my ($varname,$start,$end,$line)=@_;
1440: # my $sum=0;
1441: # for (my $i=$start;$i<=$end;$i++) {
1442: # my $func=sub {
1443: # eval("\$".$varname."=$i");
1444: # eval($line);
1445: # };
1446: # $sum+=&$func($i);
1447: # }
1448: # return $sum
1449: #}
1450:
1451: # expiremental idea
1452: sub proper_path {
1453: my ($path)=@_;
1454: if ( $external::target eq "tex" ) {
1455: return '/home/httpd/html'.$path;
1456: } else {
1457: return $path;
1458: }
1459: }
1460:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>