File:  [LON-CAPA] / loncom / homework / default_homework.lcpm
Revision 1.177: download - view: text, annotated - select for diffs
Wed Nov 6 16:20:06 2019 UTC (4 years, 5 months ago) by raeburn
Branches: MAIN
CVS tags: version_2_12_X, HEAD
- Bug 6919.  For multi-part problems containing perl script blocks inside
  part(s), if question type = randomizetry, the first call to &random()
  for each part needs to set the new seed.

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

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