Annotation of loncom/homework/default_homework.lcpm, revision 1.152.2.1

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.152.2.1! raeburn     4: # $Id: default_homework.lcpm,v 1.152 2011/02/26 17:50:13 raeburn 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.116     albertel   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--;
1.117     albertel   61: 	    return \@order;
1.116     albertel   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--;
1.117     albertel   95: 	return(\@order);
1.116     albertel   96:     }
                     97:     
                     98:     sub get_permutations_left {
                     99: 	return $num_left;
                    100:     }
                    101: }
1.3       albertel  102: 
1.91      albertel  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: 
1.117     albertel  129: 
1.7       albertel  130: sub caparesponse_check {
1.74      albertel  131:     my ($answer,$response)=@_;
1.73      albertel  132:     #not properly used yet: calc
                    133:     #not to be used: $ans_fmt
1.74      albertel  134:     my $type=$LONCAPA::CAPAresponse_args{'type'};
                    135:     my $tol=$LONCAPA::CAPAresponse_args{'tol'};
                    136:     my $sig=$LONCAPA::CAPAresponse_args{'sig'};
1.88      albertel  137:     my $ans_fmt=$LONCAPA::CAPAresponse_args{'format'};
1.74      albertel  138:     my $unit=$LONCAPA::CAPAresponse_args{'unit'};
                    139:     my $calc=$LONCAPA::CAPAresponse_args{'calc'};
                    140:     my $samples=$LONCAPA::CAPAresponse_args{'samples'};
1.73      albertel  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: 
                    147:     #type's definitons come from capaParser.h
1.116     albertel  148: 
1.73      albertel  149:     #remove leading and trailing whitespace
                    150:     if (!defined($response)) {
                    151: 	$response='';
                    152:     }
                    153:     if ($response=~ /^\s|\s$/) {
                    154: 	$response=~ s:^\s+|\s+$::g;
1.119     albertel  155: 	&LONCAPA_INTERNAL_DEBUG("Removed ws now :$response:");
1.73      albertel  156:     }
1.116     albertel  157: 
1.117     albertel  158:     #&LONCAPA_INTERNAL_DEBUG(" type is $type ");
1.100     albertel  159:     if ($type eq 'cs' || $type eq 'ci') {
1.130     www       160: 	#for string answers make sure all places spaces occur, there is 
1.76      albertel  161:         #really only 1 space, in both the answer and the response
                    162: 	$answer=~s/ +/ /g;
                    163: 	$response=~s/ +/ /g;
1.100     albertel  164:     } elsif ($type eq 'mc') {
                    165: 	$answer=~s/[\s,]//g;
                    166: 	$response=~s/[\s,]//g;
1.76      albertel  167:     }
1.91      albertel  168:     if ($type eq 'float' && $unit=~/\$/) {
1.126     www       169: 	if ($response!~/^\$|\$$/)  { return ('NO_UNIT', undef); }
1.88      albertel  170: 	$response=~s/\$//g;
                    171:     }
1.91      albertel  172:     if ($type eq 'float' && $unit=~/\,/ && (&check_commas($response)<0)) {
                    173: 	return "COMMA_FAIL:";
                    174:     }
1.88      albertel  175:     $ans_fmt=~s/\W//g;
1.91      albertel  176:     $unit=~s/[\$,]//g;
                    177:     if ($type eq 'float') { $response=~s/,//g; }
1.88      albertel  178: 
1.117     albertel  179:     if (length($response) > 500) { return ('TOO_LONG',undef); }
1.73      albertel  180: 
                    181:     if ($type eq '' ) {
1.119     albertel  182: 	&LONCAPA_INTERNAL_DEBUG("Didn't find a type :$type: defaulting");
1.73      albertel  183: 	if ( $answer eq ($answer *1.0)) { $type = 2;
                    184: 				      } else { $type = 3; }
                    185:     } else {
1.107     albertel  186: 	if    ($type eq 'cs')    { $type = 4; }
1.73      albertel  187: 	elsif ($type eq 'ci')    { $type = 3 }
                    188: 	elsif ($type eq 'mc')    { $type = 5; }
                    189: 	elsif ($type eq 'fml')   { $type = 8; }
1.107     albertel  190:         elsif ($type eq 'math')  { $type = 9; }
1.73      albertel  191: 	elsif ($type eq 'subj')  { $type = 7; }
                    192: 	elsif ($type eq 'float') { $type = 2; }
                    193: 	elsif ($type eq 'int')   { $type = 1; }
1.117     albertel  194: 	else { return ('ERROR', "Unknown type of answer: $type") }
1.73      albertel  195:     }
                    196: 
                    197:     my $points;
                    198:     my $id_list;
                    199:     #formula type setup the sample points
                    200:     if ($type eq '8') {
                    201: 	($id_list,$points)=split(/@/,$samples);
1.119     albertel  202: 	&LONCAPA_INTERNAL_DEBUG("Found :$id_list:$points: points in $samples");
1.73      albertel  203:     }
                    204:     if ($tol eq '') {
                    205: 	$tol=0.0;
                    206: 	$tol_type=1; #TOL_ABSOLUTE
                    207:     } else {
                    208: 	if ($tol =~ /%$/) {
                    209: 	    chop $tol;
                    210: 	    $tol_type=2; #TOL_PERCENTAGE
                    211: 	} else {
                    212: 	    $tol_type=1; #TOL_ABSOLUTE
                    213: 	}
                    214:     }
                    215: 
1.85      albertel  216:     ($sig_ubound,$sig_lbound)=&LONCAPA_INTERNAL_get_sigrange($sig);
                    217: 
1.73      albertel  218:     my $reterror="";
1.107     albertel  219:     my $result;
1.142     raeburn   220:     if (($type eq '9') || ($type eq '8')) {
                    221:         if ($response=~/\=/) {
                    222:             return ('BAD_FORMULA','Please submit just an expression, not an equation.');
1.143     riegler   223:         } elsif ($response =~ /\,/ and $response !~ /^\s*\{.*\}\s*$/) {
1.142     raeburn   224:             return ('BAD_FORMULA');
                    225:         }
                    226:     }
1.107     albertel  227:     if ($type eq '9') {
1.108     www       228:       $result = &maxima_check(&maxima_cas_formula_fix($response),&maxima_cas_formula_fix($answer),\$reterror);
1.107     albertel  229:     } else {
1.109     albertel  230: 	if ($type eq '8') { # fml type
                    231: 	    $response = &capa_formula_fix($response);
                    232: 	    $answer   = &capa_formula_fix($answer);
                    233: 	}
                    234:        $result = &caparesponse_capa_check_answer($response,$answer,$type,
1.73      albertel  235: 						 $tol_type,$tol,
                    236: 						 $sig_lbound,$sig_ubound,
                    237: 						 $ans_fmt,$unit,$calc,$id_list,
                    238: 						 $points,$external::randomseed,
                    239: 						 \$reterror);
1.107     albertel  240:     }
1.73      albertel  241:     if    ($result == '1') { $result='EXACT_ANS'; } 
                    242:     elsif ($result == '2') { $result='APPROX_ANS'; }
                    243:     elsif ($result == '3') { $result='SIG_FAIL'; }
                    244:     elsif ($result == '4') { $result='UNIT_FAIL'; }
                    245:     elsif ($result == '5') { $result='NO_UNIT'; }
                    246:     elsif ($result == '6') { $result='UNIT_OK'; }
                    247:     elsif ($result == '7') { $result='INCORRECT'; }
                    248:     elsif ($result == '8') { $result='UNIT_NOTNEEDED'; }
                    249:     elsif ($result == '9') { $result='ANS_CNT_NOT_MATCH'; }
                    250:     elsif ($result =='10') { $result='SUB_RECORDED'; }
                    251:     elsif ($result =='11') { $result='BAD_FORMULA'; }
1.94      albertel  252:     elsif ($result =='12' && !$response) { $result='MISSING_ANSWER'; }
                    253:     elsif ($result =='12') { $result='WANTED_NUMERIC'; }
1.77      albertel  254:     elsif ($result =='13') { $result='UNIT_INVALID_INSTRUCTOR'; }
                    255:     elsif ($result =='141') { $result='UNIT_INVALID_STUDENT'; }
                    256:     elsif ($result =='142') { $result='UNIT_INVALID_STUDENT'; }
                    257:     elsif ($result =='143') { $result='UNIT_INVALID_STUDENT'; }
                    258:     elsif ($result =='15') { $result='UNIT_IRRECONCIBLE'; }
1.73      albertel  259:     else  {$result = "ERROR: Unknown Result:$result:$@:";}
                    260: 
1.119     albertel  261:     &LONCAPA_INTERNAL_DEBUG("RetError $reterror: Answer $answer: Response $response:  type-$type|$tol|$tol_type|$sig:$sig_lbound:$sig_ubound|$unit|");
                    262:     &LONCAPA_INTERNAL_DEBUG(" $answer $response $result ");
1.139     raeburn   263:     return ($result,$reterror);
1.37      albertel  264: }
                    265: 
1.73      albertel  266: 
1.37      albertel  267: sub caparesponse_check_list {
1.119     albertel  268:     my $responses=$LONCAPA::CAPAresponse_args{'response'};
1.105     albertel  269:     &LONCAPA_INTERNAL_DEBUG("args ".join(':',%LONCAPA::CAPAresponse_args));
1.74      albertel  270:     my $type = $LONCAPA::CAPAresponse_args{'type'};
1.133     www       271:     my $answerunit=$LONCAPA::CAPAresponse_args{'unit'};
                    272:     &LONCAPA_INTERNAL_DEBUG("Got type :$type: answer unit :$answerunit:\n");
1.119     albertel  273:     
                    274:     my $num_input_lines =
                    275: 	scalar(@{$LONCAPA::CAPAresponse_answer->{'answers'}});
1.120     albertel  276:     
                    277:     if ($type ne '' ) {
1.119     albertel  278: 	if (scalar(@$responses) < $num_input_lines) {
1.105     albertel  279: 	    return 'MISSING_ANSWER';
                    280: 	}
1.119     albertel  281: 	if (scalar(@$responses) > $num_input_lines) {
                    282: 	    return 'EXTRA_ANSWER';
                    283: 	}
                    284: 
                    285:     }
                    286: 
                    287:     foreach my $which (0..($num_input_lines-1)) {
                    288: 	my $answer_size = 
                    289: 	    scalar(@{$LONCAPA::CAPAresponse_answer->{'answers'}[$which]});
                    290: 	if ($type ne '' 
                    291: 	    && $answer_size > 1) {
                    292: 	    $responses->[$which]=[split(/,/,$responses->[$which])];
                    293: 	} else {
                    294: 	    $responses->[$which]=[$responses->[$which]];
                    295: 	}
                    296:     }
                    297:     foreach my $which (0..($num_input_lines-1)) {
                    298: 	my $answer_size = 
                    299: 	    scalar(@{$LONCAPA::CAPAresponse_answer->{'answers'}[$which]});
                    300: 	my $response_size = 
                    301: 	    scalar(@{$responses->[$which]});
                    302: 	if ($answer_size > $response_size) {
                    303: 	    return 'MISSING_ANSWER';
                    304: 	}
                    305: 	if ($answer_size < $response_size) {
1.105     albertel  306: 	    return 'EXTRA_ANSWER';
                    307: 	}
1.73      albertel  308:     }
1.119     albertel  309: 
                    310:     &LONCAPA_INTERNAL_DEBUG("Initial final response :$responses->[0][-1]:");
1.105     albertel  311:     my $unit;
1.140     raeburn   312:     if ($type eq 'float' || $type eq '') {
1.73      albertel  313: 	#for numerical problems split off the unit
1.128     www       314: #	if ( $responses->[0][-1]=~ /(.*[^\s])\s+([^\s]+)/ ) {
1.132     www       315:         if ( $responses->[0][-1]=~ /^([\d\.\,\s\$]*(?:(?:[xX\*]10[\^\*]*|[eE]*)[\+\-]*\d*)*(?:^|\S)\d+)([\$\s\w\^\*\/\(\)\+\-]*[^\d\.\s\,][\$\s\w\^\*\/\(\)\+\-]*)$/ ) {
1.119     albertel  316: 	    $responses->[0][-1]=$1;
1.128     www       317: 	    $unit=&capa_formula_fix($2);
                    318:             &LONCAPA_INTERNAL_DEBUG("Found unit :$unit:");
1.73      albertel  319: 	}
                    320:     }
1.119     albertel  321:     &LONCAPA_INTERNAL_DEBUG("Final final response :$responses->[0][-1]:$unit:");
1.73      albertel  322:     $unit=~s/\s//;
1.149     raeburn   323:     my $error;
1.133     www       324:     foreach my $response (@$responses) {
                    325:        foreach my $element (@$response) {	
1.138     raeburn   326:           if (($type eq 'float') || (($type eq '') && ($unit ne ''))) {
                    327:               $element =~ s/\s//g;
                    328:           }
1.133     www       329:           my $appendunit=$unit;
1.147     www       330: # Deal with percentages
                    331: # unit is unit entered by student, answerunit is unit by author
                    332: # Deprecated: divide answer by 100 if student entered percent,
                    333: # but author did not. Too much confusion
1.146     www       334: #          if (($unit=~/\%/) && ($answerunit ne '%'))  {
                    335: #             $element=$element/100;
                    336: #             $appendunit=~s/\%//;
                    337: #          }    
1.147     www       338: # Author entered percent, student did not
                    339:           if (($unit!~/\%/) && ($answerunit=~/\%/)) {
                    340:              $element=$element*100;
                    341:              $appendunit='%'.$appendunit;
                    342:           }
                    343: # Zero does not need a dimension
1.152.2.1! raeburn   344:           if (($element =~ /^[0\.]+$/) && ($unit!~/\w/) && ($answerunit=~/\w/)) {
1.133     www       345:              $appendunit=$answerunit;
                    346:           }
1.148     raeburn   347:           if ($appendunit ne '') {
                    348:               $element .= " $appendunit";
                    349:           }  
1.133     www       350:           &LONCAPA_INTERNAL_DEBUG("Made response element :$element:");
                    351:        }
1.119     albertel  352:     }
                    353:     
1.117     albertel  354:     foreach my $thisanswer (@{ $LONCAPA::CAPAresponse_answer->{'answers'} }) {
                    355: 	if (!defined($thisanswer)) {
                    356: 	    return ('ERROR','answer was undefined');
                    357: 	}
                    358:     }
                    359: 
1.150     raeburn   360:     my $allow_control_char = 0;
                    361:     my $control_chars_removed = 0;
1.151     raeburn   362:     my $ansstring;
1.150     raeburn   363:     if ($type eq 'cs' || $type eq 'ci') {
                    364:         if (ref($LONCAPA::CAPAresponse_answer->{'answers'}) eq 'ARRAY') {
                    365:             foreach my $strans (@{$LONCAPA::CAPAresponse_answer->{'answers'}}) {
1.151     raeburn   366:                 if (ref($strans) eq 'ARRAY') {
1.152     raeburn   367:                     $ansstring = join("\0",@{$strans});
1.151     raeburn   368:                     foreach my $item (@{$strans}) {  
                    369:                         if ($item =~ /[\000-\037]/) {
                    370:                             $allow_control_char = 1;
                    371:                         }
                    372:                     }
                    373:                 }
                    374:             }
                    375:         }
                    376:     }
1.117     albertel  377: 
1.121     albertel  378: #    &LONCAPA_INTERNAL_DEBUG(&LONCAPA_INTERNAL_Dumper($responses));
1.117     albertel  379:     my %memoized;
                    380:     if ($LONCAPA::CAPAresponse_answer->{'type'}  eq 'ordered') {
1.119     albertel  381: 	for (my $i=0; $i<scalar(@$responses);$i++) {
1.117     albertel  382: 	    my $answer   = $LONCAPA::CAPAresponse_answer->{'answers'}[$i];
1.119     albertel  383: 	    my $response = $responses->[$i];
1.117     albertel  384: 	    my $key = "$answer\0$response";
1.119     albertel  385: 	    my (@awards,@msgs);
1.150     raeburn   386: 	    for (my $j=0; $j<scalar(@$response); $j++) {
                    387:                 if ($type eq 'cs' || $type eq 'ci') {
                    388:                     unless ($allow_control_char) {
                    389:                         if ($response->[$j] =~ /[\000-\037]/) { 
                    390:                             $response->[$j] =~ s/[\000-\037]//g;
                    391:                             $control_chars_removed = 1;
                    392:                         }  
                    393:                     }
                    394:                 }
1.119     albertel  395: 		my ($award,$msg) = &caparesponse_check($answer->[$j],
                    396: 						       $response->[$j]);
1.149     raeburn   397:                 if ($type eq 'cs' || $type eq 'ci') {
                    398:                     $error = &verify_stringresponse($type,$award,$response->[$j],
                    399:                                                     $answer->[$j]);
                    400:                 }
1.119     albertel  401: 		push(@awards,$award);
                    402: 		push(@msgs,  $msg);
                    403: 	    }
                    404: 	    my ($award,$msg) = 
                    405: 		&LONCAPA_INTERNAL_FINALIZEAWARDS(\@awards,\@msgs);
                    406: 	    $memoized{$key} = [$award,$msg];
1.117     albertel  407: 	}
                    408:     } else {
1.119     albertel  409: 	#FIXME broken with unorder responses where one is a <value>
                    410:         #      and the other is a <vector> (need to delay parse til
                    411:         #      inside the loop?)
                    412: 	foreach my $response (@$responses) {
                    413: 	    my $response_size = scalar(@{$response});
1.117     albertel  414: 	    foreach my $answer (@{ $LONCAPA::CAPAresponse_answer->{'answers'} }) {
                    415: 		my $key = "$answer\0$response";
1.119     albertel  416: 		my $answer_size =  scalar(@{$answer});
                    417: 		my ($award,$msg);
                    418: 		if ($answer_size > $response_size) {
                    419: 		    $award = 'MISSING_ANSWER';
                    420: 		} elsif ($answer_size < $response_size) {
                    421: 		    $award = 'EXTRA_ANSWER';
                    422: 		} else {
                    423: 		    my (@awards,@msgs);
                    424: 		    for (my $j=0; $j<scalar(@$response); $j++) {
1.150     raeburn   425:                         if ($type eq 'cs' || $type eq 'ci') {
                    426:                             unless ($allow_control_char) {
                    427:                                 if ($response->[$j] =~ /[\000-\037]/) {
                    428:                                     $response->[$j] =~ s/[\000-\037]//g;
                    429:                                     $control_chars_removed = 1;
                    430:                                 }
                    431:                             }
                    432:                         }
1.119     albertel  433: 			my ($award,$msg) = &caparesponse_check($answer->[$j],
                    434: 							       $response->[$j]);
1.149     raeburn   435:                         if ($type eq 'cs' || $type eq 'ci') {
                    436:                             $error = &verify_stringresponse($type,$award,$response->[$j],
                    437:                                                             $answer->[$j]);
                    438:                         }
1.119     albertel  439: 			push(@awards,$award);
                    440: 			push(@msgs,  $msg);
                    441: 		    }
                    442: 		    ($award,$msg) = 
                    443: 			&LONCAPA_INTERNAL_FINALIZEAWARDS(\@awards,\@msgs);
                    444: 		}
                    445: 		$memoized{$key} = [$award,$msg];
1.117     albertel  446: 	    }
                    447: 	}
                    448:     }
                    449: 
1.116     albertel  450:     my ($final_award,$final_msg);
1.119     albertel  451:     &init_permutation(scalar(@$responses),
1.116     albertel  452: 		      $LONCAPA::CAPAresponse_answer->{'type'});
1.117     albertel  453: 
1.118     albertel  454:     # possible FIXMEs
                    455:     # - significant time is spent calling non-safe space routine
                    456:     #   from safe space
                    457:     # - early outs could be possible with classifying awards is to stratas
                    458:     #   and stopping as so as hitting the top strata 
                    459:     # - some early outs also might be possible with check ing the 
                    460:     #   memoized hash of results (is correct even possible? etc.)
                    461: 
1.117     albertel  462:     my (@final_awards,@final_msg);
1.116     albertel  463:     while( &get_permutations_left() ) {
1.117     albertel  464: 	my $order = &get_next_permutation();
1.116     albertel  465: 	my (@awards, @msgs, $i);
                    466: 	foreach my $thisanswer (@{ $LONCAPA::CAPAresponse_answer->{'answers'} }) {
1.119     albertel  467: 	    my $key = "$thisanswer\0".$responses->[$order->[$i]];
1.117     albertel  468: 	    push(@awards,$memoized{$key}[0]);
                    469: 	    push(@msgs,$memoized{$key}[1]);
1.116     albertel  470: 	    $i++;
1.119     albertel  471: 
1.116     albertel  472: 	}
1.119     albertel  473: 	&LONCAPA_INTERNAL_DEBUG(" all awards ".join(':',@awards));
                    474: 
1.116     albertel  475: 	my ($possible_award,$possible_msg) = 
                    476: 	    &LONCAPA_INTERNAL_FINALIZEAWARDS(\@awards,\@msgs);
1.119     albertel  477: 	&LONCAPA_INTERNAL_DEBUG(" pos awards ".$possible_award);
1.117     albertel  478: 	push(@final_awards,$possible_award);
                    479: 	push(@final_msg,$possible_msg);
1.73      albertel  480:     }
1.117     albertel  481: 
1.119     albertel  482:     &LONCAPA_INTERNAL_DEBUG(" all final_awards ".join(':',@final_awards));
1.117     albertel  483:     my ($final_award,$final_msg) = 
                    484: 	&LONCAPA_INTERNAL_FINALIZEAWARDS(\@final_awards,\@final_msg,undef,1);
1.151     raeburn   485:     return ($final_award,$final_msg,$error,$control_chars_removed,$ansstring);
1.149     raeburn   486: }
                    487: 
                    488: sub verify_stringresponse {
                    489:     my ($type,$award,$resp,$ans) = @_;
                    490:     return if ($award eq 'EXACT_ANS');
                    491:     my $error;
                    492:     if ($resp =~ /^\s|\s$/) {
                    493:         $resp =~ s{^\s+|\s+$}{}g;
                    494:     }
                    495:     if ($ans =~ /^\s|\s$/) {
                    496:         $ans =~ s{^\s+|\s+$}{}g;
                    497:     }
                    498:     if ($type eq 'ci') {
                    499:         $resp = lc($resp);
                    500:         $ans = lc($ans);
                    501:     }
                    502:     if ($resp eq $ans) {
                    503:         if ($award eq 'INCORRECT') {
                    504:             $error = 'MISGRADED';
                    505:         }
                    506:     }
                    507:     return $error;
1.7       albertel  508: }
                    509: 
1.124     www       510: sub cas {
1.137     www       511:     my ($system,$input,$library)=@_;
1.124     www       512:     my $output;
1.145     www       513:     my $dump;
1.124     www       514:     if ($system eq 'maxima') {
1.137     www       515:        $output=&maxima_eval($input,$library);
1.144     www       516:     } elsif ($system eq 'R') {
1.145     www       517:        ($output,$dump)=&r_eval($input,$library,0);
1.137     www       518:     } else {
                    519:        $output='Error: unrecognized CAS';
1.124     www       520:     }
                    521:     return $output;
                    522: }
                    523: 
1.145     www       524: sub cas_hashref {
                    525:     my ($system,$input,$library)=@_;
                    526:     if ($system eq 'maxima') {
                    527:        return 'Error: unsupported CAS';
                    528:     } elsif ($system eq 'R') {
                    529:        return &r_eval($input,$library,1);
                    530:     } else {
                    531:        return 'Error: unrecognized CAS';
                    532:     }
                    533: }
                    534: 
                    535: #
                    536: # cas_hashref_entry takes a list of indices and gets the entry in a hash generated by Rreturn.
                    537: # Call: cas_hashref_entry(Rvalue, index1, index2, ...) where Rvalue is a hash returned by Rreturn.
                    538: # Rentry will return the first scalar value it encounters (ignoring excess indices).
                    539: # If an invalid key is given, it returns undef.
                    540: #
                    541: sub cas_hashref_entry {
                    542:     return &Rentry(@_);
                    543: }
                    544: 
                    545: #
                    546: # cas_hashref_array takes a list of indices and gets a column array from a hash generated by Rreturn.
                    547: # Call: cas_hashref_array(Rvalue, index1, index2, ...) where Rvalue is a hash returned by Rreturn.
                    548: # If an invalid key is given, it returns undef.
                    549: #
                    550: sub cas_hashref_array {
                    551:     return &Rarray(@_);
                    552: }
                    553: 
1.4       albertel  554: sub tex {
1.73      albertel  555:     if ( $external::target eq "tex" ) {
                    556: 	return $_[0];
                    557:     } else {
                    558: 	return $_[1];
                    559:     }
1.4       albertel  560: }
                    561: 
1.24      ng        562: sub var_in_tex {
1.73      albertel  563:     if ( $external::target eq "tex" ) {
                    564: 	return $_[0];
                    565:     } else {
                    566: 	return "";
                    567:     }
1.24      ng        568: }
                    569: 
1.4       albertel  570: sub web {
1.73      albertel  571:     if ( $external::target eq "tex" ) {
                    572: 	return $_[1];
1.26      ng        573:     } else {
1.73      albertel  574: 	if ( $external::target eq "web" || $external::target eq "answer") {
                    575: 	    return $_[2];
                    576: 	} else {
                    577: 	    return $_[0];
                    578: 	}
1.4       albertel  579:     }
                    580: }
                    581: 
1.24      ng        582: sub html {
1.73      albertel  583:     if ( $external::target eq "web" ) {
                    584: 	return shift;
                    585:     }
1.24      ng        586: }
                    587: 
1.1       harris41  588: sub hinton {
1.73      albertel  589:     return 0;
1.1       harris41  590: }
                    591: 
                    592: sub random {
1.61      albertel  593:     my ($start,$end,$step)=@_;
                    594:     if ( ! $hidden::RANDOMINIT ) {
                    595: 	if ($external::randomseed == 0) { $external::randomseed=1; }
                    596: 	if ($external::randomseed =~/,/) {
1.84      albertel  597: 	    my ($num1,$num2)=split(/,/,$external::randomseed);
                    598: 	    &random_set_seed(1,abs($num1));
                    599: 	} elsif ($external::randomseed =~/:/) {
                    600: 	    my ($num1,$num2)=split(/:/,$external::randomseed);
1.61      albertel  601: 	    &random_set_seed(abs($num1),abs($num2));
                    602: 	} else {
                    603: 	    &random_set_seed(1,int(abs($external::randomseed)));
                    604: 	}
                    605: 	&math_random_uniform();
                    606: 	$hidden::RANDOMINIT=1;
                    607:     }
                    608:     if (!defined($step)) { $step=1; }
                    609:     my $num=1+int(($end-$start)/$step);
                    610:     my $result=$start + int(&math_random_uniform() * $num)*$step;
                    611:     return $result;
1.1       harris41  612: }
                    613: 
1.26      ng        614: sub random_normal {
1.73      albertel  615:     my ($item_cnt,$seed,$av,$std_dev) = @_;
                    616:     my @oldseed=&random_get_seed();
                    617:     my @retArray;
                    618:     &random_set_seed_from_phrase($seed);
                    619:     @retArray=&math_random_normal($item_cnt,$av,$std_dev);
                    620:     &random_set_seed(@oldseed);
                    621:     return @retArray;
1.26      ng        622: }
                    623: 
                    624: sub random_beta {
1.73      albertel  625:     my ($item_cnt,$seed,$aa,$bb) = @_;
                    626:     my @oldseed=&random_get_seed();
                    627:     my @retArray;
                    628:     &random_set_seed_from_phrase($seed);
                    629:     @retArray=&math_random_beta($item_cnt,$aa,$bb);
                    630:     &random_set_seed(@oldseed);
                    631:     return @retArray;
1.26      ng        632: }
                    633: 
                    634: sub random_gamma {
1.73      albertel  635:     my ($item_cnt,$seed,$a,$r) = @_;
                    636:     my @oldseed=&random_get_seed();
                    637:     my @retArray;
                    638:     &random_set_seed_from_phrase($seed);
                    639:     @retArray=&math_random_gamma($item_cnt,$a,$r);
                    640:     &random_set_seed(@oldseed);
                    641:     return @retArray;
1.26      ng        642: }
                    643: 
                    644: sub random_exponential {
1.73      albertel  645:     my ($item_cnt,$seed,$av) = @_;
                    646:     my @oldseed=&random_get_seed();
                    647:     my @retArray;
                    648:     &random_set_seed_from_phrase($seed);
                    649:     @retArray=&math_random_exponential($item_cnt,$av);
                    650:     &random_set_seed(@oldseed);
                    651:     return @retArray;
1.26      ng        652: }
                    653: 
                    654: sub random_poisson {
1.73      albertel  655:     my ($item_cnt,$seed,$mu) = @_;
                    656:     my @oldseed=&random_get_seed();
                    657:     my @retArray;
                    658:     &random_set_seed_from_phrase($seed);
                    659:     @retArray=&math_random_poisson($item_cnt,$mu);
                    660:     &random_set_seed(@oldseed);
                    661:     return @retArray;
1.26      ng        662: }
                    663: 
                    664: sub random_chi {
1.73      albertel  665:     my ($item_cnt,$seed,$df) = @_;
                    666:     my @oldseed=&random_get_seed();
                    667:     my @retArray;
                    668:     &random_set_seed_from_phrase($seed);
                    669:     @retArray=&math_random_chi_square($item_cnt,$df);
                    670:     &random_set_seed(@oldseed);
                    671:     return @retArray;
1.26      ng        672: }
                    673: 
                    674: sub random_noncentral_chi {
1.73      albertel  675:     my ($item_cnt,$seed,$df,$nonc) = @_;
                    676:     my @oldseed=&random_get_seed();
                    677:     my @retArray;
                    678:     &random_set_seed_from_phrase($seed);
                    679:     @retArray=&math_random_noncentral_chi_square($item_cnt,$df,$nonc);
                    680:     &random_set_seed(@oldseed);
                    681:     return @retArray;
1.26      ng        682: }
                    683: 
                    684: sub random_f {
1.73      albertel  685:     my ($item_cnt,$seed,$dfn,$dfd) = @_;
                    686:     my @oldseed=&random_get_seed();
                    687:     my @retArray;
                    688:     &random_set_seed_from_phrase($seed);
                    689:     @retArray=&math_random_f($item_cnt,$dfn,$dfd);
                    690:     &random_set_seed(@oldseed);
                    691:     return @retArray;
1.26      ng        692: }
                    693: 
                    694: sub random_noncentral_f {
1.73      albertel  695:     my ($item_cnt,$seed,$dfn,$dfd,$nonc) = @_;
                    696:     my @oldseed=&random_get_seed();
                    697:     my @retArray;
                    698:     &random_set_seed_from_phrase($seed);
                    699:     @retArray=&math_random_noncentral_f($item_cnt,$dfn,$dfd,$nonc);
                    700:     &random_set_seed(@oldseed);
                    701:     return @retArray;
1.26      ng        702: }
                    703: 
                    704: sub random_multivariate_normal {
1.73      albertel  705:     my ($item_cnt,$seed,$mean,$covar) = @_;
                    706:     my @oldseed=&random_get_seed();
                    707:     &random_set_seed_from_phrase($seed);
1.87      albertel  708:     my @retArray=&math_random_multivariate_normal($item_cnt,@$mean,@$covar);
1.73      albertel  709:     &random_set_seed(@oldseed);
                    710:     return @retArray;
1.26      ng        711: }
                    712: 
                    713: sub random_multinomial {
1.73      albertel  714:     my ($item_cnt,$seed,@p) = @_;
                    715:     my @oldseed=&random_get_seed();
                    716:     my @retArray;
                    717:     &random_set_seed_from_phrase($seed);
1.87      albertel  718:     my @retArray=&math_random_multinomial($item_cnt,@p);
1.73      albertel  719:     &random_set_seed(@oldseed);
                    720:     return @retArray;
1.26      ng        721: }
                    722: 
                    723: sub random_permutation {
1.73      albertel  724:     my ($seed,@inArray) = @_;
                    725:     my @oldseed=&random_get_seed();
                    726:     my @retArray;
                    727:     &random_set_seed_from_phrase($seed);
                    728:     @retArray=&math_random_permutation(@inArray);
                    729:     &random_set_seed(@oldseed);
                    730:     return @retArray;
1.26      ng        731: }
                    732: 
                    733: sub random_uniform {
1.73      albertel  734:     my ($item_cnt,$seed,$low,$high) = @_;
                    735:     my @oldseed=&random_get_seed();
                    736:     my @retArray;
                    737:     &random_set_seed_from_phrase($seed);
                    738:     @retArray=&math_random_uniform($item_cnt,$low,$high);
                    739:     &random_set_seed(@oldseed);
                    740:     return @retArray;
1.26      ng        741: }
                    742: 
                    743: sub random_uniform_integer {
1.73      albertel  744:     my ($item_cnt,$seed,$low,$high) = @_;
                    745:     my @oldseed=&random_get_seed();
                    746:     my @retArray;
                    747:     &random_set_seed_from_phrase($seed);
                    748:     @retArray=&math_random_uniform_integer($item_cnt,$low,$high);
                    749:     &random_set_seed(@oldseed);
                    750:     return @retArray;
1.26      ng        751: }
                    752: 
                    753: sub random_binomial {
1.73      albertel  754:     my ($item_cnt,$seed,$nt,$p) = @_;
                    755:     my @oldseed=&random_get_seed();
                    756:     my @retArray;
                    757:     &random_set_seed_from_phrase($seed);
                    758:     @retArray=&math_random_binomial($item_cnt,$nt,$p);
                    759:     &random_set_seed(@oldseed);
                    760:     return @retArray;
1.26      ng        761: }
                    762: 
                    763: sub random_negative_binomial {
1.73      albertel  764:     my ($item_cnt,$seed,$ne,$p) = @_;
                    765:     my @oldseed=&random_get_seed();
                    766:     my @retArray;
                    767:     &random_set_seed_from_phrase($seed);
                    768:     @retArray=&math_random_negative_binomial($item_cnt,$ne,$p);
                    769:     &random_set_seed(@oldseed);
                    770:     return @retArray;
1.26      ng        771: }
                    772: 
1.103     albertel  773: sub abs { CORE::abs(shift) }
                    774: sub sin { CORE::sin(shift) }
                    775: sub cos { CORE::cos(shift) }
                    776: sub exp { CORE::exp(shift) }
                    777: sub int { CORE::int(shift) }
                    778: sub log { CORE::log(shift) }
                    779: sub atan2 { CORE::atan2($_[0],$_[1]) }
                    780: sub sqrt { CORE::sqrt(shift) }
1.23      ng        781: 
1.59      albertel  782: sub tan  { CORE::sin($_[0]) / CORE::cos($_[0]) }
1.21      harris41  783: #sub atan { atan2($_[0], 1); }
                    784: #sub acos { atan2(sqrt(1 - $_[0] * $_[0]), $_[0] ); }
                    785: #sub asin { atan2($_[0], sqrt(1- $_[0] * $_[0]) );  }
1.22      ng        786: 
1.59      albertel  787: sub log10 { CORE::log($_[0])/CORE::log(10); }
1.22      ng        788: 
1.20      harris41  789: sub factorial {
1.59      albertel  790:     my $input = CORE::int(shift);
1.20      harris41  791:     return "Error - unable to take factorial of an negative number ($input)" if $input < 0;
                    792:     return "Error - factorial result is greater than system limit ($input)" if $input > 170;
                    793:     return 1 if $input == 0;
                    794:     my $result = 1; 
                    795:     for (my $i=2; $i<=$input; $i++) { $result *= $i }
                    796:     return $result;
                    797: }
                    798: 
                    799: sub sgn {
                    800:     return -1 if $_[0] < 0;
                    801:     return 0 if $_[0] == 0;
                    802:     return 1 if $_[0] > 0;
                    803: }
                    804: 
                    805: sub min {
                    806:     my @sorted = sort { $a <=> $b || $a cmp $b } @_;
                    807:     return shift @sorted;
                    808: }
                    809: 
                    810: sub max {
                    811:     my @sorted = sort { $a <=> $b || $a cmp $b } @_;
                    812:     return pop @sorted;
                    813: }
1.1       harris41  814: 
1.20      harris41  815: sub roundto {
                    816:     my ($input,$n) = @_;
                    817:     return sprintf('%.'.$n.'f',$input);
                    818: }
                    819: 
                    820: sub to_string {
                    821:     my ($input,$n) = @_;
1.26      ng        822:     return sprintf($input) if $n eq "";
                    823:     $n = '.'.$n if $n !~ /^\./;
1.20      harris41  824:     return sprintf('%'.$n,$input) if $n ne "";
                    825: }
                    826: 
                    827: sub sub_string {
                    828:     my ($str,$start,$len) = @_;
                    829:     return substr($str,$start-1,$len);
                    830: }
1.1       harris41  831: 
                    832: sub pow   {return $_[0] ** $_[1]; }
1.59      albertel  833: sub ceil  {return (($_[0]-CORE::int($_[0]))== 0.0) ? $_[0] : (($_[0] > 0) ? (CORE::int($_[0])+ 1) : CORE::int($_[0])); }
                    834: sub floor  {return (($_[0]-CORE::int($_[0]))== 0.0) ? $_[0] : (($_[0] > 0) ? CORE::int($_[0]) : (CORE::int($_[0])-1)); }
1.27      ng        835: #sub floor {return int($_[0]); }
1.1       harris41  836: 
1.2       albertel  837: sub format {
1.73      albertel  838:     my ($value,$fmt)=@_;
1.81      albertel  839:     my ($dollarmode,$commamode,$alwaysperiod,$options);
                    840:     if ($fmt =~ /^([^\d]*)(.*)/) { $options=$1; $fmt=$2; } 
                    841:     #if ($options =~ /\$/) { $dollamode=1; }
                    842:     #if ($options =~ /,/)  { $commamode=1; }
1.82      albertel  843:     if ($options =~ /\./) { $alwaysperiod=1; }
1.99      ng        844:     my $result;
1.97      albertel  845:     if ($fmt=~/s$/i) {
                    846: 	$result=&format_significant_figures($value,$fmt);
                    847:     } else {
                    848: 	$fmt=~s/e/E/g;
1.99      ng        849: 	$result=sprintf('%.'.$fmt,$value);
1.97      albertel  850: 	if ($alwaysperiod && $fmt eq '0f') { $result .='.'; }
                    851: 	$result=~s/(E[+-]*)0/$1/;
                    852:     }
1.81      albertel  853:     #if ($dollarmode) {$result=&dollarformat($result);}
                    854:     #if ($commamode) {$result=&commaformat($result);}
1.73      albertel  855:     return $result;
1.46      albertel  856: }
                    857: 
1.75      albertel  858: sub chemparse {
                    859:     my ($reaction) = @_;
1.96      albertel  860:     my @tokens = split(/(\s\+|\->|<=>|<\-|\.)/,$reaction);
1.75      albertel  861:     my $formula = '';
                    862:     foreach my $token (@tokens) {
                    863: 	if ($token eq '->' ) {
                    864: 	    $formula .= '<m>\ensuremath{\rightarrow}</m> ';
                    865: 	    next;
                    866: 	}
1.96      albertel  867: 	if ($token eq '<-' ) {
                    868: 	    $formula .= '<m>\ensuremath{\leftarrow}</m> ';
                    869: 	    next;
                    870: 	}  
1.75      albertel  871: 	if ($token eq '<=>') {
                    872: 	    if ($external::target eq 'web' &&
                    873: 		&EXT('request.browser.unicode')) {
1.76      albertel  874: 		$formula .= '&#8652; ';
1.75      albertel  875: 	    } else {
                    876: 		$formula .= &web('<=> ','<m>\ensuremath{\rightleftharpoons}</m> ',
1.95      albertel  877: 				 '&lt;=&gt; ');
1.75      albertel  878: 	    }
                    879: 	    next;
                    880: 	}
1.96      albertel  881: 	if ($token eq '.') {
                    882: 	  $formula =~ s/(\&nbsp\;| )$//;
                    883: 	  $formula .= '&middot;';
                    884: 	  next;
                    885: 	}
                    886: 	$token =~ /^\s*([\d|\/]*(?:&frac\d\d)?)(.*)/;
1.90      albertel  887:         $formula .= $1 if ($1 ne '1');  # stoichiometric coefficient
1.75      albertel  888: 	
                    889: 	my $molecule = $2;
                    890: 	# subscripts
1.78      albertel  891: 	$molecule =~ s|(?<=[a-zA-Z\)\]\s])(\d+)|<sub>$1</sub>|g;
1.75      albertel  892: 	# superscripts
                    893: 	$molecule =~ s|\^(\d*[+\-]*)|<sup>$1</sup>|g;
                    894: 	# strip whitespace
                    895: 	$molecule =~ s/\s*//g;
                    896: 	# forced space
                    897: 	$molecule =~ s/_/ /g;
1.96      albertel  898: 	$molecule =~ s/-/&minus;/g;
1.75      albertel  899: 	$formula .= $molecule.'&nbsp;';
                    900:     }
                    901:     # get rid of trailing space
1.87      albertel  902:     $formula =~ s/(\&nbsp\;| )$//;
1.75      albertel  903:     return &xmlparse($formula);
                    904: }
                    905: 
1.46      albertel  906: sub prettyprint {
1.73      albertel  907:     my ($value,$fmt,$target)=@_;
                    908:     my $result;
                    909:     if (!$target) { $target = $external::target; }
1.75      albertel  910:     if ($fmt =~ /chem/i) { return(&chemparse($value)); }
1.81      albertel  911:     my ($dollarmode,$commamode,$alwaysperiod,$options);
                    912:     if ($fmt =~ /^([^\d]*)(.*)/) { $options=$1; $fmt=$2; } 
1.86      albertel  913:     if ($options =~ /\$/) { $dollarmode=1; }
1.81      albertel  914:     if ($options =~ /,/)  { $commamode=1; }
                    915:     if ($options =~ /\./) { $alwaysperiod=1; }
1.97      albertel  916:     if ($fmt=~/s$/i) {
                    917: 	$value=&format_significant_figures($value,$fmt);
                    918:     } elsif ($fmt) {
                    919: 	$value=sprintf('%.'.$fmt,$value);
                    920:     }
1.81      albertel  921:     if ($alwaysperiod && $fmt eq '0f') {
                    922: 	if ($target eq 'tex') {
                    923: 	    $value .='\\ensuremath{.}';
                    924: 	} else {
                    925: 	    $value .='.';
                    926: 	}
                    927:     }
1.73      albertel  928:     if ($value =~ /([0-9\.\-\+]+)E([0-9\-\+]+)/i ) {
                    929: 	my $frac=$1;
                    930: 	if ($dollarmode) { $frac=&dollarformat($frac); }
1.80      albertel  931: 	if ($commamode) { $frac=&commaformat($frac); }
1.73      albertel  932: 	my $exponent=$2;
                    933: 	$exponent=~s/^\+0*//;
                    934: 	$exponent=~s/^-0*/-/;
                    935: 	$exponent=~s/^-0*/-/;
                    936: 	if ($exponent eq '-') { undef($exponent); }
                    937: 	if ($exponent) {
                    938: 	    if ($target eq 'web') {
                    939: 		$result=$frac.'&#215;10<sup>'.$exponent.'</sup>';
                    940: 	    } elsif ($target eq 'tex') {
                    941: 		$result='\ensuremath{'.$frac.'\times 10^{'.$exponent.'}}';
                    942: 	    } else {
                    943: 		$result=$value;
                    944: 	    }
                    945: 	} else {
                    946: 	    $result=$frac;
                    947: 	}
                    948:     } else {
1.48      albertel  949: 	$result=$value;
1.86      albertel  950: 	if    ($dollarmode) { $result=&dollarformat($result,$target); }
                    951: 	elsif ($commamode)  { $result=&commaformat($result,$target); }
1.46      albertel  952:     }
1.73      albertel  953:     return $result;
1.48      albertel  954: }
                    955: 
1.80      albertel  956: sub commaformat {
1.73      albertel  957:     my ($number,$target) = @_;
                    958:     if ($number =~ /\./) {
1.102     albertel  959: 	while ($number =~ /([^0-9]*)([0-9]+)([^\.,][^\.,][^\.,])([,0-9]*\.[0-9]*)$/) {
                    960: 	    $number = $1.$2.','.$3.$4;
1.73      albertel  961: 	}
                    962:     } else {
1.102     albertel  963: 	while ($number =~ /^([^0-9]*)([0-9]+)([^,][^,][^,])([,0-9]*)$/) {
                    964: 	    $number = $1.$2.','.$3.$4;
1.73      albertel  965: 	}
                    966:     }
1.80      albertel  967:     return $number;
                    968: }
                    969: 
                    970: sub dollarformat {
                    971:     my ($number,$target) = @_;
                    972:     if (!$target) { $target = $external::target; }
                    973:     $number=&commaformat($number,$target);
1.73      albertel  974:     if ($target eq 'tex') {
                    975: 	$number='\$'.$number; #' stupid emacs
                    976:     } else {
                    977: 	$number='$'.$number; #' stupid emacs
                    978:     }
                    979:     return $number; 
1.2       albertel  980: }
1.5       albertel  981: 
1.97      albertel  982: # format of form ns or nS where n is an integer
                    983: sub format_significant_figures {
                    984:     my ($number,$format) = @_; 
                    985:     return '0' if ($number == 0);
                    986:     # extract number of significant figures needed
                    987:     my ($sig) = ($format =~ /(\d+)s/i);
                    988:     # arbitrary choice - suggestions ?? or throw error message?
                    989:     $sig = 3 if ($sig eq '');
                    990:     # save the minus sign
                    991:     my $sign = ($number < 0) ? '-' : '';
                    992:     $number = abs($number);
                    993:     # needed to correct for a number greater than 1 (or
                    994:     my $power = ($number < 1) ? 0 : 1;
                    995:     # could round up. Take the integer part of log10.
                    996:     my $x10 = int(log($number)/log(10));
                    997:     # find number with values left of decimal pt = # of sign figs.
                    998:     my $xsig = $number*10**($sig-$x10-$power);
                    999:     # get just digits left of decimal pt - also rounds off correctly
                   1000:     my $xint  = sprintf('%.0f',$xsig);
                   1001:     # save any trailing zero's
                   1002:     my ($zeros) = ($xint =~ /(0+)$/);
                   1003:     # return number to original magnitude
                   1004:     my $numSig = $xint*10**($x10-$sig+$power);
                   1005:     # insert trailing zero's if have decimal point
                   1006:     $numSig =~ s/^(\d+)\.(\d+)(\e?(.*)?)$/$1\.$2$zeros$3/;
1.98      albertel 1007:     # put a decimal pt for number ending with 0 and length = # of sig fig
                   1008:     $numSig.='.' if (length($numSig) == $sig && $numSig =~ /0$/);
                   1009:     if (length($numSig) < $sig) {
                   1010: 	$numSig.='.'.substr($zeros,0,($sig-length($numSig)));
                   1011:     }
1.97      albertel 1012:     # return number with sign
                   1013:     return $sign.$numSig;
                   1014: 
                   1015: }
                   1016: 
1.5       albertel 1017: sub map {
1.27      ng       1018:     my ($phrase,$dest,$source)=@_;
1.51      albertel 1019:     my @oldseed=&random_get_seed();
1.27      ng       1020:     my @seed = &random_seed_from_phrase($phrase);
                   1021:     &random_set_seed(@seed);
                   1022:     my $destct = scalar(@$dest);
1.28      ng       1023:     if (!$source) {
                   1024: 	my @output;
                   1025: 	my @idx = &math_random_permuted_index($destct);
                   1026: 	my $ctr = 0;
                   1027: 	while ($ctr < $destct) {
                   1028: 	    $output[$ctr] = $$dest[$idx[$ctr]];
1.27      ng       1029: 	    $ctr++;
1.28      ng       1030: 	}
1.51      albertel 1031:         &random_set_seed(@oldseed);
1.28      ng       1032: 	return @output;
1.27      ng       1033:     } else {
1.28      ng       1034: 	my $num = scalar(@$source);
                   1035: 	my @idx = &math_random_permuted_index($num);
                   1036: 	my $ctr = 0;
                   1037: 	my $tot = $num;
                   1038: 	$tot = $destct if $destct < $num;
                   1039: 	if (ref($$dest[0])) {
                   1040: 	    while ($ctr < $tot) {
                   1041: 		${$$dest[$ctr]} = $$source[$idx[$ctr]];
                   1042: 	        $ctr++;
                   1043:             }
                   1044:         } else {
                   1045: 	    while ($ctr < $tot) {
                   1046: 		$$dest[$ctr] = $$source[$idx[$ctr]];
                   1047: 		$ctr++;
                   1048: 	    }
                   1049: 	}
1.27      ng       1050:     }
1.56      albertel 1051:     &random_set_seed(@oldseed);
1.51      albertel 1052:     return '';
1.27      ng       1053: }
                   1054: 
                   1055: sub rmap {
                   1056:     my ($phrase,$dest,$source)=@_;
1.51      albertel 1057:     my @oldseed=&random_get_seed();
1.27      ng       1058:     my @seed = &random_seed_from_phrase($phrase);
                   1059:     &random_set_seed(@seed);
                   1060:     my $destct = scalar(@$dest);
1.28      ng       1061:     if (!$source) {
                   1062: 	my @idx = &math_random_permuted_index($destct);
                   1063: 	my $ctr = 0;
                   1064: 	my @r_idx;
                   1065: 	while ($ctr < $destct) {
                   1066: 	    $r_idx[$idx[$ctr]] = $ctr;
                   1067: 	    $ctr++;
                   1068: 	}
                   1069: 	my @output;
                   1070: 	$ctr = 0;
                   1071: 	while ($ctr < $destct) {
                   1072: 	    $output[$ctr] = $$dest[$r_idx[$ctr]];
1.27      ng       1073: 	    $ctr++;
1.28      ng       1074: 	}
1.51      albertel 1075:         &random_set_seed(@oldseed);
1.28      ng       1076: 	return @output;
1.27      ng       1077:     } else {
1.28      ng       1078: 	my $num = scalar(@$source);
                   1079: 	my @idx = &math_random_permuted_index($num);
                   1080: 	my $ctr = 0;
                   1081: 	my $tot = $num;
                   1082: 	$tot = $destct if $destct < $num;
                   1083: 	my @r_idx;
1.27      ng       1084: 	while ($ctr < $tot) {
1.28      ng       1085: 	    $r_idx[$idx[$ctr]] = $ctr;
1.27      ng       1086: 	    $ctr++;
1.28      ng       1087: 	}
                   1088: 	$ctr = 0;
                   1089: 	if (ref($$dest[0])) {
                   1090: 	    while ($ctr < $tot) {
                   1091: 		${$$dest[$ctr]} = $$source[$r_idx[$ctr]];
                   1092: 	        $ctr++;
                   1093:             }
                   1094:         } else {
                   1095: 	    while ($ctr < $tot) {
                   1096: 		$$dest[$ctr] = $$source[$r_idx[$ctr]];
                   1097: 		$ctr++;
                   1098: 	    }
                   1099: 	}
1.6       albertel 1100:     }
1.51      albertel 1101:     &random_set_seed(@oldseed);
                   1102:     return '';
1.5       albertel 1103: }
1.22      ng       1104: 
1.23      ng       1105: sub capa_id { return }
                   1106: 
                   1107: sub problem { return }
                   1108: 
1.22      ng       1109: sub name{
1.73      albertel 1110:     my $fullname = &EXT('environment.lastname').', '.&EXT('environment.firstname').' '.&EXT('environment.middlename');
                   1111:     $fullname = "" if $fullname eq ",  ";
                   1112:     $fullname =~ s/\%2d/-/g;
                   1113:     return $fullname;
1.22      ng       1114: }
                   1115: 
                   1116: sub student_number { 
1.73      albertel 1117:     my $id = &EXT('environment.id');
                   1118:     $id = '' if $id eq "";
                   1119:     return $id;
1.22      ng       1120: }
                   1121: 
                   1122: sub class {
1.73      albertel 1123:     my $course = &EXT('course.description');
                   1124:     $course = '' if $course eq "";
                   1125:     return $course;
1.22      ng       1126: }
                   1127: 
1.112     www      1128: sub firstname {
                   1129:     my $firstname = &EXT('environment.firstname');
                   1130:     $firstname = '' if $firstname eq "";
                   1131:     return $firstname;
                   1132: }
                   1133:                                                                                 
                   1134: sub lastname {
                   1135:     my $lastname = &EXT('environment.lastname');
                   1136:     $lastname = '' if $lastname eq "";
                   1137:     return $lastname;
                   1138: }
                   1139: 
1.22      ng       1140: sub sec { 
1.73      albertel 1141:     my $sec = &EXT('request.course.sec');
                   1142:     $sec = '' if $sec eq "";
                   1143:     return $sec;
1.22      ng       1144: }
                   1145: 
1.136     www      1146: sub submission {
                   1147:    my ($partid,$responseid,$subnumber)=@_;
                   1148:    my $sub='';
                   1149:    if ($subnumber) { $sub=$subnumber.':'; }
                   1150:    return &EXT('user.resource.'.$sub.'resource.'.$partid.'.'.$responseid.'.submission');
                   1151: }
                   1152: 
                   1153: sub currentpart {
                   1154:    return $external::part;
                   1155: }
                   1156: 
1.135     www      1157: sub eval_time {
                   1158:    my ($timestamp)=@_;
                   1159:    unless ($timestamp) { return ''; }
                   1160:    return &locallocaltime($timestamp);
                   1161: }
                   1162: 
1.23      ng       1163: sub open_date { 
1.134     www      1164:     my ($partid)=@_;
                   1165:     unless ($partid) { $partid=0; }
1.135     www      1166:     return &eval_time(&EXT('resource.'.$partid.'.opendate'));
1.23      ng       1167: }
                   1168: 
1.134     www      1169: sub due_date {
                   1170:     my ($partid)=@_;
                   1171:     unless ($partid) { $partid=0; } 
1.135     www      1172:     return &eval_time(&EXT('resource.'.$partid.'.duedate'));
1.23      ng       1173: }
                   1174: 
                   1175: sub answer_date { 
1.134     www      1176:     my ($partid)=@_;
                   1177:     unless ($partid) { $partid=0; }
1.135     www      1178:     return &eval_time(&EXT('resource.'.$partid.'.answerdate'));
1.24      ng       1179: }
                   1180: 
1.136     www      1181: sub open_date_epoch {
                   1182:     my ($partid)=@_;
                   1183:     unless ($partid) { $partid=0; }
                   1184:     return &EXT('resource.'.$partid.'.opendate');
                   1185: }
                   1186: 
                   1187: sub due_date_epoch {
                   1188:     my ($partid)=@_;
                   1189:     unless ($partid) { $partid=0; }
                   1190:     return &EXT('resource.'.$partid.'.duedate');
                   1191: }
                   1192: 
                   1193: sub answer_date_epoch {
                   1194:     my ($partid)=@_;
                   1195:     unless ($partid) { $partid=0; }
                   1196:     return &EXT('resource.'.$partid.'.answerdate');
                   1197: }
                   1198: 
1.24      ng       1199: sub array_moments {
1.73      albertel 1200:     my @input=@_;
                   1201:     my (@output,$N);
                   1202:     $N=scalar (@input);
                   1203:     $output[0]=$N;
                   1204:     if ($N <= 1) {
                   1205: 	$output[1]=$input[0];
                   1206: 	$output[1]="Input array not defined" if ($N == 0);
                   1207: 	$output[2]="variance undefined for N<=1";
                   1208: 	$output[3]="skewness undefined for N<=1";
                   1209: 	$output[4]="kurtosis undefined for N<=1";
                   1210: 	return @output;
                   1211:     }
                   1212:     my $sum=0;
                   1213:     foreach my $line (@input) {
                   1214: 	$sum+=$line;
                   1215:     }
                   1216:     $output[1] = $sum/$N;
                   1217:     my ($x,$sdev,$var,$skew,$kurt) = 0;
                   1218:     foreach my $line (@input) {
                   1219: 	$x=$line-$output[1];
                   1220: 	$var+=$x**2;
                   1221: 	$skew+=$x**3;
                   1222: 	$kurt+=$x**4;
                   1223:     }
                   1224:     $output[2]=$var/($N-1);
                   1225:     $sdev=CORE::sqrt($output[2]);
                   1226:     if ($sdev == 0) {
                   1227: 	$output[3]="inf-variance=0";
                   1228: 	$output[4]="inf-variance=0";
                   1229: 	return @output;
                   1230:     }
                   1231:     $output[3]=$skew/($sdev**3*$N);
                   1232:     $output[4]=$kurt/($sdev**4*$N)-3;
1.24      ng       1233:     return @output;
                   1234: }
1.5       albertel 1235: 
                   1236: sub choose {
1.73      albertel 1237:     my $num = $_[0];
                   1238:     return $_[$num];
1.5       albertel 1239: }
1.23      ng       1240: 
1.101     albertel 1241: #&sum1(1,$x,sub { &sum1($_[0],2*$_[0], sub { fact($_[0])**2 })});
                   1242: #sub sum1 {
                   1243: #    my ($start,$end,$sub)=@_;
                   1244: #    my $sum=0;
                   1245: #    for (my $i=$start;$i<=$end;$i++) {
                   1246: #        $sum+=&$sub($i);
                   1247: #    }
                   1248: #    return $sum
                   1249: #}
                   1250: 
                   1251: #&sum2('a',1,$x,'&sum2(\'b\',$a,2*$a, \'&factorial($b)**2\')');
                   1252: #sub sum2 {
                   1253: #    my ($varname,$start,$end,$line)=@_;
                   1254: #    my $sum=0;
                   1255: #    for (my $i=$start;$i<=$end;$i++) {
                   1256: #	my $func=sub {
                   1257: #	    eval("\$".$varname."=$i");
                   1258: #	    eval($line);
                   1259: #	};
                   1260: #        $sum+=&$func($i);
                   1261: #    }
                   1262: #    return $sum
                   1263: #}
                   1264: 
1.49      albertel 1265: # expiremental idea
                   1266: sub proper_path {
1.73      albertel 1267:     my ($path)=@_;
                   1268:     if ( $external::target eq "tex" ) {
                   1269: 	return '/home/httpd/html'.$path;
                   1270:     } else {
                   1271: 	return $path;
                   1272:     }
1.49      albertel 1273: }
1.23      ng       1274: 

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>