File:  [LON-CAPA] / loncom / homework / default_homework.lcpm
Revision 1.152.2.2: download - view: text, annotated - select for diffs
Thu Oct 6 17:20:37 2011 UTC (12 years, 6 months ago) by raeburn
Branches: version_2_10_X
CVS tags: version_2_10_1, loncapaMITrelate_1
Diff to branchpoint 1.152: preferred, unified
- Backport 1.153, 1,154, 1.155, 1.156, 1.157, 1.158, 1.159, 1.161.

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

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