[system] / trunk / pg / macros / PGbasicmacros.pl Repository:
ViewVC logotype

View of /trunk/pg/macros/PGbasicmacros.pl

Parent Directory Parent Directory | Revision Log Revision Log


Revision 2193 - (download) (as text) (annotate)
Mon May 24 01:05:03 2004 UTC (15 years, 8 months ago) by sh002i
File size: 66827 byte(s)
failover data now passed in via %envir.

    1 
    2 
    3 ####################################################################
    4 # Copyright @ 1995-1998 University of Rochester
    5 # All Rights Reserved
    6 ####################################################################
    7 
    8 =head1 NAME
    9 
   10     PGbasicmacros.pl --- located in the courseScripts directory
   11 
   12 =head1 SYNPOSIS
   13 
   14 
   15 
   16 =head1 DESCRIPTION
   17 
   18 
   19 
   20 =cut
   21 
   22 # this is equivalent to use strict, but can be used within the Safe compartment.
   23 BEGIN{
   24   be_strict;
   25 }
   26 
   27 
   28 my $displayMode;
   29 
   30 my ($PAR,
   31   $BR,
   32   $LQ,
   33   $RQ,
   34   $BM,
   35   $EM,
   36   $BDM,
   37   $EDM,
   38   $LTS,
   39   $GTS,
   40   $LTE,
   41   $GTE,
   42   $BEGIN_ONE_COLUMN,
   43   $END_ONE_COLUMN,
   44   $SOL,
   45   $SOLUTION,
   46   $HINT,
   47   $US,
   48   $SPACE,
   49   $BBOLD,
   50   $EBOLD,
   51   $BITALIC,
   52   $EITALIC,
   53   $BCENTER,
   54   $ECENTER,
   55   $HR,
   56   $LBRACE,
   57   $RBRACE,
   58   $LB,
   59   $RB,
   60   $DOLLAR,
   61   $PERCENT,
   62   $CARET,
   63   $PI,
   64   $E,
   65   @ALPHABET,
   66   $envir,
   67   $PG_random_generator,
   68   $inputs_ref,
   69   $rh_sticky_answers,
   70   $r_ans_rule_count,
   71   );
   72 
   73 sub _PGbasicmacros_init {
   74 
   75     # The big problem is that at compile time in the cached Safe compartment
   76     # main:: has one definition, probably Safe::Root1::
   77     # At runtime main has another definition Safe::Rootx:: where x is > 1
   78 
   79     # It is important to
   80     # initialize the my variable version of $displayMode from the "runtime" version
   81     # of main::displayMode
   82 
   83     $displayMode         =    main::PG_restricted_eval(q!$main::displayMode!);
   84 
   85 # This is initializes the remaining variables in the runtime main:: compartment.
   86 
   87 main::PG_restricted_eval( <<'EndOfFile');
   88     $displayMode            = $displayMode;
   89 
   90   $main::PAR        = PAR();
   91   $main::BR       = BR();
   92   $main::LQ       = LQ();
   93   $main::RQ       = RQ();
   94   $main::BM       = BM();
   95   $main::EM       = EM();
   96   $main::BDM        = BDM();
   97   $main::EDM        = EDM();
   98   $main::LTS        = LTS();
   99   $main::GTS        = GTS();
  100   $main::LTE        = LTE();
  101   $main::GTE        = GTE();
  102   $main::BEGIN_ONE_COLUMN = BEGIN_ONE_COLUMN();
  103   $main::END_ONE_COLUMN = END_ONE_COLUMN();
  104   $main::SOL        = SOLUTION_HEADING();
  105   $main::SOLUTION     = SOLUTION_HEADING();
  106   $main::HINT       = HINT_HEADING();
  107   $main::US       = US();
  108   $main::SPACE      = SPACE();
  109   $main::BBOLD      = BBOLD();
  110   $main::EBOLD      = EBOLD();
  111   $main::BITALIC      = BITALIC();
  112   $main::EITALIC          = EITALIC();
  113   $main::BCENTER          = BCENTER();
  114   $main::ECENTER          = ECENTER();
  115   $main::HR       = HR();
  116   $main::LBRACE     = LBRACE();
  117   $main::RBRACE     = RBRACE();
  118   $main::LB       = LB();
  119   $main::RB       = RB();
  120   $main::DOLLAR     = DOLLAR();
  121   $main::PERCENT      = PERCENT();
  122   $main::CARET      = CARET();
  123   $main::PI       = PI();
  124   $main::E        = E();
  125   @main::ALPHABET     = ('A'..'ZZ');
  126   %main::STICKY_ANSWERS   = ();
  127 
  128 
  129 EndOfFile
  130 
  131 # Next we transfer the correct definitions in the main:: compartment to the local my variables
  132 # This can't be done inside the eval above because my variables seem to be invisible inside the eval
  133 
  134 
  135     $PAR         = PAR();
  136   $BR            = BR();
  137   $LQ            = LQ();
  138   $RQ            = RQ();
  139   $BM            = BM();
  140   $EM            = EM();
  141   $BDM         = BDM();
  142   $EDM         = EDM();
  143   $LTS         = LTS();
  144   $GTS         = GTS();
  145   $LTE         = LTE();
  146   $GTE         = GTE();
  147   $BEGIN_ONE_COLUMN  = BEGIN_ONE_COLUMN();
  148   $END_ONE_COLUMN      = END_ONE_COLUMN();
  149   $SOL         = SOLUTION_HEADING();
  150   $SOLUTION      = SOLUTION_HEADING();
  151   $HINT        = HINT_HEADING();
  152   $US            = US();
  153   $SPACE           = SPACE();
  154   $BBOLD           = BBOLD();
  155   $EBOLD           = EBOLD();
  156   $BITALIC       = BITALIC();
  157   $EITALIC             = EITALIC();
  158   $BCENTER             = BCENTER();
  159   $ECENTER             = ECENTER();
  160   $HR            = HR();
  161   $LBRACE          = LBRACE();
  162   $RBRACE          = RBRACE();
  163   $LB            = LB();
  164   $RB            = RB();
  165   $DOLLAR          = DOLLAR();
  166   $PERCENT       = PERCENT();
  167   $CARET           = CARET();
  168   $PI            = PI();
  169   $E             = E();
  170   @ALPHABET      = ('A'..'ZZ');
  171 
  172    $envir               = PG_restricted_eval(q!\%main::envir!);
  173    $PG_random_generator = PG_restricted_eval(q!$main::PG_random_generator!);
  174    $inputs_ref          = $envir{inputs_ref};
  175    $rh_sticky_answers   = PG_restricted_eval(q!\%main::STICKY_ANSWERS!);
  176    $r_ans_rule_count     = PG_restricted_eval(q!\$ans_rule_count!);
  177 }
  178 
  179 =head2  Answer blank macros:
  180 
  181 These produce answer blanks of various sizes or pop up lists or radio answer buttons.
  182 The names for the answer blanks are
  183 generated implicitly.
  184 
  185   ans_rule( width )
  186   tex_ans_rule( width )
  187   ans_radio_buttons(value1=>label1, value2,label2 => value3,label3=>...)
  188   pop_up_list(@list)  # list consists of (value => label,  PR => "Product rule",...)
  189 
  190 To indicate the checked position of radio buttons put a '%' in front of the value: C<ans_radio_buttons(1, 'Yes','%2','No')>
  191 will have 'No' checked.  C<tex_ans_rule> works inside math equations in C<HTML_tth> mode.  It does not work in C<Latex2HTML> mode
  192 since this mode produces gif pictures.
  193 
  194 
  195 The following method is defined in F<PG.pl> for entering the answer evaluators corresponding
  196 to answer rules with automatically generated names.  The answer evaluators are matched with the
  197 answer rules in the order in which they appear on the page.
  198 
  199   ANS(ans_evaluator1, ans_evaluator2,...);
  200 
  201 These are more primitive macros which produce answer blanks for specialized cases when complete
  202 control over the matching of answers blanks and answer evaluators is desired.
  203 The names of the answer blanks must be generated manually, and it is best if they do NOT begin
  204 with the default answer prefix (currently AnSwEr).
  205 
  206   labeled_ans_rule(name, width)  # an alias for NAMED_ANS_RULE where width defaults to 20 if omitted.
  207 
  208   NAMED_ANS_RULE(name, width)
  209   NAMED_ANS_BOX(name, rows, cols)
  210   NAMED_ANS_RADIO(name, value,label,)
  211   NAMED_ANS_RADIO_EXTENSION(name, value,label)
  212   NAMED_ANS_RADIO_BUTTONS(name,value1,label1,value2,label2,...)
  213   check_box('-name' =>answer5,'-value' =>'statement3','-label' =>'I loved this course!'   )
  214   NAMED_POP_UP_LIST($name, @list) # list consists of (value => tag,  PR => "Product rule",...)
  215 
  216 (Name is the name of the variable, value is the value given to the variable when this option is selected,
  217 and label is the text printed next to the button or check box.    Check box variables can have multiple values.)
  218 
  219 NAMED_ANS_RADIO_BUTTONS creates a sequence of NAMED_ANS_RADIO and NAMED_ANS_RADIO_EXTENSION  items which
  220 are  output either as an array or, in scalar context, as the array glued together with spaces.  It is
  221 usually easier to use this than to manually construct the radio buttons by hand.  However, sometimes
  222  extra flexibility is desiredin which case:
  223 
  224 When entering radio buttons using the "NAMED" format, you should use NAMED_ANS_RADIO button for the first button
  225 and then use NAMED_ANS_RADIO_EXTENSION for the remaining buttons.  NAMED_ANS_RADIO requires a matching answer evalutor,
  226 while NAMED_ANS_RADIO_EXTENSION does not. The name used for NAMED_ANS_RADIO_EXTENSION should match the name
  227 used for NAMED_ANS_RADIO (and the associated answer evaluator).
  228 
  229 
  230 The following method is defined in  F<PG.pl> for entering the answer evaluators corresponding
  231 to answer rules with automatically generated names.  The answer evaluators are matched with the
  232 answer rules in the order in which they appear on the page.
  233 
  234       NAMED_ANS(name1 => ans_evaluator1, name2 => ans_evaluator2,...);
  235 
  236 These auxiliary macros are defined in PG.pl
  237 
  238 
  239   NEW_ANS_NAME( number );   # produces a new answer blank name from a number by adding a prefix (AnSwEr)
  240                             # and registers this name as an implicitly labeled answer
  241                             # Its use is paired with each answer evaluator being entered using ANS()
  242 
  243     ANS_NUM_TO_NAME(number);  # adds the prefix (AnSwEr) to the number, but does nothing else.
  244 
  245   RECORD_ANS_NAME( name );  # records the order in which the answer blank  is rendered
  246                             # This is called by all of the constructs above, but must
  247                             # be called explicitly if an input blank is constructed explictly
  248                             # using HTML code.
  249 
  250 These are legacy macros:
  251 
  252   ANS_RULE( number, width );                  # equivalent to NAMED_ANS_RULE( NEW_ANS_NAME(number), width)
  253   ANS_BOX( question_number,height, width );       # equivalent to NAMED_ANS_BOX( NEW_ANS_NAME(number), height, width)
  254   ANS_RADIO( question_number, value,tag );        # equivalent to NAMED_ANS_RADIO( NEW_ANS_NAME(number), value,tag)
  255   ANS_RADIO_OPTION( question_number, value,tag );   # equivalent to NAMED_ANS_RADIO_EXTENSION( ANS_NUM_TO_NAME(number), value,tag)
  256 
  257 
  258 =cut
  259 
  260 
  261 
  262 sub labeled_ans_rule {   # syntactic sugar for NAMED_ANS_RULE
  263   my($name,$col) = @_;
  264   $col = 20 unless defined($col);
  265   NAMED_ANS_RULE($name,$col);
  266 }
  267 
  268 sub NAMED_ANS_RULE {
  269   my($name,$col) = @_;
  270   my $len = 0.07*$col;
  271   my $answer_value = '';
  272   $answer_value = ${$inputs_ref}{$name} if    defined(${$inputs_ref}{$name});
  273     if ($answer_value =~ /\0/ ) {
  274       my @answers = split("\0", $answer_value);
  275       $answer_value = shift(@answers);  # use up the first answer
  276       $rh_sticky_answers->{$name}=\@answers;
  277       # store the rest -- beacuse this stores to a main:; variable
  278       # it must be evaluated at run time
  279       $answer_value= '' unless defined($answer_value);
  280   } elsif (ref($answer_value) eq 'ARRAY') {
  281     my @answers = @{ $answer_value};
  282       $answer_value = shift(@answers);  # use up the first answer
  283       $rh_sticky_answers->{$name}=\@answers;
  284       # store the rest -- beacuse this stores to a main:; variable
  285       # it must be evaluated at run time
  286       $answer_value= '' unless defined($answer_value);
  287   }
  288 
  289   $answer_value =~ tr/\\$@`//d;   ## make sure student answers can not be interpolated by e.g. EV3
  290   $name = RECORD_ANS_NAME($name);
  291 
  292   # incorporated Davide Cervone's changes
  293   # removed newlines from around <INPUT> tags
  294   # made TeX rule be based on specified width rather than varying size.
  295   my $tcol = $col/2 > 3 ? $col/2 : 3;  ## get max
  296   $tcol = $tcol < 40 ? $tcol : 40;     ## get min
  297 
  298   MODES(
  299     TeX => "\\mbox{\\parbox[t]{${tcol}ex}{\\hrulefill}}",
  300     Latex2HTML => qq!\\begin{rawhtml}<INPUT TYPE=TEXT SIZE=$col NAME=\"$name\" VALUE = \"\">\\end{rawhtml}!,
  301     HTML => qq!<INPUT TYPE=TEXT SIZE=$col NAME="$name" VALUE = "$answer_value">\n
  302                <INPUT TYPE=HIDDEN  NAME="previous_$name" VALUE = "$answer_value">
  303           !
  304 
  305   );
  306 }
  307 
  308 sub NAMED_ANS_RULE_OPTION {   # deprecated
  309   &NAMED_ANS_RULE_EXTENSION;
  310 }
  311 
  312 sub NAMED_ANS_RULE_EXTENSION {
  313   my($name,$col) = @_;
  314   my $len = 0.07*$col;
  315   my $answer_value = '';
  316   $answer_value = ${$inputs_ref}{$name} if defined(${$inputs_ref}{$name});
  317   if ( defined( $rh_sticky_answers->{$name} ) ) {
  318     $answer_value = shift( @{ $rh_sticky_answers->{$name} });
  319     $answer_value = '' unless defined($answer_value);
  320   }
  321   $answer_value =~ tr/\\$@`//d;   ## make sure student answers can not be interpolated by e.g. EV3
  322   MODES(
  323     TeX => '\\hrulefill\\quad ',
  324     Latex2HTML => qq!\\begin{rawhtml}\n<INPUT TYPE=TEXT SIZE=$col NAME=\"$name\" VALUE = \"\">\n\\end{rawhtml}\n!,
  325     HTML => qq!<INPUT TYPE=TEXT SIZE=$col NAME = "$name" VALUE = "$answer_value">\n
  326                <INPUT TYPE=HIDDEN  NAME="previous_$name" VALUE = "$answer_value">
  327               !
  328   );
  329 }
  330 
  331 sub ANS_RULE {  #deprecated
  332   my($number,$col) = @_;
  333   my $name = NEW_ANS_NAME($number);
  334     NAMED_ANS_RULE($name,$col);
  335 }
  336 
  337 
  338 sub  NAMED_ANS_BOX {
  339   my($name,$row,$col) = @_;
  340   $row = 10 unless defined($row);
  341   $col = 80 unless defined($col);
  342   $name = RECORD_ANS_NAME($name);
  343   my $len = 0.07*$col;
  344   my $height = .07*$row;
  345   my $answer_value = '';
  346   $answer_value = $inputs_ref->{$name} if defined( $inputs_ref->{$name} );
  347   $answer_value =~ tr/\\$@`//d;   ## make sure student answers can not be interpolated by e.g. EV3
  348   my $out = M3(
  349        qq!\\vskip $height in \\hrulefill\\quad !,
  350        qq!\\begin{rawhtml}<TEXTAREA NAME="$name" ROWS="$row" COLS="$col"
  351                WRAP="VIRTUAL">$answer_value</TEXTAREA>\\end{rawhtml}!,
  352          qq!<TEXTAREA NAME="$name" ROWS="$row" COLS="$col"
  353                WRAP="VIRTUAL">$answer_value</TEXTAREA>
  354              <INPUT TYPE=HIDDEN  NAME="previous_$name" VALUE = "$answer_value">
  355            !
  356          );
  357   $out;
  358 }
  359 
  360 sub  ANS_BOX { #deprecated
  361   my($number,$row,$col) = @_;
  362   my $name = NEW_ANS_NAME($number);
  363     NAMED_ANS_BOX($name,$row,$col);
  364 }
  365 
  366 sub NAMED_ANS_RADIO {
  367   my $name = shift;
  368   my $value = shift;
  369     my $tag =shift;
  370     $name = RECORD_ANS_NAME($name);
  371     my $checked = '';
  372     if ($value =~/^\%/) {
  373       $value =~ s/^\%//;
  374       $checked = 'CHECKED'
  375     }
  376   if (defined($inputs_ref->{$name}) ) {
  377     if ($inputs_ref->{$name} eq $value) {
  378       $checked = 'CHECKED'
  379     } else {
  380       $checked = '';
  381     }
  382 
  383     }
  384 
  385   MODES(
  386     TeX => qq!\\item{$tag}\n!,
  387     Latex2HTML => qq!\\begin{rawhtml}\n<INPUT TYPE=RADIO NAME="$name" VALUE="$value" $checked>\\end{rawhtml}$tag!,
  388     HTML => qq!<INPUT TYPE=RADIO NAME="$name" VALUE="$value" $checked>$tag!
  389   );
  390 
  391 }
  392 
  393 sub NAMED_ANS_RADIO_OPTION { #deprecated
  394   &NAMED_ANS_RADIO_EXTENSION;
  395 }
  396 
  397 sub NAMED_ANS_RADIO_EXTENSION {
  398   my $name = shift;
  399   my $value = shift;
  400   my $tag =shift;
  401 
  402 
  403     my $checked = '';
  404     if ($value =~/^\%/) {
  405       $value =~ s/^\%//;
  406       $checked = 'CHECKED'
  407     }
  408   if (defined($inputs_ref->{$name}) ) {
  409     if ($inputs_ref->{$name} eq $value) {
  410       $checked = 'CHECKED'
  411     } else {
  412       $checked = '';
  413     }
  414 
  415     }
  416 
  417   MODES(
  418     TeX => qq!\\item{$tag}\n!,
  419     Latex2HTML => qq!\\begin{rawhtml}\n<INPUT TYPE=RADIO NAME="$name" VALUE="$value" $checked>\\end{rawhtml}$tag!,
  420     HTML => qq!<INPUT TYPE=RADIO NAME="$name" VALUE="$value" $checked>$tag!
  421   );
  422 
  423 }
  424 
  425 sub NAMED_ANS_RADIO_BUTTONS {
  426     my $name  =shift;
  427     my $value = shift;
  428     my $tag = shift;
  429 
  430 
  431   my @out = ();
  432   push(@out, NAMED_ANS_RADIO($name, $value,$tag));
  433   my @buttons = @_;
  434   while (@buttons) {
  435     $value = shift @buttons;  $tag = shift @buttons;
  436     push(@out, NAMED_ANS_RADIO_OPTION($name, $value,$tag));
  437   }
  438   (wantarray) ? @out : join(" ",@out);
  439 }
  440 sub ANS_RADIO {
  441   my $number = shift;
  442   my $value = shift;
  443   my $tag =shift;
  444     my $name = NEW_ANS_NAME($number);
  445   NAMED_ANS_RADIO($name,$value,$tag);
  446 }
  447 
  448 sub ANS_RADIO_OPTION {
  449   my $number = shift;
  450   my $value = shift;
  451   my $tag =shift;
  452 
  453 
  454     my $name = ANS_NUM_TO_NAME($number);
  455   NAMED_ANS_RADIO_OPTION($name,$value,$tag);
  456 }
  457 sub ANS_RADIO_BUTTONS {
  458     my $number  =shift;
  459     my $value = shift;
  460     my $tag = shift;
  461 
  462 
  463   my @out = ();
  464   push(@out, ANS_RADIO($number, $value,$tag));
  465   my @buttons = @_;
  466   while (@buttons) {
  467       $value = shift @buttons; $tag = shift @buttons;
  468     push(@out, ANS_RADIO_OPTION($number, $value,$tag));
  469   }
  470   (wantarray) ? @out : join(" ",@out);
  471 }
  472 ##############################################
  473 #   contained_in( $elem, $array_reference or null separated string);
  474 #   determine whether element is equal
  475 #   ( in the sense of eq,  not ==, ) to an element in the array.
  476 ##############################################
  477 sub contained_in {
  478   my $element = shift;
  479   my @input_list    = @_;
  480   my @output_list = ();
  481   # Expand the list -- convert references to  arrays to arrays
  482   # Convert null separated strings to arrays
  483   foreach my $item   (@input_list ) {
  484     if ($item =~ /\0/) {
  485       push @output_list,   split('\0', $item);
  486      } elsif (ref($item) =~/ARRAY/) {
  487       push @output_list, @{$item};
  488      } else {
  489       push @output_list, $item;
  490      }
  491   }
  492 
  493   my @match_list = grep {$element eq $_ } @output_list;
  494   if ( @match_list ) {
  495     return 1;
  496   } else {
  497     return 0;
  498   }
  499 }
  500 
  501 ##########################
  502 # If multiple boxes are checked then the $inputs_ref->{name }will be a null separated string
  503 # or a reference to an array.
  504 ##########################
  505 
  506 sub NAMED_ANS_CHECKBOX {
  507   my $name = shift;
  508   my $value = shift;
  509     my $tag =shift;
  510     $name = RECORD_ANS_NAME($name);
  511 
  512     my $checked = '';
  513     if ($value =~/^\%/) {
  514       $value =~ s/^\%//;
  515       $checked = 'CHECKED'
  516     }
  517 
  518   if (defined($inputs_ref->{$name}) ) {
  519     if ( contained_in($value, $inputs_ref->{$name} ) ) {
  520       $checked = 'CHECKED'
  521     }
  522     else {
  523       $checked = '';
  524     }
  525 
  526     }
  527 
  528   MODES(
  529     TeX => qq!\\item{$tag}\n!,
  530     Latex2HTML => qq!\\begin{rawhtml}\n<INPUT TYPE=CHECKBOX NAME="$name" VALUE="$value" $checked>\\end{rawhtml}$tag!,
  531     HTML => qq!<INPUT TYPE=CHECKBOX NAME="$name" VALUE="$value" $checked>$tag!
  532   );
  533 
  534 }
  535 
  536 sub NAMED_ANS_CHECKBOX_OPTION {
  537   my $name = shift;
  538   my $value = shift;
  539   my $tag =shift;
  540 
  541     my $checked = '';
  542     if ($value =~/^\%/) {
  543       $value =~ s/^\%//;
  544       $checked = 'CHECKED'
  545     }
  546 
  547   if (defined($inputs_ref->{$name}) ) {
  548     if ( contained_in($value, $inputs_ref->{$name}) ) {
  549       $checked = 'CHECKED'
  550     }
  551     else {
  552       $checked = '';
  553     }
  554 
  555     }
  556 
  557   MODES(
  558     TeX => qq!\\item{$tag}\n!,
  559     Latex2HTML => qq!\\begin{rawhtml}\n<INPUT TYPE=CHECKBOX NAME="$name" VALUE="$value" $checked>\\end{rawhtml}$tag!,
  560     HTML => qq!<INPUT TYPE=CHECKBOX NAME="$name" VALUE="$value" $checked>$tag!
  561   );
  562 
  563 }
  564 
  565 sub NAMED_ANS_CHECKBOX_BUTTONS {
  566     my $name  =shift;
  567     my $value = shift;
  568     my $tag = shift;
  569 
  570   my @out = ();
  571   push(@out, NAMED_ANS_CHECKBOX($name, $value,$tag));
  572 
  573   my @buttons = @_;
  574   while (@buttons) {
  575     $value = shift @buttons;  $tag = shift @buttons;
  576     push(@out, NAMED_ANS_CHECKBOX_OPTION($name, $value,$tag));
  577   }
  578 
  579   (wantarray) ? @out : join(" ",@out);
  580 }
  581 
  582 sub ANS_CHECKBOX {
  583   my $number = shift;
  584   my $value = shift;
  585   my $tag =shift;
  586     my $name = NEW_ANS_NAME($number);
  587 
  588   NAMED_ANS_CHECKBOX($name,$value,$tag);
  589 }
  590 
  591 sub ANS_CHECKBOX_OPTION {
  592   my $number = shift;
  593   my $value = shift;
  594   my $tag =shift;
  595     my $name = ANS_NUM_TO_NAME($number);
  596 
  597   NAMED_ANS_CHECKBOX_OPTION($name,$value,$tag);
  598 }
  599 
  600 
  601 
  602 sub ANS_CHECKBOX_BUTTONS {
  603     my $number  =shift;
  604     my $value = shift;
  605     my $tag = shift;
  606 
  607   my @out = ();
  608   push(@out, ANS_CHECKBOX($number, $value, $tag));
  609 
  610   my @buttons = @_;
  611   while (@buttons) {
  612     $value = shift @buttons;  $tag = shift @buttons;
  613     push(@out, ANS_CHECKBOX_OPTION($number, $value,$tag));
  614   }
  615 
  616   (wantarray) ? @out : join(" ",@out);
  617 }
  618 
  619 sub ans_rule {
  620   my $len = shift;     # gives the optional length of the answer blank
  621   $len    = 20 unless $len ;
  622   my $name = NEW_ANS_NAME(inc_ans_rule_count());
  623   NAMED_ANS_RULE($name ,$len);
  624 }
  625 sub ans_rule_extension {
  626   my $len = shift;
  627     $len    = 20 unless $len ;
  628   my $name = NEW_ANS_NAME($$r_ans_rule_count);  # don't update the answer name
  629   NAMED_ANS_RULE($name ,$len);
  630 }
  631 sub ans_radio_buttons {
  632   my $name  = NEW_ANS_NAME(inc_ans_rule_count());
  633   my @radio_buttons = NAMED_ANS_RADIO_BUTTONS($name, @_);
  634 
  635   if ($displayMode eq 'TeX') {
  636     $radio_buttons[0] = "\n\\begin{itemize}\n" . $radio_buttons[0];
  637     $radio_buttons[$#radio_buttons] .= "\n\\end{itemize}\n";
  638   }
  639 
  640   (wantarray) ? @radio_buttons: join(" ", @radio_buttons);
  641 }
  642 
  643 #added 6/14/2000 by David Etlinger
  644 sub ans_checkbox {
  645   my $name = NEW_ANS_NAME( inc_ans_rule_count() );
  646   my @checkboxes = NAMED_ANS_CHECKBOX_BUTTONS( $name, @_ );
  647 
  648   if ($displayMode eq 'TeX') {
  649     $checkboxes[0] = "\n\\begin{itemize}\n" . $checkboxes[0];
  650     $checkboxes[$#checkboxes] .= "\n\\end{itemize}\n";
  651   }
  652 
  653   (wantarray) ? @checkboxes: join(" ", @checkboxes);
  654 }
  655 
  656 
  657 ## define a version of ans_rule which will work inside TeX math mode or display math mode -- at least for tth mode.
  658 ## This is great for displayed fractions.
  659 ## This will not work with latex2HTML mode since it creates gif equations.
  660 
  661 sub tex_ans_rule {
  662   my $len = shift;
  663   $len    = 20 unless $len ;
  664     my $name = NEW_ANS_NAME(inc_ans_rule_count());
  665     my $answer_rule = NAMED_ANS_RULE($name ,$len);  # we don't want to create three answer rules in different modes.
  666     my $out = MODES(
  667                      'TeX' => $answer_rule,
  668                      'Latex2HTML' => '\\fbox{Answer boxes cannot be placed inside typeset equations}',
  669                      'HTML_tth' => '\\begin{rawhtml} '. $answer_rule.'\\end{rawhtml}',
  670                      'HTML_dpng' => '\\fbox{Answer boxes cannot be placed inside typeset equations}',
  671                      'HTML'     => $answer_rule
  672                    );
  673 
  674     $out;
  675 }
  676 sub tex_ans_rule_extension {
  677   my $len = shift;
  678   $len    = 20 unless $len ;
  679     my $name = NEW_ANS_NAME($$r_ans_rule_count);
  680     my $answer_rule = NAMED_ANS_RULE($name ,$len);  # we don't want to create three answer rules in different modes.
  681     my $out = MODES(
  682                      'TeX' => $answer_rule,
  683                      'Latex2HTML' => '\fbox{Answer boxes cannot be placed inside typeset equations}',
  684                      'HTML_tth' => '\\begin{rawhtml} '. $answer_rule.'\\end{rawhtml}',
  685                      'HTML_dpng' => '\fbox{Answer boxes cannot be placed inside typeset equations}',
  686                      'HTML'     => $answer_rule
  687                    );
  688 
  689     $out;
  690 }
  691 # still needs some cleanup.
  692 sub NAMED_TEX_ANS_RULE {
  693     my $name = shift;
  694   my $len = shift;
  695   $len    = 20 unless $len ;
  696     my $answer_rule = NAMED_ANS_RULE($name ,$len);  # we don't want to create three answer rules in different modes.
  697     my $out = MODES(
  698                      'TeX' => $answer_rule,
  699                      'Latex2HTML' => '\\fbox{Answer boxes cannot be placed inside typeset equations}',
  700                      'HTML_tth' => '\\begin{rawhtml} '. $answer_rule.'\\end{rawhtml}',
  701                      'HTML_dpng' => '\\fbox{Answer boxes cannot be placed inside typeset equations}',
  702                      'HTML'     => $answer_rule
  703                    );
  704 
  705     $out;
  706 }
  707 sub NAMED_TEX_ANS_RULE_EXTENSION {
  708   my $name = shift;
  709   my $len = shift;
  710   $len    = 20 unless $len ;
  711     my $answer_rule = NAMED_ANS_RULE_EXTENSION($name ,$len);  # we don't want to create three answer rules in different modes.
  712     my $out = MODES(
  713                      'TeX' => $answer_rule,
  714                      'Latex2HTML' => '\fbox{Answer boxes cannot be placed inside typeset equations}',
  715                      'HTML_tth' => '\\begin{rawhtml} '. $answer_rule.'\\end{rawhtml}',
  716                      'HTML_dpng' => '\fbox{Answer boxes cannot be placed inside typeset equations}',
  717                      'HTML'     => $answer_rule
  718                    );
  719 
  720     $out;
  721 }
  722 sub ans_box {
  723   my $row = shift;
  724   my $col =shift;
  725   $row = 5 unless $row;
  726   $col = 80 unless $col;
  727   my $name = NEW_ANS_NAME(inc_ans_rule_count());
  728   NAMED_ANS_BOX($name ,$row,$col);
  729 }
  730 
  731 #this is legacy code; use ans_checkbox instead
  732 sub checkbox {
  733   my %options = @_;
  734   qq!<INPUT TYPE="checkbox" NAME="$options{'-name'}" VALUE="$options{'-value'}">$options{'-label'}!
  735 }
  736 
  737 
  738 sub NAMED_POP_UP_LIST {
  739     my $name = shift;
  740   my @list = @_;
  741   $name = RECORD_ANS_NAME($name);   # record answer name
  742     my $answer_value = '';
  743   $answer_value = ${$inputs_ref}{$name} if defined(${$inputs_ref}{$name});
  744   my $out = "";
  745   if ($displayMode eq 'HTML' or $displayMode eq 'HTML_tth' or
  746             $displayMode eq 'HTML_dpng' or $displayMode eq 'HTML_img' or $displayMode eq 'HTML_jsMath') {
  747     $out = qq!<SELECT NAME = "$name" SIZE=1> \n!;
  748     my $i;
  749     foreach ($i=0; $i< @list; $i=$i+2) {
  750       my $select_flag = ($list[$i] eq $answer_value) ? "SELECTED" : "";
  751       $out .= qq!<OPTION $select_flag VALUE ="$list[$i]" > $list[$i+1]  </OPTION>\n!;
  752     };
  753     $out .= " </SELECT>\n";
  754   } elsif ( $displayMode eq "Latex2HTML") {
  755     $out = qq! \\begin{rawhtml}<SELECT NAME = "$name" SIZE=1> \\end{rawhtml} \n !;
  756     my $i;
  757     foreach ($i=0; $i< @list; $i=$i+2) {
  758       my $select_flag = ($list[$i] eq $answer_value) ? "SELECTED" : "";
  759       $out .= qq!\\begin{rawhtml}<OPTION $select_flag VALUE ="$list[$i]" > $list[$i+1]  </OPTION>\\end{rawhtml}\n!;
  760     };
  761     $out .= " \\begin{rawhtml}</SELECT>\\end{rawhtml}\n";
  762   } elsif ( $displayMode eq "TeX") {
  763       $out .= "\\fbox{?}";
  764   }
  765 
  766 }
  767 
  768 sub pop_up_list {
  769   my @list = @_;
  770   my $name = NEW_ANS_NAME(inc_ans_rule_count());  # get new answer name
  771   NAMED_POP_UP_LIST($name, @list);
  772 }
  773 
  774 
  775 
  776 =head5  answer_matrix
  777 
  778     Usage   \[ \{   answer_matrix(rows,columns,width_of_ans_rule, @options) \} \]
  779 
  780     Creates an array of answer blanks and passes it to display_matrix which returns
  781     text which represents the matrix in TeX format used in math display mode. Answers
  782     are then passed back to whatever answer evaluators you write at the end of the problem.
  783     (note, if you have an m x n matrix, you will need mn answer evaluators, and they will be
  784     returned to the evaluaters starting in the top left hand corner and proceed to the left
  785     and then at the end moving down one row, just as you would read them.)
  786 
  787     The options are passed on to display_matrix.
  788 
  789 
  790 =cut
  791 
  792 
  793 sub answer_matrix{
  794   my $m = shift;
  795   my $n = shift;
  796   my $width = shift;
  797   my @options = @_;
  798   my @array=();
  799   for( my $i = 0; $i < $m; $i+=1)
  800   {
  801     my @row_array = ();
  802 
  803     for( my $i = 0; $i < $n; $i+=1)
  804     {
  805       push @row_array,  ans_rule($width);
  806     }
  807     my $r_row_array = \@row_array;
  808     push @array,  $r_row_array;
  809   }
  810   # display_matrix hasn't been loaded into the cache safe compartment
  811   # so we need to refer to the subroutine in this way to make
  812   # sure that main is defined correctly.
  813   my $ra_local_display_matrix=PG_restricted_eval(q!\&main::display_matrix!);
  814   &$ra_local_display_matrix( \@array, @options );
  815 
  816 }
  817 
  818 sub NAMED_ANS_ARRAY_EXTENSION{
  819 
  820   my $name = shift;
  821   my $col = shift;
  822   $col = 20 unless $col;
  823   my $answer_value = '';
  824 
  825   $answer_value = ${$inputs_ref}{$name} if    defined(${$inputs_ref}{$name});
  826   if ($answer_value =~ /\0/ ) {
  827     my @answers = split("\0", $answer_value);
  828     $answer_value = shift(@answers);
  829     $answer_value= '' unless defined($answer_value);
  830   } elsif (ref($answer_value) eq 'ARRAY') {
  831     my @answers = @{ $answer_value};
  832       $answer_value = shift(@answers);
  833         $answer_value= '' unless defined($answer_value);
  834   }
  835 
  836   $answer_value =~ tr/\\$@`//d;   ## make sure student answers can not be interpolated by e.g. EV3
  837   MODES(
  838     TeX => "\\mbox{\\parbox[t]{10pt}{\\hrulefill}}\\hrulefill\\quad ",
  839     Latex2HTML => qq!\\begin{rawhtml}\n<INPUT TYPE=TEXT SIZE=$col NAME=\"$name\" VALUE = \"\">\n\\end{rawhtml}\n!,
  840     HTML => "<INPUT TYPE=TEXT SIZE=$col NAME=\"$name\" VALUE = \"$answer_value\">\n"
  841   );
  842 }
  843 
  844 sub ans_array{
  845   my $m = shift;
  846   my $n = shift;
  847   my $col = shift;
  848   $col = 20 unless $col;
  849   my $num = inc_ans_rule_count() ;
  850   my $name = NEW_ANS_ARRAY_NAME($num,0,0);
  851   my @options = @_;
  852   my @array=();
  853   my $string;
  854   my $answer_value = "";
  855 
  856   $array[0][0] =   NAMED_ANS_RULE($name,$col);
  857 
  858   for( my $i = 1; $i < $n; $i+=1)
  859   {
  860     $name = NEW_ANS_ARRAY_NAME_EXTENSION($num,0,$i);
  861     $array[0][$i] =   NAMED_ANS_ARRAY_EXTENSION($name,$col);
  862 
  863   }
  864 
  865   for( my $j = 1; $j < $m; $j+=1 ){
  866 
  867     for( my $i = 0; $i < $n; $i+=1)
  868     {
  869       $name = NEW_ANS_ARRAY_NAME_EXTENSION($num,$j,$i);
  870       $array[$j][$i] =  NAMED_ANS_ARRAY_EXTENSION($name,$col);
  871 
  872     }
  873 
  874   }
  875   my $ra_local_display_matrix=PG_restricted_eval(q!\&main::display_matrix!);
  876   &$ra_local_display_matrix( \@array, @options );
  877 
  878 }
  879 
  880 sub ans_array_extension{
  881   my $m = shift;
  882   my $n = shift;
  883   my $col = shift;
  884   $col = 20 unless $col;
  885   my $num = PG_restricted_eval(q!$main::ans_rule_count!);
  886   my @options = @_;
  887   my $name;
  888   my @array=();
  889   my $string;
  890   my $answer_value = "";
  891 
  892   for( my $j = 0; $j < $m; $j+=1 ){
  893 
  894     for( my $i = 0; $i < $n; $i+=1)
  895     {
  896       $name = NEW_ANS_ARRAY_NAME_EXTENSION($num,$j,$i);
  897       $array[$j][$i] =  NAMED_ANS_ARRAY_EXTENSION($name,$col);
  898 
  899     }
  900 
  901   }
  902   my $ra_local_display_matrix=PG_restricted_eval(q!\&main::display_matrix!);
  903   &$ra_local_display_matrix( \@array, @options );
  904 
  905 }
  906 
  907 
  908 # end answer blank macros
  909 
  910 =head2 Hints and solutions macros
  911 
  912   solution('text','text2',...);
  913   SOLUTION('text','text2',...);   # equivalent to TEXT(solution(...));
  914 
  915   hint('text', 'text2', ...);
  916   HINT('text', 'text2',...);      # equivalent to TEXT("$BR$HINT" . hint(@_) . "$BR") if hint(@_);
  917 
  918 Solution prints its concatenated input when the check box named 'ShowSol' is set and
  919 the time is after the answer date.  The check box 'ShowSol' is visible only after the
  920 answer date or when the problem is viewed by a professor.
  921 
  922 $main::envir{'displaySolutionsQ'} is set to 1 when a solution is to be displayed.
  923 
  924 Hints are shown only after the number of attempts is greater than $:showHint
  925 ($main::showHint defaults to 1) and the check box named 'ShowHint' is set. The check box
  926 'ShowHint' is visible only after the number of attempts is greater than $main::showHint.
  927 
  928 $main::envir{'displayHintsQ'} is set to 1 when a hint is to be displayed.
  929 
  930 
  931 =cut
  932 
  933 
  934 
  935 #   solution prints its input when $displaySolutionsQ is set.
  936 #   use as TEXT(solution("blah, blah");
  937 #   \$solutionExists
  938 #   is passed to processProblem which displays a "show Solution" button
  939 #   when a solution is available for viewing
  940 
  941 
  942 sub solution {
  943   my @in = @_;
  944   my $out = '';
  945   PG_restricted_eval(q!$main::solutionExists =1!);
  946   if (PG_restricted_eval(q!$main::envir{'displaySolutionsQ'}!)) {$out = join(' ',@in);}
  947     $out;
  948 }
  949 
  950 
  951 sub SOLUTION {
  952   TEXT( solution(@_)) ;
  953 }
  954 
  955 
  956 
  957 sub hint {
  958     my @in = @_;
  959   my $out = '';
  960 
  961   PG_restricted_eval(q!$main::hintExists =1;
  962                          $main::numOfAttempts = 0 unless defined($main::numOfAttempts);
  963     !);
  964 
  965   if ($displayMode eq 'TeX')   {
  966     $out = '';  # do nothing since hints are not available for download
  967   } elsif (($envir->{'displayHintsQ'}) and
  968           PG_restricted_eval(q!($main::numOfAttempts >= $main::showHint)!))
  969 
  970    ## the second test above prevents a hint being shown if a doctored form is submitted
  971 
  972   {$out = join(' ',@in);}    # show hint
  973 
  974   $out ;
  975 }
  976 
  977 
  978 sub HINT {
  979     TEXT("$BR" . hint(@_) . "$BR") if hint(@_);
  980 }
  981 
  982 
  983 
  984 # End hints and solutions macros
  985 #################################
  986 
  987 # Produces a random number between $begin and $end with increment 1.
  988 # You do not have to worry about integer or floating point types.
  989 
  990 =head2 Pseudo-random number generator
  991 
  992   Usage:
  993   random(0,5,.1)      # produces a random number between 0 and 5 in increments of .1
  994   non_zero_random(0,5,.1) # gives a non-zero random number
  995 
  996   list_random(2,3,5,6,7,8,10) # produces random value from the list
  997   list_random(2,3, (5..8),10) # does the same thing
  998 
  999   SRAND(seed)     # resets the main random generator -- use very cautiously
 1000 
 1001 
 1002 SRAND(time) will create a different problem everytime it is called.  This makes it difficult
 1003 to check the answers :-).
 1004 
 1005 SRAND($envir->{'inputs_ref'}->{'key'} ) will create a different problem for each login session.
 1006 This is probably what is desired.
 1007 
 1008 =cut
 1009 
 1010 
 1011 sub random  {
 1012   my ($begin, $end, $incr) = @_;
 1013   $PG_random_generator->random($begin,$end,$incr);
 1014 }
 1015 
 1016 
 1017 sub non_zero_random { ##gives a non-zero random number
 1018   my (@arguments)=@_;
 1019   my $a=0;
 1020   my $i=100; #safety counter
 1021   while ($a==0 && ( 0 < $i-- ) ) {
 1022     $a=random(@arguments);
 1023   }
 1024   $a;
 1025 }
 1026 
 1027 sub list_random {
 1028         my(@li) = @_;
 1029         return $li[random(1,scalar(@li))-1];
 1030 }
 1031 
 1032 sub SRAND { # resets the main random generator -- use cautiously
 1033     my $seed = shift;
 1034   $PG_random_generator -> srand($seed);
 1035 }
 1036 
 1037 # display macros
 1038 
 1039 =head2 Display Macros
 1040 
 1041 These macros produce different output depending on the display mode being used to show
 1042 the problem on the screen, or whether the problem is being converted to TeX to produce
 1043 a hard copy output.
 1044 
 1045   MODES   ( TeX =>        "Output this in TeX mode",
 1046             HTML =>       "output this in HTML mode",
 1047             HTML_tth =>   "output this in HTML_tth mode",
 1048             HTML_dpng =>   "output this in HTML_dpng mode",
 1049             Latex2HTML => "output this in Latex2HTML mode",
 1050            )
 1051 
 1052   TEX     (tex_version, html_version) #obsolete
 1053 
 1054   M3      (tex_version, latex2html_version, html_version) #obsolete
 1055 
 1056 
 1057 
 1058 =cut
 1059 
 1060 
 1061 sub TEX {
 1062   my ($tex, $html ) = @_;
 1063   MODES(TeX => $tex, HTML => $html, HTML_tth => $html, HTML_dpng => $html);
 1064 }
 1065 
 1066 
 1067 sub M3 {
 1068   my($tex,$l2h,$html) = @_;
 1069   MODES(TeX => $tex, Latex2HTML => $l2h, HTML => $html, HTML_tth => $html, HTML_dpng => $html);
 1070 }
 1071 
 1072 # This replaces M3.  You can add new modes at will to this one.
 1073 
 1074 sub MODES {
 1075   my %options = @_;
 1076 
 1077   return $options{$displayMode} if defined $options{$displayMode};
 1078 
 1079   if (exists $envir{displayModeFailover}->{$displayMode}) {
 1080     my @backup_modes = @{$envir{displayModeFailover}->{$displayMode}};
 1081     foreach my $mode (@backup_modes) {
 1082       return $options{$mode} if defined $options{$mode};
 1083     }
 1084     die "ERROR in defining MODES: neither display mode $displayMode nor",
 1085       " any fallback modes (", join(", ", @backup_modes), ") defined.\n";
 1086   }
 1087 
 1088   die "ERROR in defining MODES: current display mode '$displayMode' not found. available modes: ",
 1089     join (", ", keys %{$envir{displayModeFailover}}), "\n";
 1090 
 1091   return $options{$displayMode}
 1092              if defined( $options{$displayMode} );
 1093 
 1094 =for comment
 1095 
 1096   # default searches.
 1097   if ($displayMode eq "Latex2HTML") {
 1098     return $options{TeX}
 1099              if defined( $options{TeX} );
 1100       return $options{HTML}
 1101              if defined( $options{HTML} );
 1102       die " ERROR in using MODES: 'HTML' and 'TeX' options not defined for 'Latex2HTML'";
 1103   }
 1104 
 1105   if ($displayMode eq "HTML_tth") {
 1106     return $options{HTML}
 1107              if defined( $options{HTML} );
 1108       die " ERROR in using MODES: 'HTML' option not defined for HTML_tth";
 1109 
 1110   }
 1111 
 1112   if ($displayMode eq "HTML_img") {
 1113     return $options{HTML_dpng} if defined $options{HTML_dpng};
 1114     return $options{HTML_tth} if defined $options{HTML_tth};
 1115     return $options{HTML}     if defined $options{HTML};
 1116     die " ERROR in using MODES: 'HTML' option not defined for HTML_img";
 1117   }
 1118 
 1119   if ($displayMode eq "HTML_dpng") {
 1120     return $options{HTML_tth}
 1121              if defined( $options{HTML_tth} );
 1122     return $options{HTML}
 1123              if defined( $options{HTML} );
 1124       die " ERROR in using MODES: 'HTML' option not defined for HTML_dpng";
 1125 
 1126   }
 1127 
 1128   if ($displayMode eq "HTML_jsMath") {
 1129     return $options{HTML_img}  if defined $options{HTML_img};
 1130     return $options{HTML_dpng} if defined $options{HTML_dpng};
 1131     return $options{HTML_tth}  if defined $options{HTML_tth};
 1132     return $options{HTML}      if defined $options{HTML};
 1133     die " ERROR in using MODES: 'HTML' option not defined for HTML_jsMath";
 1134   }
 1135 
 1136   # trap undefined errors
 1137   die "ERROR in defining MODES:  Can't find |$displayMode| among
 1138            available options:" . join(" ", keys(%options) )
 1139            . " file " . __FILE__ ." line " . __LINE__."\n\n";
 1140 
 1141 =cut
 1142 
 1143 }
 1144 
 1145 
 1146 # end display macros
 1147 
 1148 
 1149 =head2  Display constants
 1150 
 1151   @ALPHABET       ALPHABET()      capital letter alphabet -- ALPHABET[0] = 'A'
 1152   $PAR        PAR()       paragraph character (\par or <p>)
 1153   $BR             BR()        line break character
 1154   $LQ         LQ()        left double quote
 1155   $RQ         RQ()        right double quote
 1156   $BM         BM()        begin math
 1157   $EM         EM()        end math
 1158   $BDM        BDM()       begin display math
 1159   $EDM        EDM()       end display math
 1160   $LTS        LTS()       strictly less than
 1161   $GTS        GTS()       strictly greater than
 1162   $LTE        LTE()       less than or equal
 1163   $GTE        GTE()       greater than or equal
 1164   $BEGIN_ONE_COLUMN BEGIN_ONE_COLUMN()  begin one-column mode
 1165   $END_ONE_COLUMN   END_ONE_COLUMN()  end one-column mode
 1166   $SOL        SOLUTION_HEADING()  solution headline
 1167   $SOLUTION     SOLUTION_HEADING()  solution headline
 1168   $HINT       HINT_HEADING()    hint headline
 1169   $US         US()        underscore character
 1170   $SPACE        SPACE()       space character (tex and latex only)
 1171   $BBOLD        BBOLD()       begin bold typeface
 1172   $EBOLD        EBOLD()       end bold typeface
 1173   $BITALIC        BITALIC()       begin italic typeface
 1174   $EITALIC        EITALIC()       end italic typeface
 1175   $BCENTER        BCENTER()       begin centered environment
 1176   $ECENTER        ECENTER()       end centered environment
 1177   $HR         HR()        horizontal rule
 1178   $LBRACE       LBRACE()      left brace
 1179   $LB         LB ()       left brace
 1180   $RBRACE       RBRACE()      right brace
 1181   $RB         RB ()       right brace
 1182   $DOLLAR       DOLLAR()      a dollar sign
 1183   $PERCENT      PERCENT()     a percent sign
 1184   $CARET        CARET()       a caret sign
 1185   $PI         PI()        the number pi
 1186   $E          E()         the number e
 1187 
 1188 =cut
 1189 
 1190 
 1191 
 1192 
 1193 
 1194 # A utility variable.  Notice that "B"=$ALPHABET[1] and
 1195 # "ABCD"=@ALPHABET[0..3].
 1196 
 1197 sub ALPHABET  {
 1198   ('A'..'ZZ')[@_];
 1199 }
 1200 
 1201 ###############################################################
 1202 # Some constants which are different in tex and in HTML
 1203 # The order of arguments is TeX, Latex2HTML, HTML
 1204 # Adopted Davide Cervone's improvements to PAR, LTS, GTS, LTE, GTE, LBRACE, RBRACE, LB, RB. 7-14-03 AKP
 1205 sub PAR { MODES( TeX => '\\par ', Latex2HTML => '\\begin{rawhtml}<P>\\end{rawhtml}', HTML => '<P>'); };
 1206 sub BR { MODES( TeX => '\\par\\noindent ', Latex2HTML => '\\begin{rawhtml}<BR>\\end{rawhtml}', HTML => '<BR>'); };
 1207 # Alternate definition of BR which is slightly more flexible and gives more white space in printed output
 1208 # which looks better but kills more trees.
 1209 #sub BR { MODES( TeX => '\\\\', Latex2HTML => '\\begin{rawhtml}<BR>\\end{rawhtml}', HTML => '<BR>'); };
 1210 sub LQ { MODES( TeX => "``", Latex2HTML =>   '"',  HTML =>  '&quot;' ); };
 1211 sub RQ { MODES( TeX => "''", Latex2HTML =>   '"',   HTML =>  '&quot;' ); };
 1212 sub BM { MODES(TeX => '\\(', Latex2HTML => '\\(', HTML =>  ''); };  # begin math mode
 1213 sub EM { MODES(TeX => '\\)', Latex2HTML => '\\)', HTML => ''); };  # end math mode
 1214 sub BDM { MODES(TeX => '\\[', Latex2HTML =>   '\\[', HTML =>   '<P ALIGN=CENTER>'); };  #begin displayMath mode
 1215 sub EDM { MODES(TeX => '\\]',  Latex2HTML =>  '\\]', HTML => '</P>'); };              #end displayMath mode
 1216 sub LTS { MODES(TeX => '<', Latex2HTML => '\\lt ', HTML => '&lt;', HTML_tth => '<' ); };
 1217 sub GTS { MODES(TeX => '>', Latex2HTML => '\\gt ', HTML => '&gt;', HTML_tth => '>' ); };
 1218 sub LTE { MODES(TeX => '\\le ', Latex2HTML => '\\le ', HTML => '<U>&lt;</U>', HTML_tth => '\\le ' ); };
 1219 sub GTE { MODES(TeX => '\\ge ', Latex2HTML => '\\ge ', HTML => '<U>&gt;</U>', HTML_tth => '\\ge ' ); };
 1220 sub BEGIN_ONE_COLUMN { MODES(TeX => " \\end{multicols}\n",  Latex2HTML => " ", HTML =>   " "); };
 1221 sub END_ONE_COLUMN { MODES(TeX =>
 1222               " \\begin{multicols}{2}\n\\columnwidth=\\linewidth\n",
 1223                             Latex2HTML => ' ', HTML => ' ');
 1224 
 1225 };
 1226 sub SOLUTION_HEADING { MODES( TeX => '\\par {\\bf Solution:}',
 1227                  Latex2HTML => '\\par {\\bf Solution:}',
 1228                HTML =>  '<P><B>Solution:</B>');
 1229               };
 1230 sub HINT_HEADING { MODES( TeX => "\\par {\\bf Hint:}", Latex2HTML => "\\par {\\bf Hint:}", HTML => "<P><B>Hint:</B>"); };
 1231 sub US { MODES(TeX => '\\_', Latex2HTML => '\\_', HTML => '_');};  # underscore, e.g. file${US}name
 1232 sub SPACE { MODES(TeX => '\\ ',  Latex2HTML => '\\ ', HTML => '&nbsp;');};  # force a space in latex, doesn't force extra space in html
 1233 sub BBOLD { MODES(TeX => '{\\bf ',  Latex2HTML => '{\\bf ', HTML => '<B>'); };
 1234 sub EBOLD { MODES( TeX => '}', Latex2HTML =>  '}',HTML =>  '</B>'); };
 1235 sub BITALIC { MODES(TeX => '{\\it ',  Latex2HTML => '{\\it ', HTML => '<I>'); };
 1236 sub EITALIC { MODES(TeX => '} ',  Latex2HTML => '} ', HTML => '</I>'); };
 1237 sub BCENTER { MODES(TeX => '\\begin{center} ',  Latex2HTML => ' \\begin{rawhtml} <div align="center"> \\end{rawhtml} ', HTML => '<div align="center">'); };
 1238 sub ECENTER { MODES(TeX => '\\end{center} ',  Latex2HTML => ' \\begin{rawhtml} </div> \\end{rawhtml} ', HTML => '</div>'); };
 1239 sub HR { MODES(TeX => '\\par\\hrulefill\\par ', Latex2HTML => '\\begin{rawhtml} <HR> \\end{rawhtml}', HTML =>  '<HR>'); };
 1240 sub LBRACE { MODES( TeX => '\{', Latex2HTML =>   '\\lbrace',  HTML =>  '{' , HTML_tth=> '\\lbrace' ); };
 1241 sub RBRACE { MODES( TeX => '\}', Latex2HTML =>   '\\rbrace',  HTML =>  '}' , HTML_tth=> '\\rbrace',); };
 1242 sub LB { MODES( TeX => '\{', Latex2HTML =>   '\\lbrace',  HTML =>  '{' , HTML_tth=> '\\lbrace' ); };
 1243 sub RB { MODES( TeX => '\}', Latex2HTML =>   '\\rbrace',  HTML =>  '}' , HTML_tth=> '\\rbrace',); };
 1244 sub DOLLAR { MODES( TeX => '\\$', Latex2HTML => '\\$', HTML => '$' ); };
 1245 sub PERCENT { MODES( TeX => '\\%', Latex2HTML => '\\%', HTML => '%' ); };
 1246 sub CARET { MODES( TeX => '\\verb+^+', Latex2HTML => '\\verb+^+', HTML => '^' ); };
 1247 sub PI {4*atan2(1,1);};
 1248 sub E {exp(1);};
 1249 
 1250 ###############################################################
 1251 ## Evaluation macros
 1252 
 1253 
 1254 =head2 TEXT macros
 1255 
 1256   Usage:
 1257     TEXT(@text);
 1258 
 1259 This is the simplest way to print text from a problem.  The strings in the array C<@text> are concatenated
 1260 with spaces between them and printed out in the text of the problem.  The text is not processed in any other way.
 1261 C<TEXT> is defined in PG.pl.
 1262 
 1263   Usage:
 1264     BEGIN_TEXT
 1265       text.....
 1266     END_TEXT
 1267 
 1268 This is the most common way to enter text into the problem.  All of the text between BEGIN_TEXT and END_TEXT
 1269 is processed by the C<EV3> macro described below and then printed using the C<TEXT> command.  The two key words
 1270 must appear on lines by themselves.  The preprocessing that makes this construction work is done in F<PGtranslator.pm>.
 1271 See C<EV3> below for details on the processing.
 1272 
 1273 
 1274 =cut
 1275 
 1276 =head2 Evaluation macros
 1277 
 1278 =head3 EV3
 1279 
 1280         TEXT(EV3("This is a formulat \( \int_0^5 x^2 \, dx \) ");
 1281         TEXT(EV3(@text));
 1282 
 1283     TEXT(EV3(<<'END_TEXT'));
 1284       text stuff...
 1285     END_TEXT
 1286 
 1287 
 1288 The BEGIN_TEXT/END_TEXT construction is translated into the construction above by PGtranslator.pm.  END_TEXT must appear
 1289 on a line by itself and be left justified.  (The << construction is known as a "here document" in UNIX and in PERL.)
 1290 
 1291 The single quotes around END_TEXT mean that no automatic interpolation of variables takes place in the text.
 1292 Using EV3 with strings which have been evaluated by double quotes may lead to unexpected results.
 1293 
 1294 
 1295 The evaluation macro E3 first evaluates perl code inside the braces:  C<\{  code \}>.
 1296 Any perl statment can be put inside the braces.  The
 1297 result of the evaluation (i.e. the last statement evaluated) replaces the C<\{ code \}> construction.
 1298 
 1299 Next interpolation of all variables (e.g. C<$var or @array> ) is performed.
 1300 
 1301 Then mathematical formulas in TeX are evaluated within the
 1302 C<\(  tex math mode \)> and
 1303 C<\[ tex display math mode \] >
 1304 constructions, in that order:
 1305 
 1306 =head3 FEQ
 1307 
 1308   FEQ($string);   # processes and outputs the string
 1309 
 1310 
 1311 The mathematical formulas are run through the macro C<FEQ> (Format EQuations) which performs
 1312 several substitutions (see below).
 1313 In C<HTML_tth> mode the resulting code is processed by tth to obtain an HTML version
 1314 of the formula. (In the future processing by WebEQ may be added here as another option.)
 1315 The Latex2HTML mode does nothing
 1316 at this stage; it creates the entire problem before running it through
 1317 TeX and creating the GIF images of the equations.
 1318 
 1319 The resulting string is output (and usually fed into TEXT to be printed in the problem).
 1320 
 1321   Usage:
 1322 
 1323     $string2 = FEQ($string1);
 1324 
 1325 This is a filter which is used to format equations by C<EV2> and C<EV3>, but can also be used on its own.  It is best
 1326 understood with an example.
 1327 
 1328     $string1 = "${a}x^2 + ${b}x + {$c:%.1f}"; $a = 3;, $b = -2; $c = -7.345;
 1329 
 1330 when interpolated becomes:
 1331 
 1332     $string1 = '3x^2 + -2x + {-7.345:%0.1f}
 1333 
 1334 FEQ first changes the number of decimal places displayed, so that the last term becomes -7.3 Then it removes the
 1335 extraneous plus and minus signs, so that the final result is what you want:
 1336 
 1337     $string2 = '3x^2 - 2x -7.3';
 1338 
 1339 (The %0.1f construction
 1340 is the same formatting convention used by Perl and nearly identical to the one used by the C printf statement. Some common
 1341 usage:  %0.3f 3 decimal places, fixed notation; %0.3e 3 significant figures exponential notation; %0.3g uses either fixed
 1342 or exponential notation depending on the size of the number.)
 1343 
 1344 Two additional legacy formatting constructions are also supported:
 1345 
 1346 C<?{$c:%0.3f} > will give a number with 3 decimal places and a negative
 1347 sign if the number is negative, no sign if the number is positive.
 1348 
 1349 C<!{$c:%0.3f}> determines the sign and prints it
 1350 whether the number is positive or negative.
 1351 
 1352 =head3 EV2
 1353 
 1354     TEXT(EV2(@text));
 1355 
 1356     TEXT(EV2(<<END_OF_TEXT));
 1357       text stuff...
 1358     END_OF_TEXT
 1359 
 1360 This is a precursor to EV3.  In this case the constants are interpolated first, before the evaluation of the \{ ...code...\}
 1361 construct. This can lead to unexpected results.  For example C<\{ join(" ", @text) \}> with C<@text = ("Hello","World");> becomes,
 1362 after interpolation, C<\{ join(" ",Hello World) \}> which then causes an error when evaluated because Hello is a bare word.
 1363 C<EV2> can still be useful if you allow for this, and in particular it works on double quoted strings, which lead to
 1364 unexpected results with C<EV3>. Using single quoted strings with C<EV2> may lead to unexpected results.
 1365 
 1366 The unexpected results have to do with the number of times backslashed constructions have to be escaped. It is quite messy.  For
 1367 more details get a good Perl book and then read the code. :-)
 1368 
 1369 
 1370 
 1371 
 1372 =cut
 1373 
 1374 
 1375 sub ev_substring {
 1376     my $string      = shift;
 1377   my $start_delim = shift;
 1378   my $end_delim   = shift;
 1379   my $actionRef   = shift;
 1380   my ($eval_out,$PG_eval_errors,$PG_full_error_report)=();
 1381     my $out = "";
 1382                 #
 1383                 #  DPVC -- 2001/12/07
 1384                 #     original "while ($string)" fails to process the string "0" correctly
 1385                 #
 1386     while ($string ne "") {
 1387                 #
 1388                 #  end DPVC
 1389                 #
 1390         if ($string =~ /\Q$start_delim\E/s) {
 1391        #print "$start_delim $end_delim evaluating_substring=$string<BR>";
 1392         $string =~ s/^(.*?)\Q$start_delim\E//s;  # get string up to next \{ ---treats string as a single line, ignoring returns
 1393         $out .= $1;
 1394        #print "$start_delim $end_delim substring_out=$out<BR>";
 1395         $string =~ s/^(.*?)\Q$end_delim\E//s;  # get perl code up to \} ---treats string as a single line,  ignoring returns
 1396            #print "$start_delim $end_delim evaluate_string=$1<BR>";
 1397         ($eval_out,$PG_eval_errors,$PG_full_error_report) = &$actionRef($1);
 1398         $eval_out = "$start_delim $eval_out $end_delim" if $PG_full_error_report;
 1399         $out = $out . $eval_out;
 1400        #print "$start_delim $end_delim new substring_out=$out<BR><p><BR>";
 1401         $out .="$PAR ERROR $0 in ev_substring, PGbasicmacros.pl:$PAR <PRE>  $@ </PRE>$PAR" if $@;
 1402         }
 1403       else {
 1404         $out .= $string;  # flush the last part of the string
 1405         last;
 1406         }
 1407 
 1408       }
 1409   $out;
 1410 }
 1411 sub  safe_ev {
 1412     my ($out,$PG_eval_errors,$PG_full_error_report) = &old_safe_ev;   # process input by old_safe_ev first
 1413     $out =~s/\\/\\\\/g;   # protect any new backslashes introduced.
 1414   ($out,$PG_eval_errors,$PG_full_error_report)
 1415 }
 1416 
 1417 sub  old_safe_ev {
 1418     my $in = shift;
 1419     my   ($out,$PG_eval_errors,$PG_full_error_report) = PG_restricted_eval("$in;");
 1420     # the addition of the ; seems to provide better error reporting
 1421     if ($PG_eval_errors) {
 1422       my @errorLines = split("\n",$PG_eval_errors);
 1423     #$out = "<PRE>$PAR % ERROR in $0:old_safe_ev, PGbasicmacros.pl: $PAR % There is an error occuring inside evaluation brackets \\{ ...code... \\} $BR % somewhere in an EV2 or EV3 or BEGIN_TEXT block. $BR % Code evaluated:$BR $in $BR % $BR % $errorLines[0]\n % $errorLines[1]$BR % $BR % $BR </PRE> ";
 1424     warn " ERROR in old_safe_ev, PGbasicmacros.pl: <PRE>
 1425      ## There is an error occuring inside evaluation brackets \\{ ...code... \\}
 1426      ## somewhere in an EV2 or EV3 or BEGIN_TEXT block.
 1427      ## Code evaluated:
 1428      ## $in
 1429      ##" .join("\n     ", @errorLines). "
 1430      ##</PRE>$BR
 1431      ";
 1432      $out ="$PAR $BBOLD  $in $EBOLD $PAR";
 1433 
 1434 
 1435   }
 1436 
 1437   ($out,$PG_eval_errors,$PG_full_error_report);
 1438 }
 1439 
 1440 sub FEQ   {    # Format EQuations
 1441   my $in = shift;
 1442    # formatting numbers -- the ?{} and !{} constructions
 1443   $in =~s/\?\s*\{([.\-\$\w\d]+):?([%.\da-z]*)\}/${ \( &sspf($1,$2) )}/g;
 1444   $in =~s/\!\s*\{([.\-\$\w\d]+):?([%.\da-z]*)\}/${ \( &spf($1,$2) )}/g;
 1445 
 1446   # more formatting numbers -- {number:format} constructions
 1447   $in =~ s/\{(\s*[\+\-\d\.]+[eE]*[\+\-]*\d*):(\%\d*.\d*\w)}/${ \( &spf($1,$2) )}/g;
 1448   $in =~ s/\+\s*\-/ - /g;
 1449   $in =~ s/\-\s*\+/ - /g;
 1450   $in =~ s/\+\s*\+/ + /g;
 1451   $in =~ s/\-\s*\-/ + /g;
 1452   $in;
 1453 }
 1454 
 1455 #sub math_ev3 {
 1456 # my $in = shift; #print "in=$in<BR>";
 1457 # my ($out,$PG_eval_errors,$PG_full_error_report);
 1458 # $in = FEQ($in);
 1459 # $in =~ s/%/\\%/g;   #  % causes trouble in TeX and HTML_tth it usually (always?) indicates an error, not comment
 1460 # return("$BM $in $EM") unless ($displayMode eq 'HTML_tth');
 1461 # $in = "\\(" . $in . "\\)";
 1462 # $out = tth($in);
 1463 # ($out,$PG_eval_errors,$PG_full_error_report);
 1464 #
 1465 #}
 1466 #
 1467 #sub display_math_ev3 {
 1468 # my $in = shift; #print "in=$in<BR>";
 1469 # my ($out,$PG_eval_errors,$PG_full_error_report);
 1470 # $in = FEQ($in);
 1471 # $in =~ s/%/\\%/g;
 1472 # return("$main::BDM $in $main::EDM") unless $displayMode eq 'HTML_tth' ;
 1473 # $in = "\\[" . $in . "\\]";
 1474 # $out =tth($in);
 1475 # ($out,$PG_eval_errors,$PG_full_error_report);
 1476 #}
 1477 
 1478 sub math_ev3 {
 1479   my $in = shift;
 1480   return general_math_ev3($in, "inline");
 1481 }
 1482 
 1483 sub display_math_ev3 {
 1484   my $in = shift;
 1485   return general_math_ev3($in, "display");
 1486 }
 1487 
 1488 sub general_math_ev3 {
 1489   my $in = shift;
 1490   my $mode = shift || "inline";
 1491 
 1492   $in = FEQ($in); # Format EQuations
 1493   $in =~ s/%/\\%/g; # avoid % becoming TeX comments
 1494 
 1495   ## remove leading and trailing spaces so that HTML mode will
 1496   ## not include unwanted spaces as per Davide Cervone.
 1497   $in =~ s/^\s+//;
 1498   $in =~ s/\s+$//;
 1499   ## If it ends with a backslash, there should be another space
 1500   ## at the end
 1501   if($in =~ /\\$/) { $in .= ' ';}
 1502 
 1503   # some modes want the delimiters, some don't
 1504   my $in_delim = $mode eq "inline"
 1505     ? "\\($in\\)"
 1506     : "\\[$in\\]";
 1507 
 1508   my $out;
 1509   if($displayMode eq "HTML_tth") {
 1510     $out = tth($in_delim);
 1511     ## remove leading and trailing spaces as per Davide Cervone.
 1512     $in =~ s/^\s+//;
 1513     $in =~ s/\s+$//;
 1514   } elsif ($displayMode eq "HTML_dpng") {
 1515     # for jj's version of ImageGenerator
 1516     $out = $envir->{'imagegen'}->add($in_delim);
 1517     # for my version of ImageGenerator
 1518     #$out = $envir->{'imagegen'}->add($in, $mode);
 1519   } elsif ($displayMode eq "HTML_img") {
 1520     $out = math2img($in, $mode);
 1521   } elsif ($displayMode eq "HTML_jsMath") {
 1522     $out = '<SPAN CLASS="math">'.$in.'</SPAN>' if $mode eq "inline";
 1523     $out = '<DIV CLASS="math">'.$in.'</DIV>' if $mode eq "display";
 1524   } else {
 1525     $out = "\\($in\\)" if $mode eq "inline";
 1526     $out = "\\[$in\\]" if $mode eq "display";
 1527   }
 1528   return $out;
 1529 }
 1530 
 1531 sub EV2 {
 1532   my $string = join(" ",@_);
 1533   # evaluate code inside of \{  \}  (no nesting allowed)
 1534     $string = ev_substring($string,"\\{","\\}",\&old_safe_ev);
 1535     $string = ev_substring($string,"\\<","\\>",\&old_safe_ev);
 1536   $string = ev_substring($string,"\\(","\\)",\&math_ev3);
 1537   $string = ev_substring($string,"\\[","\\]",\&display_math_ev3);
 1538   # macros for displaying math
 1539   $string =~ s/\\\(/$BM/g;
 1540   $string =~ s/\\\)/$EM/g;
 1541   $string =~ s/\\\[/$BDM/g;
 1542   $string =~ s/\\\]/$EDM/g;
 1543   $string;
 1544 }
 1545 
 1546 sub EV3{
 1547   my $string = join(" ",@_);
 1548   # evaluate code inside of \{  \}  (no nesting allowed)
 1549     $string = ev_substring($string,"\\\\{","\\\\}",\&safe_ev);  # handles \{ \} in single quoted strings of PG files
 1550   # interpolate variables
 1551   my ($evaluated_string,$PG_eval_errors,$PG_full_errors) = PG_restricted_eval("<<END_OF_EVALUATION_STRING\n$string\nEND_OF_EVALUATION_STRING\n");
 1552   if ($PG_eval_errors) {
 1553       my @errorLines = split("\n",$PG_eval_errors);
 1554       $string =~ s/</&lt;/g; $string =~ s/>/&gt;/g;
 1555     $evaluated_string = "<PRE>$PAR % ERROR in $0:EV3, PGbasicmacros.pl: $PAR % There is an error occuring in the following code:$BR $string $BR % $BR % $errorLines[0]\n % $errorLines[1]$BR % $BR % $BR </PRE> ";
 1556     $@="";
 1557   }
 1558   $string = $evaluated_string;
 1559   $string = ev_substring($string,"\\(","\\)",\&math_ev3);
 1560     $string = ev_substring($string,"\\[","\\]",\&display_math_ev3);
 1561   $string;
 1562 }
 1563 
 1564 sub EV4{
 1565     if ($displayMode eq "HTML_dpng") {
 1566         my $string = join(" ",@_);
 1567         my ($evaluated_string,$PG_eval_errors,$PG_full_errors) = PG_restricted_eval("<<END_OF_EVALUATION_STRING\n$string\nEND_OF_EVALUATION_STRING\n");
 1568         if ($PG_eval_errors) {
 1569             my @errorLines = split("\n",$PG_eval_errors);
 1570             $string =~ s/</&lt;/g; $string =~ s/>/&gt;/g;
 1571             $evaluated_string = "<PRE>$PAR % ERROR in $0:EV3, PGbasicmacros.pl:".
 1572       "$PAR % There is an error occuring in the following code:$BR ".
 1573       "$string $BR % $BR % $errorLines[0]\n % $errorLines[1]$BR ".
 1574       "% $BR % $BR </PRE> ";
 1575         }
 1576         $string = $evaluated_string;
 1577         $string = $envir{'imagegen'}->add($string);
 1578         $string;
 1579     } else {
 1580       EV3(@_);
 1581     }
 1582 }
 1583 
 1584 
 1585 =head2 Formatting macros
 1586 
 1587   beginproblem()  # generates text listing number and the point value of
 1588                   # the problem. It will also print the file name containing
 1589                   # the problem for users listed in the PRINT_FILE_NAMES_FOR PG_environment
 1590                   # variable.
 1591   OL(@array)      # formats the array as an Ordered List ( <OL> </OL> ) enumerated by letters.
 1592 
 1593   htmlLink($url, $text)
 1594                   # Places a reference to the URL with the specified text in the problem.
 1595                   # A common usage is \{ htmlLink(alias('prob1_help.html') \}, 'for help')
 1596                   # where alias finds the full address of the prob1_help.html file in the same directory
 1597                   # as the problem file
 1598   appletLink($url, $parameters)
 1599                   # For example
 1600                   # appletLink(q!  archive="http: //webwork.math.rochester.edu/gage/xFunctions/xFunctions.zip"
 1601                                   code="xFunctionsLauncher.class"  width=100 height=14!,
 1602                   " parameter text goes here")
 1603                   # will link to xFunctions.
 1604 
 1605   low level:
 1606 
 1607   spf($number, $format)   # prints the number with the given format
 1608   sspf($number, $format)  # prints the number with the given format, always including a sign.
 1609   nicestring($coefficients, $terms) # print a linear combinations of terms using coefficients
 1610   nicestring($coefficients) # uses the coefficients to make a polynomial
 1611       # For example
 1612       # nicestring([1,-2, 0]) produces 'x^2-2x'
 1613       # nicestring([2,0,-1],['', 't', 't^2']) produces '2-t^2'
 1614   protect_underbar($string) # protects the underbar (class_name) in strings which may have to pass through TeX.
 1615 
 1616 =cut
 1617 
 1618 sub beginproblem {
 1619   my $out = "";
 1620   my $problemValue = $envir->{problemValue};
 1621   my $fileName     = $envir->{fileName};
 1622   my $probNum      = $envir->{probNum};
 1623     my $TeXFileName = protect_underbar($envir->{fileName});
 1624     my $l2hFileName = protect_underbar($envir->{fileName});
 1625   my %inlist;
 1626   my $points ='pts';
 1627 
 1628   $points = 'pt' if $problemValue == 1;
 1629   ##    Prepare header for the problem
 1630   grep($inlist{$_}++,@{ $envir->{'PRINT_FILE_NAMES_FOR'} });
 1631   if ( defined($inlist{$envir->{studentLogin}}) and ($inlist{$envir->{studentLogin}} > 0) ) {
 1632     $out = &M3("\n\n\\medskip\\hrule\\smallskip\\par{\\bf ${probNum}.{\\footnotesize ($problemValue $points) $TeXFileName}}\\newline ",
 1633     " \\begin{rawhtml} ($problemValue $points) <B>$l2hFileName</B><BR>\\end{rawhtml}",
 1634      "($problemValue $points) <B>$fileName</B><BR>"
 1635        ) if ($problemValue ne "");
 1636   } else {
 1637     $out = &M3("\n\n\\smallskip\\hrule\\smallskip\\par{\\bf ${probNum}.}($problemValue $points) ",
 1638     "($problemValue $points) ",
 1639      "($problemValue $points) "
 1640        ) if ($problemValue ne "");
 1641   }
 1642   $out;
 1643 
 1644 }
 1645 
 1646 sub nicestring {
 1647     my($thingy) = shift;
 1648     my(@coefs) = @{$thingy};
 1649     my $n = scalar(@coefs);
 1650     $thingy = shift;
 1651     my(@others);
 1652     if(defined($thingy)) {
 1653   @others = @{$thingy};
 1654     } else {
 1655   my($j);
 1656   for $j (1..($n-2)) {
 1657       $others[$j-1] = "x^".($n-$j);
 1658   }
 1659   if($n>=2) { $others[$n-2] = "x";}
 1660   $others[$n-1] = "";
 1661     }
 1662     my($j, $k)=(0,0);
 1663     while(($k<$n) && ($coefs[$k]==0)) {$k++;}
 1664     if($k==$n) {return("0");}
 1665     my $ans;
 1666     if($coefs[$k]==1) {$ans = ($others[$k]) ? "$others[$k]" : "1";}
 1667     elsif($coefs[$k]== -1) {$ans =  ($others[$k]) ? "- $others[$k]" : "-1"}
 1668     else { $ans = "$coefs[$k] $others[$k]";}
 1669     $k++;
 1670     for $j ($k..($n-1)) {
 1671   if($coefs[$j] != 0) {
 1672       if($coefs[$j] == 1) {
 1673     $ans .= ($others[$j]) ? "+ $others[$j]" : "+ 1";
 1674       } elsif($coefs[$j] == -1) {
 1675     $ans .= ($others[$j]) ? "- $others[$j]" : "-1";
 1676       } else {
 1677     $ans .= "+ $coefs[$j] $others[$j]";
 1678       }
 1679   }
 1680     }
 1681     return($ans);
 1682 }
 1683 
 1684 # kludge to clean up path names
 1685             ## allow underscore character in set and section names and also allows line breaks at /
 1686 sub protect_underbar {
 1687     my $in = shift;
 1688     if ($displayMode eq 'TeX')  {
 1689 
 1690         $in =~ s|_|\\\_|g;
 1691         $in =~ s|/|\\\-/|g;  # allows an optional hyphenation of the path (in tex)
 1692     }
 1693     $in;
 1694 }
 1695 
 1696 
 1697 # An example of a macro which prints out a list (with letters)
 1698 sub OL {
 1699   my(@array) = @_;
 1700   my $i = 0;
 1701   my  $out=   &M3(
 1702           "\\begin{enumerate}\n",
 1703           " \\begin{rawhtml} <OL TYPE=\"A\" VALUE=\"1\"> \\end{rawhtml} ",
 1704           "<OL TYPE=\"A\" VALUE=\"1\">\n"
 1705           ) ;
 1706   my $elem;
 1707   foreach $elem (@array) {
 1708                 $out .= MODES(
 1709                         TeX=>   "\\item[$ALPHABET[$i].] $elem\n",
 1710                         Latex2HTML=>    " \\begin{rawhtml} <LI> \\end{rawhtml} $elem  ",
 1711                         HTML=>  "<LI> $elem\n",
 1712                         HTML_dpng=>     "<LI> $elem <br /> <br /> \n"
 1713                                         );
 1714     $i++;
 1715   }
 1716   $out .= &M3(
 1717         "\\end{enumerate}\n",
 1718         " \\begin{rawhtml} </OL>\n \\end{rawhtml} ",
 1719         "</OL>\n"
 1720         ) ;
 1721 }
 1722 
 1723 sub htmlLink {
 1724   my $url = shift;
 1725   my $text = shift;
 1726   my $options = shift;
 1727   $options = "" unless defined($options);
 1728   return "$BBOLD\[ broken link:  $text \] $EBOLD" unless defined($url);
 1729   M3( "{\\bf \\underline{$text}  }",
 1730       "\\begin{rawhtml} <A HREF=\"$url\" $options> $text </A>\\end{rawhtml}",
 1731       "<A HREF=\"$url\" $options> $text </A>"
 1732       );
 1733 }
 1734 
 1735 
 1736 sub helpLink {
 1737   my $type1 = shift;
 1738   return "" if(not defined($envir{'localHelpURL'}));
 1739   my $type = lc($type1);
 1740   my %typeHash = (
 1741     'interval notation' => 'IntervalNotation.html',
 1742     'units' => 'Units.html',
 1743     );
 1744 
 1745   my $infoRef = $typeHash{$type};
 1746   return htmlLink( $envir{'localHelpURL'}.$infoRef, $type1,
 1747 'target="ww_help" onclick="window.open(this.href,this.target,\'width=550,height=350,scrollbars=yes,resizable=on\'); return false;"');
 1748 }
 1749 
 1750 sub appletLink {
 1751   my $url = shift;
 1752   my $options = shift;
 1753   $options = "" unless defined($options);
 1754   M3( "{\\bf \\underline{APPLET}  }",
 1755       "\\begin{rawhtml} <APPLET $url> $options </APPLET>\\end{rawhtml}",
 1756       "<APPLET $url> $options </APPLET>"
 1757       );
 1758 }
 1759 sub spf {
 1760   my($number,$format) = @_;  # attention, the order of format and number are reversed
 1761   $format = "%4.3g" unless $format;   # default value for format
 1762   sprintf($format, $number);
 1763   }
 1764 sub sspf {
 1765   my($number,$format) = @_;  # attention, the order of format and number are reversed
 1766   $format = "%4.3g" unless $format;   # default value for format
 1767   my $sign = $number>=0 ? " + " : " - ";
 1768   $number = $number>=0 ? $number : -$number;
 1769   $sign .sprintf($format, $number);
 1770   }
 1771 
 1772 =head2  Sorting and other list macros
 1773 
 1774 
 1775 
 1776   Usage:
 1777   lex_sort(@list);   # outputs list in lexigraphic (alphabetical) order
 1778   num_sort(@list);   # outputs list in numerical order
 1779   uniq( @list);      # outputs a list with no duplicates.  Order is unspecified.
 1780 
 1781   PGsort( \&sort_subroutine, @list);
 1782   # &sort_subroutine defines order. It's output must be 1 or 0 (true or false)
 1783 
 1784 =cut
 1785 
 1786 #  uniq gives unique elements of a list:
 1787  sub uniq {
 1788    my (@in) =@_;
 1789    my %temp = ();
 1790    while (@in) {
 1791           $temp{shift(@in)}++;
 1792       }
 1793    my @out =  keys %temp;  # sort is causing trouble with Safe.??
 1794    @out;
 1795 }
 1796 
 1797 sub lex_sort {
 1798   PGsort sub {$_[0] lt $_[1]}, @_;
 1799 }
 1800 sub num_sort {
 1801   PGsort sub {$_[0] < $_[1]}, @_;
 1802 }
 1803 
 1804 
 1805 =head2 Macros for handling tables
 1806 
 1807   Usage:
 1808   begintable( number_of_columns_in_table)
 1809   row(@dataelements)
 1810   endtable()
 1811 
 1812 Example of useage:
 1813 
 1814   BEGIN_TEXT
 1815     This problem tests calculating new functions from old ones:$BR
 1816     From the table below calculate the quantities asked for:$BR
 1817     \{begintable(scalar(@firstrow)+1)\}
 1818     \{row(" \(x\) ",@firstrow)\}
 1819     \{row(" \(f(x)\) ", @secondrow)\}
 1820     \{row(" \(g(x)\) ", @thirdrow)\}
 1821     \{row(" \(f'(x)\) ", @fourthrow)\}
 1822     \{row(" \(g'(x)\) ", @fifthrow)\}
 1823     \{endtable()\}
 1824 
 1825    (The arrays contain numbers which are placed in the table.)
 1826 
 1827   END_TEXT
 1828 
 1829 =cut
 1830 
 1831 sub begintable {
 1832   my ($number)=shift;   #number of columns in table
 1833   my %options = @_;
 1834   warn "begintable(cols) requires a number indicating the number of columns" unless defined($number);
 1835   my $out = "";
 1836   if ($displayMode eq 'TeX') {
 1837     $out .= "\n\\par\\smallskip\\begin{center}\\begin{tabular}{"  .  "|c" x $number .  "|} \\hline\n";
 1838     }
 1839   elsif ($displayMode eq 'Latex2HTML') {
 1840     $out .= "\n\\begin{rawhtml} <TABLE , BORDER=1>\n\\end{rawhtml}";
 1841     }
 1842   elsif ($displayMode eq 'HTML' || $displayMode eq 'HTML_tth' || $displayMode eq 'HTML_dpng' || $displayMode eq 'HTML_img' || $displayMode eq 'HTML_jsMath') {
 1843     $out .= "<TABLE BORDER=1>\n"
 1844   }
 1845   else {
 1846     $out = "Error: PGbasicmacros: begintable: Unknown displayMode: $displayMode.\n";
 1847     }
 1848   $out;
 1849   }
 1850 
 1851 sub endtable {
 1852   my $out = "";
 1853   if ($displayMode eq 'TeX') {
 1854     $out .= "\n\\end {tabular}\\end{center}\\par\\smallskip\n";
 1855     }
 1856   elsif ($displayMode eq 'Latex2HTML') {
 1857     $out .= "\n\\begin{rawhtml} </TABLE >\n\\end{rawhtml}";
 1858     }
 1859   elsif ($displayMode eq 'HTML' || $displayMode eq 'HTML_tth' || $displayMode eq 'HTML_dpng' ||$displayMode eq 'HTML_img' || $displayMode eq 'HTML_jsMath') {
 1860     $out .= "</TABLE>\n";
 1861     }
 1862   else {
 1863     $out = "Error: PGbasicmacros: endtable: Unknown displayMode: $displayMode.\n";
 1864     }
 1865   $out;
 1866   }
 1867 
 1868 
 1869 sub row {
 1870   my @elements = @_;
 1871   my $out = "";
 1872   if ($displayMode eq 'TeX') {
 1873     while (@elements) {
 1874       $out .= shift(@elements) . " &";
 1875       }
 1876      chop($out); # remove last &
 1877      $out .= "\\\\ \\hline \n";
 1878      # carriage returns must be added manually for tex
 1879     }
 1880   elsif ($displayMode eq 'Latex2HTML') {
 1881     $out .= "\n\\begin{rawhtml}\n<TR>\n\\end{rawhtml}\n";
 1882     while (@elements) {
 1883       $out .= " \n\\begin{rawhtml}\n<TD> \n\\end{rawhtml}\n" . shift(@elements) . " \n\\begin{rawhtml}\n</TD> \n\\end{rawhtml}\n";
 1884       }
 1885     $out .= " \n\\begin{rawhtml}\n</TR> \n\\end{rawhtml}\n";
 1886   }
 1887   elsif ($displayMode eq 'HTML' || $displayMode eq 'HTML_tth' || $displayMode eq 'HTML_dpng'||$displayMode eq 'HTML_img' || $displayMode eq 'HTML_jsMath') {
 1888     $out .= "<TR>\n";
 1889     while (@elements) {
 1890       $out .= "<TD>" . shift(@elements) . "</TD>";
 1891       }
 1892     $out .= "\n</TR>\n";
 1893   }
 1894   else {
 1895     $out = "Error: PGbasicmacros: row: Unknown displayMode: $displayMode.\n";
 1896     }
 1897   $out;
 1898 }
 1899 
 1900 =head2 Macros for displaying static images
 1901 
 1902   Usage:
 1903   $string = image($image, width => 100, height => 100, tex_size => 800)
 1904   $string = image([$image1, $image2], width => 100, height => 100, tex_size => 800)
 1905   $string = caption($string);
 1906   $string = imageRow([$image1, $image2 ], [$caption1, $caption2]);
 1907            # produces a complete table with rows of pictures.
 1908 
 1909 
 1910 =cut
 1911 
 1912 #   More advanced macros
 1913 sub image {
 1914   my $image_ref  = shift;
 1915   my @opt = @_;
 1916   unless (scalar(@opt) % 2 == 0 ) {
 1917     warn "ERROR in image macro.  A list of macros must be inclosed in square brackets.";
 1918   }
 1919   my %in_options = @opt;
 1920   my %known_options = (
 1921     width    => 100,
 1922     height   => 100,
 1923     tex_size => 800,
 1924   );
 1925   # handle options
 1926   my %out_options = %known_options;
 1927   foreach my $opt_name (keys %in_options) {
 1928     if ( exists( $known_options{$opt_name} ) ) {
 1929       $out_options{$opt_name} = $in_options{$opt_name} if exists( $in_options{$opt_name} ) ;
 1930     } else {
 1931       die "Option $opt_name not defined for image. " .
 1932           "Default options are:<BR> ", display_options2(%known_options);
 1933     }
 1934   }
 1935   my $width       = $out_options{width};
 1936   my $height      = $out_options{height};
 1937   my $tex_size    = $out_options{tex_size};
 1938   my $width_ratio = $tex_size*(.001);
 1939   my @image_list  = ();
 1940 
 1941   if (ref($image_ref) =~ /ARRAY/ ) {
 1942     @image_list = @{$image_ref};
 1943   } else {
 1944     push(@image_list,$image_ref);
 1945   }
 1946 
 1947   my @output_list = ();
 1948     while(@image_list) {
 1949     my $imageURL = alias(shift @image_list);
 1950     my $out="";
 1951 
 1952     if ($displayMode eq 'TeX') {
 1953       my $imagePath = $imageURL; # in TeX mode, alias gives us a path, not a URL
 1954       if (defined $envir->{texDisposition} and $envir->{texDisposition} eq "pdf") {
 1955         # We're going to create PDF files with our TeX (using pdflatex), so
 1956         # alias should have given us the path to a PNG image. What we need
 1957         # to do is find out the dimmensions of this image, since pdflatex
 1958         # is too dumb to live.
 1959 
 1960         #my ($height, $width) = getImageDimmensions($imagePath);
 1961         ##warn "&image: $imagePath $height $width\n";
 1962         #unless ($height and $width) {
 1963         # warn "Couldn't get the dimmensions of image $imagePath.\n"
 1964         #}
 1965         #$out = "\\includegraphics[bb=0 0 $height $width,width=$width_ratio\\linewidth]{$imagePath}\n";
 1966         $out = "\\includegraphics[width=$width_ratio\\linewidth]{$imagePath}\n";
 1967       } else {
 1968         # Since we're not creating PDF files, alias should have given us the
 1969         # path to an EPS file. latex can get its dimmensions no problem!
 1970 
 1971         $out = "\\includegraphics[width=$width_ratio\\linewidth]{$imagePath}\n";
 1972       }
 1973     } elsif ($displayMode eq 'Latex2HTML') {
 1974       $out = qq!\\begin{rawhtml}\n<A HREF= "$imageURL" TARGET="ZOOM"><IMG SRC="$imageURL"  WIDTH="$width" HEIGHT="$height"></A>\n
 1975       \\end{rawhtml}\n !
 1976     } elsif ($displayMode eq 'HTML' || $displayMode eq 'HTML_tth' || $displayMode eq 'HTML_dpng' || $displayMode eq 'HTML_img' || $displayMode eq 'HTML_jsMath') {
 1977       $out = qq!<A HREF= "$imageURL" TARGET="ZOOM"><IMG SRC="$imageURL"  WIDTH="$width" HEIGHT="$height"></A>
 1978       !
 1979     } else {
 1980       $out = "Error: PGbasicmacros: image: Unknown displayMode: $displayMode.\n";
 1981     }
 1982     push(@output_list, $out);
 1983   }
 1984   return wantarray ? @output_list : $output_list[0];
 1985 }
 1986 
 1987 # This is legacy code.
 1988 sub images {
 1989   my @in = @_;
 1990   my @outlist = ();
 1991   while (@in) {
 1992      push(@outlist,&image( shift(@in) ) );
 1993    }
 1994   @outlist;
 1995 }
 1996 
 1997 
 1998 sub caption {
 1999   my ($out) = @_;
 2000   $out = " $out \n" if $displayMode eq 'TeX';
 2001   $out = " $out  " if $displayMode eq 'HTML';
 2002   $out = " $out  " if $displayMode eq 'HTML_tth';
 2003   $out = " $out  " if $displayMode eq 'HTML_dpng';
 2004   $out = " $out  " if $displayMode eq 'HTML_img';
 2005   $out = " $out  " if $displayMode eq 'HTML_jsMath';
 2006   $out = " $out  " if $displayMode eq 'Latex2HTML';
 2007     $out;
 2008 }
 2009 
 2010 sub captions {
 2011   my @in = @_;
 2012   my @outlist = ();
 2013   while (@in) {
 2014      push(@outlist,&caption( shift(@in) ) );
 2015   }
 2016   @outlist;
 2017 }
 2018 
 2019 sub imageRow {
 2020 
 2021   my $pImages = shift;
 2022   my $pCaptions=shift;
 2023   my $out = "";
 2024   my @images = @$pImages;
 2025   my @captions = @$pCaptions;
 2026   my $number = @images;
 2027   # standard options
 2028   my %options = ( 'tex_size' => 200,  # width for fitting 4 across
 2029                   'height' => 100,
 2030                   'width' => 100,
 2031                   @_            # overwrite any default options
 2032                 );
 2033 
 2034   if ($displayMode eq 'TeX') {
 2035     $out .= "\n\\par\\smallskip\\begin{center}\\begin{tabular}{"  .  "|c" x $number .  "|} \\hline\n";
 2036     while (@images) {
 2037       $out .= &image( shift(@images),%options ) . '&';
 2038     }
 2039     chop($out);
 2040     $out .= "\\\\ \\hline \n";
 2041     while (@captions) {
 2042       $out .= &caption( shift(@captions) ) . '&';
 2043     }
 2044     chop($out);
 2045     $out .= "\\\\ \\hline \n\\end {tabular}\\end{center}\\par\\smallskip\n";
 2046   } elsif ($displayMode eq 'Latex2HTML'){
 2047 
 2048     $out .= "\n\\begin{rawhtml} <TABLE  BORDER=1><TR>\n\\end{rawhtml}\n";
 2049     while (@images) {
 2050       $out .= "\n\\begin{rawhtml} <TD>\n\\end{rawhtml}\n" . &image( shift(@images),%options )
 2051               . "\n\\begin{rawhtml} </TD>\n\\end{rawhtml}\n" ;
 2052     }
 2053 
 2054     $out .= "\n\\begin{rawhtml}</TR><TR>\\end{rawhtml}\n";
 2055     while (@captions) {
 2056       $out .= "\n\\begin{rawhtml} <TH>\n\\end{rawhtml}\n".&caption( shift(@captions) )
 2057               . "\n\\begin{rawhtml} </TH>\n\\end{rawhtml}\n" ;
 2058     }
 2059 
 2060     $out .= "\n\\begin{rawhtml} </TR> </TABLE >\n\\end{rawhtml}";
 2061   } elsif ($displayMode eq 'HTML' || $displayMode eq 'HTML_tth' || $displayMode eq 'HTML_dpng'|| $displayMode eq 'HTML_img' || $displayMode eq 'HTML_jsMath'){
 2062     $out .= "<P>\n <TABLE BORDER=2 CELLPADDING=3 CELLSPACING=2 ><TR ALIGN=CENTER    VALIGN=MIDDLE>\n";
 2063     while (@images) {
 2064       $out .= " \n<TD>". &image( shift(@images),%options ) ."</TD>";
 2065     }
 2066     $out .= "</TR>\n<TR>";
 2067     while (@captions) {
 2068       $out .= " <TH>". &caption( shift(@captions) ) ."</TH>";
 2069     }
 2070     $out .= "\n</TR></TABLE></P>\n"
 2071   }
 2072   else {
 2073     $out = "Error: PGbasicmacros: imageRow: Unknown languageMode: $displayMode.\n";
 2074     warn $out;
 2075   }
 2076   $out;
 2077 }
 2078 
 2079 
 2080 ###########
 2081 # Auxiliary macros
 2082 
 2083 sub display_options2{
 2084   my %options = @_;
 2085   my $out_string = "";
 2086   foreach my $key (keys %options) {
 2087     $out_string .= " $key => $options{$key},<BR>";
 2088   }
 2089   $out_string;
 2090 }
 2091 
 2092 
 2093 1;

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9