File:  [LON-CAPA] / loncom / homework / default_homework.lcpm
Revision 1.106: download - view: text, annotated - select for diffs
Tue Dec 20 20:00:42 2005 UTC (18 years, 4 months ago) by albertel
Branches: MAIN
CVS tags: version_2_1_X, version_2_1_3, version_2_1_2, version_2_1_1, version_2_1_0, version_2_0_99_1, HEAD
- need to wlak the response array.

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

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