Annotation of loncom/homework/default_homework.lcpm, revision 1.111
1.42 albertel 1: # The LearningOnline Network with CAPA
1.1 harris41 2: # used by lonxml::xmlparse() as input variable $safeinit to Apache::run::run()
1.42 albertel 3: #
1.111 ! www 4: # $Id: default_homework.lcpm,v 1.110 2006/07/17 21:11:21 www Exp $
1.42 albertel 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: #
1.20 harris41 28: #
1.76 albertel 29:
1.25 albertel 30: #init some globals
1.38 albertel 31: $hidden::RANDOMINIT=0;
1.22 ng 32: $pi=atan2(1,1)*4;
33: $rad2deg=180.0/$pi;
34: $deg2rad=$pi/180.0;
1.44 matthew 35: $"=' ';
1.3 albertel 36:
1.91 albertel 37: sub check_commas {
38: my ($response)=@_;
39: #print("$response ");
40: my @numbers=split(',',$response);
41: #print(" numbers ".join('-',@numbers)." ");
42: if (scalar(@numbers) > 1) {
43: #print(" numbers[0] ".$numbers[0]." ");
44: if (length($numbers[0]) > 3 || length($numbers[0]) == 0) { return -1; }
45: shift(@numbers);
46: #print(" numbers ".scalar(@numbers)." ");
47: while (scalar(@numbers) > 1) {
48: #print(" numbers ".join('-',@numbers)." ");
49: if (length($numbers[0]) != 3) { return -2; }
50: shift(@numbers);
51: }
52: my ($number)=split('\.',$numbers[0]);
53: #print(" number ".$number." ");
54: #print(" numbers[0] ".$numbers[0]." ");
55: if (length($number) != 3) { return -3; }
56: } else {
57: my ($number)=split('\.',$numbers[0]);
58: if (length($number) > 3) { return -4; }
59: }
60: return 1;
61: }
62:
1.7 albertel 63: sub caparesponse_check {
1.74 albertel 64: my ($answer,$response)=@_;
1.73 albertel 65: #not properly used yet: calc
66: #not to be used: $ans_fmt
1.74 albertel 67: my $type=$LONCAPA::CAPAresponse_args{'type'};
68: my $tol=$LONCAPA::CAPAresponse_args{'tol'};
69: my $sig=$LONCAPA::CAPAresponse_args{'sig'};
1.88 albertel 70: my $ans_fmt=$LONCAPA::CAPAresponse_args{'format'};
1.74 albertel 71: my $unit=$LONCAPA::CAPAresponse_args{'unit'};
72: my $calc=$LONCAPA::CAPAresponse_args{'calc'};
73: my $samples=$LONCAPA::CAPAresponse_args{'samples'};
1.73 albertel 74:
75: my $tol_type=''; # gets it's value from whether tol has a % or not done
76: my $sig_lbound=''; #done
77: my $sig_ubound=''; #done
78:
79:
80: #type's definitons come from capaParser.h
81: my $message='';
82: #remove leading and trailing whitespace
83: if (!defined($response)) {
84: $response='';
85: }
86: if ($response=~ /^\s|\s$/) {
87: $response=~ s:^\s+|\s+$::g;
88: $message .="Removed ws now :$response:\n";
89: } else {
90: $message .="no ws in :$response:\n";
91: }
1.100 albertel 92: &LONCAPA_INTERNAL_DEBUG(" type is $type ");
93: if ($type eq 'cs' || $type eq 'ci') {
1.76 albertel 94: #for string answers make surec all places spaces occur, there is
95: #really only 1 space, in both the answer and the response
96: $answer=~s/ +/ /g;
97: $response=~s/ +/ /g;
1.100 albertel 98: } elsif ($type eq 'mc') {
99: $answer=~s/[\s,]//g;
100: $response=~s/[\s,]//g;
1.76 albertel 101: }
1.91 albertel 102: if ($type eq 'float' && $unit=~/\$/) {
1.88 albertel 103: if ($response!~/^\$/) { return "NO_UNIT: Missing \$ "; }
104: $response=~s/\$//g;
105: }
1.91 albertel 106: if ($type eq 'float' && $unit=~/\,/ && (&check_commas($response)<0)) {
107: return "COMMA_FAIL:";
108: }
1.88 albertel 109: $ans_fmt=~s/\W//g;
1.91 albertel 110: $unit=~s/[\$,]//g;
111: if ($type eq 'float') { $response=~s/,//g; }
1.88 albertel 112:
1.73 albertel 113: if (length($response) > 500) { return "TOO_LONG: Answer too long"; }
114:
115: if ($type eq '' ) {
1.74 albertel 116: $message .= "Didn't find a type :$type: defaulting\n";
1.73 albertel 117: if ( $answer eq ($answer *1.0)) { $type = 2;
118: } else { $type = 3; }
119: } else {
1.107 albertel 120: if ($type eq 'cs') { $type = 4; }
1.73 albertel 121: elsif ($type eq 'ci') { $type = 3 }
122: elsif ($type eq 'mc') { $type = 5; }
123: elsif ($type eq 'fml') { $type = 8; }
1.107 albertel 124: elsif ($type eq 'math') { $type = 9; }
1.73 albertel 125: elsif ($type eq 'subj') { $type = 7; }
126: elsif ($type eq 'float') { $type = 2; }
127: elsif ($type eq 'int') { $type = 1; }
128: else { return "ERROR: Unknown type of answer: $type" }
129: }
130:
131: my $points;
132: my $id_list;
133: #formula type setup the sample points
134: if ($type eq '8') {
135: ($id_list,$points)=split(/@/,$samples);
136: $message.="Found :$id_list:$points: points in $samples\n";
137: }
138: if ($tol eq '') {
139: $tol=0.0;
140: $tol_type=1; #TOL_ABSOLUTE
141: } else {
142: if ($tol =~ /%$/) {
143: chop $tol;
144: $tol_type=2; #TOL_PERCENTAGE
145: } else {
146: $tol_type=1; #TOL_ABSOLUTE
147: }
148: }
149:
1.85 albertel 150: ($sig_ubound,$sig_lbound)=&LONCAPA_INTERNAL_get_sigrange($sig);
151:
1.73 albertel 152: my $reterror="";
1.107 albertel 153: my $result;
154: if ($type eq '9') {
1.108 www 155: $result = &maxima_check(&maxima_cas_formula_fix($response),&maxima_cas_formula_fix($answer),\$reterror);
1.107 albertel 156: } else {
1.109 albertel 157: if ($type eq '8') { # fml type
158: $response = &capa_formula_fix($response);
159: $answer = &capa_formula_fix($answer);
160: }
161: $result = &caparesponse_capa_check_answer($response,$answer,$type,
1.73 albertel 162: $tol_type,$tol,
163: $sig_lbound,$sig_ubound,
164: $ans_fmt,$unit,$calc,$id_list,
165: $points,$external::randomseed,
166: \$reterror);
1.107 albertel 167: }
1.73 albertel 168: if ($result == '1') { $result='EXACT_ANS'; }
169: elsif ($result == '2') { $result='APPROX_ANS'; }
170: elsif ($result == '3') { $result='SIG_FAIL'; }
171: elsif ($result == '4') { $result='UNIT_FAIL'; }
172: elsif ($result == '5') { $result='NO_UNIT'; }
173: elsif ($result == '6') { $result='UNIT_OK'; }
174: elsif ($result == '7') { $result='INCORRECT'; }
175: elsif ($result == '8') { $result='UNIT_NOTNEEDED'; }
176: elsif ($result == '9') { $result='ANS_CNT_NOT_MATCH'; }
177: elsif ($result =='10') { $result='SUB_RECORDED'; }
178: elsif ($result =='11') { $result='BAD_FORMULA'; }
1.94 albertel 179: elsif ($result =='12' && !$response) { $result='MISSING_ANSWER'; }
180: elsif ($result =='12') { $result='WANTED_NUMERIC'; }
1.77 albertel 181: elsif ($result =='13') { $result='UNIT_INVALID_INSTRUCTOR'; }
182: elsif ($result =='141') { $result='UNIT_INVALID_STUDENT'; }
183: elsif ($result =='142') { $result='UNIT_INVALID_STUDENT'; }
184: elsif ($result =='143') { $result='UNIT_INVALID_STUDENT'; }
185: elsif ($result =='15') { $result='UNIT_IRRECONCIBLE'; }
1.73 albertel 186: else {$result = "ERROR: Unknown Result:$result:$@:";}
187:
1.82 albertel 188: return ("$result:\nRetError $reterror:\nAnswer $answer:\nResponse $response:\n type-$type|$tol|$tol_type|$sig:$sig_lbound:$sig_ubound|$unit|\n$message",$reterror);
1.37 albertel 189: }
190:
1.108 www 191: sub maxima_cas_formula_fix {
192: my ($expression)=@_;
193: return &implicit_multiplication($expression);
194: }
195:
196: sub capa_formula_fix {
197: my ($expression)=@_;
198: return &implicit_multiplication($expression);
199: }
200:
201: sub implicit_multiplication {
202: my ($expression)=@_;
1.111 ! www 203: # Escape scientific notation, so 3e8 does not become 3*e*8
! 204: # 3e8 -> 3&8; 3e-8 -> 3&-8; 3E+8 -> e&+8
1.110 www 205: $expression=~s/(\d+)e([\+\-]*\d+)/$1\&\($2\)/gsi;
1.111 ! www 206: # 3x10^8 -> 3&8; 3*10^-8 -> 3&-8
1.110 www 207: $expression=~s/(\d+)(?:x|\*)10(?:\^|\*\*)([\+\-]*\d+)/$1\&\($2\)/gsi;
1.111 ! www 208: # Fill in multiplication signs
! 209: # a b -> a*b
1.110 www 210: $expression=~s/\s+/\*/gs;
1.111 ! www 211: # 3a -> 3*a; 3( -> 3*(; 3A -> 3*a
1.110 www 212: $expression=~s/(\d)([a-zA-Z\(])/$1\*$2/gs;
1.111 ! www 213: # a3 -> a*3; )3 -> )*3
1.110 www 214: $expression=~s/([a-zA-Z])(\d)/$1\*$2/gs;
1.111 ! www 215: # )a -> )*a
1.110 www 216: $expression=~s/\)(\w)/\)\*$1/gs;
1.111 ! www 217: # 3&8 -> 3e8; 3&-4 -> 3e-4
1.110 www 218: $expression=~s/(\d+)\&\(([\+\-]*\d+)\)/$1e$2/gs;
1.108 www 219: return $expression;
220: }
1.73 albertel 221:
1.37 albertel 222: sub caparesponse_check_list {
1.74 albertel 223: my $response=$LONCAPA::CAPAresponse_args{'response'};
1.105 albertel 224: my $result="Got response :".join(':',@LONCAPA::CAPAresponse_answer).":\n";
225: &LONCAPA_INTERNAL_DEBUG("args ".join(':',%LONCAPA::CAPAresponse_args));
1.73 albertel 226: my @responselist;
1.74 albertel 227: my $type = $LONCAPA::CAPAresponse_args{'type'};
1.73 albertel 228: $result.="Got type :$type:\n";
1.105 albertel 229: if ($type ne '' && $#LONCAPA::CAPAresponse_answer > 0) {
1.104 albertel 230: (@responselist)=split(/,/,$response);
1.105 albertel 231: if (@responselist < @LONCAPA::CAPAresponse_answer) {
232: return 'MISSING_ANSWER';
233: }
234: if (@responselist > @LONCAPA::CAPAresponse_answer) {
235: return 'EXTRA_ANSWER';
236: }
1.73 albertel 237: } else {
238: (@responselist)=($response);
239: }
240: $result.="Initial final response :$responselist['-1']:\n";
1.105 albertel 241: my $unit;
1.73 albertel 242: if ($type eq '' || $type eq 'float') {
243: #for numerical problems split off the unit
244: if ( $responselist['-1']=~ /(.*[^\s])\s+([^\s]+)/ ) {
245: $responselist['-1']=$1;
246: $unit=$2;
247: }
248: }
1.82 albertel 249: $result.="Final final response :$responselist['-1']:$unit:\n";
1.73 albertel 250: $unit=~s/\s//;
1.105 albertel 251:
1.106 albertel 252: my ($awards, @msgs, $i);
1.105 albertel 253: foreach my $thisanswer (@LONCAPA::CAPAresponse_answer) {
254: my ($msg,$aresult);
1.73 albertel 255: $result.="trying answer :$thisanswer:\n";
1.105 albertel 256: if (defined($thisanswer)) {
1.104 albertel 257: if ($unit eq '') {
258: ($aresult,$msg)=&caparesponse_check($thisanswer,
259: $responselist[$i]);
260: } else {
261: ($aresult,$msg)=&caparesponse_check($thisanswer,
262: $responselist[$i]." $unit");
263: }
1.73 albertel 264: } else {
1.104 albertel 265: $aresult='ERROR';
1.105 albertel 266: $msg='answer was undefined';
1.73 albertel 267: }
1.105 albertel 268: &LONCAPA_INTERNAL_DEBUG("after if $aresult -- $msg");
1.104 albertel 269: my ($temp)=split(/:/, $aresult);
1.73 albertel 270: $awards.="$temp,";
271: $result.=$aresult;
272: push(@msgs,$msg);
1.106 albertel 273: $i++;
1.73 albertel 274: }
1.104 albertel 275: chop($awards);
1.73 albertel 276: return ("$awards:\n$result",@msgs);
1.7 albertel 277: }
278:
1.4 albertel 279: sub tex {
1.73 albertel 280: if ( $external::target eq "tex" ) {
281: return $_[0];
282: } else {
283: return $_[1];
284: }
1.4 albertel 285: }
286:
1.24 ng 287: sub var_in_tex {
1.73 albertel 288: if ( $external::target eq "tex" ) {
289: return $_[0];
290: } else {
291: return "";
292: }
1.24 ng 293: }
294:
1.4 albertel 295: sub web {
1.73 albertel 296: if ( $external::target eq "tex" ) {
297: return $_[1];
1.26 ng 298: } else {
1.73 albertel 299: if ( $external::target eq "web" || $external::target eq "answer") {
300: return $_[2];
301: } else {
302: return $_[0];
303: }
1.4 albertel 304: }
305: }
306:
1.24 ng 307: sub html {
1.73 albertel 308: if ( $external::target eq "web" ) {
309: return shift;
310: }
1.24 ng 311: }
312:
1.1 harris41 313: sub hinton {
1.73 albertel 314: return 0;
1.1 harris41 315: }
316:
317: sub random {
1.61 albertel 318: my ($start,$end,$step)=@_;
319: if ( ! $hidden::RANDOMINIT ) {
320: if ($external::randomseed == 0) { $external::randomseed=1; }
321: if ($external::randomseed =~/,/) {
1.84 albertel 322: my ($num1,$num2)=split(/,/,$external::randomseed);
323: &random_set_seed(1,abs($num1));
324: } elsif ($external::randomseed =~/:/) {
325: my ($num1,$num2)=split(/:/,$external::randomseed);
1.61 albertel 326: &random_set_seed(abs($num1),abs($num2));
327: } else {
328: &random_set_seed(1,int(abs($external::randomseed)));
329: }
330: &math_random_uniform();
331: $hidden::RANDOMINIT=1;
332: }
333: if (!defined($step)) { $step=1; }
334: my $num=1+int(($end-$start)/$step);
335: my $result=$start + int(&math_random_uniform() * $num)*$step;
336: return $result;
1.1 harris41 337: }
338:
1.26 ng 339: sub random_normal {
1.73 albertel 340: my ($item_cnt,$seed,$av,$std_dev) = @_;
341: my @oldseed=&random_get_seed();
342: my @retArray;
343: &random_set_seed_from_phrase($seed);
344: @retArray=&math_random_normal($item_cnt,$av,$std_dev);
345: &random_set_seed(@oldseed);
346: return @retArray;
1.26 ng 347: }
348:
349: sub random_beta {
1.73 albertel 350: my ($item_cnt,$seed,$aa,$bb) = @_;
351: my @oldseed=&random_get_seed();
352: my @retArray;
353: &random_set_seed_from_phrase($seed);
354: @retArray=&math_random_beta($item_cnt,$aa,$bb);
355: &random_set_seed(@oldseed);
356: return @retArray;
1.26 ng 357: }
358:
359: sub random_gamma {
1.73 albertel 360: my ($item_cnt,$seed,$a,$r) = @_;
361: my @oldseed=&random_get_seed();
362: my @retArray;
363: &random_set_seed_from_phrase($seed);
364: @retArray=&math_random_gamma($item_cnt,$a,$r);
365: &random_set_seed(@oldseed);
366: return @retArray;
1.26 ng 367: }
368:
369: sub random_exponential {
1.73 albertel 370: my ($item_cnt,$seed,$av) = @_;
371: my @oldseed=&random_get_seed();
372: my @retArray;
373: &random_set_seed_from_phrase($seed);
374: @retArray=&math_random_exponential($item_cnt,$av);
375: &random_set_seed(@oldseed);
376: return @retArray;
1.26 ng 377: }
378:
379: sub random_poisson {
1.73 albertel 380: my ($item_cnt,$seed,$mu) = @_;
381: my @oldseed=&random_get_seed();
382: my @retArray;
383: &random_set_seed_from_phrase($seed);
384: @retArray=&math_random_poisson($item_cnt,$mu);
385: &random_set_seed(@oldseed);
386: return @retArray;
1.26 ng 387: }
388:
389: sub random_chi {
1.73 albertel 390: my ($item_cnt,$seed,$df) = @_;
391: my @oldseed=&random_get_seed();
392: my @retArray;
393: &random_set_seed_from_phrase($seed);
394: @retArray=&math_random_chi_square($item_cnt,$df);
395: &random_set_seed(@oldseed);
396: return @retArray;
1.26 ng 397: }
398:
399: sub random_noncentral_chi {
1.73 albertel 400: my ($item_cnt,$seed,$df,$nonc) = @_;
401: my @oldseed=&random_get_seed();
402: my @retArray;
403: &random_set_seed_from_phrase($seed);
404: @retArray=&math_random_noncentral_chi_square($item_cnt,$df,$nonc);
405: &random_set_seed(@oldseed);
406: return @retArray;
1.26 ng 407: }
408:
409: sub random_f {
1.73 albertel 410: my ($item_cnt,$seed,$dfn,$dfd) = @_;
411: my @oldseed=&random_get_seed();
412: my @retArray;
413: &random_set_seed_from_phrase($seed);
414: @retArray=&math_random_f($item_cnt,$dfn,$dfd);
415: &random_set_seed(@oldseed);
416: return @retArray;
1.26 ng 417: }
418:
419: sub random_noncentral_f {
1.73 albertel 420: my ($item_cnt,$seed,$dfn,$dfd,$nonc) = @_;
421: my @oldseed=&random_get_seed();
422: my @retArray;
423: &random_set_seed_from_phrase($seed);
424: @retArray=&math_random_noncentral_f($item_cnt,$dfn,$dfd,$nonc);
425: &random_set_seed(@oldseed);
426: return @retArray;
1.26 ng 427: }
428:
429: sub random_multivariate_normal {
1.73 albertel 430: my ($item_cnt,$seed,$mean,$covar) = @_;
431: my @oldseed=&random_get_seed();
432: &random_set_seed_from_phrase($seed);
1.87 albertel 433: my @retArray=&math_random_multivariate_normal($item_cnt,@$mean,@$covar);
1.73 albertel 434: &random_set_seed(@oldseed);
435: return @retArray;
1.26 ng 436: }
437:
438: sub random_multinomial {
1.73 albertel 439: my ($item_cnt,$seed,@p) = @_;
440: my @oldseed=&random_get_seed();
441: my @retArray;
442: &random_set_seed_from_phrase($seed);
1.87 albertel 443: my @retArray=&math_random_multinomial($item_cnt,@p);
1.73 albertel 444: &random_set_seed(@oldseed);
445: return @retArray;
1.26 ng 446: }
447:
448: sub random_permutation {
1.73 albertel 449: my ($seed,@inArray) = @_;
450: my @oldseed=&random_get_seed();
451: my @retArray;
452: &random_set_seed_from_phrase($seed);
453: @retArray=&math_random_permutation(@inArray);
454: &random_set_seed(@oldseed);
455: return @retArray;
1.26 ng 456: }
457:
458: sub random_uniform {
1.73 albertel 459: my ($item_cnt,$seed,$low,$high) = @_;
460: my @oldseed=&random_get_seed();
461: my @retArray;
462: &random_set_seed_from_phrase($seed);
463: @retArray=&math_random_uniform($item_cnt,$low,$high);
464: &random_set_seed(@oldseed);
465: return @retArray;
1.26 ng 466: }
467:
468: sub random_uniform_integer {
1.73 albertel 469: my ($item_cnt,$seed,$low,$high) = @_;
470: my @oldseed=&random_get_seed();
471: my @retArray;
472: &random_set_seed_from_phrase($seed);
473: @retArray=&math_random_uniform_integer($item_cnt,$low,$high);
474: &random_set_seed(@oldseed);
475: return @retArray;
1.26 ng 476: }
477:
478: sub random_binomial {
1.73 albertel 479: my ($item_cnt,$seed,$nt,$p) = @_;
480: my @oldseed=&random_get_seed();
481: my @retArray;
482: &random_set_seed_from_phrase($seed);
483: @retArray=&math_random_binomial($item_cnt,$nt,$p);
484: &random_set_seed(@oldseed);
485: return @retArray;
1.26 ng 486: }
487:
488: sub random_negative_binomial {
1.73 albertel 489: my ($item_cnt,$seed,$ne,$p) = @_;
490: my @oldseed=&random_get_seed();
491: my @retArray;
492: &random_set_seed_from_phrase($seed);
493: @retArray=&math_random_negative_binomial($item_cnt,$ne,$p);
494: &random_set_seed(@oldseed);
495: return @retArray;
1.26 ng 496: }
497:
1.103 albertel 498: sub abs { CORE::abs(shift) }
499: sub sin { CORE::sin(shift) }
500: sub cos { CORE::cos(shift) }
501: sub exp { CORE::exp(shift) }
502: sub int { CORE::int(shift) }
503: sub log { CORE::log(shift) }
504: sub atan2 { CORE::atan2($_[0],$_[1]) }
505: sub sqrt { CORE::sqrt(shift) }
1.23 ng 506:
1.59 albertel 507: sub tan { CORE::sin($_[0]) / CORE::cos($_[0]) }
1.21 harris41 508: #sub atan { atan2($_[0], 1); }
509: #sub acos { atan2(sqrt(1 - $_[0] * $_[0]), $_[0] ); }
510: #sub asin { atan2($_[0], sqrt(1- $_[0] * $_[0]) ); }
1.22 ng 511:
1.59 albertel 512: sub log10 { CORE::log($_[0])/CORE::log(10); }
1.22 ng 513:
1.20 harris41 514: sub factorial {
1.59 albertel 515: my $input = CORE::int(shift);
1.20 harris41 516: return "Error - unable to take factorial of an negative number ($input)" if $input < 0;
517: return "Error - factorial result is greater than system limit ($input)" if $input > 170;
518: return 1 if $input == 0;
519: my $result = 1;
520: for (my $i=2; $i<=$input; $i++) { $result *= $i }
521: return $result;
522: }
523:
524: sub sgn {
525: return -1 if $_[0] < 0;
526: return 0 if $_[0] == 0;
527: return 1 if $_[0] > 0;
528: }
529:
530: sub min {
531: my @sorted = sort { $a <=> $b || $a cmp $b } @_;
532: return shift @sorted;
533: }
534:
535: sub max {
536: my @sorted = sort { $a <=> $b || $a cmp $b } @_;
537: return pop @sorted;
538: }
1.1 harris41 539:
1.20 harris41 540: sub roundto {
541: my ($input,$n) = @_;
542: return sprintf('%.'.$n.'f',$input);
543: }
544:
545: sub to_string {
546: my ($input,$n) = @_;
1.26 ng 547: return sprintf($input) if $n eq "";
548: $n = '.'.$n if $n !~ /^\./;
1.20 harris41 549: return sprintf('%'.$n,$input) if $n ne "";
550: }
551:
552: sub sub_string {
553: my ($str,$start,$len) = @_;
554: return substr($str,$start-1,$len);
555: }
1.1 harris41 556:
557: sub pow {return $_[0] ** $_[1]; }
1.59 albertel 558: sub ceil {return (($_[0]-CORE::int($_[0]))== 0.0) ? $_[0] : (($_[0] > 0) ? (CORE::int($_[0])+ 1) : CORE::int($_[0])); }
559: sub floor {return (($_[0]-CORE::int($_[0]))== 0.0) ? $_[0] : (($_[0] > 0) ? CORE::int($_[0]) : (CORE::int($_[0])-1)); }
1.27 ng 560: #sub floor {return int($_[0]); }
1.1 harris41 561:
1.2 albertel 562: sub format {
1.73 albertel 563: my ($value,$fmt)=@_;
1.81 albertel 564: my ($dollarmode,$commamode,$alwaysperiod,$options);
565: if ($fmt =~ /^([^\d]*)(.*)/) { $options=$1; $fmt=$2; }
566: #if ($options =~ /\$/) { $dollamode=1; }
567: #if ($options =~ /,/) { $commamode=1; }
1.82 albertel 568: if ($options =~ /\./) { $alwaysperiod=1; }
1.99 ng 569: my $result;
1.97 albertel 570: if ($fmt=~/s$/i) {
571: $result=&format_significant_figures($value,$fmt);
572: } else {
573: $fmt=~s/e/E/g;
1.99 ng 574: $result=sprintf('%.'.$fmt,$value);
1.97 albertel 575: if ($alwaysperiod && $fmt eq '0f') { $result .='.'; }
576: $result=~s/(E[+-]*)0/$1/;
577: }
1.81 albertel 578: #if ($dollarmode) {$result=&dollarformat($result);}
579: #if ($commamode) {$result=&commaformat($result);}
1.73 albertel 580: return $result;
1.46 albertel 581: }
582:
1.75 albertel 583: sub chemparse {
584: my ($reaction) = @_;
1.96 albertel 585: my @tokens = split(/(\s\+|\->|<=>|<\-|\.)/,$reaction);
1.75 albertel 586: my $formula = '';
587: foreach my $token (@tokens) {
588: if ($token eq '->' ) {
589: $formula .= '<m>\ensuremath{\rightarrow}</m> ';
590: next;
591: }
1.96 albertel 592: if ($token eq '<-' ) {
593: $formula .= '<m>\ensuremath{\leftarrow}</m> ';
594: next;
595: }
1.75 albertel 596: if ($token eq '<=>') {
597: if ($external::target eq 'web' &&
598: &EXT('request.browser.unicode')) {
1.76 albertel 599: $formula .= '⇌ ';
1.75 albertel 600: } else {
601: $formula .= &web('<=> ','<m>\ensuremath{\rightleftharpoons}</m> ',
1.95 albertel 602: '<=> ');
1.75 albertel 603: }
604: next;
605: }
1.96 albertel 606: if ($token eq '.') {
607: $formula =~ s/(\ \;| )$//;
608: $formula .= '·';
609: next;
610: }
611: $token =~ /^\s*([\d|\/]*(?:&frac\d\d)?)(.*)/;
1.90 albertel 612: $formula .= $1 if ($1 ne '1'); # stoichiometric coefficient
1.75 albertel 613:
614: my $molecule = $2;
615: # subscripts
1.78 albertel 616: $molecule =~ s|(?<=[a-zA-Z\)\]\s])(\d+)|<sub>$1</sub>|g;
1.75 albertel 617: # superscripts
618: $molecule =~ s|\^(\d*[+\-]*)|<sup>$1</sup>|g;
619: # strip whitespace
620: $molecule =~ s/\s*//g;
621: # forced space
622: $molecule =~ s/_/ /g;
1.96 albertel 623: $molecule =~ s/-/−/g;
1.75 albertel 624: $formula .= $molecule.' ';
625: }
626: # get rid of trailing space
1.87 albertel 627: $formula =~ s/(\ \;| )$//;
1.75 albertel 628: return &xmlparse($formula);
629: }
630:
1.46 albertel 631: sub prettyprint {
1.73 albertel 632: my ($value,$fmt,$target)=@_;
633: my $result;
634: if (!$target) { $target = $external::target; }
1.75 albertel 635: if ($fmt =~ /chem/i) { return(&chemparse($value)); }
1.81 albertel 636: my ($dollarmode,$commamode,$alwaysperiod,$options);
637: if ($fmt =~ /^([^\d]*)(.*)/) { $options=$1; $fmt=$2; }
1.86 albertel 638: if ($options =~ /\$/) { $dollarmode=1; }
1.81 albertel 639: if ($options =~ /,/) { $commamode=1; }
640: if ($options =~ /\./) { $alwaysperiod=1; }
1.97 albertel 641: if ($fmt=~/s$/i) {
642: $value=&format_significant_figures($value,$fmt);
643: } elsif ($fmt) {
644: $value=sprintf('%.'.$fmt,$value);
645: }
1.81 albertel 646: if ($alwaysperiod && $fmt eq '0f') {
647: if ($target eq 'tex') {
648: $value .='\\ensuremath{.}';
649: } else {
650: $value .='.';
651: }
652: }
1.73 albertel 653: if ($value =~ /([0-9\.\-\+]+)E([0-9\-\+]+)/i ) {
654: my $frac=$1;
655: if ($dollarmode) { $frac=&dollarformat($frac); }
1.80 albertel 656: if ($commamode) { $frac=&commaformat($frac); }
1.73 albertel 657: my $exponent=$2;
658: $exponent=~s/^\+0*//;
659: $exponent=~s/^-0*/-/;
660: $exponent=~s/^-0*/-/;
661: if ($exponent eq '-') { undef($exponent); }
662: if ($exponent) {
663: if ($target eq 'web') {
664: $result=$frac.'×10<sup>'.$exponent.'</sup>';
665: } elsif ($target eq 'tex') {
666: $result='\ensuremath{'.$frac.'\times 10^{'.$exponent.'}}';
667: } else {
668: $result=$value;
669: }
670: } else {
671: $result=$frac;
672: }
673: } else {
1.48 albertel 674: $result=$value;
1.86 albertel 675: if ($dollarmode) { $result=&dollarformat($result,$target); }
676: elsif ($commamode) { $result=&commaformat($result,$target); }
1.46 albertel 677: }
1.73 albertel 678: return $result;
1.48 albertel 679: }
680:
1.80 albertel 681: sub commaformat {
1.73 albertel 682: my ($number,$target) = @_;
683: if ($number =~ /\./) {
1.102 albertel 684: while ($number =~ /([^0-9]*)([0-9]+)([^\.,][^\.,][^\.,])([,0-9]*\.[0-9]*)$/) {
685: $number = $1.$2.','.$3.$4;
1.73 albertel 686: }
687: } else {
1.102 albertel 688: while ($number =~ /^([^0-9]*)([0-9]+)([^,][^,][^,])([,0-9]*)$/) {
689: $number = $1.$2.','.$3.$4;
1.73 albertel 690: }
691: }
1.80 albertel 692: return $number;
693: }
694:
695: sub dollarformat {
696: my ($number,$target) = @_;
697: if (!$target) { $target = $external::target; }
698: $number=&commaformat($number,$target);
1.73 albertel 699: if ($target eq 'tex') {
700: $number='\$'.$number; #' stupid emacs
701: } else {
702: $number='$'.$number; #' stupid emacs
703: }
704: return $number;
1.2 albertel 705: }
1.5 albertel 706:
1.97 albertel 707: # format of form ns or nS where n is an integer
708: sub format_significant_figures {
709: my ($number,$format) = @_;
710: return '0' if ($number == 0);
711: # extract number of significant figures needed
712: my ($sig) = ($format =~ /(\d+)s/i);
713: # arbitrary choice - suggestions ?? or throw error message?
714: $sig = 3 if ($sig eq '');
715: # save the minus sign
716: my $sign = ($number < 0) ? '-' : '';
717: $number = abs($number);
718: # needed to correct for a number greater than 1 (or
719: my $power = ($number < 1) ? 0 : 1;
720: # could round up. Take the integer part of log10.
721: my $x10 = int(log($number)/log(10));
722: # find number with values left of decimal pt = # of sign figs.
723: my $xsig = $number*10**($sig-$x10-$power);
724: # get just digits left of decimal pt - also rounds off correctly
725: my $xint = sprintf('%.0f',$xsig);
726: # save any trailing zero's
727: my ($zeros) = ($xint =~ /(0+)$/);
728: # return number to original magnitude
729: my $numSig = $xint*10**($x10-$sig+$power);
730: # insert trailing zero's if have decimal point
731: $numSig =~ s/^(\d+)\.(\d+)(\e?(.*)?)$/$1\.$2$zeros$3/;
1.98 albertel 732: # put a decimal pt for number ending with 0 and length = # of sig fig
733: $numSig.='.' if (length($numSig) == $sig && $numSig =~ /0$/);
734: if (length($numSig) < $sig) {
735: $numSig.='.'.substr($zeros,0,($sig-length($numSig)));
736: }
1.97 albertel 737: # return number with sign
738: return $sign.$numSig;
739:
740: }
741:
1.5 albertel 742: sub map {
1.27 ng 743: my ($phrase,$dest,$source)=@_;
1.51 albertel 744: my @oldseed=&random_get_seed();
1.27 ng 745: my @seed = &random_seed_from_phrase($phrase);
746: &random_set_seed(@seed);
747: my $destct = scalar(@$dest);
1.28 ng 748: if (!$source) {
749: my @output;
750: my @idx = &math_random_permuted_index($destct);
751: my $ctr = 0;
752: while ($ctr < $destct) {
753: $output[$ctr] = $$dest[$idx[$ctr]];
1.27 ng 754: $ctr++;
1.28 ng 755: }
1.51 albertel 756: &random_set_seed(@oldseed);
1.28 ng 757: return @output;
1.27 ng 758: } else {
1.28 ng 759: my $num = scalar(@$source);
760: my @idx = &math_random_permuted_index($num);
761: my $ctr = 0;
762: my $tot = $num;
763: $tot = $destct if $destct < $num;
764: if (ref($$dest[0])) {
765: while ($ctr < $tot) {
766: ${$$dest[$ctr]} = $$source[$idx[$ctr]];
767: $ctr++;
768: }
769: } else {
770: while ($ctr < $tot) {
771: $$dest[$ctr] = $$source[$idx[$ctr]];
772: $ctr++;
773: }
774: }
1.27 ng 775: }
1.56 albertel 776: &random_set_seed(@oldseed);
1.51 albertel 777: return '';
1.27 ng 778: }
779:
780: sub rmap {
781: my ($phrase,$dest,$source)=@_;
1.51 albertel 782: my @oldseed=&random_get_seed();
1.27 ng 783: my @seed = &random_seed_from_phrase($phrase);
784: &random_set_seed(@seed);
785: my $destct = scalar(@$dest);
1.28 ng 786: if (!$source) {
787: my @idx = &math_random_permuted_index($destct);
788: my $ctr = 0;
789: my @r_idx;
790: while ($ctr < $destct) {
791: $r_idx[$idx[$ctr]] = $ctr;
792: $ctr++;
793: }
794: my @output;
795: $ctr = 0;
796: while ($ctr < $destct) {
797: $output[$ctr] = $$dest[$r_idx[$ctr]];
1.27 ng 798: $ctr++;
1.28 ng 799: }
1.51 albertel 800: &random_set_seed(@oldseed);
1.28 ng 801: return @output;
1.27 ng 802: } else {
1.28 ng 803: my $num = scalar(@$source);
804: my @idx = &math_random_permuted_index($num);
805: my $ctr = 0;
806: my $tot = $num;
807: $tot = $destct if $destct < $num;
808: my @r_idx;
1.27 ng 809: while ($ctr < $tot) {
1.28 ng 810: $r_idx[$idx[$ctr]] = $ctr;
1.27 ng 811: $ctr++;
1.28 ng 812: }
813: $ctr = 0;
814: if (ref($$dest[0])) {
815: while ($ctr < $tot) {
816: ${$$dest[$ctr]} = $$source[$r_idx[$ctr]];
817: $ctr++;
818: }
819: } else {
820: while ($ctr < $tot) {
821: $$dest[$ctr] = $$source[$r_idx[$ctr]];
822: $ctr++;
823: }
824: }
1.6 albertel 825: }
1.51 albertel 826: &random_set_seed(@oldseed);
827: return '';
1.5 albertel 828: }
1.22 ng 829:
1.23 ng 830: sub capa_id { return }
831:
832: sub problem { return }
833:
1.22 ng 834: sub name{
1.73 albertel 835: my $fullname = &EXT('environment.lastname').', '.&EXT('environment.firstname').' '.&EXT('environment.middlename');
836: $fullname = "" if $fullname eq ", ";
837: $fullname =~ s/\%2d/-/g;
838: return $fullname;
1.22 ng 839: }
840:
841: sub student_number {
1.73 albertel 842: my $id = &EXT('environment.id');
843: $id = '' if $id eq "";
844: return $id;
1.22 ng 845: }
846:
847: sub class {
1.73 albertel 848: my $course = &EXT('course.description');
849: $course = '' if $course eq "";
850: return $course;
1.22 ng 851: }
852:
853: sub sec {
1.73 albertel 854: my $sec = &EXT('request.course.sec');
855: $sec = '' if $sec eq "";
856: return $sec;
1.22 ng 857: }
858:
1.23 ng 859: sub open_date {
1.73 albertel 860: my @dc = split(/\s+/,localtime(&EXT('resource.0.opendate')));
861: return '' if ($dc[0] eq "Wed" and $dc[2] == 31 and $dc[4] == 1969);
862: my @hm = split(/:/,$dc[3]);
863: my $ampm = " am";
864: if ($hm[0] > 12) {
865: $hm[0]-=12;
866: $ampm = " pm";
867: }
868: return $dc[0].', '.$dc[1].' '.$dc[2].', '.$dc[4].' at '.$hm[0].':'.$hm[1].$ampm;
1.23 ng 869: }
870:
871: sub due_date {
1.73 albertel 872: my @dc = split(/\s+/,localtime(&EXT('resource.0.duedate')));
873: return '' if ($dc[0] eq "Wed" and $dc[2] == 31 and $dc[4] == 1969);
874: my @hm = split(/:/,$dc[3]);
875: my $ampm = " am";
876: if ($hm[0] > 12) {
877: $hm[0]-=12;
878: $ampm = " pm";
879: }
880: return $dc[0].', '.$dc[1].' '.$dc[2].', '.$dc[4].' at '.$hm[0].':'.$hm[1].$ampm;
1.23 ng 881: }
882:
883: sub answer_date {
1.73 albertel 884: my @dc = split(/\s+/,localtime(&EXT('resource.0.answerdate')));
885: return '' if ($dc[0] eq "Wed" and $dc[2] == 31 and $dc[4] == 1969);
886: my @hm = split(/:/,$dc[3]);
887: my $ampm = " am";
888: if ($hm[0] > 12) {
889: $hm[0]-=12;
890: $ampm = " pm";
891: }
892: return $dc[0].', '.$dc[1].' '.$dc[2].', '.$dc[4].' at '.$hm[0].':'.$hm[1].$ampm;
1.24 ng 893: }
894:
895: sub array_moments {
1.73 albertel 896: my @input=@_;
897: my (@output,$N);
898: $N=scalar (@input);
899: $output[0]=$N;
900: if ($N <= 1) {
901: $output[1]=$input[0];
902: $output[1]="Input array not defined" if ($N == 0);
903: $output[2]="variance undefined for N<=1";
904: $output[3]="skewness undefined for N<=1";
905: $output[4]="kurtosis undefined for N<=1";
906: return @output;
907: }
908: my $sum=0;
909: foreach my $line (@input) {
910: $sum+=$line;
911: }
912: $output[1] = $sum/$N;
913: my ($x,$sdev,$var,$skew,$kurt) = 0;
914: foreach my $line (@input) {
915: $x=$line-$output[1];
916: $var+=$x**2;
917: $skew+=$x**3;
918: $kurt+=$x**4;
919: }
920: $output[2]=$var/($N-1);
921: $sdev=CORE::sqrt($output[2]);
922: if ($sdev == 0) {
923: $output[3]="inf-variance=0";
924: $output[4]="inf-variance=0";
925: return @output;
926: }
927: $output[3]=$skew/($sdev**3*$N);
928: $output[4]=$kurt/($sdev**4*$N)-3;
1.24 ng 929: return @output;
930: }
1.5 albertel 931:
932: sub choose {
1.73 albertel 933: my $num = $_[0];
934: return $_[$num];
1.5 albertel 935: }
1.23 ng 936:
1.101 albertel 937: #&sum1(1,$x,sub { &sum1($_[0],2*$_[0], sub { fact($_[0])**2 })});
938: #sub sum1 {
939: # my ($start,$end,$sub)=@_;
940: # my $sum=0;
941: # for (my $i=$start;$i<=$end;$i++) {
942: # $sum+=&$sub($i);
943: # }
944: # return $sum
945: #}
946:
947: #&sum2('a',1,$x,'&sum2(\'b\',$a,2*$a, \'&factorial($b)**2\')');
948: #sub sum2 {
949: # my ($varname,$start,$end,$line)=@_;
950: # my $sum=0;
951: # for (my $i=$start;$i<=$end;$i++) {
952: # my $func=sub {
953: # eval("\$".$varname."=$i");
954: # eval($line);
955: # };
956: # $sum+=&$func($i);
957: # }
958: # return $sum
959: #}
960:
1.49 albertel 961: # expiremental idea
962: sub proper_path {
1.73 albertel 963: my ($path)=@_;
964: if ( $external::target eq "tex" ) {
965: return '/home/httpd/html'.$path;
966: } else {
967: return $path;
968: }
1.49 albertel 969: }
1.23 ng 970:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>