File:  [LON-CAPA] / loncom / homework / default_homework.lcpm
Revision 1.159: download - view: text, annotated - select for diffs
Thu Jun 9 15:43:56 2011 UTC (12 years, 10 months ago) by www
Branches: MAIN
CVS tags: HEAD
Bug #53: custom units now possible, new parameter "customunits"
Format: unita=unitb,unitc=4*unitb,...

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

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