File:  [LON-CAPA] / loncom / homework / default_homework.lcpm
Revision 1.149: download - view: text, annotated - select for diffs
Thu Oct 14 19:54:56 2010 UTC (13 years, 6 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 5531.
  - Detect where student resubmits previous answer for case sensitive
    stringreponse item and award changes to EXACT_ANS.
    Detect for case insensitive stringresponse when previous award changes
    to EXACT_ANS for submissions whch only differ by case.
    - logs to lonnet.log and sends e-mail to recipients of "errormail" for
      course domain.
  - For cs and ci types if award is INCORRECT use perl to compare
    response with answer, and log if disagreement with result from
    strcasecmp() or strcmp() to capa_check_answer() in capaCommon.

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

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