File:  [LON-CAPA] / loncom / homework / default_homework.lcpm
Revision 1.111: download - view: text, annotated - select for diffs
Tue Jul 18 14:06:17 2006 UTC (17 years, 9 months ago) by www
Branches: MAIN
CVS tags: HEAD
The Style Police apparently believes that regular expressions are not
self-explanatory.

    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.111 2006/07/18 14:06:17 www Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: #
   29: 
   30: #init some globals
   31: $hidden::RANDOMINIT=0;
   32: $pi=atan2(1,1)*4;
   33: $rad2deg=180.0/$pi;
   34: $deg2rad=$pi/180.0;
   35: $"=' ';
   36: 
   37: sub check_commas {
   38:     my ($response)=@_;
   39:     #print("$response ");
   40:     my @numbers=split(',',$response);
   41:     #print(" numbers ".join('-',@numbers)." ");
   42:     if (scalar(@numbers) > 1) {
   43:         #print(" numbers[0] ".$numbers[0]." "); 
   44: 	if (length($numbers[0]) > 3 || length($numbers[0]) == 0) { return -1; }
   45: 	shift(@numbers);
   46: 	#print(" numbers ".scalar(@numbers)." ");
   47: 	while (scalar(@numbers) > 1) {
   48: 	    #print(" numbers ".join('-',@numbers)." ");
   49: 	    if (length($numbers[0]) != 3) { return -2; }
   50: 	    shift(@numbers);
   51: 	}
   52: 	my ($number)=split('\.',$numbers[0]);
   53: 	#print(" number ".$number." ");
   54: 	#print(" numbers[0] ".$numbers[0]." ");
   55: 	if (length($number) != 3) { return -3; }
   56:     } else {
   57: 	my ($number)=split('\.',$numbers[0]);
   58: 	if (length($number) > 3) { return -4; }
   59:     }
   60:     return 1;
   61: }
   62: 
   63: sub caparesponse_check {
   64:     my ($answer,$response)=@_;
   65:     #not properly used yet: calc
   66:     #not to be used: $ans_fmt
   67:     my $type=$LONCAPA::CAPAresponse_args{'type'};
   68:     my $tol=$LONCAPA::CAPAresponse_args{'tol'};
   69:     my $sig=$LONCAPA::CAPAresponse_args{'sig'};
   70:     my $ans_fmt=$LONCAPA::CAPAresponse_args{'format'};
   71:     my $unit=$LONCAPA::CAPAresponse_args{'unit'};
   72:     my $calc=$LONCAPA::CAPAresponse_args{'calc'};
   73:     my $samples=$LONCAPA::CAPAresponse_args{'samples'};
   74:     
   75:     my $tol_type=''; # gets it's value from whether tol has a % or not done
   76:     my $sig_lbound=''; #done
   77:     my $sig_ubound=''; #done
   78: 
   79: 
   80:     #type's definitons come from capaParser.h
   81:     my $message='';
   82:     #remove leading and trailing whitespace
   83:     if (!defined($response)) {
   84: 	$response='';
   85:     }
   86:     if ($response=~ /^\s|\s$/) {
   87: 	$response=~ s:^\s+|\s+$::g;
   88: 	$message .="Removed ws now :$response:\n";
   89:     } else {
   90: 	$message .="no ws in :$response:\n";
   91:     }
   92:     &LONCAPA_INTERNAL_DEBUG(" type is $type ");
   93:     if ($type eq 'cs' || $type eq 'ci') {
   94: 	#for string answers make surec all places spaces occur, there is 
   95:         #really only 1 space, in both the answer and the response
   96: 	$answer=~s/ +/ /g;
   97: 	$response=~s/ +/ /g;
   98:     } elsif ($type eq 'mc') {
   99: 	$answer=~s/[\s,]//g;
  100: 	$response=~s/[\s,]//g;
  101:     }
  102:     if ($type eq 'float' && $unit=~/\$/) {
  103: 	if ($response!~/^\$/)  { return "NO_UNIT: Missing \$ "; }
  104: 	$response=~s/\$//g;
  105:     }
  106:     if ($type eq 'float' && $unit=~/\,/ && (&check_commas($response)<0)) {
  107: 	return "COMMA_FAIL:";
  108:     }
  109:     $ans_fmt=~s/\W//g;
  110:     $unit=~s/[\$,]//g;
  111:     if ($type eq 'float') { $response=~s/,//g; }
  112: 
  113:     if (length($response) > 500) { return "TOO_LONG: Answer too long"; }
  114: 
  115:     if ($type eq '' ) {
  116: 	$message .= "Didn't find a type :$type: defaulting\n";
  117: 	if ( $answer eq ($answer *1.0)) { $type = 2;
  118: 				      } else { $type = 3; }
  119:     } else {
  120: 	if    ($type eq 'cs')    { $type = 4; }
  121: 	elsif ($type eq 'ci')    { $type = 3 }
  122: 	elsif ($type eq 'mc')    { $type = 5; }
  123: 	elsif ($type eq 'fml')   { $type = 8; }
  124:         elsif ($type eq 'math')  { $type = 9; }
  125: 	elsif ($type eq 'subj')  { $type = 7; }
  126: 	elsif ($type eq 'float') { $type = 2; }
  127: 	elsif ($type eq 'int')   { $type = 1; }
  128: 	else { return "ERROR: Unknown type of answer: $type" }
  129:     }
  130: 
  131:     my $points;
  132:     my $id_list;
  133:     #formula type setup the sample points
  134:     if ($type eq '8') {
  135: 	($id_list,$points)=split(/@/,$samples);
  136: 	$message.="Found :$id_list:$points: points in $samples\n";
  137:     }
  138:     if ($tol eq '') {
  139: 	$tol=0.0;
  140: 	$tol_type=1; #TOL_ABSOLUTE
  141:     } else {
  142: 	if ($tol =~ /%$/) {
  143: 	    chop $tol;
  144: 	    $tol_type=2; #TOL_PERCENTAGE
  145: 	} else {
  146: 	    $tol_type=1; #TOL_ABSOLUTE
  147: 	}
  148:     }
  149: 
  150:     ($sig_ubound,$sig_lbound)=&LONCAPA_INTERNAL_get_sigrange($sig);
  151: 
  152:     my $reterror="";
  153:     my $result;
  154:     if ($type eq '9') {
  155:       $result = &maxima_check(&maxima_cas_formula_fix($response),&maxima_cas_formula_fix($answer),\$reterror);
  156:     } else {
  157: 	if ($type eq '8') { # fml type
  158: 	    $response = &capa_formula_fix($response);
  159: 	    $answer   = &capa_formula_fix($answer);
  160: 	}
  161:        $result = &caparesponse_capa_check_answer($response,$answer,$type,
  162: 						 $tol_type,$tol,
  163: 						 $sig_lbound,$sig_ubound,
  164: 						 $ans_fmt,$unit,$calc,$id_list,
  165: 						 $points,$external::randomseed,
  166: 						 \$reterror);
  167:     }
  168:     if    ($result == '1') { $result='EXACT_ANS'; } 
  169:     elsif ($result == '2') { $result='APPROX_ANS'; }
  170:     elsif ($result == '3') { $result='SIG_FAIL'; }
  171:     elsif ($result == '4') { $result='UNIT_FAIL'; }
  172:     elsif ($result == '5') { $result='NO_UNIT'; }
  173:     elsif ($result == '6') { $result='UNIT_OK'; }
  174:     elsif ($result == '7') { $result='INCORRECT'; }
  175:     elsif ($result == '8') { $result='UNIT_NOTNEEDED'; }
  176:     elsif ($result == '9') { $result='ANS_CNT_NOT_MATCH'; }
  177:     elsif ($result =='10') { $result='SUB_RECORDED'; }
  178:     elsif ($result =='11') { $result='BAD_FORMULA'; }
  179:     elsif ($result =='12' && !$response) { $result='MISSING_ANSWER'; }
  180:     elsif ($result =='12') { $result='WANTED_NUMERIC'; }
  181:     elsif ($result =='13') { $result='UNIT_INVALID_INSTRUCTOR'; }
  182:     elsif ($result =='141') { $result='UNIT_INVALID_STUDENT'; }
  183:     elsif ($result =='142') { $result='UNIT_INVALID_STUDENT'; }
  184:     elsif ($result =='143') { $result='UNIT_INVALID_STUDENT'; }
  185:     elsif ($result =='15') { $result='UNIT_IRRECONCIBLE'; }
  186:     else  {$result = "ERROR: Unknown Result:$result:$@:";}
  187: 
  188:     return ("$result:\nRetError $reterror:\nAnswer $answer:\nResponse $response:\n type-$type|$tol|$tol_type|$sig:$sig_lbound:$sig_ubound|$unit|\n$message",$reterror);
  189: }
  190: 
  191: sub maxima_cas_formula_fix {
  192:    my ($expression)=@_;
  193:    return &implicit_multiplication($expression);
  194: }
  195: 
  196: sub capa_formula_fix {
  197:    my ($expression)=@_;
  198:    return &implicit_multiplication($expression);
  199: }
  200: 
  201: sub implicit_multiplication {
  202:     my ($expression)=@_;
  203: # Escape scientific notation, so 3e8 does not become 3*e*8
  204: # 3e8 -> 3&8; 3e-8 -> 3&-8; 3E+8 -> e&+8
  205:     $expression=~s/(\d+)e([\+\-]*\d+)/$1\&\($2\)/gsi;
  206: # 3x10^8 -> 3&8; 3*10^-8 -> 3&-8
  207:     $expression=~s/(\d+)(?:x|\*)10(?:\^|\*\*)([\+\-]*\d+)/$1\&\($2\)/gsi;
  208: # Fill in multiplication signs
  209: # a b -> a*b
  210:     $expression=~s/\s+/\*/gs;
  211: # 3a -> 3*a; 3( -> 3*(; 3A -> 3*a
  212:     $expression=~s/(\d)([a-zA-Z\(])/$1\*$2/gs;
  213: # a3 -> a*3; )3 -> )*3
  214:     $expression=~s/([a-zA-Z])(\d)/$1\*$2/gs;
  215: # )a -> )*a
  216:     $expression=~s/\)(\w)/\)\*$1/gs;
  217: # 3&8 -> 3e8; 3&-4 -> 3e-4
  218:     $expression=~s/(\d+)\&\(([\+\-]*\d+)\)/$1e$2/gs;
  219:     return $expression;
  220: }
  221: 
  222: sub caparesponse_check_list {
  223:     my $response=$LONCAPA::CAPAresponse_args{'response'};
  224:     my $result="Got response :".join(':',@LONCAPA::CAPAresponse_answer).":\n";
  225:     &LONCAPA_INTERNAL_DEBUG("args ".join(':',%LONCAPA::CAPAresponse_args));
  226:     my @responselist;
  227:     my $type = $LONCAPA::CAPAresponse_args{'type'};
  228:     $result.="Got type :$type:\n";
  229:     if ($type ne '' && $#LONCAPA::CAPAresponse_answer > 0) {
  230: 	(@responselist)=split(/,/,$response);
  231: 	if (@responselist < @LONCAPA::CAPAresponse_answer) {
  232: 	    return 'MISSING_ANSWER';
  233: 	}
  234: 	if (@responselist > @LONCAPA::CAPAresponse_answer) {
  235: 	    return 'EXTRA_ANSWER';
  236: 	}
  237:     } else {
  238: 	(@responselist)=($response);
  239:     }
  240:     $result.="Initial final response :$responselist['-1']:\n";
  241:     my $unit;
  242:     if ($type eq '' || $type eq 'float') {
  243: 	#for numerical problems split off the unit
  244: 	if ( $responselist['-1']=~ /(.*[^\s])\s+([^\s]+)/ ) {
  245: 	    $responselist['-1']=$1;
  246: 	    $unit=$2;
  247: 	}
  248:     }
  249:     $result.="Final final response :$responselist['-1']:$unit:\n";
  250:     $unit=~s/\s//;
  251: 
  252:     my ($awards, @msgs, $i);
  253:     foreach my $thisanswer (@LONCAPA::CAPAresponse_answer) {
  254: 	my ($msg,$aresult);
  255: 	$result.="trying answer :$thisanswer:\n";
  256: 	if (defined($thisanswer)) {
  257: 	    if ($unit eq '') {
  258: 		($aresult,$msg)=&caparesponse_check($thisanswer,
  259: 						    $responselist[$i]);
  260: 	    } else {
  261: 		($aresult,$msg)=&caparesponse_check($thisanswer,
  262: 						    $responselist[$i]." $unit");
  263: 	    }
  264: 	} else {
  265: 	    $aresult='ERROR';
  266: 	    $msg='answer was undefined';
  267: 	}
  268: 	&LONCAPA_INTERNAL_DEBUG("after if $aresult -- $msg");
  269: 	my ($temp)=split(/:/, $aresult);
  270: 	$awards.="$temp,";
  271: 	$result.=$aresult;
  272: 	push(@msgs,$msg);
  273: 	$i++;
  274:     }
  275:     chop($awards);
  276:     return ("$awards:\n$result",@msgs);
  277: }
  278: 
  279: sub tex {
  280:     if ( $external::target eq "tex" ) {
  281: 	return $_[0];
  282:     } else {
  283: 	return $_[1];
  284:     }
  285: }
  286: 
  287: sub var_in_tex {
  288:     if ( $external::target eq "tex" ) {
  289: 	return $_[0];
  290:     } else {
  291: 	return "";
  292:     }
  293: }
  294: 
  295: sub web {
  296:     if ( $external::target eq "tex" ) {
  297: 	return $_[1];
  298:     } else {
  299: 	if ( $external::target eq "web" || $external::target eq "answer") {
  300: 	    return $_[2];
  301: 	} else {
  302: 	    return $_[0];
  303: 	}
  304:     }
  305: }
  306: 
  307: sub html {
  308:     if ( $external::target eq "web" ) {
  309: 	return shift;
  310:     }
  311: }
  312: 
  313: sub hinton {
  314:     return 0;
  315: }
  316: 
  317: sub random {
  318:     my ($start,$end,$step)=@_;
  319:     if ( ! $hidden::RANDOMINIT ) {
  320: 	if ($external::randomseed == 0) { $external::randomseed=1; }
  321: 	if ($external::randomseed =~/,/) {
  322: 	    my ($num1,$num2)=split(/,/,$external::randomseed);
  323: 	    &random_set_seed(1,abs($num1));
  324: 	} elsif ($external::randomseed =~/:/) {
  325: 	    my ($num1,$num2)=split(/:/,$external::randomseed);
  326: 	    &random_set_seed(abs($num1),abs($num2));
  327: 	} else {
  328: 	    &random_set_seed(1,int(abs($external::randomseed)));
  329: 	}
  330: 	&math_random_uniform();
  331: 	$hidden::RANDOMINIT=1;
  332:     }
  333:     if (!defined($step)) { $step=1; }
  334:     my $num=1+int(($end-$start)/$step);
  335:     my $result=$start + int(&math_random_uniform() * $num)*$step;
  336:     return $result;
  337: }
  338: 
  339: sub random_normal {
  340:     my ($item_cnt,$seed,$av,$std_dev) = @_;
  341:     my @oldseed=&random_get_seed();
  342:     my @retArray;
  343:     &random_set_seed_from_phrase($seed);
  344:     @retArray=&math_random_normal($item_cnt,$av,$std_dev);
  345:     &random_set_seed(@oldseed);
  346:     return @retArray;
  347: }
  348: 
  349: sub random_beta {
  350:     my ($item_cnt,$seed,$aa,$bb) = @_;
  351:     my @oldseed=&random_get_seed();
  352:     my @retArray;
  353:     &random_set_seed_from_phrase($seed);
  354:     @retArray=&math_random_beta($item_cnt,$aa,$bb);
  355:     &random_set_seed(@oldseed);
  356:     return @retArray;
  357: }
  358: 
  359: sub random_gamma {
  360:     my ($item_cnt,$seed,$a,$r) = @_;
  361:     my @oldseed=&random_get_seed();
  362:     my @retArray;
  363:     &random_set_seed_from_phrase($seed);
  364:     @retArray=&math_random_gamma($item_cnt,$a,$r);
  365:     &random_set_seed(@oldseed);
  366:     return @retArray;
  367: }
  368: 
  369: sub random_exponential {
  370:     my ($item_cnt,$seed,$av) = @_;
  371:     my @oldseed=&random_get_seed();
  372:     my @retArray;
  373:     &random_set_seed_from_phrase($seed);
  374:     @retArray=&math_random_exponential($item_cnt,$av);
  375:     &random_set_seed(@oldseed);
  376:     return @retArray;
  377: }
  378: 
  379: sub random_poisson {
  380:     my ($item_cnt,$seed,$mu) = @_;
  381:     my @oldseed=&random_get_seed();
  382:     my @retArray;
  383:     &random_set_seed_from_phrase($seed);
  384:     @retArray=&math_random_poisson($item_cnt,$mu);
  385:     &random_set_seed(@oldseed);
  386:     return @retArray;
  387: }
  388: 
  389: sub random_chi {
  390:     my ($item_cnt,$seed,$df) = @_;
  391:     my @oldseed=&random_get_seed();
  392:     my @retArray;
  393:     &random_set_seed_from_phrase($seed);
  394:     @retArray=&math_random_chi_square($item_cnt,$df);
  395:     &random_set_seed(@oldseed);
  396:     return @retArray;
  397: }
  398: 
  399: sub random_noncentral_chi {
  400:     my ($item_cnt,$seed,$df,$nonc) = @_;
  401:     my @oldseed=&random_get_seed();
  402:     my @retArray;
  403:     &random_set_seed_from_phrase($seed);
  404:     @retArray=&math_random_noncentral_chi_square($item_cnt,$df,$nonc);
  405:     &random_set_seed(@oldseed);
  406:     return @retArray;
  407: }
  408: 
  409: sub random_f {
  410:     my ($item_cnt,$seed,$dfn,$dfd) = @_;
  411:     my @oldseed=&random_get_seed();
  412:     my @retArray;
  413:     &random_set_seed_from_phrase($seed);
  414:     @retArray=&math_random_f($item_cnt,$dfn,$dfd);
  415:     &random_set_seed(@oldseed);
  416:     return @retArray;
  417: }
  418: 
  419: sub random_noncentral_f {
  420:     my ($item_cnt,$seed,$dfn,$dfd,$nonc) = @_;
  421:     my @oldseed=&random_get_seed();
  422:     my @retArray;
  423:     &random_set_seed_from_phrase($seed);
  424:     @retArray=&math_random_noncentral_f($item_cnt,$dfn,$dfd,$nonc);
  425:     &random_set_seed(@oldseed);
  426:     return @retArray;
  427: }
  428: 
  429: sub random_multivariate_normal {
  430:     my ($item_cnt,$seed,$mean,$covar) = @_;
  431:     my @oldseed=&random_get_seed();
  432:     &random_set_seed_from_phrase($seed);
  433:     my @retArray=&math_random_multivariate_normal($item_cnt,@$mean,@$covar);
  434:     &random_set_seed(@oldseed);
  435:     return @retArray;
  436: }
  437: 
  438: sub random_multinomial {
  439:     my ($item_cnt,$seed,@p) = @_;
  440:     my @oldseed=&random_get_seed();
  441:     my @retArray;
  442:     &random_set_seed_from_phrase($seed);
  443:     my @retArray=&math_random_multinomial($item_cnt,@p);
  444:     &random_set_seed(@oldseed);
  445:     return @retArray;
  446: }
  447: 
  448: sub random_permutation {
  449:     my ($seed,@inArray) = @_;
  450:     my @oldseed=&random_get_seed();
  451:     my @retArray;
  452:     &random_set_seed_from_phrase($seed);
  453:     @retArray=&math_random_permutation(@inArray);
  454:     &random_set_seed(@oldseed);
  455:     return @retArray;
  456: }
  457: 
  458: sub random_uniform {
  459:     my ($item_cnt,$seed,$low,$high) = @_;
  460:     my @oldseed=&random_get_seed();
  461:     my @retArray;
  462:     &random_set_seed_from_phrase($seed);
  463:     @retArray=&math_random_uniform($item_cnt,$low,$high);
  464:     &random_set_seed(@oldseed);
  465:     return @retArray;
  466: }
  467: 
  468: sub random_uniform_integer {
  469:     my ($item_cnt,$seed,$low,$high) = @_;
  470:     my @oldseed=&random_get_seed();
  471:     my @retArray;
  472:     &random_set_seed_from_phrase($seed);
  473:     @retArray=&math_random_uniform_integer($item_cnt,$low,$high);
  474:     &random_set_seed(@oldseed);
  475:     return @retArray;
  476: }
  477: 
  478: sub random_binomial {
  479:     my ($item_cnt,$seed,$nt,$p) = @_;
  480:     my @oldseed=&random_get_seed();
  481:     my @retArray;
  482:     &random_set_seed_from_phrase($seed);
  483:     @retArray=&math_random_binomial($item_cnt,$nt,$p);
  484:     &random_set_seed(@oldseed);
  485:     return @retArray;
  486: }
  487: 
  488: sub random_negative_binomial {
  489:     my ($item_cnt,$seed,$ne,$p) = @_;
  490:     my @oldseed=&random_get_seed();
  491:     my @retArray;
  492:     &random_set_seed_from_phrase($seed);
  493:     @retArray=&math_random_negative_binomial($item_cnt,$ne,$p);
  494:     &random_set_seed(@oldseed);
  495:     return @retArray;
  496: }
  497: 
  498: sub abs { CORE::abs(shift) }
  499: sub sin { CORE::sin(shift) }
  500: sub cos { CORE::cos(shift) }
  501: sub exp { CORE::exp(shift) }
  502: sub int { CORE::int(shift) }
  503: sub log { CORE::log(shift) }
  504: sub atan2 { CORE::atan2($_[0],$_[1]) }
  505: sub sqrt { CORE::sqrt(shift) }
  506: 
  507: sub tan  { CORE::sin($_[0]) / CORE::cos($_[0]) }
  508: #sub atan { atan2($_[0], 1); }
  509: #sub acos { atan2(sqrt(1 - $_[0] * $_[0]), $_[0] ); }
  510: #sub asin { atan2($_[0], sqrt(1- $_[0] * $_[0]) );  }
  511: 
  512: sub log10 { CORE::log($_[0])/CORE::log(10); }
  513: 
  514: sub factorial {
  515:     my $input = CORE::int(shift);
  516:     return "Error - unable to take factorial of an negative number ($input)" if $input < 0;
  517:     return "Error - factorial result is greater than system limit ($input)" if $input > 170;
  518:     return 1 if $input == 0;
  519:     my $result = 1; 
  520:     for (my $i=2; $i<=$input; $i++) { $result *= $i }
  521:     return $result;
  522: }
  523: 
  524: sub sgn {
  525:     return -1 if $_[0] < 0;
  526:     return 0 if $_[0] == 0;
  527:     return 1 if $_[0] > 0;
  528: }
  529: 
  530: sub min {
  531:     my @sorted = sort { $a <=> $b || $a cmp $b } @_;
  532:     return shift @sorted;
  533: }
  534: 
  535: sub max {
  536:     my @sorted = sort { $a <=> $b || $a cmp $b } @_;
  537:     return pop @sorted;
  538: }
  539: 
  540: sub roundto {
  541:     my ($input,$n) = @_;
  542:     return sprintf('%.'.$n.'f',$input);
  543: }
  544: 
  545: sub to_string {
  546:     my ($input,$n) = @_;
  547:     return sprintf($input) if $n eq "";
  548:     $n = '.'.$n if $n !~ /^\./;
  549:     return sprintf('%'.$n,$input) if $n ne "";
  550: }
  551: 
  552: sub sub_string {
  553:     my ($str,$start,$len) = @_;
  554:     return substr($str,$start-1,$len);
  555: }
  556: 
  557: sub pow   {return $_[0] ** $_[1]; }
  558: sub ceil  {return (($_[0]-CORE::int($_[0]))== 0.0) ? $_[0] : (($_[0] > 0) ? (CORE::int($_[0])+ 1) : CORE::int($_[0])); }
  559: sub floor  {return (($_[0]-CORE::int($_[0]))== 0.0) ? $_[0] : (($_[0] > 0) ? CORE::int($_[0]) : (CORE::int($_[0])-1)); }
  560: #sub floor {return int($_[0]); }
  561: 
  562: sub format {
  563:     my ($value,$fmt)=@_;
  564:     my ($dollarmode,$commamode,$alwaysperiod,$options);
  565:     if ($fmt =~ /^([^\d]*)(.*)/) { $options=$1; $fmt=$2; } 
  566:     #if ($options =~ /\$/) { $dollamode=1; }
  567:     #if ($options =~ /,/)  { $commamode=1; }
  568:     if ($options =~ /\./) { $alwaysperiod=1; }
  569:     my $result;
  570:     if ($fmt=~/s$/i) {
  571: 	$result=&format_significant_figures($value,$fmt);
  572:     } else {
  573: 	$fmt=~s/e/E/g;
  574: 	$result=sprintf('%.'.$fmt,$value);
  575: 	if ($alwaysperiod && $fmt eq '0f') { $result .='.'; }
  576: 	$result=~s/(E[+-]*)0/$1/;
  577:     }
  578:     #if ($dollarmode) {$result=&dollarformat($result);}
  579:     #if ($commamode) {$result=&commaformat($result);}
  580:     return $result;
  581: }
  582: 
  583: sub chemparse {
  584:     my ($reaction) = @_;
  585:     my @tokens = split(/(\s\+|\->|<=>|<\-|\.)/,$reaction);
  586:     my $formula = '';
  587:     foreach my $token (@tokens) {
  588: 	if ($token eq '->' ) {
  589: 	    $formula .= '<m>\ensuremath{\rightarrow}</m> ';
  590: 	    next;
  591: 	}
  592: 	if ($token eq '<-' ) {
  593: 	    $formula .= '<m>\ensuremath{\leftarrow}</m> ';
  594: 	    next;
  595: 	}  
  596: 	if ($token eq '<=>') {
  597: 	    if ($external::target eq 'web' &&
  598: 		&EXT('request.browser.unicode')) {
  599: 		$formula .= '&#8652; ';
  600: 	    } else {
  601: 		$formula .= &web('<=> ','<m>\ensuremath{\rightleftharpoons}</m> ',
  602: 				 '&lt;=&gt; ');
  603: 	    }
  604: 	    next;
  605: 	}
  606: 	if ($token eq '.') {
  607: 	  $formula =~ s/(\&nbsp\;| )$//;
  608: 	  $formula .= '&middot;';
  609: 	  next;
  610: 	}
  611: 	$token =~ /^\s*([\d|\/]*(?:&frac\d\d)?)(.*)/;
  612:         $formula .= $1 if ($1 ne '1');  # stoichiometric coefficient
  613: 	
  614: 	my $molecule = $2;
  615: 	# subscripts
  616: 	$molecule =~ s|(?<=[a-zA-Z\)\]\s])(\d+)|<sub>$1</sub>|g;
  617: 	# superscripts
  618: 	$molecule =~ s|\^(\d*[+\-]*)|<sup>$1</sup>|g;
  619: 	# strip whitespace
  620: 	$molecule =~ s/\s*//g;
  621: 	# forced space
  622: 	$molecule =~ s/_/ /g;
  623: 	$molecule =~ s/-/&minus;/g;
  624: 	$formula .= $molecule.'&nbsp;';
  625:     }
  626:     # get rid of trailing space
  627:     $formula =~ s/(\&nbsp\;| )$//;
  628:     return &xmlparse($formula);
  629: }
  630: 
  631: sub prettyprint {
  632:     my ($value,$fmt,$target)=@_;
  633:     my $result;
  634:     if (!$target) { $target = $external::target; }
  635:     if ($fmt =~ /chem/i) { return(&chemparse($value)); }
  636:     my ($dollarmode,$commamode,$alwaysperiod,$options);
  637:     if ($fmt =~ /^([^\d]*)(.*)/) { $options=$1; $fmt=$2; } 
  638:     if ($options =~ /\$/) { $dollarmode=1; }
  639:     if ($options =~ /,/)  { $commamode=1; }
  640:     if ($options =~ /\./) { $alwaysperiod=1; }
  641:     if ($fmt=~/s$/i) {
  642: 	$value=&format_significant_figures($value,$fmt);
  643:     } elsif ($fmt) {
  644: 	$value=sprintf('%.'.$fmt,$value);
  645:     }
  646:     if ($alwaysperiod && $fmt eq '0f') {
  647: 	if ($target eq 'tex') {
  648: 	    $value .='\\ensuremath{.}';
  649: 	} else {
  650: 	    $value .='.';
  651: 	}
  652:     }
  653:     if ($value =~ /([0-9\.\-\+]+)E([0-9\-\+]+)/i ) {
  654: 	my $frac=$1;
  655: 	if ($dollarmode) { $frac=&dollarformat($frac); }
  656: 	if ($commamode) { $frac=&commaformat($frac); }
  657: 	my $exponent=$2;
  658: 	$exponent=~s/^\+0*//;
  659: 	$exponent=~s/^-0*/-/;
  660: 	$exponent=~s/^-0*/-/;
  661: 	if ($exponent eq '-') { undef($exponent); }
  662: 	if ($exponent) {
  663: 	    if ($target eq 'web') {
  664: 		$result=$frac.'&#215;10<sup>'.$exponent.'</sup>';
  665: 	    } elsif ($target eq 'tex') {
  666: 		$result='\ensuremath{'.$frac.'\times 10^{'.$exponent.'}}';
  667: 	    } else {
  668: 		$result=$value;
  669: 	    }
  670: 	} else {
  671: 	    $result=$frac;
  672: 	}
  673:     } else {
  674: 	$result=$value;
  675: 	if    ($dollarmode) { $result=&dollarformat($result,$target); }
  676: 	elsif ($commamode)  { $result=&commaformat($result,$target); }
  677:     }
  678:     return $result;
  679: }
  680: 
  681: sub commaformat {
  682:     my ($number,$target) = @_;
  683:     if ($number =~ /\./) {
  684: 	while ($number =~ /([^0-9]*)([0-9]+)([^\.,][^\.,][^\.,])([,0-9]*\.[0-9]*)$/) {
  685: 	    $number = $1.$2.','.$3.$4;
  686: 	}
  687:     } else {
  688: 	while ($number =~ /^([^0-9]*)([0-9]+)([^,][^,][^,])([,0-9]*)$/) {
  689: 	    $number = $1.$2.','.$3.$4;
  690: 	}
  691:     }
  692:     return $number;
  693: }
  694: 
  695: sub dollarformat {
  696:     my ($number,$target) = @_;
  697:     if (!$target) { $target = $external::target; }
  698:     $number=&commaformat($number,$target);
  699:     if ($target eq 'tex') {
  700: 	$number='\$'.$number; #' stupid emacs
  701:     } else {
  702: 	$number='$'.$number; #' stupid emacs
  703:     }
  704:     return $number; 
  705: }
  706: 
  707: # format of form ns or nS where n is an integer
  708: sub format_significant_figures {
  709:     my ($number,$format) = @_; 
  710:     return '0' if ($number == 0);
  711:     # extract number of significant figures needed
  712:     my ($sig) = ($format =~ /(\d+)s/i);
  713:     # arbitrary choice - suggestions ?? or throw error message?
  714:     $sig = 3 if ($sig eq '');
  715:     # save the minus sign
  716:     my $sign = ($number < 0) ? '-' : '';
  717:     $number = abs($number);
  718:     # needed to correct for a number greater than 1 (or
  719:     my $power = ($number < 1) ? 0 : 1;
  720:     # could round up. Take the integer part of log10.
  721:     my $x10 = int(log($number)/log(10));
  722:     # find number with values left of decimal pt = # of sign figs.
  723:     my $xsig = $number*10**($sig-$x10-$power);
  724:     # get just digits left of decimal pt - also rounds off correctly
  725:     my $xint  = sprintf('%.0f',$xsig);
  726:     # save any trailing zero's
  727:     my ($zeros) = ($xint =~ /(0+)$/);
  728:     # return number to original magnitude
  729:     my $numSig = $xint*10**($x10-$sig+$power);
  730:     # insert trailing zero's if have decimal point
  731:     $numSig =~ s/^(\d+)\.(\d+)(\e?(.*)?)$/$1\.$2$zeros$3/;
  732:     # put a decimal pt for number ending with 0 and length = # of sig fig
  733:     $numSig.='.' if (length($numSig) == $sig && $numSig =~ /0$/);
  734:     if (length($numSig) < $sig) {
  735: 	$numSig.='.'.substr($zeros,0,($sig-length($numSig)));
  736:     }
  737:     # return number with sign
  738:     return $sign.$numSig;
  739: 
  740: }
  741: 
  742: sub map {
  743:     my ($phrase,$dest,$source)=@_;
  744:     my @oldseed=&random_get_seed();
  745:     my @seed = &random_seed_from_phrase($phrase);
  746:     &random_set_seed(@seed);
  747:     my $destct = scalar(@$dest);
  748:     if (!$source) {
  749: 	my @output;
  750: 	my @idx = &math_random_permuted_index($destct);
  751: 	my $ctr = 0;
  752: 	while ($ctr < $destct) {
  753: 	    $output[$ctr] = $$dest[$idx[$ctr]];
  754: 	    $ctr++;
  755: 	}
  756:         &random_set_seed(@oldseed);
  757: 	return @output;
  758:     } else {
  759: 	my $num = scalar(@$source);
  760: 	my @idx = &math_random_permuted_index($num);
  761: 	my $ctr = 0;
  762: 	my $tot = $num;
  763: 	$tot = $destct if $destct < $num;
  764: 	if (ref($$dest[0])) {
  765: 	    while ($ctr < $tot) {
  766: 		${$$dest[$ctr]} = $$source[$idx[$ctr]];
  767: 	        $ctr++;
  768:             }
  769:         } else {
  770: 	    while ($ctr < $tot) {
  771: 		$$dest[$ctr] = $$source[$idx[$ctr]];
  772: 		$ctr++;
  773: 	    }
  774: 	}
  775:     }
  776:     &random_set_seed(@oldseed);
  777:     return '';
  778: }
  779: 
  780: sub rmap {
  781:     my ($phrase,$dest,$source)=@_;
  782:     my @oldseed=&random_get_seed();
  783:     my @seed = &random_seed_from_phrase($phrase);
  784:     &random_set_seed(@seed);
  785:     my $destct = scalar(@$dest);
  786:     if (!$source) {
  787: 	my @idx = &math_random_permuted_index($destct);
  788: 	my $ctr = 0;
  789: 	my @r_idx;
  790: 	while ($ctr < $destct) {
  791: 	    $r_idx[$idx[$ctr]] = $ctr;
  792: 	    $ctr++;
  793: 	}
  794: 	my @output;
  795: 	$ctr = 0;
  796: 	while ($ctr < $destct) {
  797: 	    $output[$ctr] = $$dest[$r_idx[$ctr]];
  798: 	    $ctr++;
  799: 	}
  800:         &random_set_seed(@oldseed);
  801: 	return @output;
  802:     } else {
  803: 	my $num = scalar(@$source);
  804: 	my @idx = &math_random_permuted_index($num);
  805: 	my $ctr = 0;
  806: 	my $tot = $num;
  807: 	$tot = $destct if $destct < $num;
  808: 	my @r_idx;
  809: 	while ($ctr < $tot) {
  810: 	    $r_idx[$idx[$ctr]] = $ctr;
  811: 	    $ctr++;
  812: 	}
  813: 	$ctr = 0;
  814: 	if (ref($$dest[0])) {
  815: 	    while ($ctr < $tot) {
  816: 		${$$dest[$ctr]} = $$source[$r_idx[$ctr]];
  817: 	        $ctr++;
  818:             }
  819:         } else {
  820: 	    while ($ctr < $tot) {
  821: 		$$dest[$ctr] = $$source[$r_idx[$ctr]];
  822: 		$ctr++;
  823: 	    }
  824: 	}
  825:     }
  826:     &random_set_seed(@oldseed);
  827:     return '';
  828: }
  829: 
  830: sub capa_id { return }
  831: 
  832: sub problem { return }
  833: 
  834: sub name{
  835:     my $fullname = &EXT('environment.lastname').', '.&EXT('environment.firstname').' '.&EXT('environment.middlename');
  836:     $fullname = "" if $fullname eq ",  ";
  837:     $fullname =~ s/\%2d/-/g;
  838:     return $fullname;
  839: }
  840: 
  841: sub student_number { 
  842:     my $id = &EXT('environment.id');
  843:     $id = '' if $id eq "";
  844:     return $id;
  845: }
  846: 
  847: sub class {
  848:     my $course = &EXT('course.description');
  849:     $course = '' if $course eq "";
  850:     return $course;
  851: }
  852: 
  853: sub sec { 
  854:     my $sec = &EXT('request.course.sec');
  855:     $sec = '' if $sec eq "";
  856:     return $sec;
  857: }
  858: 
  859: sub open_date { 
  860:     my @dc = split(/\s+/,localtime(&EXT('resource.0.opendate')));
  861:     return '' if ($dc[0] eq "Wed" and $dc[2] == 31 and $dc[4] == 1969);
  862:     my @hm = split(/:/,$dc[3]);
  863:     my $ampm = " am";
  864:     if ($hm[0] > 12) {
  865: 	$hm[0]-=12;
  866: 	$ampm = " pm";
  867:     }
  868:     return $dc[0].', '.$dc[1].' '.$dc[2].', '.$dc[4].' at '.$hm[0].':'.$hm[1].$ampm;
  869: }
  870: 
  871: sub due_date { 
  872:     my @dc = split(/\s+/,localtime(&EXT('resource.0.duedate')));
  873:     return '' if ($dc[0] eq "Wed" and $dc[2] == 31 and $dc[4] == 1969);
  874:     my @hm = split(/:/,$dc[3]);
  875:     my $ampm = " am";
  876:     if ($hm[0] > 12) {
  877: 	$hm[0]-=12;
  878: 	$ampm = " pm";
  879:     }
  880:     return $dc[0].', '.$dc[1].' '.$dc[2].', '.$dc[4].' at '.$hm[0].':'.$hm[1].$ampm;
  881: }
  882: 
  883: sub answer_date { 
  884:     my @dc = split(/\s+/,localtime(&EXT('resource.0.answerdate')));
  885:     return '' if ($dc[0] eq "Wed" and $dc[2] == 31 and $dc[4] == 1969);
  886:     my @hm = split(/:/,$dc[3]);
  887:     my $ampm = " am";
  888:     if ($hm[0] > 12) {
  889: 	$hm[0]-=12;
  890: 	$ampm = " pm";
  891:     }
  892:     return $dc[0].', '.$dc[1].' '.$dc[2].', '.$dc[4].' at '.$hm[0].':'.$hm[1].$ampm;
  893: }
  894: 
  895: sub array_moments {
  896:     my @input=@_;
  897:     my (@output,$N);
  898:     $N=scalar (@input);
  899:     $output[0]=$N;
  900:     if ($N <= 1) {
  901: 	$output[1]=$input[0];
  902: 	$output[1]="Input array not defined" if ($N == 0);
  903: 	$output[2]="variance undefined for N<=1";
  904: 	$output[3]="skewness undefined for N<=1";
  905: 	$output[4]="kurtosis undefined for N<=1";
  906: 	return @output;
  907:     }
  908:     my $sum=0;
  909:     foreach my $line (@input) {
  910: 	$sum+=$line;
  911:     }
  912:     $output[1] = $sum/$N;
  913:     my ($x,$sdev,$var,$skew,$kurt) = 0;
  914:     foreach my $line (@input) {
  915: 	$x=$line-$output[1];
  916: 	$var+=$x**2;
  917: 	$skew+=$x**3;
  918: 	$kurt+=$x**4;
  919:     }
  920:     $output[2]=$var/($N-1);
  921:     $sdev=CORE::sqrt($output[2]);
  922:     if ($sdev == 0) {
  923: 	$output[3]="inf-variance=0";
  924: 	$output[4]="inf-variance=0";
  925: 	return @output;
  926:     }
  927:     $output[3]=$skew/($sdev**3*$N);
  928:     $output[4]=$kurt/($sdev**4*$N)-3;
  929:     return @output;
  930: }
  931: 
  932: sub choose {
  933:     my $num = $_[0];
  934:     return $_[$num];
  935: }
  936: 
  937: #&sum1(1,$x,sub { &sum1($_[0],2*$_[0], sub { fact($_[0])**2 })});
  938: #sub sum1 {
  939: #    my ($start,$end,$sub)=@_;
  940: #    my $sum=0;
  941: #    for (my $i=$start;$i<=$end;$i++) {
  942: #        $sum+=&$sub($i);
  943: #    }
  944: #    return $sum
  945: #}
  946: 
  947: #&sum2('a',1,$x,'&sum2(\'b\',$a,2*$a, \'&factorial($b)**2\')');
  948: #sub sum2 {
  949: #    my ($varname,$start,$end,$line)=@_;
  950: #    my $sum=0;
  951: #    for (my $i=$start;$i<=$end;$i++) {
  952: #	my $func=sub {
  953: #	    eval("\$".$varname."=$i");
  954: #	    eval($line);
  955: #	};
  956: #        $sum+=&$func($i);
  957: #    }
  958: #    return $sum
  959: #}
  960: 
  961: # expiremental idea
  962: sub proper_path {
  963:     my ($path)=@_;
  964:     if ( $external::target eq "tex" ) {
  965: 	return '/home/httpd/html'.$path;
  966:     } else {
  967: 	return $path;
  968:     }
  969: }
  970: 

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