File:  [LON-CAPA] / loncom / homework / default_homework.lcpm
Revision 1.108: download - view: text, annotated - select for diffs
Fri Jun 30 21:24:27 2006 UTC (17 years, 10 months ago) by www
Branches: MAIN
CVS tags: HEAD
Partial bug #977: implicit multiplication in clear-cut places

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

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