File:  [LON-CAPA] / loncom / homework / caparesponse / caparesponse.pm
Revision 1.266: download - view: text, annotated - select for diffs
Thu Feb 20 06:36:00 2025 UTC (2 days, 16 hours ago) by raeburn
Branches: MAIN
CVS tags: version_2_12_X, HEAD
- WCAG 2 compliance.

    1: # The LearningOnline Network with CAPA
    2: # caparesponse definition
    3: #
    4: # $Id: caparesponse.pm,v 1.266 2025/02/20 06:36:00 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: package Apache::caparesponse;
   30: use strict;
   31: use capa;
   32: use Safe::Hole;
   33: use Apache::lonmaxima();
   34: use Apache::lonlocal;
   35: use Apache::lonnet;
   36: use Apache::lonmsg();
   37: use Apache::response();
   38: use Storable qw(dclone);
   39: use Apache::lonnet;
   40: 
   41: BEGIN {
   42:     &Apache::lonxml::register('Apache::caparesponse',('numericalresponse','stringresponse','formularesponse'));
   43: }
   44: 
   45: my %answer;
   46: my @answers;
   47: my @alphabet=('A'..'Z');
   48: 
   49: sub get_answer { return %answer; };
   50: sub push_answer{ push(@answers,dclone(\%answer)); undef(%answer) }
   51: sub pop_answer { %answer = %{pop(@answers)}; };
   52: 
   53: my $cur_name;
   54: my $tag_internal_answer_name = 'INTERNAL';
   55: 
   56: sub start_answer {
   57:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
   58:     my $result;
   59:     $cur_name = &Apache::lonxml::get_param('name',$parstack,$safeeval);
   60:     if ($cur_name =~ /^\s*$/) { $cur_name = $Apache::lonxml::curdepth; }
   61:     my $type = &Apache::lonxml::get_param('type',$parstack,$safeeval);
   62:     if (!defined($type) && $tagstack->[-2] eq 'answergroup') {
   63: 	$type = &Apache::lonxml::get_param('type',$parstack,$safeeval,-2);
   64:     }
   65:     if (!defined($type)) { $type = 'ordered' };
   66:     $answer{$cur_name}= { 'type' => $type,
   67: 			  'answers' => [] };
   68:     if ($target eq 'edit') {
   69:   	$result.=&Apache::edit::tag_start($target,$token);
   70: 	$result.=&Apache::edit::text_arg('Name:','name',$token);
   71: 	$result.=&Apache::edit::select_arg('Type:','type',
   72: 					   [['ordered',  'Ordered'  ],
   73: 					    ['unordered','Unordered'],],
   74: 					   $token);
   75: 	$result.=&Apache::edit::end_row().&Apache::edit::start_spanning_row();
   76:     } elsif ($target eq 'modified') {
   77: 	my $constructtag = &Apache::edit::get_new_args($token,$parstack,
   78: 						       $safeeval,'name',
   79: 						       'type');
   80: 	if ($constructtag) {
   81: 	    $result = &Apache::edit::rebuild_tag($token);
   82: 	    $result.= &Apache::edit::handle_insert();
   83: 	}
   84:     }
   85:     return $result;
   86: }
   87: 
   88: sub end_answer {
   89:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
   90:     my $result;
   91:     if ($target eq 'edit') {
   92: 	$result .= &Apache::edit::tag_end();
   93:     }
   94: 
   95:     undef($cur_name);
   96:     return $result;
   97: }
   98: 
   99: sub insert_answer {
  100:     return '
  101:         <answer>
  102:             <value></value>
  103:         </answer>';
  104: }
  105: 
  106: sub start_answergroup {
  107:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
  108:     my $result;
  109:     if ($target eq 'edit') {
  110:   	$result.=&Apache::edit::tag_start($target,$token);
  111: 	$result.=&Apache::edit::select_arg('Type:','type',
  112: 					   [['ordered',  'Ordered'  ],
  113: 					    ['unordered','Unordered'],],
  114: 					   $token);
  115: 	$result.=&Apache::edit::end_row().&Apache::edit::start_spanning_row();
  116:     } elsif ($target eq 'modified') {
  117: 	my $constructtag = &Apache::edit::get_new_args($token,$parstack,
  118: 						       $safeeval,'name',
  119: 						       'type');
  120: 	if ($constructtag) {
  121: 	    $result = &Apache::edit::rebuild_tag($token);
  122: 	    $result.= &Apache::edit::handle_insert();
  123: 	}
  124:     }
  125:     return $result;
  126: }
  127: 
  128: sub end_answergroup {
  129:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
  130:     my $result;
  131:     if ($target eq 'web') {
  132:     	if (  &Apache::response::show_answer() ) {  
  133: 	    my $partid = $Apache::inputtags::part;
  134: 	    my $id = $Apache::inputtags::response[-1];
  135: 	    &set_answertext($Apache::lonhomework::history{"resource.$partid.$id.answername"},
  136: 			    $target,$token,$tagstack,$parstack,$parser,
  137: 			    $safeeval,-2);
  138: 	}
  139:     } elsif ($target eq 'edit') {
  140: 	$result .= &Apache::edit::tag_end();
  141:     }
  142:     return $result;
  143: }
  144: 
  145: sub insert_answergroup {
  146:     return '
  147:     <answergroup>
  148:         <answer>
  149:             <value></value>
  150:         </answer>
  151:     </answergroup>';
  152: }
  153: 
  154: sub start_value {
  155:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  156:     my $result;
  157:     if ( $target eq 'web' || $target eq 'tex' ||
  158: 	 $target eq 'grade' || $target eq 'webgrade' ||
  159: 	 $target eq 'answer' || $target eq 'analyze' ) {
  160: 	my $bodytext = &Apache::lonxml::get_all_text("/value",$parser,$style);
  161: 	$bodytext = &Apache::run::evaluate($bodytext,$safeeval,
  162: 					   $$parstack[-1]);
  163: 	
  164: 	push(@{ $answer{$cur_name}{'answers'} },[$bodytext]);
  165: 	
  166:     } elsif ($target eq 'edit') {
  167:   	$result.=&Apache::edit::tag_start($target,$token);
  168: 	my $bodytext = &Apache::lonxml::get_all_text("/value",$parser,$style);
  169: 	$result.=&Apache::edit::editline($token->[1],$bodytext,undef,40).
  170: 	    &Apache::edit::end_row();
  171:     } elsif ($target eq 'modified') {
  172: 	$result=$token->[4].&Apache::edit::modifiedfield('/value',$parser);
  173:     }
  174:     return $result;
  175: }
  176: 
  177: sub end_value {
  178:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
  179:     my $result;
  180:     if ($target eq 'edit') {
  181: 	$result = &Apache::edit::end_table();
  182:     }
  183:     return $result;
  184: }
  185: 
  186: sub insert_value {
  187:     return '
  188:             <value></value>';
  189: }
  190: 
  191: sub start_vector {
  192:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  193:     my $result;
  194:     if ( $target eq 'web' || $target eq 'tex' ||
  195: 	 $target eq 'grade' || $target eq 'webgrade' ||
  196: 	 $target eq 'answer' || $target eq 'analyze' ) {
  197: 	my $bodytext = &Apache::lonxml::get_all_text("/vector",$parser,$style);
  198: 	my @values = &Apache::run::run($bodytext,$safeeval,$$parstack[-1]);
  199: 	if (@values == 1) {
  200: 	    @values = split(',',$values[0]);
  201: 	}
  202: 	push(@{ $answer{$cur_name}{'answers'} },\@values);
  203:     } elsif ($target eq 'edit') {
  204:   	$result.=&Apache::edit::tag_start($target,$token);
  205: 	my $bodytext = &Apache::lonxml::get_all_text("/vector",$parser,$style);
  206: 	$result.=&Apache::edit::editline($token->[1],$bodytext,undef,40).
  207: 	    &Apache::edit::end_row();
  208:     } elsif ($target eq 'modified') {
  209: 	$result=$token->[4].&Apache::edit::modifiedfield('/vector',$parser);
  210:     }
  211:     return $result;
  212: }
  213: 
  214: sub end_vector {
  215:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
  216:     my $result;
  217:     if ($target eq 'edit') {
  218: 	$result = &Apache::edit::end_table();
  219:     }
  220:     return $result;
  221: }
  222: 
  223: sub insert_vector {
  224:     return '
  225:             <value></value>';
  226: }
  227: 
  228: sub start_array {
  229:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  230:     my $result;
  231:     if ( $target eq 'web' || $target eq 'tex' ||
  232: 	 $target eq 'grade' || $target eq 'webgrade' ||
  233: 	 $target eq 'answer' || $target eq 'analyze' ) {
  234: 	my $bodytext = &Apache::lonxml::get_all_text("/array",$parser,$style);
  235: 	my @values = &Apache::run::evaluate($bodytext,$safeeval,
  236: 					    $$parstack[-1]);
  237: 	push(@{ $answer{$cur_name}{'answers'} },@values);
  238:     }
  239:     return $result;
  240: }
  241: 
  242: sub end_array {
  243:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
  244:     my $result;
  245:     return $result;
  246: }
  247: 
  248: sub start_unit {
  249:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
  250:     my $result;
  251:     return $result;
  252: }
  253: 
  254: sub end_unit {
  255:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
  256:     my $result;
  257:     return $result;
  258: }
  259: 
  260: sub start_numericalresponse {
  261:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
  262:     &Apache::lonxml::register('Apache::caparesponse',
  263: 			      ('answer','answergroup','value','array','unit',
  264: 			       'vector'));
  265:     push(@Apache::lonxml::namespace,'caparesponse');
  266:     my $id = &Apache::response::start_response($parstack,$safeeval);
  267:     my $result;
  268:     undef(%answer);
  269:     undef(%{$safeeval->varglob('LONCAPA::CAPAresponse_args')});
  270:     if ($target eq 'edit') {
  271: 	$result.=&Apache::edit::tag_start($target,$token);
  272: 	$result.=&Apache::edit::text_arg('Answer:','answer',$token);
  273: 	if ($token->[1] eq 'numericalresponse') {
  274: 	    $result.=&Apache::edit::text_arg('Incorrect Answers:','incorrect',
  275: 					     $token).
  276: 		&Apache::loncommon::help_open_topic('numerical_wrong_answers');
  277: 	    $result.=&Apache::edit::text_arg('Unit:','unit',$token,5).
  278: 		&Apache::loncommon::help_open_topic('Physical_Units');
  279: 	    $result.=&Apache::edit::text_arg('Format:','format',$token,4).
  280: 		&Apache::loncommon::help_open_topic('Numerical_Response_Format');
  281: 	} elsif ($token->[1] eq 'formularesponse') {
  282: 	    $result.=&Apache::edit::text_arg('Sample Points:','samples',
  283: 					     $token,40).
  284: 	      &Apache::loncommon::help_open_topic('Formula_Response_Sampling');
  285: 	}
  286:         $result.=&Apache::edit::text_arg('Pre-Processor Subroutine:','preprocess',
  287:                                              $token,10);
  288: 	$result.=&Apache::edit::end_row().&Apache::edit::start_spanning_row();
  289:     } elsif ($target eq 'modified') {
  290: 	my $constructtag;
  291: 	if ($token->[1] eq 'numericalresponse') {
  292: 	    $constructtag=&Apache::edit::get_new_args($token,$parstack,
  293: 						      $safeeval,'answer',
  294:  						      'incorrect','unit',
  295: 						      'format','preprocess');
  296: 	} elsif ($token->[1] eq 'formularesponse') {
  297: 	    $constructtag=&Apache::edit::get_new_args($token,$parstack,
  298: 						      $safeeval,'answer',
  299: 						      'samples','preprocess');
  300: 	}
  301: 	if ($constructtag) {
  302: 	    $result = &Apache::edit::rebuild_tag($token);
  303: 	    $result.=&Apache::edit::handle_insert();
  304: 	}
  305:     } elsif ($target eq 'meta') {
  306: 	$result=&Apache::response::meta_package_write('numericalresponse');
  307:     } elsif ($target eq 'answer' || $target eq 'grade') {
  308: 	&Apache::response::reset_params();
  309:     } elsif ($target eq 'web') {
  310: 	my $partid = $Apache::inputtags::part;
  311: 	my $hideunit=&Apache::lonnet::EXT('resource.'.$partid.'_'.$id.'.turnoffunit');
  312: 	&Apache::lonxml::debug("Got unit $hideunit for $partid $id");
  313: 	#no way to enter units, with radio buttons
  314: 	if ((lc($hideunit) eq "yes") && ($Apache::lonhomework::type ne 'exam')) {
  315: 	    my $unit=&Apache::lonxml::get_param_var('unit',$parstack,
  316: 						    $safeeval);
  317: 	    if ($unit =~ /\S/) { $result.=" (in $unit) "; }
  318: 	}
  319: 	if (  &Apache::response::show_answer() ) {
  320: 	    &set_answertext($tag_internal_answer_name,$target,$token,$tagstack,
  321: 			    $parstack,$parser,$safeeval,-1);
  322: 	}
  323:     }
  324:     return $result;
  325: }
  326: 
  327: sub set_answertext {
  328:     my ($name,$target,$token,$tagstack,$parstack,$parser,$safeeval,
  329: 	$response_level) = @_;
  330:     my $stringify;
  331:     if (scalar(@$tagstack)) {
  332:         if ($$tagstack[-1] eq 'formularesponse') {
  333:             if (&Apache::lonxml::get_param('samples',$parstack,$safeeval)) {
  334:                 $stringify = 1;
  335:             }
  336:         } elsif ($$tagstack[-1] eq 'numericalresponse') {
  337:             $stringify = 1;
  338:         }
  339:     }
  340:     &add_in_tag_answer($parstack,$safeeval,$stringify,$response_level);
  341: 
  342:     if ($name eq '' || !ref($answer{$name})) {
  343: 	if (ref($answer{$tag_internal_answer_name})) {
  344: 	    $name = $tag_internal_answer_name;
  345: 	} else {
  346: 	    $name = (sort(keys(%answer)))[0];
  347: 	}
  348:     }
  349:     return if ($name eq '' || !ref($answer{$name}));
  350: 
  351:     my (@formats)=&Apache::lonxml::get_param_var('format',$parstack,
  352: 						 $safeeval,$response_level);
  353:     my $unit=&Apache::lonxml::get_param_var('unit',$parstack,$safeeval,
  354: 					    $response_level);
  355: 
  356:     &Apache::lonxml::debug("answer looks to be $name");
  357:     my @answertxt;
  358:     for (my $i=0; $i < scalar(@{$answer{$name}{'answers'}}); $i++) {
  359: 	my $answertxt;
  360: 	my $answer=$answer{$name}{'answers'}[$i];
  361: 	foreach my $element (@$answer) {
  362: 	    if ( scalar(@$tagstack)
  363: 		 && $tagstack->[$response_level] ne 'numericalresponse') {
  364: 		$answertxt.=$element.',';
  365: 	    } else {
  366: 		my $format;
  367: 		if ($#formats > 0) {
  368: 		    $format=$formats[$i];
  369: 		} else {
  370: 		    $format=$formats[0];
  371: 		}
  372: 		if ($unit=~/\$/) { $format="\$".$format; $unit=~s/\$//g; }
  373: 		if ($unit=~/\,/) { $format="\,".$format; $unit=~s/\,//g; }
  374: 		my $formatted=&format_number($element,$format,$target,
  375: 					     $safeeval);
  376: 		$answertxt.=' '.$formatted.',';
  377: 	    }
  378: 	    
  379: 	}
  380: 	chop($answertxt);
  381: 	if ($target eq 'web') {
  382: 	    $answertxt.=" $unit ";
  383: 	}
  384: 
  385: 	push(@answertxt,$answertxt)
  386:     }
  387: 	
  388:     my $id = $Apache::inputtags::response[-1];
  389:     $Apache::inputtags::answertxt{$id}=\@answertxt;
  390: }
  391: 
  392: sub setup_capa_args {
  393:     my ($safeeval,$parstack,$args,$response) = @_;
  394:     my $args_ref= \%{$safeeval->varglob('LONCAPA::CAPAresponse_args')};
  395:     undef(%{ $args_ref });
  396:  
  397:     foreach my $arg (@{$args}) {
  398: 	$$args_ref{$arg}=
  399: 	    &Apache::lonxml::get_param($arg,$parstack,$safeeval);
  400:     }
  401:     foreach my $key (keys(%Apache::inputtags::params)) {
  402: 	$$args_ref{$key}=$Apache::inputtags::params{$key};
  403:     }
  404:     &setup_capa_response($args_ref,$response);
  405:     return $args_ref;
  406: }
  407: 
  408: sub setup_capa_response {
  409:     my ($args_ref,$response) = @_;   
  410: 
  411:     if (ref($response)) {
  412: 	$$args_ref{'response'}=dclone($response);
  413:     } else {
  414: 	$$args_ref{'response'}=dclone(["$response"]);
  415:     }
  416: }
  417: 
  418: sub check_submission {
  419:     my ($response,$partid,$id,$tag,$parstack,$safeeval,$ignore_sig)=@_;
  420:     my @args = ('type','tol','sig','format','unit','calc','samples','preprocess');
  421:     my $args_ref = &setup_capa_args($safeeval,$parstack,\@args,$response);
  422:     my $stringify;
  423: 
  424:     my $hideunit=
  425: 	&Apache::lonnet::EXT('resource.'.$partid.'_'.$id.'.turnoffunit');
  426:         #no way to enter units, with radio buttons
  427:     if ($Apache::lonhomework::type eq 'exam' ||
  428: 	lc($hideunit) eq "yes") {
  429: 	delete($$args_ref{'unit'});
  430:     }
  431:     #sig fig don't make much sense either
  432:     if (($Apache::lonhomework::type eq 'exam' ||
  433: 	 &Apache::response::submitted('scantron') ||
  434: 	 $ignore_sig) &&
  435: 	$tag eq 'numericalresponse') {
  436: 	delete($$args_ref{'sig'});
  437:     }
  438:     
  439:     if ($tag eq 'formularesponse') {
  440: 	if ($$args_ref{'samples'}) {
  441: 	    $$args_ref{'type'}='fml';
  442:             $stringify = 1;
  443: 	} else {
  444: 	    $$args_ref{'type'}='math';
  445: 	}
  446:     } elsif ($tag eq 'numericalresponse') {
  447: 	$$args_ref{'type'}='float';
  448:         $stringify = 1;
  449:     } elsif ($tag eq 'stringresponse') {
  450:         if ($$args_ref{'type'} eq '') {
  451:             $$args_ref{'type'} = 'ci';
  452:         }
  453:     }
  454: 
  455:     &add_in_tag_answer($parstack,$safeeval,$stringify);
  456: 
  457:     if (!%answer) {
  458: 	&Apache::lonxml::error("No answers are defined");
  459:     }
  460: 
  461:     my (@final_awards,@final_msgs,@names);
  462:     foreach my $name (keys(%answer)) {
  463: 	&Apache::lonxml::debug(" doing $name with ".join(':',@{ $answer{$name}{'answers'} }));
  464: 	
  465: 	${$safeeval->varglob('LONCAPA::CAPAresponse_answer')}=dclone($answer{$name});
  466: 	&setup_capa_response($args_ref,$response);
  467: 	use Time::HiRes;
  468: 	my $t0 = [Time::HiRes::gettimeofday()];
  469: 	my ($result,@msgs) = 
  470: 	    &Apache::run::run("&caparesponse_check_list()",$safeeval);
  471: 	&Apache::lonxml::debug("checking $name $result with $response took ".&Time::HiRes::tv_interval($t0));
  472: 	&Apache::lonxml::debug('msgs are '.join(':',@msgs));
  473: 	my ($awards)=split(/:/,$result);
  474: 	my @awards= split(/,/,$awards);
  475: 	my ($ad, $msg) = &Apache::inputtags::finalizeawards(\@awards,\@msgs);
  476: 	push(@final_awards,$ad);
  477: 	push(@final_msgs,$msg);
  478: 	push(@names,$name);
  479:     }
  480:     my ($ad, $msg, $name) = &Apache::inputtags::finalizeawards(\@final_awards,
  481: 							       \@final_msgs,
  482: 							       \@names,1);
  483:     &Apache::lonxml::debug(" name of picked award is $name from ".join(', ',@names));
  484:     return($ad,$msg, $name);
  485: }
  486: 
  487: sub stringresponse_gradechange {
  488:     my ($part,$id,$previous,$caller,$response,$ad,$type) = @_;
  489:     return unless (ref($previous) eq 'HASH');
  490:     my ($prevarray,$prevaward);
  491:     my %typenames = (
  492:                      cs => 'Case sensitive',
  493:                      ci => 'Case insensitive',
  494:                     );
  495:     if ($caller eq 'cs') {
  496:         return unless (ref($previous->{'version'}) eq 'ARRAY');
  497:         $prevarray = $previous->{'version'};
  498:         $prevaward = $previous->{'award'};
  499:     } elsif ($caller eq 'ci') {
  500:         return unless (ref($previous->{'versionci'}) eq 'ARRAY');
  501:         $prevarray = $previous->{'versionci'};
  502:         $prevaward = $previous->{'awardci'};
  503:     } else {
  504:         return;
  505:     }
  506:     my $count=0;
  507:     my %count_lookup;
  508:     foreach my $i (1..$Apache::lonhomework::history{'version'}) {
  509:         my $prefix = $i.":resource.$part";
  510:         next if (!exists($Apache::lonhomework::history{"$prefix.award"}));
  511:         $count++;
  512:         $count_lookup{$i} = $count;
  513:     }
  514:     my ($symb,$courseid,$domain,$name) = &Apache::lonnet::whichuser();
  515:     my %coursedesc = &Apache::lonnet::coursedescription($courseid);
  516:     my $cdom = $coursedesc{'domain'};
  517:     my $versions = ' (submissions: '.join(', ',map {$count_lookup{$_} } @{$prevarray}).')';
  518:     my $warning = "String Response ($typenames{$type}) grading discrepancy: award for response of $response changed from $prevaward".$versions." to $ad; user: $name:$domain in course: $courseid for part: $part response: $id for symb: $symb";
  519:     &Apache::lonnet::logthis($warning);
  520:     my $origmail = $Apache::lonnet::perlvar{'lonAdmEMail'};
  521:     my $recipients = &Apache::loncommon::build_recipient_list(undef,'errormail',
  522:                                                               $cdom,$origmail);
  523:     if ($recipients ne '') {
  524:         &Apache::lonmsg::sendemail($recipients,'Stringresponse Grading Discrepancy',$warning);
  525:     }
  526:     return;
  527: }
  528: 
  529: sub add_in_tag_answer {
  530:     my ($parstack,$safeeval,$stringify,$response_level) = @_;
  531:     my @answer=&Apache::lonxml::get_param_var('answer',$parstack,$safeeval,
  532: 					      $response_level);
  533:     &Apache::lonxml::debug('answer is'.join(':',@answer));
  534:     if (@answer && $answer[0] =~ /\S/) {
  535:         if ($stringify) {
  536:             @answer = map { $_ .= ''; } @answer;
  537:         }
  538: 	$answer{$tag_internal_answer_name}= {'type' => 'ordered',
  539: 					     'answers' => [\@answer] };
  540:     }
  541: }
  542: 
  543: sub capa_formula_fix {
  544:    my ($expression)=@_;
  545:    return &Apache::response::implicit_multiplication($expression);
  546: }
  547: 
  548: sub end_numericalresponse {
  549:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  550: 
  551:     &Apache::lonxml::deregister('Apache::caparesponse',
  552: 			      ('answer','answergroup','value','array','unit',
  553: 			       'vector'));
  554:     pop(@Apache::lonxml::namespace);
  555: 
  556:     my $increment=1;
  557:     my $result = '';
  558:     if (!$Apache::lonxml::default_homework_loaded) {
  559: 	&Apache::lonxml::default_homework_load($safeeval);
  560:     }
  561:     my $partid = $Apache::inputtags::part;
  562:     my $id = $Apache::inputtags::response[-1];
  563:     my ($tag,$stringify);
  564:     my $safehole = new Safe::Hole;
  565:     $safeeval->share_from('capa',['&caparesponse_capa_check_answer']);
  566: 
  567:     if (scalar(@$tagstack)) { $tag=$$tagstack[-1]; }
  568:     if ( $target eq 'grade' && &Apache::response::submitted() ) {
  569: 	&Apache::response::setup_params($tag,$safeeval);
  570: 	if ($Apache::lonhomework::type eq 'exam' && 
  571: 	    (($tag eq 'formularesponse') || ($tag eq 'mathresponse'))) {
  572: 	    $increment=&Apache::response::scored_response($partid,$id);
  573: 	} else {
  574: 	    my $response = &Apache::response::getresponse();
  575: 	    if ( $response =~ /[^\s]/) {
  576: 		my %previous = &Apache::response::check_for_previous($response,$partid,$id);
  577: 		&Apache::lonxml::debug("submitted a $response<br>\n");
  578: 		&Apache::lonxml::debug($$parstack[-1] . "\n<br>");
  579: 		
  580: 		if ( &Apache::response::submitted('scantron')) {
  581:                     if ($tag eq 'numericalresponse') {
  582:                         $stringify = 1;
  583:                     } elsif ($tag eq 'formularesponse') {
  584:                         if (&Apache::lonxml::get_param('samples',$parstack,$safeeval)) {
  585:                             $stringify = 1;
  586:                         }
  587:                     }
  588: 	            &add_in_tag_answer($parstack,$safeeval,$stringify);
  589: 	            my ($values,$display)=&make_numerical_bubbles($partid,$id,$target,
  590: 					                          $parstack,$safeeval);
  591: 	            $response=$values->[$response];
  592: 	        }
  593: 	        $Apache::lonhomework::results{"resource.$partid.$id.submission"}=$response;
  594: 		my ($ad,$msg,$name)=&check_submission($response,$partid,$id,
  595: 						      $tag,$parstack,
  596: 						      $safeeval);
  597: 
  598: 		&Apache::lonxml::debug('ad is'.$ad);
  599: 		if ($ad eq 'SIG_FAIL') {
  600: 		    my ($sig_u,$sig_l)=
  601: 			&get_sigrange($Apache::inputtags::params{'sig'});
  602: 		    $msg=join(':',$msg,$sig_l,$sig_u);
  603: 		    &Apache::lonxml::debug("sigs bad $sig_u $sig_l ".
  604: 					   $Apache::inputtags::params{'sig'});
  605: 		}
  606: 		&Apache::lonxml::debug("\n<br>result:$result:$Apache::lonxml::curdepth<br>\n");
  607:                 if (($ad eq 'INCORRECT' || $ad eq 'APPROX_ANS' ||
  608:                      $ad eq 'EXACT_ANS')) {
  609: 		    if ($Apache::lonhomework::type eq 'survey') {
  610: 		        $ad='SUBMITTED';
  611: 		    } elsif ($Apache::lonhomework::type eq 'surveycred') {
  612:                         $ad='SUBMITTED_CREDIT';
  613:                     } elsif ($Apache::lonhomework::type eq 'anonsurvey') {
  614:                         $ad='ANONYMOUS';
  615:                     } elsif ($Apache::lonhomework::type eq 'anonsurveycred') {
  616:                         $ad='ANONYMOUS_CREDIT';                     
  617:                     }
  618:                 }
  619: 		&Apache::response::handle_previous(\%previous,$ad);
  620: 		$Apache::lonhomework::results{"resource.$partid.$id.awarddetail"}=$ad;
  621: 		$Apache::lonhomework::results{"resource.$partid.$id.awardmsg"}=$msg;
  622: 		$Apache::lonhomework::results{"resource.$partid.$id.answername"}=$name;
  623: 		$result='';
  624: 	    }
  625: 	}
  626:     } elsif ($target eq 'web' || $target eq 'tex') {
  627:         if ($tag eq 'numericalresponse') {
  628:             $stringify = 1;
  629:         } elsif ($tag eq 'formularesponse') {
  630:             if (&Apache::lonxml::get_param('samples',$parstack,$safeeval)) {
  631:                 $stringify = 1;
  632:             }
  633:         }
  634: 	&check_for_answer_errors($parstack,$safeeval,$stringify);
  635: 	my $award = $Apache::lonhomework::history{"resource.$Apache::inputtags::part.solved"};
  636: 	my $status = $Apache::inputtags::status['-1'];
  637: 	if ($Apache::lonhomework::type eq 'exam') {
  638: 	    # FIXME support multi dimensional numerical problems
  639:             #       in exam bubbles
  640: 	    my ($bubble_values,$bubble_display)=
  641: 		&make_numerical_bubbles($partid,$id,$target,$parstack,
  642: 					$safeeval);
  643: 	    my $number_of_bubbles = scalar(@{ $bubble_values });
  644: 	    my $unit=&Apache::lonxml::get_param_var('unit',$parstack,
  645: 						    $safeeval);
  646: 	    if ($target eq 'web') {
  647: 		if ($tag eq 'numericalresponse') {
  648: 		    if ($unit=~/\S/) {$result.=' (in '.$unit.')<br /><br />';}
  649: 		    $result.= '<table border="1"><tr>';
  650: 		    my $previous=$Apache::lonhomework::history{"resource.$Apache::inputtags::part.$id.submission"};
  651: 		    for (my $ind=0;$ind<$number_of_bubbles;$ind++) {
  652: 			my $checked='';
  653: 			if ($previous eq $bubble_values->[$ind]) {
  654: 			    $checked=" checked='on' ";
  655: 			}
  656: 			$result.='<td><label><input type="radio" name="HWVAL_'.$id.
  657: 			    '" value="'.$bubble_values->[$ind].'" '.$checked
  658: 			    .' /><b>'.$alphabet[$ind].'</b>: '.
  659: 			    $bubble_display->[$ind].'</label></td>';
  660: 		    }
  661: 		    $result.='</tr></table>';
  662: 		}
  663: 	    } elsif ($target eq 'tex') {
  664: 		if ((defined $unit) and ($unit=~/\S/) and ($Apache::lonhomework::type eq 'exam')) {
  665: 		    $result.=' \textit{(in} \verb|'.$unit.'|\textit{)} ';
  666: 		}
  667: 		if ($tag eq 'numericalresponse') {
  668: 		    $result .= &make_horizontal_latex_bubbles($bubble_values, $bubble_display,
  669: 			'$\bigcirc$');
  670: 		} else {
  671: 		    $increment = &Apache::response::repetition();
  672: 		}
  673: 	    }
  674: 	}
  675: 
  676: 	&Apache::response::setup_prior_tries_hash(\&format_prior_response_numerical);
  677:     } elsif ($target eq 'edit') {
  678: 	$result.='</td></tr>'.&Apache::edit::end_table;
  679:     } elsif ($target eq 'answer' || $target eq 'analyze') {
  680: 	my $part_id="$partid.$id";
  681:         my $samples;
  682: 	if ($target eq 'analyze') {
  683: 	    push (@{ $Apache::lonhomework::analyze{"parts"} },$part_id);
  684: 	    $Apache::lonhomework::analyze{"$part_id.type"} = $tag;
  685: 	    my (@incorrect)=&Apache::lonxml::get_param_var('incorrect',$parstack,$safeeval);
  686: 	    if ($#incorrect eq 0) { @incorrect=(split(/,/,$incorrect[0])); }
  687: 	    push (@{ $Apache::lonhomework::analyze{"$part_id.incorrect"} }, @incorrect);
  688: 	    &Apache::response::check_if_computed($token,$parstack,
  689: 						 $safeeval,'answer');
  690: 	}
  691: 	if (scalar(@$tagstack)) {
  692: 	    &Apache::response::setup_params($tag,$safeeval);
  693: 	}
  694:         if ($tag eq 'numericalresponse') {
  695:             $stringify = 1;
  696:         } elsif ($tag eq 'formularesponse') {
  697:             $samples=&Apache::lonxml::get_param('samples',$parstack,$safeeval);
  698:             if ($samples) {
  699:                 $stringify = 1;
  700:             }
  701:         }
  702: 	&add_in_tag_answer($parstack,$safeeval,$stringify);
  703: 	my (@formats)=&Apache::lonxml::get_param_var('format',$parstack,$safeeval);
  704: 
  705: 	my $unit=&Apache::lonxml::get_param_var('unit',$parstack,$safeeval);
  706: 	my ($needsdollar,$needscomma);
  707: 	if ($unit =~ /\$/) {
  708: 	    $needsdollar = 1;
  709: 	}
  710: 	if ($unit =~ /\,/) {
  711: 	    $needscomma = 1;
  712: 	}
  713: 
  714: 	if ($target eq 'answer') {
  715: 	    $result.=&Apache::response::answer_header($tag,undef,
  716: 						      scalar(keys(%answer)));
  717: 	    if ($tag eq 'numericalresponse'
  718: 		&& $Apache::lonhomework::type eq 'exam') {
  719: 		my ($bubble_values,undef,$correct) = &make_numerical_bubbles($partid,
  720: 					     $id,$target,$parstack,$safeeval);
  721: 		$result.=&Apache::response::answer_part($tag,$correct);
  722: 	    }
  723: 	}
  724: 	foreach my $name (sort(keys(%answer))) {
  725: 	    my @answers = @{ $answer{$name}{'answers'} };
  726: 	    if ($target eq 'analyze') {
  727: 		foreach my $info ('answer','ans_high','ans_low','format') {
  728: 		    $Apache::lonhomework::analyze{"$part_id.$info"}{$name}=[];
  729: 		}
  730: 	    }
  731: 	    my ($sigline,$tolline);
  732: 	    if ($name ne $tag_internal_answer_name 
  733: 		|| scalar(keys(%answer)) > 1) {
  734: 		$result.=&Apache::response::answer_part($tag,$name);
  735: 	    }
  736: 	    for(my $i=0;$i<=$#answers;$i++) {
  737: 		my $ans=$answers[$i];
  738: 		my $fmt=$formats[0];
  739: 		if (@formats && $#formats) {$fmt=$formats[$i];}
  740: 		my ($sighigh,$siglow);
  741: 		if ($Apache::inputtags::params{'sig'}) {
  742: 		    ($sighigh,$siglow)=&get_sigrange($Apache::inputtags::params{'sig'});
  743: 		}
  744: 		my @vector;
  745: 		if (ref($ans)) {
  746: 		    @vector = @{ $ans };
  747: 		} else {
  748: 		    @vector = ($ans);
  749: 		}
  750: 		my @all_answer_info;
  751: 		foreach my $element (@vector) {
  752: 		    my ($high,$low);
  753: 		    if ($Apache::inputtags::params{'tol'}) {
  754: 			($high,$low)=&get_tolrange($element,$Apache::inputtags::params{'tol'});
  755: 		    }
  756: 		    if ($target eq 'answer') {
  757: 			if ($fmt && $tag eq 'numericalresponse') {
  758: 			    $fmt=~s/e/E/g;
  759: 			    if ($unit=~/\$/) { $fmt="\$".$fmt; $unit=~s/\$//g; }
  760: 			    if ($unit=~/\,/) { $fmt="\,".$fmt; $unit=~s/\,//g; }
  761: 			    $element = &format_number($element,$fmt,$target,$safeeval);
  762: 			    #if ($high) {
  763: 			    #    $high=&format_number($high,$fmt,$target,$safeeval);
  764: 			    #    $low =&format_number($low,$fmt,$target,$safeeval);
  765: 			    #}
  766: 			}
  767: 			if ($high && $tag eq 'numericalresponse') {
  768: 			    $element.='; ['.$low.'; '.$high.']';
  769: 			    $tolline .= "[$low, $high]";
  770: 			}
  771: 			if (defined($sighigh) && $tag eq 'numericalresponse') {
  772: 			    if ($env{'form.answer_output_mode'} eq 'tex') {
  773: 				$element.= "; Sig $siglow - $sighigh";
  774: 			    } else {
  775: 				$element.= " Sig <i>$siglow - $sighigh</i>";
  776: 				$sigline .= "[$siglow, $sighigh]";
  777: 			    }
  778: 			}
  779: 			push(@all_answer_info,$element);
  780: 			
  781: 		    } elsif ($target eq 'analyze') {
  782: 			push (@{ $Apache::lonhomework::analyze{"$part_id.answer"}{$name}[$i] }, $element);
  783: 			if ($high) {
  784: 			    push (@{ $Apache::lonhomework::analyze{"$part_id.ans_high"}{$name}[$i] }, $high);
  785: 			    push (@{ $Apache::lonhomework::analyze{"$part_id.ans_low"}{$name}[$i] }, $low);
  786: 			}
  787: 			if ($fmt) {
  788: 			    push (@{ $Apache::lonhomework::analyze{"$part_id.format"}{$name}[$i] }, $fmt);
  789: 			}
  790: 		    }
  791: 		}
  792: 		if ($target eq 'answer') {
  793: 		    $result.= &Apache::response::answer_part($tag,join('; ',@all_answer_info));
  794: 		}
  795: 	    }
  796: 
  797: 	    my @fmt_ans;
  798: 	    for(my $i=0;$i<=$#answers;$i++) {
  799: 		my $ans=$answers[$i];
  800: 		my $fmt=$formats[0];
  801: 		if (@formats && $#formats) {$fmt=$formats[$i];}
  802: 		my @answers;
  803: 		if (ref($ans) eq 'ARRAY') {
  804: 		    @answers = (@{$ans});
  805: 		}
  806: 		foreach my $element (@answers) {		    
  807: 		    if ($fmt && $tag eq 'numericalresponse') {
  808: 			$fmt=~s/e/E/g;
  809: 			if ($unit=~/\$/) { $fmt="\$".$fmt; $unit=~s/\$//g; }
  810: 			if ($unit=~/\,/) { $fmt="\,".$fmt; $unit=~s/\,//g; }
  811: 			$element = &format_number($element,$fmt,$target,
  812: 						  $safeeval);
  813: 			if ($fmt=~/\$/ && !$needsdollar) { $element=~s/\$//; }
  814: 		    }
  815: 		}
  816: 		push(@fmt_ans,join(',',@answers));
  817: 	    }
  818: 	    my $response=\@fmt_ans;
  819: 
  820: 	    my $hideunit=&Apache::lonnet::EXT('resource.'.$partid.'_'.
  821: 					      $id.'.turnoffunit');
  822: 	    if ($unit ne ''  && 
  823: 		! ($Apache::lonhomework::type eq 'exam' ||
  824: 		   lc($hideunit) eq "yes") )  {
  825: 		my $cleanunit=$unit;
  826: 		$cleanunit=~s/[\$,]//g;
  827: 		foreach my $ans (@fmt_ans) {
  828: 		    $ans.=" $cleanunit";
  829: 		}
  830: 	    }
  831: 	    my ($ad,$msg)=&check_submission($response,$partid,$id,$tag,
  832: 					    $parstack,$safeeval);
  833: 	    if ($ad ne 'EXACT_ANS' && $ad ne 'APPROX_ANS') {
  834: 		my $error;
  835: 		if ($tag eq 'formularesponse') {
  836: 		    $error=&mt("Computer's answer is incorrect ([_1]).",'"'.join(', ',@$response).'"');
  837: 		} else {
  838: 		    # answer failed check if it is sig figs that is failing
  839: 		    my ($ad,$msg)=&check_submission($response,$partid,$id,
  840: 						    $tag,$parstack,
  841: 						    $safeeval,1);
  842: 		    $error=&mt("Computer's answer is incorrect ([_1]).",'"'.join(', ',@$response).'"').' ';
  843:                     if (($ad eq 'NO_UNIT') && $needsdollar) {
  844:                         $error.=&mt('The unit attribute includes [_1] but the answer format does not.','$').' '.
  845:                                 &mt('Either remove the [_1] from the unit or prepend [_1] to the answer format.','$');    
  846:                     } elsif (($ad eq 'COMMA_FAIL') && $needscomma) {
  847:                         $error.=&mt('The unit attribute includes [_1] but the answer format does not.',',').' '.
  848:                                 &mt('Either remove the [_1] from the unit or prepend [_1] to the answer format.',',');
  849:                     } elsif ($ad eq 'UNIT_INVALID_STUDENT') {
  850:                         $error.=&mt('Unable to interpret units. Computer reads units as "[_1]".',$msg).' '.
  851:                                 &mt('The unit attribute in the numericalresponse item needs to be a supported physical unit.');
  852: 		    } elsif ($sigline ne '') {
  853: 			$error.=&mt('It is likely that the tolerance range [_1] or significant figures [_2] need to be adjusted.',$tolline,$sigline);
  854: 		    } else {
  855: 			$error.=&mt('It is likely that the tolerance range [_1] needs to be adjusted.',$tolline);
  856: 		    }
  857: 		}
  858: 		if ($ad ne 'EXACT_ANS' && $ad ne 'APPROX_ANS') {
  859: 		    &Apache::lonxml::error($error);
  860: 		} else {
  861: 		    &Apache::lonxml::warning($error);
  862: 		}
  863: 	    }
  864: 
  865: 	    if (defined($unit) and ($unit ne '') and
  866: 		$tag eq 'numericalresponse') {
  867: 		if ($target eq 'answer') {
  868: 		    if ($env{'form.answer_output_mode'} eq 'tex') {
  869: 			$result.=&Apache::response::answer_part($tag,
  870: 								" Unit: $unit ");
  871: 		    } else {
  872: 			$result.=&Apache::response::answer_part($tag,
  873: 								"Unit: <b>$unit</b>");
  874: 		    }
  875: 		} elsif ($target eq 'analyze') {
  876: 		    push (@{ $Apache::lonhomework::analyze{"$part_id.unit"} }, $unit);
  877: 		}
  878: 	    }
  879: 	    if ($tag eq 'formularesponse' && $target eq 'answer') {
  880: 		$result.=&Apache::response::answer_part($tag,$samples);
  881: 	    }
  882: 	    $result.=&Apache::response::next_answer($tag,$name);
  883: 	}
  884: 	if ($target eq 'answer') {
  885: 	    $result.=&Apache::response::answer_footer($tag);
  886: 	}
  887:     }
  888:     if ($target eq 'grade' || $target eq 'web' || $target eq 'answer' || 
  889: 	$target eq 'tex' || $target eq 'analyze') {
  890:         if (($tag eq 'formularesponse') && ($target eq 'analyze')) {
  891:             my $type = &Apache::lonnet::EXT('resource.'.$partid.'_'.$id.'.type');
  892:             if ($type eq 'exam') {
  893:                 $increment = &Apache::response::repetition();
  894:             }
  895:         }
  896: 	&Apache::lonxml::increment_counter($increment,"$partid.$id");
  897: 	if ($target eq 'analyze') {
  898: 	    &Apache::lonhomework::set_bubble_lines();
  899: 	}
  900:     }
  901:     &Apache::response::end_response();
  902:     return $result;
  903: }
  904: 
  905: sub format_prior_response_numerical {
  906:     my ($mode,$answer) = @_;
  907:     if (ref($answer)) {
  908: 	my $result = '<table class="LC_prior_numerical"><tr>';
  909: 	foreach my $element (@{ $answer }) {
  910: 	    $result.= '<td><span class="LC_prior_numerical">'.
  911: 		&HTML::Entities::encode($element,'"<>&').'</span></td>';
  912: 	}
  913: 	$result.='</tr></table>';
  914: 	return $result;
  915:     }
  916:     return '<span class="LC_prior_numerical">'.
  917: 	    &HTML::Entities::encode($answer,'"<>&').'</span>';
  918: 
  919: }
  920: 
  921: sub check_for_answer_errors {
  922:     my ($parstack,$safeeval,$stringify) = @_;
  923:     &add_in_tag_answer($parstack,$safeeval,$stringify);
  924:     my %counts;
  925:     foreach my $name (keys(%answer)) {
  926: 	push(@{$counts{scalar(@{$answer{$name}{'answers'}})}},$name);
  927:     }
  928:     if (scalar(keys(%counts)) > 1) {
  929: 	my $counts = join(' ',map {
  930: 	    my $count = $_;
  931: 	    &mt("Answers [_1] had [_2] components.",
  932: 		'<tt>'.join(', ',@{$counts{$count}}).'</tt>',
  933: 		$count);
  934: 	} (sort(keys(%counts))));
  935: 	&Apache::lonxml::error(&mt("All answers must have the same number of components. Varying numbers of answers were seen. ").$counts);
  936:     }
  937:     my $expected_number_of_inputs = (keys(%counts))[0];
  938:     if ( $expected_number_of_inputs > 0 
  939: 	 && $expected_number_of_inputs != scalar(@Apache::inputtags::inputlist)) {
  940: 	&Apache::lonxml::error(&mt("Expected [_1] input fields, but there were only [_2] seen.", 
  941: 				   $expected_number_of_inputs,
  942: 				   scalar(@Apache::inputtags::inputlist)));
  943:     }
  944: }
  945: 
  946: sub get_table_sizes {
  947:     my ($number_of_bubbles,$rbubble_values)=@_;
  948:     my $scale=2; #mm for one digit
  949:     my $cell_width=0;
  950:     foreach my $member (@$rbubble_values) {
  951: 	my $cell_width_real=0;
  952: 	if ($member=~/(\+|-)?(\d*)\.?(\d*)\s*\$?\\times\s*10\^\{(\+|-)?(\d+)}\$?/) {
  953: 	    $cell_width_real=(length($2)+length($3)+length($5)+7)*$scale;
  954: 	} elsif ($member=~/(\d*)\.?(\d*)(E|e)(\+|-)?(\d*)/) {
  955: 	    $cell_width_real=(length($1)+length($2)+length($5)+9)*$scale;
  956:         } elsif ($member=~/(\d*)\.(\d*)/) {
  957: 	    $cell_width_real=(length($1)+length($2)+3)*$scale;
  958: 	} else {
  959: 	    $cell_width_real=(length($member)+1)*$scale*0.9;
  960: 	}
  961: 	if ($cell_width_real>$cell_width) {$cell_width=$cell_width_real;}
  962:     }
  963:     $cell_width+=8; 
  964:     my $textwidth;
  965:     if ($env{'form.textwidth'} ne '') {
  966: 	$env{'form.textwidth'}=~/(\d*)\.?(\d*)/;
  967: 	$textwidth=$1.'.'.$2;
  968:     } else {
  969: 	$env{'form.textwidth'}=~/(\d+)\.?(\d*)/;
  970: 	$textwidth=$1.'.'.$2;
  971:     }
  972:     my $bubbles_per_line=int($textwidth/$cell_width);
  973:     if ($bubbles_per_line > $number_of_bubbles) {
  974: 	$bubbles_per_line=$number_of_bubbles;
  975:     } elsif (($bubbles_per_line > $number_of_bubbles/2) 
  976: 	     && ($number_of_bubbles % 2==0)) {
  977: 	$bubbles_per_line=$number_of_bubbles/2;
  978:     }
  979:     if ($bubbles_per_line < 1) {
  980: 	$bubbles_per_line=1;
  981:     }
  982:     my $number_of_tables = int($number_of_bubbles/$bubbles_per_line);
  983:     my @table_range = ();
  984:     for (my $i=0;$i<$number_of_tables;$i++) {push @table_range,$bubbles_per_line;}
  985:     if ($number_of_bubbles % $bubbles_per_line) {
  986: 	$number_of_tables++;
  987: 	push @table_range,($number_of_bubbles % $bubbles_per_line);
  988:     }
  989:     $cell_width-=8;
  990:     $cell_width=$cell_width*3/4;
  991:     return ($cell_width,$number_of_tables,@table_range);
  992: }
  993: 
  994: sub format_number {
  995:     my ($number,$format,$target,$safeeval)=@_;
  996:     my $ans;
  997:     if ($format eq '') {
  998: 	#What is the number? (integer,decimal,floating point)
  999: 	if ($number=~/^(\d*\.?\d*)(E|e)[+\-]?(\d*)$/) {
 1000: 	    $format = '3e';
 1001: 	} elsif ($number=~/^(\d*)\.(\d*)$/) {
 1002: 	    $format = '4f';
 1003: 	} elsif ($number=~/^(\d*)$/) {
 1004: 	    $format = 'd';
 1005: 	}
 1006:     }
 1007:     if (!$Apache::lonxml::default_homework_loaded) {
 1008: 	&Apache::lonxml::default_homework_load($safeeval);
 1009:     }
 1010:     $ans=&Apache::run::run("&prettyprint(q\0$number\0,q\0$format\0,q\0$target\0)",$safeeval);
 1011:     return $ans;
 1012: }
 1013: 
 1014: sub make_numerical_bubbles {
 1015:     my ($part,$id,$target,$parstack,$safeeval) =@_;
 1016: 
 1017:     if (!%answer) {
 1018: 	&Apache::lonxml::error(&mt("No answers defined for response [_1] in part [_2] to make bubbles for.",$id,$part));
 1019: 	return ([],[],undef);
 1020:     }
 1021:     
 1022:     my $number_of_bubbles = 
 1023: 	&Apache::response::get_response_param($part.'_'.$id,'numbubbles',8);
 1024: 
 1025:     #
 1026:     # Fixes for BZ 6519 - number of bubbles <= 0 or non-integer.
 1027:     # 
 1028:     $number_of_bubbles = int($number_of_bubbles + 0.5);
 1029:     if ($number_of_bubbles <= 0) {
 1030: 	$number_of_bubbles = 8;
 1031:     }
 1032:     
 1033: 
 1034:     my ($format)=&Apache::lonxml::get_param_var('format',$parstack,$safeeval);
 1035:     my $name = (exists($answer{$tag_internal_answer_name}) 
 1036: 		? $tag_internal_answer_name
 1037: 		: (sort(keys(%answer)))[0]);
 1038: 
 1039:     if ( scalar(@{$answer{$name}{'answers'}}) > 1) {
 1040: 	&Apache::lonxml::error("Only answers with 1 component are supported in exam mode");
 1041:     }
 1042:     if (scalar(@{$answer{$name}{'answers'}[0]}) > 1) {
 1043: 	&Apache::lonxml::error("Vector answers are unsupported in exam mode.");
 1044:     }
 1045: 
 1046:     my $answer = $answer{$name}{'answers'}[0][0];
 1047:     my (@incorrect)=&Apache::lonxml::get_param_var('incorrect',$parstack,
 1048: 						   $safeeval);
 1049:     if ($#incorrect eq 0) { @incorrect=(split(/,/,$incorrect[0])); }
 1050:     
 1051:     my @bubble_values=();
 1052:     my @alphabet=('A'..'Z');
 1053: 
 1054:     &Apache::lonxml::debug("answer is $answer incorrect is @incorrect");
 1055:     my @oldseed=&Math::Random::random_get_seed();
 1056:     if (@incorrect) {
 1057: 	&Apache::lonxml::debug("inside ".(scalar(@incorrect)+1 gt $number_of_bubbles));
 1058: 	if (defined($incorrect[0]) &&
 1059: 	    scalar(@incorrect)+1 >= $number_of_bubbles) {
 1060: 	    &Apache::lonxml::debug("inside ".(scalar(@incorrect)+1).":$number_of_bubbles");
 1061: 	    &Apache::response::setrandomnumber();
 1062: 	    my @rand_inc=&Math::Random::random_permutation(@incorrect);
 1063: 	    @bubble_values=@rand_inc[0..($number_of_bubbles-2)];
 1064: 	    @bubble_values=sort {$a <=> $b} (@bubble_values,$answer);
 1065: 	    &Apache::lonxml::debug("Answer was :$answer: returning :".$#bubble_values.": which are :".join(':',@bubble_values));
 1066: 	    &Math::Random::random_set_seed(@oldseed);
 1067: 
 1068: 	    my $correct;
 1069: 	    for(my $i=0; $i<=$#bubble_values;$i++) {
 1070: 		if ($bubble_values[$i] eq $answer) {
 1071: 		    $correct = $alphabet[$i];
 1072: 		    last;
 1073: 		}
 1074: 	    }
 1075: 
 1076: 	    if (defined($format) && $format ne '') {
 1077: 		my @bubble_display;
 1078: 		foreach my $value (@bubble_values) {
 1079: 		    push(@bubble_display,
 1080: 			 &format_number($value,$format,$target,$safeeval));
 1081: 		}
 1082: 		return (\@bubble_values,\@bubble_display,$correct);
 1083: 	    } else {
 1084: 		return (\@bubble_values,\@bubble_values,$correct);
 1085: 	    }
 1086: 	}
 1087: 	if (defined($incorrect[0]) &&
 1088: 	    scalar(@incorrect)+1 < $number_of_bubbles) {
 1089: 	    &Apache::lonxml::warning("Not enough incorrect answers were specified in the incorrect array, ignoring the specified incorrect answers and instead generating them (".join(',',@incorrect).").");
 1090: 	}
 1091:     }
 1092:     my @factors = (1.13,1.17,1.25,1.33,1.45); #default values of factors
 1093:     my @powers = (1..$number_of_bubbles);
 1094:     &Apache::response::setrandomnumber();
 1095:     my $ind=&Math::Random::random_uniform_integer(1,0,$#powers);
 1096:     my $power = $powers[$ind];
 1097:     $ind=&Math::Random::random_uniform_integer(1,0,$#factors);
 1098:     my $factor = $factors[$ind];
 1099:     my @bubble_display;
 1100:     my $answerfactor=$answer;
 1101:     if ($answer==0) { 
 1102:        $answerfactor=&Math::Random::random_uniform_integer(1,1,100)/
 1103:                      &Math::Random::random_uniform_integer(1,1,10);
 1104:     }
 1105:     for ($ind=0;$ind<$number_of_bubbles;$ind++) {
 1106: 	my $exponent = $power-$powers[$#powers-$ind];
 1107: 	$bubble_values[$ind] = $answerfactor*($factor**$exponent);
 1108: 
 1109: 	# If bubble is for correct answer (i.e., exponent = 0), and value
 1110: 	# of $answerfactor * factor**$exponent is an integer with more than
 1111: 	# 15 digits, assign $answerfactor itself as bubble value.
 1112: 	# This prevents a "use fewer digits" issue on 64bit servers
 1113: 	# when correct answer is >= 1e+16, and when correct bubble is A.
 1114: 
 1115: 	if ($exponent == 0) {
 1116: 	    if ($bubble_values[$ind] =~ /^-?(\d+)$/) {
 1117: 		if (length($1) > 15) {
 1118: 		    $bubble_values[$ind] = $answerfactor;
 1119: 		}
 1120: 	    }
 1121: 	}
 1122: 
 1123: 	$bubble_display[$ind] = &format_number($bubble_values[$ind],
 1124: 					       $format,$target,$safeeval);
 1125:     }
 1126:     my $correct = $alphabet[$number_of_bubbles-$power];
 1127:     if ($answer==0) {
 1128:        $correct='A';
 1129:        $bubble_values[0]=0;
 1130:        $bubble_display[0] = &format_number($bubble_values[0],
 1131:                                            $format,$target,$safeeval);
 1132:     }
 1133:     &Math::Random::random_set_seed(@oldseed);
 1134:     return (\@bubble_values,\@bubble_display,$correct);
 1135: }
 1136: 
 1137: ##
 1138: # Produce LaTeX bubbles laid out horizontally given a set of bubble values:
 1139: #
 1140: # @param bubble_values  - reference to an array of bubble 'values'
 1141: # @param bubble_display - reference to the array of texts to display to the user
 1142: #                         for each bubble_value (this is mostly for numerical response
 1143: #                         when the displayed value may not be an exact
 1144: #                         representation of the bubble value. 
 1145: # @param bubble_fragment- The LaTeX fragment that will be plugged in to make
 1146: #                         the bubble itself. Note that the code will autonomously
 1147: #                         label each bubble with a lable...and that it's perfectly
 1148: #                         acceptable to use "" for the bubble_fragment.
 1149: # 
 1150: # @return string - the LaTeX fragment that produces the bubbles.
 1151: #
 1152: sub make_horizontal_latex_bubbles {
 1153:     my ($bubble_values, $bubble_display, $bubble_fragment)     = @_;
 1154:     my $result;
 1155: 
 1156:     my $number_of_bubbles = scalar(@{$bubble_values}); 
 1157: 
 1158:     # Get the number of rows and columns in each row of the bubble
 1159:     # table:
 1160: 
 1161:     my ($celllength, $number_of_tables, @table_range) =
 1162: 	&get_table_sizes($number_of_bubbles, $bubble_display);
 1163: 
 1164:     my $j=0;
 1165:     my $cou=0;
 1166:     $result.='\vskip 2mm \noindent ';
 1167:     if ($Apache::lonhomework::type eq 'exam') {
 1168:         $result .= '\textbf{'.$Apache::lonxml::counter.'.} \vskip -3mm ';
 1169:     }
 1170: 
 1171:     for (my $i=0;$i<$number_of_tables;$i++) {
 1172: 	if ($i == 0) {
 1173: 	    $result .= '\vskip -1mm ';
 1174: 	} else {
 1175: 	    $result .= '\vskip 1mm ';
 1176: 	}
 1177: 	$result.='\noindent \setlength{\tabcolsep}{2 mm}\hskip 2pc\begin{tabular}{';
 1178: 	for (my $ind=0;$ind<$table_range[$j];$ind++) {
 1179: 	    $result.='p{4 mm}p{'.$celllength.' mm}';
 1180: 	}
 1181: 	$result.='}';
 1182: 	for (my $ind=$cou;$ind<$cou+$table_range[$j];$ind++) {
 1183: 	    $result.='\hskip -4 mm {\small \textbf{ '.$alphabet[$ind].'}}'
 1184: 		. $bubble_fragment 
 1185: 		. '& \hskip -3 mm {\small '.$bubble_display->[$ind].'} ';
 1186: 	    if ($ind != $cou+$table_range[$j]-1) {
 1187: 		$result.=' & ';
 1188: 	    }
 1189: 	}
 1190: 	$cou += $table_range[$j];
 1191: 	$j++;
 1192: 	$result.='\\\\\end{tabular}\vskip 0 mm ';
 1193:     }
 1194:     return $result;
 1195: }
 1196: 
 1197: sub get_tolrange {
 1198:     my ($ans,$tol)=@_;
 1199:     my ($high,$low);
 1200:     if ($tol =~ /%$/) {
 1201: 	chop($tol);
 1202: 	my $change=$ans*($tol/100.0);
 1203: 	$high=$ans+$change;
 1204: 	$low=$ans-$change;
 1205:     } else {
 1206: 	$high=$ans+$tol;
 1207: 	$low=$ans-$tol;
 1208:     }
 1209:     return ($high,$low);
 1210: }
 1211: 
 1212: sub get_sigrange {
 1213:     my ($sig)=@_;
 1214:     #&Apache::lonxml::debug("Got a sig of :$sig:");
 1215:     my $courseid=$env{'request.course.id'};
 1216:     if ($env{'request.state'} ne 'construct'
 1217: 	&& lc($env{"course.$courseid.disablesigfigs"}) eq 'yes') {
 1218: 	return (15,0);
 1219:     }
 1220:     my $sig_lbound;
 1221:     my $sig_ubound;
 1222:     if ($sig eq '') {
 1223: 	$sig_lbound = 0; #SIG_LB_DEFAULT
 1224: 	$sig_ubound =15; #SIG_UB_DEFAULT
 1225:     } else {
 1226: 	($sig_lbound,$sig_ubound) = split(/,/,$sig);
 1227: 	if (!defined($sig_lbound)) {
 1228: 	    $sig_lbound = 0; #SIG_LB_DEFAULT
 1229: 	    $sig_ubound =15; #SIG_UB_DEFAULT
 1230: 	}
 1231: 	if (!defined($sig_ubound)) { $sig_ubound=$sig_lbound; }
 1232:     }
 1233:     if (($sig_ubound<$sig_lbound) ||
 1234: 	($sig_lbound > 15) ||
 1235: 	($sig =~/(\+|-)/ ) ) {
 1236: 	my $errormsg=&mt("Invalid Significant figures detected")." ($sig)";
 1237: 	if ($env{'request.state'} eq 'construct') {
 1238: 	    $errormsg.=
 1239: 		&Apache::loncommon::help_open_topic('Significant_Figures');
 1240: 	}
 1241: 	&Apache::lonxml::error($errormsg);
 1242:     }
 1243:     return ($sig_ubound,$sig_lbound);
 1244: }
 1245: 
 1246: sub format_prior_response_string {
 1247:     my ($mode,$answer) =@_;
 1248:     return '<span class="LC_prior_string">'.
 1249: 	    &HTML::Entities::encode($answer,'"<>&').'</span>';
 1250: }
 1251: 
 1252: sub start_stringresponse {
 1253:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1254:     my $result;
 1255:     my $id = &Apache::response::start_response($parstack,$safeeval);
 1256:     undef(%answer);
 1257:     if ($target eq 'meta') {
 1258: 	$result=&Apache::response::meta_package_write('stringresponse');
 1259:     } elsif ($target eq 'edit') {
 1260: 	$result.=&Apache::edit::tag_start($target,$token);
 1261: 	$result.=&Apache::edit::text_arg('Answer:','answer',$token);
 1262: 	$result.=&Apache::edit::select_arg('Type:','type',
 1263: 			 [['cs','Case Sensitive'],['ci','Case Insensitive'],
 1264: 			  ['mc','Case Insensitive, Any Order'],
 1265: 			  ['re','Regular Expression']],$token);
 1266: 	$result.=&Apache::edit::text_arg('String to display for answer:',
 1267: 					 'answerdisplay',$token);
 1268:         $result.=&Apache::edit::text_arg('Pre-Processor Subroutine:','preprocess',
 1269:                                              $token,10);
 1270: 	$result.=&Apache::edit::end_row().&Apache::edit::start_spanning_row();
 1271:     } elsif ($target eq 'modified') {
 1272: 	my $constructtag;
 1273: 	$constructtag=&Apache::edit::get_new_args($token,$parstack,
 1274: 						  $safeeval,'answer',
 1275: 						  'type','answerdisplay','preprocess');
 1276: 	if ($constructtag) {
 1277: 	    $result = &Apache::edit::rebuild_tag($token);
 1278: 	    $result.=&Apache::edit::handle_insert();
 1279: 	}
 1280:     } elsif ($target eq 'web') {
 1281: 	if (  &Apache::response::show_answer() ) {
 1282: 	    my $answer=
 1283: 	       &Apache::lonxml::get_param('answerdisplay',$parstack,$safeeval);
 1284: 	    if (!defined $answer || $answer eq '') {
 1285: 		$answer=
 1286: 		    &Apache::lonxml::get_param('answer',$parstack,$safeeval);
 1287: 	    }
 1288: 	    $Apache::inputtags::answertxt{$id}=[$answer];
 1289: 	} 
 1290:     } elsif ($target eq 'answer' || $target eq 'grade') {
 1291: 	&Apache::response::reset_params();
 1292:     }
 1293:     return $result;
 1294: }
 1295: 
 1296: sub end_stringresponse {
 1297:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1298: 
 1299:     my $result = '';
 1300:     my $part=$Apache::inputtags::part;
 1301:     my $id=$Apache::inputtags::response[-1];
 1302:     my $answer=&Apache::lonxml::get_param('answer',$parstack,$safeeval);
 1303:     my $type=&Apache::lonxml::get_param('type',$parstack,$safeeval);
 1304:     my $answerdisplay=&Apache::lonxml::get_param('answerdisplay',$parstack,$safeeval);
 1305:     &Apache::lonxml::debug("current $answer ".$token->[2]);
 1306:     if (!$Apache::lonxml::default_homework_loaded) {
 1307: 	&Apache::lonxml::default_homework_load($safeeval);
 1308:     }
 1309:     my $tag;
 1310:     if (scalar(@$tagstack)) { $tag=$$tagstack[-1]; }
 1311:     if ( $target eq 'grade' && &Apache::response::submitted() ) {
 1312: 	&Apache::response::setup_params('stringresponse',$safeeval);
 1313: 	$safeeval->share_from('capa',['&caparesponse_capa_check_answer']);
 1314: 	if ($Apache::lonhomework::type eq 'exam' ||
 1315: 	    &Apache::response::submitted('scantron')) {
 1316: 	    &Apache::response::scored_response($part,$id);
 1317: 
 1318: 	} else {
 1319: 	    my $response = &Apache::response::getresponse();
 1320: 	    if ( $response =~ /[^\s]/) {
 1321: 		my %previous = &Apache::response::check_for_previous($response,
 1322: 								    $part,$id,
 1323:                                                                     undef,$type);
 1324: 		&Apache::lonxml::debug("submitted a $response<br>\n");
 1325: 		&Apache::lonxml::debug($$parstack[-1] . "\n<br>");
 1326: 		$Apache::lonhomework::results{"resource.$part.$id.submission"}=
 1327: 		    $response;
 1328: 		my ($ad,$msg);
 1329: 		if ($type eq 're' ) { 
 1330: 		    # if the RE wasn't in a var it likely got munged,
 1331:                     # thus grab it from the var directly
 1332: #		    my $testans=$token->[2]->{'answer'};
 1333: #		    if ($testans !~ m/^\s*\$/) {
 1334: #			$answer=$token->[2]->{'answer'};
 1335: #		    }
 1336: 		    ${$safeeval->varglob('LONCAPA::response')}=$response;
 1337:                     my $preprocess=&Apache::lonxml::get_param('preprocess',$parstack,$safeeval);
 1338:                     $preprocess=~s/^\&//;
 1339:                     if (defined($preprocess)) {
 1340:                         &Apache::run::run('$LONCAPA::response=&'.$preprocess.'($LONCAPA::response);',$safeeval);
 1341:                     }
 1342: 		    $result = &Apache::run::run('if ($LONCAPA::response=~m'.$answer.') { return 1; } else { return 0; }',$safeeval);
 1343: 		    &Apache::lonxml::debug("current $response");
 1344: 		    &Apache::lonxml::debug("current $answer");
 1345: 		    $ad = ($result) ? 'APPROX_ANS' : 'INCORRECT';
 1346: 		} else {
 1347: 		    my @args = ('type','preprocess');
 1348: 		    my $args_ref = &setup_capa_args($safeeval,$parstack,
 1349: 						    \@args,$response);
 1350:                     if ($$args_ref{'type'} eq '') {
 1351:                         $$args_ref{'type'} = 'ci';
 1352:                     }
 1353:                     my $stringify = 1;
 1354: 		    &add_in_tag_answer($parstack,$safeeval,$stringify);
 1355: 		    my (@final_awards,@final_msgs,@names,%ansstring);
 1356: 		    foreach my $name (keys(%answer)) {
 1357: 			&Apache::lonxml::debug(" doing $name with ".join(':',@{ $answer{$name}{'answers'} }));
 1358: 			${$safeeval->varglob('LONCAPA::CAPAresponse_answer')}=dclone($answer{$name});
 1359: 			my ($result, @msgs)=&Apache::run::run("&caparesponse_check_list()",$safeeval);
 1360:                         if ($$args_ref{'type'} =~ /^c[si]$/) {
 1361:                             $ansstring{$name} = pop(@msgs);
 1362:                             my $control_chars_removed = pop(@msgs);
 1363:                             my $error = pop(@msgs);
 1364:                             if (($error ne '') || 
 1365:                                 ($control_chars_removed)) {
 1366:                                 my ($symb,$courseid,$sdomain,$sname) =
 1367:                                     &Apache::lonnet::whichuser();
 1368:                                 if ($control_chars_removed) {
 1369:                                     my $showresponse = $response;
 1370:                                     if ($response =~ /[\000-\037]/) {
 1371:                                         $response =~ s/[\000-\037]//g;
 1372:                                     }
 1373:                                     if ($showresponse  =~ /[\r\n\f]/) {
 1374:                                         my @lines = split(/[\r\n\f]+/,$showresponse);
 1375:                                         $showresponse = join('\\n',@lines);
 1376:                                     }
 1377:                                     &Apache::lonnet::logthis("Stringresponse grading: control characters stripped from submission ".$showresponse." for $sname:$sdomain in $courseid for part: $part response: $id and symb: $symb");
 1378:                                     $Apache::lonhomework::results{"resource.$part.$id.submission"} = $response;
 1379:                                 }
 1380:                                 if ($error ne '') {
 1381:                                     &Apache::lonnet::logthis("Stringresponse grading error: $error for $sname:$sdomain in $courseid for part: $part response: $id and symb: $symb");
 1382:                                 }
 1383:                             }
 1384:                         }
 1385: 			&Apache::lonxml::debug('msgs are'.join(':',@msgs));
 1386: 			my ($awards)=split(/:/,$result);
 1387: 			my (@awards) = split(/,/,$awards);
 1388: 			($ad,$msg) = 
 1389: 			    &Apache::inputtags::finalizeawards(\@awards,\@msgs);
 1390: 			push(@final_awards,$ad);
 1391: 			push(@final_msgs,$msg);
 1392: 			push(@names,$name);
 1393: 			&Apache::lonxml::debug("\n<br>result:$result:$Apache::lonxml::curdepth<br>\n");
 1394: 		    }
 1395: 		    ($ad, $msg, my $name) = 
 1396: 			&Apache::inputtags::finalizeawards(\@final_awards,
 1397: 							   \@final_msgs,
 1398: 							   \@names,1);
 1399:                     if (keys(%ansstring) > 0) {
 1400:                         $Apache::lonhomework::results{"resource.$part.$id.answerstring"} = &Apache::lonnet::hash2str(%ansstring);
 1401:                     }
 1402: 		}
 1403:                 if (($ad eq 'INCORRECT' || $ad eq 'APPROX_ANS' ||
 1404:                      $ad eq 'EXACT_ANS')) {
 1405: 		    if ($Apache::lonhomework::type eq 'survey') {
 1406: 		        $ad='SUBMITTED';
 1407: 		    } elsif ($Apache::lonhomework::type eq 'surveycred') {
 1408:                         $ad='SUBMITTED_CREDIT';
 1409:                     } elsif ($Apache::lonhomework::type eq 'anonsurvey') {
 1410:                         $ad='ANONYMOUS';
 1411:                     } elsif ($Apache::lonhomework::type eq 'anonsurveycred') {
 1412:                         $ad='ANONYMOUS_CREDIT';
 1413:                     }
 1414:                 }
 1415:                 unless (($env{'request.state'} eq 'construct') || 
 1416:                         ($Apache::lonhomework::type eq 'randomizetry')) {
 1417:                     if (($ad eq 'INCORRECT' || $ad eq 'APPROX_ANS' || $ad eq 'EXACT_ANS')) {
 1418:                         if ($previous{'used'}) {
 1419:                             if ($ad ne $previous{'award'}) {
 1420:                                 if (($previous{'award'} eq 'INCORRECT' || 
 1421:                                      $previous{'award'} eq 'APPROX_ANS' ||
 1422:                                      $previous{'award'} eq 'EXACT_ANS')) {
 1423:                                     &stringresponse_gradechange($part,$id,\%previous,
 1424:                                                                 'cs',$response,$ad,$type);
 1425:                                 }
 1426:                             }
 1427:                         } elsif ($previous{'usedci'}) {
 1428:                             if ($ad ne $previous{'awardci'}) {
 1429:                                 if (($previous{'awardci'} eq 'INCORRECT' || 
 1430:                                      $previous{'awardci'} eq 'APPROX_ANS' ||
 1431:                                      $previous{'awardci'} eq 'EXACT_ANS')) {
 1432:                                     &stringresponse_gradechange($part,$id,\%previous,
 1433:                                                                 'ci',$response,$ad,$type);
 1434:                                 }
 1435:                             }
 1436:                         }
 1437:                     }
 1438:                 }
 1439: 		&Apache::response::handle_previous(\%previous,$ad);
 1440: 		$Apache::lonhomework::results{"resource.$part.$id.awarddetail"}=$ad;
 1441: 		$Apache::lonhomework::results{"resource.$part.$id.awardmsg"}=$msg;
 1442: 	    }
 1443: 	}
 1444:     } elsif ($target eq 'answer' || $target eq 'analyze') {
 1445:         my $stringify;
 1446:         if ($type ne 're') {
 1447:             $stringify = 1;
 1448:         }
 1449: 	&add_in_tag_answer($parstack,$safeeval,$stringify);
 1450: 	if ($target eq 'analyze') {
 1451: 	    push (@{ $Apache::lonhomework::analyze{"parts"} },"$part.$id");
 1452: 	    $Apache::lonhomework::analyze{"$part.$id.type"} = 'stringresponse';
 1453: 	    &Apache::response::check_if_computed($token,$parstack,$safeeval,
 1454: 						 'answer');
 1455: 	}
 1456: 	&Apache::response::setup_params('stringresponse',$safeeval);
 1457: 	if ($target eq 'answer') {
 1458: 	    $result.=&Apache::response::answer_header('stringresponse');
 1459: 	}
 1460: 	foreach my $name (keys(%answer)) {
 1461: 	    my @answers = @{ $answer{$name}{'answers'} };
 1462: 	    for (my $i=0;$i<=$#answers;$i++) {
 1463: 		my $answer_part = $answers[$i];
 1464: 		foreach my $element (@{$answer_part}) {
 1465: 		    if ($target eq 'answer') {
 1466: 			$result.=&Apache::response::answer_part('stringresponse',
 1467: 								$element);
 1468:                         if ($env{'form.grade_retrieveanswers'}) {
 1469:                             $env{'form.grade_answers.resource.'.$part.'.'.$id} = $element;
 1470:                         }
 1471: 		    } elsif ($target eq 'analyze') {
 1472: 			push (@{ $Apache::lonhomework::analyze{"$part.$id.answer"}{$name}[$i] },
 1473: 			      $element);
 1474: 		    }
 1475: 		}
 1476: 		if ($target eq 'answer' && $type eq 're') {
 1477: 		    $result.=&Apache::response::answer_part('stringresponse',
 1478: 							    $answerdisplay);
 1479: 		}
 1480: 	    }
 1481: 	}
 1482: 	my $string='Case Insensitive';
 1483: 	if ($type eq 'mc') {
 1484: 	    $string='Multiple Choice';
 1485: 	} elsif ($type eq 'cs') {
 1486: 	    $string='Case Sensitive';
 1487: 	} elsif ($type eq 'ci') {
 1488: 	    $string='Case Insensitive';
 1489: 	} elsif ($type eq 're') {
 1490: 	    $string='Regular Expression';
 1491: 	}
 1492: 	if ($target eq 'answer') {
 1493: 	    if ($env{'form.answer_output_mode'} eq 'tex') {
 1494: 		$result.=&Apache::response::answer_part('stringresponse',
 1495: 							"$string");
 1496: 	    } else {
 1497: 		$result.=&Apache::response::answer_part('stringresponse',
 1498: 							"<b>$string</b>");
 1499: 	    }
 1500: 	} elsif ($target eq 'analyze') {
 1501: 	    push (@{$Apache::lonhomework::analyze{"$part.$id.str_type"}},
 1502: 		  $type);
 1503: 	}
 1504: 	if ($target eq 'answer') {
 1505: 	    $result.=&Apache::response::answer_footer('stringresponse');
 1506: 	}
 1507:     } elsif ($target eq 'edit') {
 1508: 	$result.='</td></tr>'.&Apache::edit::end_table;
 1509:     } elsif ($target eq 'web' || $target eq 'tex') {
 1510: 	&Apache::response::setup_prior_tries_hash(\&format_prior_response_string);
 1511:     }
 1512:     if ($target eq 'grade' || $target eq 'web' || $target eq 'answer' || 
 1513: 	$target eq 'tex' || $target eq 'analyze') {
 1514:         my $repetition = &Apache::response::repetition();
 1515: 	&Apache::lonxml::increment_counter($repetition,"$part.$id");
 1516: 	if ($target eq 'analyze') {
 1517: 	    &Apache::lonhomework::set_bubble_lines();
 1518: 	}
 1519:     }
 1520:     &Apache::response::end_response;
 1521:     return $result;
 1522: }
 1523: 
 1524: sub start_formularesponse {
 1525:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1526:     my $result;
 1527:     if ($target eq 'meta') {
 1528: 	&Apache::response::start_response($parstack,$safeeval);
 1529: 	$result=&Apache::response::meta_package_write('formularesponse');
 1530: 	&Apache::response::end_response();
 1531:     } else {
 1532: 	$result.=&start_numericalresponse(@_);
 1533:     }
 1534:     return $result;
 1535: }
 1536: 
 1537: sub end_formularesponse {
 1538:     return end_numericalresponse(@_);
 1539: }
 1540: 
 1541: 1;
 1542: __END__
 1543: 

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