Annotation of loncom/homework/default_homework.lcpm, revision 1.97

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

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