summaryrefslogtreecommitdiff
path: root/Master/texmf-dist/scripts
diff options
context:
space:
mode:
authorKarl Berry <karl@freefriends.org>2019-03-16 22:43:33 +0000
committerKarl Berry <karl@freefriends.org>2019-03-16 22:43:33 +0000
commit7e80fa208736f4ab99b1d57dd1571da41f1e3744 (patch)
tree606bd82a5737d587ef239fd58a5a58c256666178 /Master/texmf-dist/scripts
parent9de7d0ea371387f647487812b48b51030c739bdf (diff)
webquiz
git-svn-id: svn://tug.org/texlive/trunk@50419 c570f23f-e606-0410-a88d-b1316a301751
Diffstat (limited to 'Master/texmf-dist/scripts')
-rwxr-xr-xMaster/texmf-dist/scripts/webquiz/CHANGES.rst92
-rwxr-xr-xMaster/texmf-dist/scripts/webquiz/LICENCE226
-rwxr-xr-xMaster/texmf-dist/scripts/webquiz/README-scripts16
l---------Master/texmf-dist/scripts/webquiz/webquiz1
-rwxr-xr-xMaster/texmf-dist/scripts/webquiz/webquiz.bat14
-rwxr-xr-xMaster/texmf-dist/scripts/webquiz/webquiz.py1095
-rwxr-xr-xMaster/texmf-dist/scripts/webquiz/webquiz_layout.py73
-rwxr-xr-xMaster/texmf-dist/scripts/webquiz/webquiz_makequiz.py550
-rwxr-xr-xMaster/texmf-dist/scripts/webquiz/webquiz_templates.py391
-rwxr-xr-xMaster/texmf-dist/scripts/webquiz/webquiz_util.py128
-rwxr-xr-xMaster/texmf-dist/scripts/webquiz/webquiz_xml.py386
11 files changed, 2972 insertions, 0 deletions
diff --git a/Master/texmf-dist/scripts/webquiz/CHANGES.rst b/Master/texmf-dist/scripts/webquiz/CHANGES.rst
new file mode 100755
index 00000000000..e29b7e5cfb2
--- /dev/null
+++ b/Master/texmf-dist/scripts/webquiz/CHANGES.rst
@@ -0,0 +1,92 @@
+===============
+WebQuiz Changes
+===============
+
+Version 5.1:
+------------
+ - code reorganised n zip file for TeXLive inclusion
+ - \dref, \qref and \Qref commands
+ - error and debugging code reorganised
+ - javascript session history following Hendrik Suess
+ - unix man page
+
+Version 5.0:
+------------
+ - added button for hiding/showing question buttons
+ - added colour theme support
+ - added language support
+ - added support for colour and listings in the quiz files
+ - added lualatex and xelatex engine support
+ - added displayasimage
+ - added more comparison options for inputted answers
+ - all files converted to utf8 using codecs
+ - bash script wrapper replaced with python, using argparser, making it more portable and more flexible
+ - better installation support
+ - changed name from mathquiz to webquiz
+ - drop-down menu for quiz index file
+ - export to ctan in setup.py
+ - images for buttons etc replaced by css
+ - implemented a suggestion of Michal Hoftich to workaround tikz/pgf bugs
+ - implemented a suggestion to Herbert Voss to fix a pstricks issue using pst2pdf
+ - made compatible with setup tools, together with option to export to ctan
+ - many more document class options
+ - new (off-line) manual with automatically generated images via makeimages script
+ - now using make4ht
+ - option for pst2pdf preprocessing for quizzes using pstricks/postscript
+ - option for tikz that fixes a few bugs of pgf/tikz
+ - program packaged for uploading to ctan and texlive
+ - programmable breadcrumbs
+ - python and javascript streamlined and largely rewritten
+ - randomorder and onepage options added
+ - replaced Choice environment with smarter choice environment
+ - rewrote xml parser
+ - side menu and breadcrumbs automatically disappear on small screens
+ - system webquizrc configuration file added wiith optional user .webquizrc file
+ - thechoice controls the labels for multiple choice options
+ - updated to use html5, mathjax and mathml
+ - using git and bitbucket for version management control
+ - using pgfkeys for processing document class and environment options
+ - using sass to generate css for different themes
+ - various webquiz defaults can be stored in the rc-file
+ - windows batch file
+
+Version 4.6:
+------------
+ - Updated to use MathML
+
+Version 4.5:
+------------
+ - Updated and streamlined many aspects of the code
+
+Version 4.0:
+------------
+ - separated allowed default and localised versions for the quiz page payout
+ with the SMS versiion calling Bob Howlett's update programs to generate
+ the quiz web pages
+
+Version 3:
+----------
+ - code taken over by Andrew Mathas
+ - latex class file, mathquiz.cls, written and integrated with tex4ht code
+ - documentation written
+ - SMS quizzes converted to mathquiz format
+
+Versions 1 and 2:
+-----------------
+2001-03-21 Don Taylor - initial prototype by Don Taylor
+
+
+To do
+-----
+Rather than a to-do list, here are some possible future improvements:
+ - (?) improve quiz "security" (would be a side-effect of moving to vue...)
+ - (?) randomise order of questions parts with document-class option randomorder
+ - (?) allow variables in questions (hardest part is finding a good syntax)
+ - (?) rewrite javascript to use vue to render and control quiz pages
+ - (?) allow vertical/horizontal/none customisations of question buttons
+ - (?) record marks of students...would need a interface for login details etc
+ - (?) add timer and/or time limits to quiz
+ - (?) responsive columns to replace columns=? in choice environments
+ - (?) dynamic themes (easy)
+ - (?) dynamic languages (harder)
+
diff --git a/Master/texmf-dist/scripts/webquiz/LICENCE b/Master/texmf-dist/scripts/webquiz/LICENCE
new file mode 100755
index 00000000000..b83b60f8687
--- /dev/null
+++ b/Master/texmf-dist/scripts/webquiz/LICENCE
@@ -0,0 +1,226 @@
+
+GNU GENERAL PUBLIC LICENSE
+
+Version 3, 29 June 2007
+
+Copyright © 2007 Free Software Foundation, Inc. <http://fsf.org/>
+
+Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
+Preamble
+
+The GNU General Public License is a free, copyleft license for software and other kinds of works.
+
+The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.
+
+When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
+
+To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.
+
+For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
+
+Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.
+
+For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.
+
+Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.
+
+Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.
+
+The precise terms and conditions for copying, distribution and modification follow.
+TERMS AND CONDITIONS
+0. Definitions.
+
+“This License” refers to version 3 of the GNU General Public License.
+
+“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
+
+“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations.
+
+To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work.
+
+A “covered work” means either the unmodified Program or a work based on the Program.
+
+To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
+
+To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
+
+An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
+1. Source Code.
+
+The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work.
+
+A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
+
+The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
+
+The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
+
+The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
+
+The Corresponding Source for a work in source code form is that same work.
+2. Basic Permissions.
+
+All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
+
+You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
+
+Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
+3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
+
+When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
+4. Conveying Verbatim Copies.
+
+You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
+
+You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
+5. Conveying Modified Source Versions.
+
+You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
+ b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”.
+ c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
+ d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
+
+A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
+6. Conveying Non-Source Forms.
+
+You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
+ b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
+ c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
+ d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
+ e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
+
+A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
+
+A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
+
+“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
+
+If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
+
+The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
+
+Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
+7. Additional Terms.
+
+“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
+
+When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
+
+Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
+ b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
+ c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
+ d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
+ e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
+ f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
+
+All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
+
+If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
+
+Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
+8. Termination.
+
+You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
+
+However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
+
+Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
+
+Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
+9. Acceptance Not Required for Having Copies.
+
+You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
+10. Automatic Licensing of Downstream Recipients.
+
+Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
+
+An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
+
+You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
+11. Patents.
+
+A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”.
+
+A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
+
+Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
+
+In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
+
+If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
+
+If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
+
+A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
+
+Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
+12. No Surrender of Others' Freedom.
+
+If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
+13. Use with the GNU Affero General Public License.
+
+Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.
+14. Revised Versions of this License.
+
+The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.
+
+If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
+
+Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
+15. Disclaimer of Warranty.
+
+THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+16. Limitation of Liability.
+
+IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
+17. Interpretation of Sections 15 and 16.
+
+If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
+
+END OF TERMS AND CONDITIONS
+How to Apply These Terms to Your New Programs
+
+If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
+
+To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:
+
+ <program> Copyright (C) <year> <name of author>
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”.
+
+You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <http://www.gnu.org/licenses/>.
+
+The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <http://www.gnu.org/philosophy/why-not-lgpl.html>.
diff --git a/Master/texmf-dist/scripts/webquiz/README-scripts b/Master/texmf-dist/scripts/webquiz/README-scripts
new file mode 100755
index 00000000000..8199d0ccc37
--- /dev/null
+++ b/Master/texmf-dist/scripts/webquiz/README-scripts
@@ -0,0 +1,16 @@
+The WebQuiz executable is webquiz.py. On unix-like systems it is enough to
+create a soft link to this file using something like:
+ ln -s $(pwd)/webquiz.py /usr/local/bin/webquiz
+
+The batch file webquiz.bat comes from
+ https://tex.stackexchange.com/questions/40937/how-to-publish-a-package-that-includes-scripts-and-or-executables/40971
+
+The files in this directory are:
+ - webquiz.py* = processes command-line options and settings
+ - webquiz_layout.py = determines the final layout of the web pages
+ - webquiz_makequiz.py = converts the XML into HTML
+ - webquiz_templates.py = template strings for HTML and
+ - webquiz_util.py = utility functions
+ - webquiz_xml.py = read and interpret the webquiz XML file
+ - CHANGES.rst = list of changes to program
+ - LICENCE = copy of the GPL licence
diff --git a/Master/texmf-dist/scripts/webquiz/webquiz b/Master/texmf-dist/scripts/webquiz/webquiz
new file mode 120000
index 00000000000..8d8dccbc1db
--- /dev/null
+++ b/Master/texmf-dist/scripts/webquiz/webquiz
@@ -0,0 +1 @@
+webquiz.py \ No newline at end of file
diff --git a/Master/texmf-dist/scripts/webquiz/webquiz.bat b/Master/texmf-dist/scripts/webquiz/webquiz.bat
new file mode 100755
index 00000000000..c92a60d3a29
--- /dev/null
+++ b/Master/texmf-dist/scripts/webquiz/webquiz.bat
@@ -0,0 +1,14 @@
+@echo off
+setlocal enableextensions
+rem assuming the main script is in the same directory
+if not exist "%~dpn0.py" (
+ echo %~nx0: main script "%~dpn0.py" not found>&2
+ exit /b 1
+)
+rem check if interpreter is on the PATH
+for %%I in (python.exe) do set "PYTHONEXE=%%~$PATH:I"
+if not defined PYTHONEXE (
+ echo %~nx0: Python interpreter not installed or not on the PATH>&2
+ exit /b 1
+)
+"%PYTHONEXE%" "%~dpn0.py" %*
diff --git a/Master/texmf-dist/scripts/webquiz/webquiz.py b/Master/texmf-dist/scripts/webquiz/webquiz.py
new file mode 100755
index 00000000000..283f21d1321
--- /dev/null
+++ b/Master/texmf-dist/scripts/webquiz/webquiz.py
@@ -0,0 +1,1095 @@
+#!/usr/bin/env python3
+r'''
+------------------------------------------------------------------------------
+ webquiz | Online quizzes generated from LaTeX using python and TeX4ht
+ | This module mainly deals with command-line options and
+ | settings and then calls MakeWebQuiz to build the quiz
+------------------------------------------------------------------------------
+ Copyright (C) Andrew Mathas and Donald Taylor, University of Sydney
+
+ Distributed under the terms of the GNU General Public License (GPL)
+ http://www.gnu.org/licenses/
+
+ This file is part of the WebQuiz system.
+
+ <Andrew.Mathas@sydney.edu.au>
+------------------------------------------------------------------------------
+'''
+
+import argparse
+import codecs
+import errno
+import glob
+import os
+import re
+import shutil
+import signal
+import subprocess
+import sys
+
+# imports of webquiz code
+import webquiz_makequiz
+import webquiz_templates
+import webquiz_util
+
+#################################################################################
+# read in basic meta data such as author, version, ... and set debugging=False
+try:
+ metadata = webquiz_util.MetaData(webquiz_util.kpsewhich('webquiz.ini'), debugging=False)
+except subprocess.CalledProcessError:
+ # check to see if we are running from the zip file
+ ini_file = os.path.join(webquiz_util.webquiz_file(''), '..', 'latex', 'webquiz.ini')
+ try:
+ metadata = webquiz_util.MetaData(ini_file, debugging=False)
+ except (FileNotFoundError, subprocess.CalledProcessError):
+ print('webquiz installation error: unable to find webquiz.ini -> {}'.format(ini_file))
+ sys.exit(1)
+
+# ---------------------------------------------------------------------------------------
+def graceful_exit(sig, frame):
+ ''' exit gracefully on SIGINT and SIGTERM'''
+ if metadata:
+ webquiz_util.webquiz_error(False, 'program terminated (signal {}\n {})'.format(sig, frame))
+ else:
+ webquiz_util.webquiz_error(False, 'program terminated (signal {})'.format(sig))
+
+signal.signal(signal.SIGINT, graceful_exit)
+signal.signal(signal.SIGTERM, graceful_exit)
+
+
+#################################################################################
+def preprocess_with_pst2pdf(options, quiz_file):
+ r'''
+ Preprocess the latex file using pst2pdf. As we are preprocessing the file it
+ is not enough to have latex pass us a flag that tells us to use pst2pdf.
+ Instead, we have to extract the class file option from the tex file
+
+ INPUT: quiz_file should be the name of the quiz file, WITHOUT the .tex extension
+ '''
+ options.talk('Preprocessing {} with pst2pdsf'.format(quiz_file))
+ try:
+ # pst2pdf converts pspicture environments to svg images and makes a
+ # new latex file quiz_file+'-pdf' that includes these
+ cmd = 'pst2pdf --svg --imgdir={q_file} {q_file}.tex'.format(q_file=quiz_file)
+ options.run(cmd)
+ except OSError as err:
+ if err.errno == errno.ENOENT:
+ webquiz_util.webquiz_error(options.debugging, 'pst2pdf not found. You need to install pst2pdf to use the pst2pdf option', err)
+ else:
+ webquiz_util.webquiz_error(options.debugging, 'error running pst2pdf on {}'.format(quiz_file), err)
+
+ # match \includegraphics commands
+ fix_svg = re.compile(r'(\\includegraphics\[scale=1\])\{('+quiz_file+r'-fig-[0-9]*)\}')
+ # the svg images are in the quiz_file subdirectory but latex can't
+ # find them so we update the tex file to look in the right place
+ try:
+ with codecs.open(quiz_file + '-pdf.tex', 'r', encoding='utf8') as pst_file:
+ with codecs.open(quiz_file + '-pdf-fixed.tex', 'w', encoding='utf8') as pst_fixed:
+ for line in pst_file:
+ pst_fixed.write(fix_svg.sub(r'\1{%s/\2.svg}' % quiz_file, line))
+ except OSError as err:
+ webquiz_util.webquiz_error(options.debugging,
+ 'there was an problem running pst2pdf for {}'.format(quiz_file),
+ err
+ )
+
+class WebQuizSettings:
+ r'''
+ Class for initialising webquiz. This covers both reading and writing the
+ webquizrc file and copying files into the web directories during
+ initialisation. The settings themselves are stored in the attribute
+ settings, which is a dictionary. The class reads and writes the settings to
+ the webquizrc file and the values of the settings are available as items:
+ >>> wq = WebQuizSettings()
+ >>> wq['webquiz_url']
+ ... /WebQuiz
+ >>> wq['webquiz_url'] = '/new_url'
+ '''
+
+ # default of settings for the webquizrc file - a dictionary of dictionaries
+ # the 'help' field is for printing descriptions of the settings to help the
+ # user - they are also printed in the webquizrc file
+ settings = dict(
+ webquiz_url={
+ 'default': '',
+ 'advanced': False,
+ 'help': 'Relative URL for the webquiz web directory',
+ },
+ webquiz_www={
+ 'default': '',
+ 'advanced': False,
+ 'help': 'Full path to WebQuiz web directory',
+ },
+ language={
+ 'default': 'english',
+ 'advanced': False,
+ 'help': 'Default language used on web pages'
+ },
+ engine = {
+ 'default': 'latex',
+ 'advanced': False,
+ 'help': 'Default TeX engine used to compile web pages',
+ 'values': dict(latex='', lua='--lua', xelatex='--xetex')
+ },
+ theme={
+ 'default': 'default',
+ 'advanced': False,
+ 'help': 'Default colour theme used on web pages'
+ },
+ breadcrumbs={
+ 'default': '',
+ 'advanced': False,
+ 'help': 'Breadcrumbs at the top of quiz page',
+ },
+ department={
+ 'default': '',
+ 'advanced': False,
+ 'help': 'Name of department',
+ },
+ department_url={
+ 'default': '/',
+ 'advanced': False,
+ 'help': 'URL for department',
+ },
+ institution={
+ 'default': '',
+ 'advanced': False,
+ 'help': 'Institution or university',
+ },
+ institution_url={
+ 'default': '/',
+ 'advanced': False,
+ 'help': 'URL for institution or university',
+ },
+ hide_side_menu={
+ 'default': 'false',
+ 'advanced': False,
+ 'help': 'Do not display the side menu at start of quiz',
+ },
+ one_page={
+ 'default': 'false',
+ 'advanced': False,
+ 'help': 'Display questions on one page',
+ },
+ random_order={
+ 'default': 'false',
+ 'advanced': False,
+ 'help': 'Randomly order the quiz questions',
+ },
+ webquiz_layout={
+ 'default': 'webquiz_layout',
+ 'advanced': True,
+ 'help': 'Name of python module that formats the quizzes',
+ },
+ make4ht={
+ 'default': '',
+ 'advanced': True,
+ 'help': 'Build file for make4ht',
+ },
+ mathjax={
+ 'default':
+ 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js',
+ 'advanced':
+ True,
+ 'help':
+ 'URL for mathjax',
+ },
+ version={
+ 'advanced': False,
+ 'help': 'WebQuiz version number for webquizrc settings',
+ })
+
+ # by default we assume we don't need to print a initialisation warning
+ initialise_warning = ''
+
+ # turn debugging on by default because any error message that we hit before
+ # we process the command line options really should not happen
+ debugging = True
+
+ # keep track of whether we have initialised
+ have_initialised = False
+
+ def __init__(self):
+ '''
+ First read the system webquizrc file and then read the
+ to use some system settings and to override others.
+
+ By default, there is no webquiz initialisation file. We first
+ look for webquizrc in the webquiz source directory and then
+ for .webquizrc file in the users home directory.
+ '''
+ self.settings['version']['default'] = metadata.version
+ for key in self.settings:
+ self.settings[key]['value'] = self.settings[key]['default']
+ if not 'editable' in self.settings[key]:
+ self.settings[key]['editable'] = False
+
+ # define user and system rc file and load the ones that exist
+
+ self.system_rcfile = os.path.join(webquiz_util.kpsewhich('-var TEXMFLOCAL'),
+ 'tex',
+ 'latex',
+ 'webquiz',
+ 'webquizrc'
+ )
+ self.read_webquizrc(self.system_rcfile)
+
+ # the user rc file defaults to:
+ # ~/.dotfiles/config/webquizrc if .dotfiles/config exists
+ # ~/.config/webquizrc if .config exists
+ # and otherwise to ~/.webquizrc
+ if os.path.isdir(os.path.join(os.path.expanduser('~'), '.dotfiles', 'config')):
+ self.user_rcfile = os.path.join(os.path.expanduser('~'), '.dotfiles', 'config', 'webquizrc')
+ elif os.path.isdir(os.path.join(os.path.expanduser('~'), '.config')):
+ self.user_rcfile = os.path.join(os.path.expanduser('~'), '.config', 'webquizrc')
+ else:
+ self.user_rcfile = os.path.join(os.path.expanduser('~'), '.webquizrc')
+
+ self.read_webquizrc(self.user_rcfile)
+
+ def webquiz_debug(self, msg):
+ r'''
+ Customised debugging message for the MakeSettings module
+ '''
+ webquiz_util.webquiz_debug(self.debugging, 'main: '+msg)
+
+ def webquiz_error(self, msg, err=None):
+ r'''
+ Customised error messages for the Module
+ '''
+ webquiz_util.webquiz_error(self.debugging, 'settings: '+msg, err)
+
+ def __getitem__(self, key):
+ r'''
+ Return the value of the corresponding setting. That is, it returns
+ self.settings[key]['value']
+ and an error if the key is unknown.
+ '''
+ if key in self.settings:
+ return self.settings[key]['value']
+
+ self.webquiz_error('getitem: unknown setting "{}" in webquizrc.'.format(key))
+
+ def __setitem__(self, key, value):
+ r'''
+ Set the value of the corresponding setting. This is the equivalent of
+ self.settings[key]['value'] = value
+ and an error if the key is unknown.
+ '''
+ if key in self.settings:
+ self.settings[key]['value'] = value
+ else:
+ self.webquiz_error('setitem: unknown setting "{}" in webquizrc'.format(key))
+
+ def read_webquizrc(self, rcfile, must_exist=False):
+ r'''
+ Read the settings from the specified webquizrc file - if it exists, in
+ which case set self.rcfile equal to this directory. If the file does
+ not exist then return without changing the current settings.
+ '''
+ if os.path.isfile(rcfile):
+ try:
+ with codecs.open(rcfile, 'r', encoding='utf8') as webquizrc:
+ for line in webquizrc:
+ if '#' in line: # remove comments
+ line = line[:line.index('#')]
+ if '=' in line:
+ key, value = line.split('=')
+ key = key.strip().lower().replace('-','_')
+ value = value.strip()
+ if key in self.settings:
+ if value != self[key]:
+ self[key] = value
+ elif key != '':
+ self.webquiz_error('unknown setting "{}" in {}'.format(key, rcfile))
+
+ # record the rcfile for later use
+ self.rcfile = rcfile
+
+ except OSError as err:
+ self.webquiz_error('there was a problem reading the rc-file {}'.format(rcfile), err)
+
+ except Exception as err:
+ self.webquiz_error('there was an error reading the webquizrc file,', err)
+
+ elif must_exist:
+ # this is only an error if we have been asked to read this file
+ self.webquiz_error('the rc-file "{}" does not exist'.format(rcfile))
+
+ def keys(self):
+ r'''
+ Return a list of keys for all settings, ordered alphabetically with the
+ advanced options last/
+ '''
+ return sorted(self.settings.keys(), key=lambda k: '{}{}'.format(self.settings[k]['advanced'], k))
+
+ def write_webquizrc(self):
+ r'''
+ Write the settings to the webquizrc file, defaulting to the user
+ rcfile if unable to write to the system rcfile
+ '''
+ if not hasattr(self, 'rcfile'):
+ # when initialising an rcfile will not exist yet
+ self.rcfile = self.system_rcfile
+
+ file_not_written = True
+ while file_not_written:
+ try:
+ dire = os.path.dirname(self.rcfile)
+ if dire != '' and not os.path.isdir(dire):
+ os.makedirs(dire, exist_ok=True)
+ with codecs.open(self.rcfile, 'w', encoding='utf8') as rcfile:
+ for key in self.keys():
+ # Only save settings in the rcfile if they have changed
+ # Note that changed means changed from the last read
+ # rcfile rather than from the default (of course, the
+ # defaults serve as the "initial rcfile")
+ if key == 'version' or self.settings[key]['default']!=self[key]:
+ rcfile.write('# {}\n{:<17} = {}\n'.format(
+ self.settings[key]['help'],
+ key.replace('_','-'),
+ self[key])
+ )
+
+ print('\nWebQuiz settings saved in {}\n'.format( self.rcfile))
+ input('Press RETURN to continue... ')
+ file_not_written = False
+
+ except (OSError, PermissionError) as err:
+ # if writing to the system_rcfile then try to write to user_rcfile
+ alt_rcfile = self.user_rcfile if self.rcfile != self.user_rcfile else self.system_rcfile
+ response = input(
+ webquiz_templates.rc_permission_error.format(
+ error=err,
+ rcfile=self.rcfile,
+ alt_rcfile=alt_rcfile))
+ if response.startswith('2'):
+ self.rcfile = alt_rcfile
+ elif response.startswith('3'):
+ rcfile = input('WebQuiz rc-file: ')
+ print('\nTo access this rc-file you will need to use: webquiz --rcfile {} ...'.format(rcfile))
+ self.rcfile = os.path.expanduser(rcfile)
+ elif not response.startswith('1'):
+ print('exiting...')
+ sys.exit(1)
+
+ def list_settings(self, setting='all'):
+ r'''
+ Print the non-default settings for webquiz from the webquizrc
+ '''
+ if not hasattr(self, 'rcfile'):
+ print(
+ 'Please initialise WebQuiz using the command: webquiz --initialise\n'
+ )
+
+ if setting not in ['all', 'verbose', 'help']:
+ setting = setting.replace('-', '_')
+ if setting in self.settings:
+ print(self.settings[setting]['value'])
+ else:
+ self.webquiz_error('{} is an invalid setting'.format(setting))
+
+ elif setting=='all':
+ dash = '-'*len('WebQuiz rc-file: {}'.format(self.rcfile))
+ print('{dash}\nWebQuiz rc-file: {rcfile}\n{dash}'.format(rcfile=self.rcfile, dash=dash))
+ for key in self.keys():
+ print('{:<17} = {}'.format(key.replace('_', '-'), self[key]))
+ print('{dash}'.format(dash=dash))
+
+ elif setting=='help':
+ for key in self.keys():
+ print('{:<17} {}'.format(key.replace('_', '-'), self.settings[key]['help'].lower()))
+
+ else:
+ print('WebQuiz settings from {}'.format(self.rcfile))
+ for key in self.keys():
+ print('# {}{}\n{:<17} = {:<17} {}'.format(
+ self.settings[key]['help'],
+ ' (advanced)' if self.settings[key]['advanced'] else '',
+ key.replace('_', '-'),
+ self[key],
+ '(default)' if self[key]==self.settings[key]['default'] else ''
+ )
+ )
+
+ def initialise_webquiz(self, need_to_initialise=False, developer=False):
+ r'''
+ Set the root for the WebQuiz web directory and copy the www files into
+ this directory. Once this is done save the settings to webquizrc.
+ This method should only be used when WebQuiz is being set up.
+
+ If `need_to_initialise` is `True` then this is a forced initialisation.
+ '''
+
+ # keep track of whether we have initialised
+ self.have_initialised = True
+
+ if need_to_initialise:
+ self.initialise_warning = webquiz_templates.web_initialise_warning
+ initialise = input(webquiz_templates.initialise_invite)
+ if initialise!='' and initialise.strip().lower()[0]!='y':
+ self['webquiz_url'] = 'http://www.maths.usyd.edu.au/u/mathas/WebQuiz'
+ return
+
+ if self['webquiz_url']=='':
+ self['webquiz_url'] = '/WebQuiz'
+
+ # prompt for directory and copy files - are these reasonable defaults
+ # for each OS?
+ if sys.platform == 'darwin':
+ default_root = '/Library/WebServer/Documents/WebQuiz'
+ platform = 'Mac OSX'
+ elif sys.platform.startswith('win'):
+ default_root = ' c:\inetpub\wwwroot\WebQuiz'
+ platform = 'Windows'
+ else:
+ default_root = '/var/www/html/WebQuiz'
+ platform = sys.platform.capitalize()
+
+ if self['webquiz_www'] != '':
+ webquiz_root = self['webquiz_www']
+ else:
+ webquiz_root = default_root
+
+ print(webquiz_templates.initialise_introduction)
+ input('Press RETURN to continue... ')
+
+ print(webquiz_templates.webroot_request.format(
+ platform=platform,
+ webquiz_dir = webquiz_root)
+ )
+ input('Press RETURN to continue... ')
+
+ files_copied = False
+ while not files_copied:
+ web_dir = input('\nWebQuiz web directory:\n[{}] '.format(webquiz_root))
+ if web_dir == '':
+ web_dir = webquiz_root
+ else:
+ web_dir = os.path.expanduser(web_dir)
+
+ print('Web directory set to {}'.format(web_dir))
+ if web_dir=='SMS':
+ # undocumented: allow links to SMS web pages
+ self['webquiz_www'] = 'SMS'
+ self['webquiz_url'] = 'http://www.maths.usyd.edu.au/u/mathas/WebQuiz'
+
+ else:
+ try:
+ # ...remove the doc directory
+ web_doc = os.path.join(web_dir, 'doc')
+ if os.path.isfile(web_doc) or os.path.islink(web_doc):
+ os.remove(web_doc)
+ elif os.path.isdir(web_doc):
+ shutil.rmtree(web_doc)
+
+ # Need to locate the www directory, which should be a subdirectory
+ # of the webquiz doc directory. First try using texdoc
+ webquiz_doc = ''
+ try:
+ webquiz_pdf = webquiz_util.shell_command('texdoc --list --machine webquiz.pdf').split()[-1]
+ if webquiz_pdf.endswith('webquiz.pdf'):
+ webquiz_doc = os.path.dirname(webquiz_pdf)
+ except subprocess.CalledProcessError:
+ pass
+
+ # if texdoc failed then try using TEXMFMAIN
+ if webquiz_doc=='':
+ try:
+ webquiz_doc = os.path.join(webquiz_util.kpsewhich('-var TEXMFMAIN'), 'doc','latex', 'webquiz')
+ except subprocess.CalledProcessError:
+ pass
+
+ # if we still don't have webquiz_doc then try working backwards from webquiz.cls
+ # unlikely to work if TEXMFMAIN doesn't
+ if not os.path.isdir(webquiz_doc):
+ parent = os.path.dirname
+ try:
+ texdist_dir = parent(parent(parent(parent(parent(webquiz_util.kpsewhich('webquiz.cls'))))))
+ except subprocess.CalledProcessError:
+ print(webquiz_templates.not_installed.format(metadata.repository))
+ sys.exit(1)
+
+ webquiz_doc = os.path.join(texdist_dir, 'doc', 'latex', 'webquiz')
+
+ # get the root directory of the source code for developer
+ # mode and just in case webquiz_www still does not exist
+ webquiz_src = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
+
+ webquiz_www = os.path.join(webquiz_doc, 'www')
+ if not os.path.isdir(webquiz_www):
+ webquiz_www = os.path.join(webquiz_src, 'doc', 'www')
+
+ if developer and os.path.isdir(os.path.join(webquiz_src, 'doc')):
+ # this is a development version so add links from the
+ # web directory to the css,doc and js directories
+ print('\nInstalling files for development version')
+ print('Linking web files {} -> {} ...\n'.format(web_dir, webquiz_src))
+ if not os.path.exists(web_dir):
+ os.makedirs(web_dir)
+
+ for (src, target) in [('javascript', 'js'), ('css', 'css'), ('doc', 'doc')]:
+ newlink = os.path.join(web_dir, target)
+ try:
+ os.remove(newlink)
+ except FileNotFoundError:
+ pass
+ try:
+ os.symlink(os.path.join(webquiz_src,src), newlink)
+ except OSError as err:
+ print('There was a problem linking {}: {}'.format(newlink, err))
+
+ else:
+ # loop until we find some files to install or exit
+ while not os.path.isdir(webquiz_www) or webquiz_www=='':
+ print('\nUnable to find the WebQuiz web files')
+ webquiz_www = input('Please enter the location of the WebQuiz www directory\nor press RETURN to exit: ')
+ webquiz_www = os.path.expanduser(webquiz_www)
+ if webquiz_www=='':
+ sys.exit()
+ if not (webquiz_www.endswith('www/') or webquiz_www.endswith('www')):
+ print('\nThe webquiz web directory is called www, so\n {}\ncannot be the right directory.'.format(
+ webquiz_www)
+ )
+ webquiz_www = False
+
+
+ # the www directory exists so we copy it to web_dir
+ print('\nCopying web files to {} ...'.format(web_dir))
+ webquiz_util.copytree(webquiz_www, web_dir)
+
+ self['webquiz_www'] = web_dir
+ files_copied = True
+
+ except PermissionError:
+ print(webquiz_templates.permission_error.format(web_dir))
+
+ except OSError as err:
+ print(webquiz_templates.oserror_copying.format(web_dir=web_dir, err=err))
+
+ if self['webquiz_www']!='SMS':
+ # now prompt for the relative url
+ webquiz_url = input(webquiz_templates.webquiz_url_message.format(self['webquiz_url']))
+ if webquiz_url != '':
+ # removing trailing slashes from webquiz_url
+ while webquiz_url[-1] == '/':
+ webquiz_url = webquiz_url[:len(webquiz_url) - 1]
+
+ if webquiz_url[0] != '/': # force URL to start with /
+ webquiz_url = '/' + webquiz_url
+
+ if not web_dir.endswith(webquiz_url):
+ print(webquiz_templates.webquiz_url_warning)
+ input('Press RETURN to continue... ')
+
+ self['webquiz_url'] = webquiz_url
+
+ # save the settings and exit
+ self.write_webquizrc()
+ print(webquiz_templates.initialise_ending.format(web_dir=self['webquiz_www']))
+
+ def edit_settings(self):
+ r'''
+ Change current default values for the WebQuiz settings
+ '''
+ advanced_not_started = True
+ for key in self.keys():
+ if key not in ['webquiz_www', 'version']:
+ if advanced_not_started and self.settings[key]['advanced']:
+ print(webquiz_templates.advanced_settings)
+ advanced_not_started = False
+
+ skey = '{}'.format(self[key])
+ setting = input('{}{}[{}]: '.format(
+ self.settings[key]['help'],
+ ' ' if len(skey)<40 else '\n',
+ skey
+ )
+ ).strip()
+ if setting != '':
+ if key == 'webquiz_url' and setting[0] != '/':
+ print(" ** prepending '/' to webquiz_url **")
+ setting = '/' + setting
+
+ elif key == 'webquiz_layout':
+ setting = os.path.expanduser(setting)
+ if setting.endswith('.py'):
+ print(" ** removing .py extension from webquiz_layout **")
+ setting = setting[:-3]
+
+ elif key == 'engine' and setting not in self.settings['engine'].values:
+ print('setting not changed: {} is not a valid TeX engine'.format(setting))
+ setting = self['engine']
+
+ elif key in ['hide_side_menu', 'random_order']:
+ setting = setting.lower()
+ if setting not in ['true', 'false']:
+ print('setting not changed: {} must be True or False'.format(key))
+ setting = self[key]
+
+ elif setting=='NONE':
+ setting = ''
+
+ self[key] = setting
+
+ # save the settings, print them and exit
+ self.write_webquizrc()
+ self.list_settings()
+
+ def tex_install(self):
+ r'''
+ Install the tex files into the standard locations in TEXMFMAIN:
+ scripts -> TEXMFMAIN/scripts/webquiz
+ doc -> TEXMFMAIN/doc/latex/webquiz
+ latex -> TEXMFMAIN/tex/latex/webquiz
+ It is assumed that this is run from the zipfile installation. There
+ is little in the way of error checking or debugging.
+
+ Undocumented feature - useful for debugging initialisation routine
+ '''
+ webquiz_top = os.path.abspath(webquiz_util.webquiz_file('..'))
+ texmf = webquiz_util.kpsewhich('-var TEXMFMAIN')
+ for (src, target) in [('scripts', 'scripts'),
+ ('latex', 'tex/latex'),
+ ('doc', 'doc/latex')]:
+ try:
+ webquiz_util.copytree(os.path.join(webquiz_top,src), os.path.join(texmf, target, 'webquiz'))
+
+ except (FileExistsError,FileNotFoundError):
+ continue
+
+ except PermissionError as err:
+ print(webquiz_templates.insufficient_permissions.format(err))
+ sys.exit(1)
+
+ try:
+
+ # add a link to webquiz.py
+ texbin = os.path.dirname(webquiz_util.shell_command('which pdflatex').split()[-1])
+ os.symlink(os.path.join(texmf,'scripts','webquiz','webquiz.py'), os.path.join(texbin, 'webquiz'))
+ subprocess.call('mktexlsr', shell=True)
+
+ except (FileExistsError,FileNotFoundError):
+ pass
+
+ except PermissionError as err:
+ print(webquiz_templates.insufficient_permissions.format(err))
+ sys.exit(1)
+
+ except subprocess.CalledProcessError as err:
+ print('There was a problem running mktexlsr')
+ sys.exit(1)
+
+ def tex_uninstall(self):
+ r'''
+ UnInstall the tex files into TEXMFMAIN. It is assumed that the files
+ are installed in the natural locations in the TEXMFMAIN tree, namely:
+ scripts -> TEXMFMAIN/scripts/webquiz
+ doc -> TEXMFMAIN/doc/latex/webquiz
+ latex -> TEXMFMAIN/tex/latex/webquiz
+ There is little in the way of error checking or debugging.
+
+ Undocumented feature - useful for debugging initialisation routine
+ '''
+ webquiz_top = os.path.abspath(webquiz_util.webquiz_file('..'))
+ texmf = webquiz_util.kpsewhich('-var TEXMFMAIN')
+ for target in ['scripts', 'tex/latex', 'doc/latex']:
+ try:
+ shutil.rmtree(os.path.join(texmf, target, 'webquiz'))
+
+ except (FileExistsError,FileNotFoundError):
+ pass
+
+ except PermissionError as err:
+ print(webquiz_templates.insufficient_permissions.format(err))
+ sys.exit(1)
+
+ try:
+ # remove link from texbin to webquiz.py
+ texbin = os.path.dirname(webquiz_util.shell_command('which pdflatex').split()[-1])
+ os.remove(os.path.join(texbin, 'webquiz'))
+
+ except (FileExistsError,FileNotFoundError):
+ pass
+
+ except PermissionError as err:
+ print(webquiz_templates.insufficient_permissions.format(err))
+ sys.exit(1)
+
+ # remove any rcfiles that exist in obvious places
+ try:
+ if os.path.isfile(self.system_rcfile):
+ os.remove(self.system_rcfile)
+ if os.path.isfile(self.user_rcfile):
+ os.remove(self.user_rcfile)
+ if os.path.isfile(self.rcfile):
+ os.remove(self.rcfile)
+ except PermissionError:
+ print(webquiz_templates.insufficient_permissions.format(err))
+ sys.exit(1)
+
+ # remove link to webquiz.py
+ texbin = os.path.dirname(webquiz_util.shell_command('which pdflatex').split()[-1])
+ webquiz = os.path.join(texbin,'webquiz')
+ try:
+ target = os.readlink(webquiz)
+ if target==os.path.join(texmf,'scripts','webquiz','webquiz.py'):
+ os.remove(webquiz)
+
+ except (FileExistsError,FileNotFoundError):
+ pass
+
+ except OSError as err:
+ print('There was a problem removing the link to webquiz: {}'.format(err))
+
+ def uninstall_webquiz(self):
+ r'''
+ Remove all of the webquiz files from the webserver
+ '''
+
+ if os.path.isdir(self['webquiz_www']):
+ remove = input('Do you really want to remove the WebQuiz from your web server [N/yes]? ')
+ if remove != 'yes':
+ print('WebQuiz unistall aborted!')
+ return
+
+ try:
+ shutil.rmtree(self['webquiz_www'])
+ print('WebQuiz files successfully removed from {}'.format(self['webquiz_www']))
+
+ except PermissionError as err:
+ print(webquiz_templates.insufficient_permissions.format(err))
+ sys.exit(1)
+
+ except OSError as err:
+ self.webquiz_error('There was a problem removing webquiz files from {}'.format(self['webquiz_www']), err)
+
+ # now reset and save the locations of the webquiz files and URL
+ self['webquiz_url'] = ''
+ self['webquiz_www'] = ''
+ self.write_webquizrc()
+
+ else:
+ self.webquiz_error('uninstall: no webwquiz files are installed on your web server??')
+
+ for rfile in ['system', 'user']:
+ rcfile = getattr(self, rfile+'_rcfile')
+ if os.path.isfile(rcfile):
+ rm = input('Remove {} rcfile {}\n[Y/no] '.format(rfile, rcfile))
+ if rm != 'no':
+ try:
+ os.remove(rcfile)
+ except (OSError, PermissionError) as err:
+ self.webquiz_error('There was a problem deleting {}'.format(rcfile), err)
+
+
+# =====================================================
+if __name__ == '__main__':
+ try:
+ settings = WebQuizSettings()
+
+ # parse the command line options
+ parser = argparse.ArgumentParser(description=metadata.description)
+
+ parser.add_argument(
+ 'quiz_file',
+ nargs='*',
+ type=str,
+ default=None,
+ help='latex quiz files')
+
+ parser.add_argument(
+ '-q',
+ '--quiet',
+ action='count',
+ default=0,
+ help='Suppress tex4ht messages (also -qq etc)')
+
+ parser.add_argument(
+ '-d', '--draft',
+ action='store_true',
+ default=False,
+ help='Use make4ht draft mode')
+
+ parser.add_argument(
+ '-s',
+ '--shell-escape',
+ action='store_true',
+ default=False,
+ help='Shell escape for tex4ht/make4ht')
+
+ engine = parser.add_mutually_exclusive_group()
+ engine.add_argument(
+ '--latex',
+ action='store_const',
+ const='latex',
+ default=settings['engine'],
+ dest='engine',
+ help='Use latex to compile document with make4ht (default)')
+ engine.add_argument(
+ '-l',
+ '--lua',
+ action='store_const',
+ const='lua',
+ dest='engine',
+ help='Use lualatex to compile the quiz')
+ engine.add_argument(
+ '-x',
+ '--xelatex',
+ action='store_const',
+ const='xelatex',
+ dest='engine',
+ help='Use xelatex to compile the quiz')
+
+ parser.add_argument(
+ '-r',
+ '--rcfile',
+ action='store',
+ default=None,
+ help='Specify location of the webquiz rc-file ')
+
+ settings_parser = parser.add_mutually_exclusive_group()
+ settings_parser.add_argument(
+ '-i',
+ '--initialise',
+ action='store_true',
+ default=False,
+ help='Install web components of webquiz')
+ settings_parser.add_argument(
+ '-e', '--edit-settings',
+ action='store_true',
+ default=False,
+ help='Edit default settings for webquiz')
+ settings_parser.add_argument(
+ '--settings',
+ action='store',
+ const='all',
+ default='',
+ nargs='?',
+ type=str,
+ help='List default settings for webquiz'
+ )
+ settings_parser.add_argument(
+ '--developer',
+ action='store_true',
+ default=False,
+ help=argparse.SUPPRESS
+ )
+
+ # options suppressed from the help message
+ parser.add_argument(
+ '-m',
+ '--make4ht',
+ action='store',
+ type=str,
+ dest='make4ht_options',
+ default=settings['make4ht'],
+ help=argparse.SUPPRESS
+ )
+
+ parser.add_argument(
+ '--webquiz_layout',
+ action='store',
+ type=str,
+ dest='webquiz_layout',
+ default=settings['webquiz_layout'],
+ help=argparse.SUPPRESS
+ )
+
+ install_parser = parser.add_mutually_exclusive_group()
+ install_parser.add_argument(
+ '--tex-install',
+ action='store_true',
+ default=False,
+ help=argparse.SUPPRESS
+ )
+ install_parser.add_argument(
+ '--tex-uninstall',
+ action='store_true',
+ default=False,
+ help=argparse.SUPPRESS
+ )
+ install_parser.add_argument(
+ '--uninstall',
+ action='store_true',
+ default=False,
+ help=argparse.SUPPRESS
+ )
+
+ parser.add_argument(
+ '--version',
+ action='version',
+ version='%(prog)s version {}'.format(metadata.version),
+ help=argparse.SUPPRESS)
+
+ parser.add_argument(
+ '--debugging',
+ action='store_true',
+ default=False,
+ help=argparse.SUPPRESS)
+
+ parser.add_argument(
+ '--shorthelp',
+ action='store_true',
+ default=False,
+ help=argparse.SUPPRESS
+ )
+
+ # parse the options
+ options = parser.parse_args()
+ options.prog = parser.prog
+
+ # set debugging mode from options
+ settings.debugging = options.debugging
+
+ # read the rcfile and throw an error if we are not adjusting the settings
+ if options.rcfile is not None:
+ rcfile = os.path.expanduser(options.rcfile)
+ settings.read_webquizrc(rcfile)
+
+ if options.uninstall:
+ # uninstall web files and exit
+ settings.uninstall_webquiz()
+ sys.exit()
+ elif options.tex_install:
+ # install files from zip file into tex distribution and then exit
+ settings.tex_install()
+ sys.exit()
+ elif options.tex_uninstall:
+ # install files from zip file into tex distribution and then exit
+ settings.tex_uninstall()
+ sys.exit()
+
+ # initialise and exit
+ if options.initialise or options.developer:
+ settings.initialise_webquiz(developer=options.developer)
+
+ # force initialisation if the url is not set
+ elif settings['webquiz_url'] == '':
+ settings.initialise_webquiz(need_to_initialise=True)
+
+ # list settings and exit
+ if options.settings != '':
+ settings.list_settings(options.settings)
+ sys.exit()
+
+ # edit settings and exit
+ if options.edit_settings:
+ settings.edit_settings()
+ sys.exit()
+
+ # print short help and exit
+ if options.shorthelp:
+ parser.print_usage()
+ sys.exit()
+
+ # if no filename then exit
+ if options.quiz_file==[]:
+ if settings.have_initialised:
+ sys.exit()
+ else:
+ parser.print_help()
+ sys.exit(1)
+
+ # import the local page formatter
+ mod_dir, mod_layout = os.path.split(options.webquiz_layout)
+ if mod_dir != '':
+ sys.path.insert(0, mod_dir)
+ options.write_web_page = __import__(mod_layout).write_web_page
+
+ # run() is a shorthand for executing system commands depending on the quietness
+ # - we need to use shell=True because otherwise pst2pdf gives an error
+ # options.talk() is a shorthand for letting the user know what is happening
+ if options.quiet == 0:
+ options.run = lambda cmd: subprocess.call(cmd, shell=True)
+ options.talk = lambda msg: print(msg)
+ elif options.quiet == 1:
+ options.run = lambda cmd: subprocess.call(cmd, shell=True, stdout=open(os.devnull, 'wb'))
+ options.talk = lambda msg: print(msg)
+ else:
+ options.run = lambda cmd: subprocess.call(cmd, shell=True, stdout=open(os.devnull, 'wb'), stderr=open(os.devnull, 'wb'))
+ options.talk = lambda msg: None
+
+ # run through the list of quizzes and make them
+ for quiz_file in options.quiz_file:
+ if len(options.quiz_file) > 1 and options.quiet < 3:
+ print('Making web page for {}'.format(quiz_file))
+ # quiz_file is assumed to be a tex file if no extension is given
+ if not '.' in quiz_file:
+ quiz_file += '.tex'
+
+ if not os.path.isfile(quiz_file):
+ print('WebQuiz error: cannot read file {}'.format(quiz_file))
+
+ else:
+
+ # the quiz name and the quiz_file will be if pst2pdf is used
+ quiz_name = quiz_file
+ if options.quiet < 2:
+ print('WebQuiz generating web page for {}'.format(quiz_file))
+
+ # If the pst2podf option is used then we need to preprocess
+ # the latex file BEFORE passing it to MakeWebQuiz. Set
+ # options.pst2pdf = True if pst2pdf is given as an option to
+ # the webquiz documentclass
+ with codecs.open(quiz_file, 'r', encoding='utf8') as q_file:
+ doc = q_file.read()
+
+ options.pst2pdf = False
+ try:
+ brac = doc.index(r'\documentclass[') + 15 # start of class options
+ if 'pst2pdf' in [
+ opt.strip()
+ for opt in doc[brac:brac+doc[brac:].index(']')].split(',')
+ ]:
+ preprocess_with_pst2pdf(options, quiz_file[:-4])
+ options.pst2pdf = True
+ # now run webquiz on the modified tex file
+ quiz_file = quiz_file[:-4] + '-pdf-fixed.tex'
+ except ValueError:
+ pass
+
+ # the file exists and is readable so make the quiz
+ webquiz_makequiz.MakeWebQuiz(quiz_name, quiz_file, options, settings, metadata)
+
+ quiz_name = quiz_name[:quiz_name.index('.')] # remove the extension
+
+ # move the css file into the directory for the quiz
+ css_file = os.path.join(quiz_name, quiz_name + '.css')
+ if os.path.isfile(quiz_name + '.css'):
+ if os.path.isfile(css_file):
+ os.remove(css_file)
+ shutil.move(quiz_name + '.css', css_file)
+
+ # now clean up unless debugging
+ if not options.debugging:
+ for ext in ['4ct', '4tc', 'dvi', 'idv', 'lg', 'log',
+ 'ps', 'pdf', 'tmp', 'xml', 'xref'
+ ]:
+ if os.path.isfile(quiz_name + '.' + ext):
+ os.remove(quiz_name + '.' + ext)
+
+ # files created when using pst2pdf
+ if options.pst2pdf:
+ for file in glob.glob(quiz_name + '-pdf.*'):
+ os.remove(file)
+ for file in glob.glob(quiz_name + '-pdf-fixed.*'):
+ os.remove(file)
+ for extention in ['.preamble', '.plog', '-tmp.tex',
+ '-pst.tex', '-fig.tex'
+ ]:
+ if os.path.isfile(quiz_name + extention):
+ os.remove(quiz_name + extention)
+ if os.path.isdir(os.path.join(quiz_name, quiz_name)):
+ shutil.rmtree(os.path.join(quiz_name, quiz_name))
+
+ if settings.initialise_warning != '':
+ print(webquiz_templates.text_initialise_warning)
+
+ except Exception as err:
+
+ # there is a small chance that there is an error before we the
+ # settings.debugging flag has been set
+ webquiz_util.webquiz_error(settings.debugging if 'settings' in globals() else True,
+ 'unknown problem.\n\nIf you think this is a bug please report it by creating an issue at\n {}\n'
+ .format(metadata.repository), err)
diff --git a/Master/texmf-dist/scripts/webquiz/webquiz_layout.py b/Master/texmf-dist/scripts/webquiz/webquiz_layout.py
new file mode 100755
index 00000000000..89b5f3d94e4
--- /dev/null
+++ b/Master/texmf-dist/scripts/webquiz/webquiz_layout.py
@@ -0,0 +1,73 @@
+r'''
+-----------------------------------------------------------------------------
+ webquiz_local | default layout of webquiz quiz pages.
+-----------------------------------------------------------------------------
+
+ Copyright (C) Andrew Mathas, University of Sydney
+
+ Distributed under the terms of the GNU General Public License (GPL)
+ http://www.gnu.org/licenses/
+
+ This file is part of the WebQuiz system.
+
+ <Andrew.Mathas@sydney.edu.au>
+-----------------------------------------------------------------------------
+'''
+
+# -*- encoding: utf-8 -*-
+
+from webquiz_templates import no_script
+
+# If you want to create a new version of this file to change the
+# quiz web page layout then the following "dictionary" of code variables
+# is likely to be useful:
+# quiz.breadcrumbs = HTML for breadcrunbs
+# quiz.css = css includes for quisz
+# quiz.department = department from \UnitDepartment
+# quiz.department_url = unit url from \UnitURL
+# quiz.header = header links for quiz
+# quiz.institution = institution from \Institution
+# quiz.institution_url = unit url from \InstitutionURL
+# quiz.javascript = javascript includes for quiz
+# quiz.quiz_header = HTMK for quiz title and navigation arrows
+# quiz.quiz_questions = html for quiz
+# quiz.side_menu = HTML for side menu, including navigation buttons
+# quiz.title = web page title from \title{...} command
+# quiz.unit_code = unit code from \UnitCode
+# quiz.unit_name = unit name from \UnitName
+# quiz.unit_url = unit url from \UnitURL
+# quiz.webquiz_init = javascript for initialising quiz page.
+# This MUST appear tow<M-C-D-A>rds the end of HTML body
+
+def write_web_page(quiz):
+ return quiz_page.format(
+ title=quiz.quiz.title, # page title
+ htmlpreamble=quiz.header + quiz.javascript + quiz.css, # header material
+ breadcrumbs=quiz.breadcrumbs, # bread crumb constructed above
+ side_menu=quiz.side_menu, # navigation menu for quiz
+ quiz_header=quiz.quiz_header, # quiz title + navigation arrows
+ quiz_questions=quiz.quiz_questions, # html for quiz
+ no_script=no_script, # error when javascript is not enabled
+ webquiz_init=quiz.webquiz_init # parting javascript callsWebQuizInt
+ )
+
+
+quiz_page = r'''<!DOCTYPE HTML>
+<html lang="en">
+<head>
+ <title> {title} </title>
+ {htmlpreamble}
+</head>
+<body>
+ {no_script}{breadcrumbs}
+ <div class="quiz-page">
+ {side_menu}
+ <div class="quiz-questions">
+ {quiz_header}
+ {quiz_questions}
+ </div>
+ </div>
+ {webquiz_init}
+</body>
+</html>
+'''
diff --git a/Master/texmf-dist/scripts/webquiz/webquiz_makequiz.py b/Master/texmf-dist/scripts/webquiz/webquiz_makequiz.py
new file mode 100755
index 00000000000..cca12a664f5
--- /dev/null
+++ b/Master/texmf-dist/scripts/webquiz/webquiz_makequiz.py
@@ -0,0 +1,550 @@
+#!/usr/bin/env python3
+r'''
+------------------------------------------------------------------------------
+ webquiz_makequiz | build and generate the quiz page using webquiz_xml
+ | and webquiz_layout
+------------------------------------------------------------------------------
+ Copyright (C) Andrew Mathas, University of Sydney
+
+ Distributed under the terms of the GNU General Public License (GPL)
+ http://www.gnu.org/licenses/
+
+ This file is part of the WebQuiz system.
+
+ <Andrew.Mathas@sydney.edu.au>
+ <Donald.Taylor@sydney.edu.au>
+------------------------------------------------------------------------------
+'''
+import subprocess
+import codecs
+import shutil
+import os
+import re
+
+import webquiz_templates
+import webquiz_util
+import webquiz_xml
+
+#################################################################################
+class MakeWebQuiz(object):
+ """
+ Convert a webquiz latex file to an online quiz.
+
+ There are several steps:
+ 1. If given a LaTeX file then run htlatex/make4ht on the latex file to generate an
+ xml file for the quiz that has all LaTeS markup converted to html.
+ 2. Read in the xml file version of the quiz
+ 3. Spit out the html version
+
+ The HTMl is constructed using the template strings in webquiz_templates
+ """
+ # attributes that will form part of the generated web page
+ header = '' # page header: title, meta data, links
+ css = '' # css specifications
+ javascript = '' # javascript code
+ quiz_questions = '' # the main quiz page
+ side_menu = '' # the left hand quiz menu
+
+ def __init__(self, quiz_name, quiz_file, options, settings, metadata):
+ self.options = options
+ self.settings = settings
+ self.metadata = metadata
+ self.quiz_name = quiz_name.split('.')[0]
+ self.quiz_file, extension = quiz_file.split('.')
+ self.webquiz_url = settings['webquiz_url']
+ if self.webquiz_url[-1] == '/':
+ self.webquiz_url = self.webquiz_url[:len(self.webquiz_url)-1]
+
+ # run htlatex only if quiz_file has a .tex extension
+ if extension == 'tex':
+ self.htlatex_quiz_file()
+
+ self.read_xml_file()
+
+ # use kpsewhich to fine the webquiz language file
+ try:
+ language_file = webquiz_util.kpsewhich('webquiz-{}.lang'.format(self.quiz.language))
+ except subprocess.CalledProcessError:
+ self.webquiz_error(
+ 'kpsewhich is unable to find language file for "{}"'.format(self.quiz.language)
+ )
+ # read the language file and store as a dictonary
+ self.language = webquiz_util.MetaData(language_file)
+
+ # initialise number of quiz and discussion items
+ self.number_discussions = len(self.quiz.discussion_list)
+ self.number_questions = len(self.quiz.question_list)
+
+ # build the different components of the quiz web page
+ self.add_meta_data()
+ self.add_question_javascript()
+ self.add_side_menu()
+ self.add_quiz_header_and_questions()
+ self.add_breadcrumbs()
+
+ # add the initialisation warning if webquiz has not been initialised
+ if self.settings.initialise_warning != '':
+ self.breadcrumbs = self.settings.initialise_warning + self.breadcrumbs
+
+ # now write the quiz to the html file
+ with codecs.open(self.quiz_name + '.html', 'w', encoding='utf8') as file:
+ # write the quiz in the specified format
+ file.write(self.options.write_web_page(self))
+
+ def webquiz_debug(self, msg):
+ r'''
+ Customised debugging message for the makequiz module
+ '''
+ webquiz_util.webquiz_debug(self.settings.debugging, 'makequiz: '+msg)
+
+ def webquiz_error(self, msg, err=None):
+ r'''
+ Customised eror message for the makequiz module
+ '''
+ webquiz_util.webquiz_error(self.settings.debugging, 'makequiz: '+msg, err)
+
+ def add_breadcrumbs(self):
+ r'''
+ Build the breadcrumbs by appropriately parsing the magic crumbs
+ '''
+ self.breadcrumbs = ''
+ if self.quiz.breadcrumbs != '':
+ # build the bread crumbs
+ crumbs = '\n '
+ for crumb in self.quiz.breadcrumbs.split('|'):
+ crumb = crumb.strip()
+
+ if crumb == 'breadcrumb':
+ crumbs += self.add_breadcrumb_line(self.quiz.breadcrumb, missing='breadcrumb')
+
+ elif crumb == 'department':
+ crumbs += self.add_breadcrumb_line(
+ text=self.quiz.department,
+ url=self.quiz.department_url,
+ missing='department')
+
+ elif crumb == 'institution':
+ crumbs += self.add_breadcrumb_line(
+ text=self.quiz.institution,
+ url=self.quiz.institution_url,
+ missing='institution')
+
+ elif crumb == 'quizindex':
+ if self.quiz.quiz_index == []:
+ crumbs += webquiz_templates.breadcrumb_quizindex.format(
+ quizzes_url=self.quiz.quizzes_url,
+ **self.language)
+ else:
+ crumbs += self.add_breadcrumb_line('Quizzes')
+
+ elif crumb == 'Title':
+ crumbs += self.add_breadcrumb_line(text = self.quiz.title, missing='title')
+
+ elif crumb == 'title':
+ title = self.quiz.title
+ crumbs += self.add_breadcrumb_line(
+ text = title[:title.index(':')] if ':' in title else title,
+ missing='title'
+ )
+
+ elif crumb == 'unitcode':
+ crumbs += self.add_breadcrumb_line(
+ text=self.quiz.unit_code,
+ url=self.quiz.unit_url,
+ missing='unit code')
+
+ elif crumb == 'unitname':
+ crumbs += self.add_breadcrumb_line(
+ text=self.quiz.unit_name,
+ url=self.quiz.unit_url,
+ missing='unit name')
+
+ elif crumb != '':
+ lastSpace = crumb.rfind(' ')
+ url = crumb[lastSpace:].strip()
+ if url[0] == '/' or url.lower()[:4] == 'http':
+ crumbs += self.add_breadcrumb_line(text=crumb[:lastSpace], url=url)
+ else:
+ crumbs += self.add_breadcrumb_line(crumb)
+
+ self.breadcrumbs = webquiz_templates.breadcrumbs.format(crumbs=crumbs)
+
+ def add_breadcrumb_line(self, text, url='', missing='??'):
+ r'''
+ Return a line to add the bread crumbs, with errors if necessary
+ '''
+ if url == '':
+ return webquiz_templates.breadcrumb_line_text.format(
+ text=text if text != '' else '?? ' + missing)
+
+ return webquiz_templates.breadcrumb_line_url.format(
+ url=url, text=text if text != '' else '?? ' + missing)
+
+ def htlatex_quiz_file(self):
+ r'''
+ Process the file using htlatex/make4ht. This converts the quiz to an xml
+ with markup specifying the different elements of the quiz page.
+ '''
+ # at the minimum we put a css file into a <quiz_name> subdirectory
+ if not os.path.exists(self.quiz_name):
+ os.makedirs(self.quiz_name)
+
+ try:
+ self.options.talk('Processing {}.tex with TeX4ht'.format(self.quiz_name))
+ # there is a slightly torturous process to convert the engine
+ # settings into a command line option that make4ht understands
+ cmd = 'make4ht --utf8 --config webquiz.cfg {draft} {engine} {escape} {make4ht_options} {quiz_file}.tex'.format(
+ draft='--mode draft' if self.options.draft else '',
+ engine=self.settings.settings['engine']['values'][self.options.engine],
+ escape='--shell-escape' if self.options.shell_escape else '',
+ make4ht_options=self.options.make4ht_options,
+ quiz_file=self.quiz_file
+ )
+ self.options.run(cmd)
+
+ # move the css file into the quiz_file subdirectory
+ if os.path.exists(self.quiz_file + '.css'):
+ shutil.move(
+ self.quiz_file + '.css',
+ os.path.join(self.quiz_name, self.quiz_name + '.css'))
+
+ # Now move any images that were created into the quiz_name
+ # subdirectory and update the links in the html file As htlatex
+ # generates an html file, we rename this as an xml file at the same
+ # time - in the cfg file, \Preamable{ext=xml} should lead to an xml
+ # file being created but this doesn't seem to work ??
+ try:
+ fix_img = re.compile(r'^(|.* )\b(data|src)="([-0-9a-zA-Z]*\.(?:png|svg))" (.*)$')
+ with codecs.open(self.quiz_file + '.html', 'r', encoding='utf8') as make4ht_file:
+ with codecs.open(self.quiz_name + '.xml', 'w', encoding='utf8') as xml_file:
+ for line in make4ht_file:
+ match = fix_img.match(line)
+ if match is None:
+ xml_file.write(line)
+ else:
+ # update html link and move file
+ start, src, image, rest_of_line = match.groups()
+ xml_file.write(r'{}{}="{}/{}" {}'.format(
+ start, src, self.quiz_name, image, rest_of_line))
+ shutil.move(image, os.path.join(self.quiz_name, image))
+
+ except OSError as err:
+ self.webquiz_error(
+ 'there was a problem moving the image files for {}'.format(
+ self.quiz_name), err)
+
+ except Exception as err:
+ self.webquiz_error( 'something went wrong when running htlatex on {}'.format(self.quiz_file), err)
+
+ def read_xml_file(self):
+ r'''
+ Read in the webquiz xml file for the quiz and store the xml document
+ tree in ``self.quiz``.
+ '''
+ try:
+ # read in the xml version of the quiz
+ if not os.path.isfile(self.quiz_name + '.xml'):
+ self.webquiz_error('{}.xml does not exist!?'.format(self.quiz_name))
+ self.quiz = webquiz_xml.ReadWebQuizXmlFile(self.quiz_name + '.xml', self.settings)
+ except Exception as err:
+ self.webquiz_error('error reading the xml generated for {}. Please check your latex source.'
+ .format(self.quiz_name), err)
+
+ def add_meta_data(self):
+ """ add the meta data for the web page to self.header """
+ # meta tags`
+ self.header += webquiz_templates.html_meta.format(
+ version=self.metadata.version,
+ authors=self.metadata.authors,
+ webquiz_url=self.webquiz_url,
+ description=self.metadata.description,
+ copyright=self.metadata.copyright,
+ department=self.quiz.department,
+ institution=self.quiz.institution,
+ quiz_file=self.quiz_name,
+ theme=self.quiz.theme)
+ if self.quiz.mathjs:
+ self.header += webquiz_templates.mathjs
+
+ def add_side_menu(self):
+ """ construct the left hand quiz menu """
+ if self.quiz.discussion_list != []: # links for discussion items
+ discussion_list = '\n <ul>\n {}\n </ul>'.format(
+ '\n '.join(
+ webquiz_templates.discuss.format(b=q + 1, title=d.short_heading)
+ for (q, d) in enumerate(self.quiz.discussion_list)))
+ else:
+ discussion_list = ''
+
+ # department and institution links
+ department = '''<a href="{0.department_url}">{0.department}</a>'''.format(self.quiz)
+ institution = '''<a href="{0.institution_url}">{0.institution}</a>'''.format(self.quiz)
+
+ # question buttons
+ if self.number_questions == 0:
+ question_buttons = ''
+ else:
+ buttons = '\n' + '\n'.join(
+ webquiz_templates.button.format(b=q,
+ cls='button-selected' if self.quiz.discussion_list==[] and q==1 else 'blank'
+ )
+ for q in range(1, self.number_questions + 1))
+ question_buttons=webquiz_templates.question_buttons.format(
+ buttons=buttons, **self.language
+ )
+
+ # the full side menu
+ self.side_menu = webquiz_templates.side_menu.format(
+ discussion_list=discussion_list,
+ version=self.metadata.version,
+ department=department,
+ institution=institution,
+ side_questions=self.language['questions'] if self.number_questions>0 else '',
+ question_buttons=question_buttons,
+ copyright_years=self.metadata.copyright[:self.metadata.copyright.index(' ')],
+ **self.language)
+
+ def add_question_javascript(self):
+ """
+ Add the javascript for the questions to self and write the javascript
+ initialisation file, <quiz>/quiz_specs.js, for the quiz. When the quiz
+ page is loaded, WebQuizInit reads the quiz_specs initialisation file to
+ load the answers to the questions, and the headers for the discussion
+ items. We don't explicitly list quiz_specs.js in the meta data for the
+ quiz page because we want to hide this information from the student,
+ although they can easily get this if they open by the javascript
+ console and know what to look for.
+ """
+
+ try:
+ os.makedirs(self.quiz_name, exist_ok=True)
+ os.chmod(self.quiz_name, mode=0o755)
+ with codecs.open(os.path.join(self.quiz_name, 'wq-' + self.quiz_name + '.js'), 'w',
+ encoding='utf8') as quiz_specs:
+ if self.number_discussions > 0:
+ for (i, d) in enumerate(self.quiz.discussion_list):
+ quiz_specs.write('Discussion[{}]="{}";\n'.format(i+1, d.heading))
+ if self.number_questions > 0:
+ for (i, question) in enumerate(self.quiz.question_list):
+ # QuizSpecifications is a 0-based array
+ quiz_specs.write('QuizSpecifications[{}]=[];\n'.format(i+1))
+ quiz_specs.write('QuizSpecifications[{}].type="{}";\n'.format(i+1, question.type))
+ if question.type == 'input':
+ quiz_specs.write('QuizSpecifications[{}].value="{}";\n'.format(i+1,
+ question.answer.lower() if question.comparison=='lowercase'
+ else question.answer
+ )
+ )
+ quiz_specs.write('QuizSpecifications[{}].comparison="{}";\n'.format(i+1, question.comparison))
+ else:
+ quiz_specs.write(''.join(
+ 'QuizSpecifications[{}][{}]={};\n'.format(i+1, j, s.correct)
+ for (j, s) in enumerate(question.items)
+ )
+ )
+
+ if self.quiz.hide_side_menu:
+ quiz_specs.write('toggle_side_menu();\n')
+ if self.quiz.one_page:
+ quiz_specs.write('onePage = true;\n')
+ if self.quiz.random_order:
+ quiz_specs.write('shuffleQuestions();\n')
+ quiz_specs.write('initSession();\n')
+ if self.number_discussions+self.number_questions>0:
+ quiz_specs.write('gotoQuestion({});'.format(
+ -1 if self.number_discussions>0 else 1)
+ )
+
+ except Exception as err:
+ self.webquiz_error('error writing quiz specifications', err)
+
+ self.javascript = webquiz_templates.questions_javascript.format(
+ webquiz_url=self.webquiz_url,
+ mathjax=self.settings['mathjax']
+ )
+ self.webquiz_init = webquiz_templates.webquiz_init.format(
+ number_questions=self.number_questions,
+ number_discussions=self.number_discussions,
+ quiz_file=self.quiz_name,
+ )
+
+ def add_quiz_header_and_questions(self):
+ r'''
+ Write the quiz head and the main body of the quiz.
+ '''
+ if self.quiz.one_page:
+ arrows = ''
+ else:
+ arrows = webquiz_templates.navigation_arrows.format(
+ question_number=self.quiz.discussion_list[0].heading
+ if self.quiz.discussion_list != []
+ else '1' if self.quiz.question_list > []
+ else '',
+ **self.language
+ )
+
+ # specify the quiz header - this will be wrapped in <div class="question-header>...</div>
+ self.quiz_header = webquiz_templates.quiz_header.format(
+ title=self.quiz.title,
+ arrows=arrows,
+ **self.language
+ )
+
+ # index for quiz
+ if self.quiz.quiz_index != []:
+ # add index to the web page
+ self.quiz_questions += webquiz_templates.quiz_index_div.format(
+ title=self.quiz.title if self.quiz.title!='' else self.quiz.unit_name,
+ quiz_index='\n '.join(
+ webquiz_templates.index_item.format(
+ url=q.url,
+ title='{} {}. {}'.format(self.language['quiz'],num+1,q.title)
+ if q.prompt else q.title,
+ ) for (num, q) in enumerate(self.quiz.quiz_index)),
+ **self.language)
+ # write a javascript file for displaying the menu
+ # quizmenu = the index file for the quizzes in this directory
+ with codecs.open('quizindex.js', 'w', encoding='utf8') as quizmenu:
+ quizmenu.write('var QuizTitles = [\n{titles}\n];\n'.format(
+ titles=',\n'.join(" ['{}', '{}']".format(
+ '{} {}. {}'.format(self.language['quiz'],num+1,q.title)
+ if q.prompt else q.title,
+ q.url)
+ for (num,q) in enumerate(self.quiz.quiz_index))
+ )
+ )
+ quizmenu.write(webquiz_templates.create_quizindex_menu)
+
+ # now comes the main page text
+ # discussion(s) masquerade as negative questions
+ if self.quiz.discussion_list != []:
+ dnum = 0
+ for d in self.quiz.discussion_list:
+ dnum += 1
+ self.quiz_questions += webquiz_templates.discussion.format(
+ dnum=dnum,
+ discussion=d,
+ display='inline' if self.quiz.one_page else 'none',
+ heading=webquiz_templates.discussion_heading.format(d.heading)
+ if self.quiz.one_page else ''
+ )
+
+ # finally we print the questions
+ if self.quiz.question_list != []:
+ self.quiz_questions += ''.join(
+ webquiz_templates.question_wrapper.format(
+ qnum=qnum + 1,
+ question_number='{} {}. '.format(self.language.question, qnum+1)
+ if self.quiz.one_page else '',
+ display='inline' if self.quiz.one_page else 'none',
+ question=self.print_question(quiz_question, qnum + 1),
+ feedback=self.print_feedback(quiz_question, qnum + 1)
+ )
+ for (qnum, quiz_question) in enumerate(self.quiz.question_list))
+
+ def print_question(self, question, qnum):
+ r'''Here:
+ - question is the question
+ - qnum is the number of the question
+ '''
+ if question.type == 'input':
+ self.webquiz_debug('Q{}: after_text={}.'.format(qnum, question.after_text))
+ question_options = webquiz_templates.input_answer.format(
+ size=5+len('{}'.format(question.answer)),
+ after_text=question.after_text,
+ qnum=qnum,
+ answer=self.language['answer']+':' if question.prompt else ''
+ )
+ elif question.type in ['single', 'multiple']:
+ question_options = webquiz_templates.choice_answer.format(
+ after_text=question.after_text,
+ choices='\n'.join(self.print_choices(qnum, question, choice)
+ for choice in range(len(question.items)))
+ )
+ else:
+ self.webquiz_error('Unknown question type "{}" in question {}'.format(question.type, qnum))
+ return webquiz_templates.question_text.format(
+ qnum=qnum,
+ question_text=question.text,
+ nextquestion='' if self.quiz.one_page else webquiz_templates.nextquestion.format(**self.language),
+ question_options=question_options,
+ **self.language)
+
+ def print_choices(self, qnum, question, part):
+ r'''
+ Here:
+ - qnum = question number
+ - question = current question
+ - part = number of the option we need to process.
+ We put the parts into question.columns multicolumn format, so we have
+ to add '<tr>' and '</tr>' tags depending on part.
+ '''
+ choice = question.items[part]
+ item = '<tr>' if question.columns == 1 or (part % question.columns) == 0 else '<td>&nbsp;</td>'
+ if question.type == 'single':
+ item += webquiz_templates.single_item.format(choice=choice.symbol, qnum=qnum, text=choice.text)
+ elif question.type == 'multiple':
+ item += webquiz_templates.multiple_item.format(
+ choice=choice.symbol,
+ qnum=qnum,
+ optnum=part,
+ text=choice.text
+ )
+ else:
+ item += '<!-- internal error: %s -->\n' % question.type
+ self.webquiz_error('Unknown question type "{}" in question {}'.format(question.type, qnum))
+
+ if question.columns == 1 or (part+1) % question.columns == 0 or part == len(question.items) - 1:
+ item += ' </tr><!-- part={}, cols={}, # answers = {} -->\n'.format(
+ part, question.columns, len(question.items))
+ return item
+
+ def print_feedback(self, question, qnum):
+ r'''
+ Generate the HTML for displaying the feedback help text when the user
+ answers a question.
+ '''
+ if question.type == 'input':
+ feedback = webquiz_templates.tf_feedback_text.format(
+ choice=qnum,
+ feedback='true',
+ correct_answer=self.language.correct,
+ answer2='',
+ text=question.feedback_right)
+ feedback += webquiz_templates.tf_feedback_text.format(
+ choice=qnum,
+ feedback='false',
+ correct_answer=self.language.incorrect,
+ answer2=self.language.try_again,
+ text=question.feedback_wrong)
+ elif question.type == "single":
+ feedback = '\n' + '\n'.join(
+ webquiz_templates.single_feedback.format(
+ qnum=qnum,
+ part=snum + 1,
+ correct_answer=self.language.correct if s.correct == 'true' else self.language.incorrect,
+ alpha_choice=self.language.choice.format(s.symbol),
+ feedback=s.feedback,
+ **self.language)
+ for (snum, s) in enumerate(question.items))
+ elif question.type == "multiple":
+ feedback = '\n' + '\n'.join(webquiz_templates.multiple_feedback.format(
+ qnum=qnum,
+ part=snum + 1,
+ correct_answer=getattr(self.language, s.correct).capitalize(),
+ feedback=s.feedback,
+ multiple_choice_opener=self.language.multiple_incorrect.
+ format(s.symbol),
+ **self.language)
+ for (snum, s) in enumerate(question.items)
+ )
+ feedback += webquiz_templates.multiple_feedback_correct.format(
+ qnum=qnum,
+ feedback='\n'.join(webquiz_templates.multiple_feedback_answer.format(
+ correct_answer=getattr(self.language, s.correct).capitalize(),
+ reason=s.feedback) for s in question.items),
+ **self.language)
+ else:
+ self.webquiz_error('Unknown question type "{}" in question {}'.format(question.type, qnum))
+
+ return '<div class="answer">' + feedback + '</div>'
diff --git a/Master/texmf-dist/scripts/webquiz/webquiz_templates.py b/Master/texmf-dist/scripts/webquiz/webquiz_templates.py
new file mode 100755
index 00000000000..a3c8f849945
--- /dev/null
+++ b/Master/texmf-dist/scripts/webquiz/webquiz_templates.py
@@ -0,0 +1,391 @@
+r'''
+-----------------------------------------------------------------------
+ webquiz_templates | html template file
+-----------------------------------------------------------------------
+
+ Copyright (C) Andrew Mathas, University of Sydney
+
+ Distributed under the terms of the GNU General Public License (GPL)
+ http://www.gnu.org/licenses/
+
+ This file is part of the WebQuiz system.
+
+ <Andrew.Mathas@sydney.edu.au>
+----------------------------------------------------------------------
+'''
+
+# -*- encoding: utf-8 -*-
+
+## The quiz web pages are built using the following "template" strings
+
+# html meta statements
+html_meta = r'''<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
+ <meta name="viewport" content="width=device-width,initial-scale=1.0">
+ <meta name="generator" content="WebQuiz {version} (http://www.maths.usyd.edu.au/u/mathas/WebQuiz/webquiz-online-manual.html)">
+ <meta name="description" content="{description}">
+ <meta name="authors" content="WebQuiz: {authors}">
+ <meta name="organization" content="{department}, {institution}">
+ <meta name="Copyright" content="WebQuiz: {copyright}">
+ <meta name="keywords" content="WebQuiz, TeX4ht, make4ht, latex, python, quiz, mathematics">
+ <link href="{webquiz_url}/css/webquiz-{theme}.css" type="text/css" rel="stylesheet">
+ <link href="{quiz_file}/{quiz_file}.css" type="text/css" rel="stylesheet">
+'''
+
+# javascript for setting up the questions
+questions_javascript = r''' <script src="{webquiz_url}/js/webquiz.js"></script>
+ <script defer src="{mathjax}?config=MML_CHTML"></script>'''
+
+mathjs=r' <script defer src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/5.4.0/math.min.js"></script>'
+
+webquiz_init = r'''<div style="display: none;">
+ <script src="quizindex.js"></script>
+ <script>WebQuizInit({number_questions}, {number_discussions}, '{quiz_file}');</script>
+ </div>'''
+
+# Bread crumbs including a drop down menu for all of the quizzes for the unit.
+# The drop-down-menu is added by create_quizindex_menu() in webquiz.js
+breadcrumb_line_text = ' <li>{text}</li>\n'
+breadcrumb_line_url = ' <li><a href="{url}">{text}</a></li>\n'
+breadcrumb_quizindex = r''' <li><a href="{quizzes_url}">{quizzes}</a>
+ <span onclick="toggle_quizindex_menu();" id="quizzes-menu-icon"></span>
+ <ul id="quizindex-menu" onclick="toggle_quizindex_menu();"></ul>
+ </li>
+'''
+create_quizindex_menu = r'''// construct the drop down menu if QuizTitles has some entries
+if (QuizTitles.length > 0 && quizindex_menu) {
+ create_quizindex_menu();
+}
+'''
+breadcrumbs = r'''<div class="breadcrumbs">
+ <nav>
+ <div class="navleft">
+ <ul>{crumbs} </ul>
+ </div>
+ </nav>
+ </div>
+'''
+
+# Should we add a menu to change the theme dynamically? If so then the code
+# below should be added to the breadcrumbs and then fixed a little. Perhaps the
+# trickiest bit is finding the current list of supported themes.
+theme_menu=r'''
+ <div class="navright" >
+ <span onclick="toggle_theme_menu();">Theme &#9881;</span>
+ <ul><li>
+ <ul id="theme-menu" onclick="toggle_theme_menu();">
+ <li>one</li><li>two</li>
+ </ul>
+ </li>
+ </ul>
+ </div>
+'''
+
+# Add a drop-down menu to the navigation to dynamically change the theme?
+
+# question buttons
+button = r' <div id="button{b}" class="button {cls}" content=" " onClick="gotoQuestion({b})">{b}</div>'
+discuss = r' <li id="button-{b}" class="discussion" onClick="gotoQuestion(-{b})">{title}</li>'
+side_menu = r'''<div id="menu-icon">
+ <span id="sidelabelclosed" class="question-label" onclick="toggle_side_menu();">&#10070;</span>
+ <span id="sidelabelopen" class="question-label" onclick="toggle_side_menu();">&#10006;&nbsp;{side_questions}
+ </span>
+ </div>
+ <div id="sidemenu" class="side-menu">{discussion_list}{question_buttons}
+ <div class="school">
+ {department}<p>
+ {institution}
+ </div>
+ <div class="copyright">
+ <a href="http://www.maths.usyd.edu.au/u/mathas/WebQuiz/credits.html">
+ <span class="webquizlogo">WebQuiz</span><span class="TEX">T<span class="E">E</span>X</span>
+ </a>
+ <br>&copy; Copyright<br><span style="overflow: visible;">{copyright_years}</span>
+ </div>
+ </div>'''
+
+question_buttons = r'''
+ <div class="buttons">
+ <br>{buttons}
+ </div>
+ <table class="marking-key">
+ <tr><td class="star">&starf;</td><td style="width: 14ex;">{side_menu_star}</td></tr>
+ <tr><td class="tick">&check;</td><td>{side_menu_tick}</td></tr>
+ <tr><td class="cross">&cross;</td><td>{side_menu_cross}</td></tr>
+ </table>'''
+
+# quiz title and navigation arrows
+quiz_header = r'''<div class="quiz-header">
+ <div class="quiz-title">{title}</div><div></div>{arrows}
+ </div>'''
+navigation_arrows = r'''
+ <span id="question-label" class="question-label">{question}</span>
+ <span id="question-number" class="question-label">{question_number}</span>
+ <span class="arrows">
+ <a onClick="nextQuestion(-1);" title="{previous_question}">&#x25c4;</a>
+ <span class="question-label">{questions}</span>
+ <a onClick="nextQuestion(1);" title="{next_question}">&#x25ba;</a>
+ </span>'''
+
+# discussion item
+discussion = r'''<div id="question-{dnum}" class="question" style="display:{display};">
+ {heading}{discussion.text}
+ </div>
+'''
+discussion_heading = r'''<div class="question-label">{}</div>
+ '''
+
+#quiz index
+quiz_index_div = r''' <div class="quiz-index">
+ <ul>
+ {quiz_index}
+ </ul>
+ </div>'''
+index_item = r'''<li><a href={url}>{title}</a></li>'''
+
+# now we come to the question wrappers
+question_wrapper = r'''<div id="question{qnum}" class="question" style="display:{display};">
+ <span class="question-label">{question_number}</span>{question}
+ {feedback}
+ </div>
+'''
+
+question_text = r''' {question_text}
+ <form id="Q{qnum}Form" onSubmit="return false;">
+ {question_options}
+ <p>
+ <input type="button" value="{check_answer}" name="answer" class="input-button" onClick="checkAnswer({qnum});"/>
+ {nextquestion}
+ </p>
+ </form>
+'''
+nextquestion='<input type="button" value="{next_question}" class="input-button" title="{next_question}" name="next" onClick="nextQuestion(1);"/>'
+
+# Questions and feedback:
+input_answer = '{answer}&nbsp;<input type="text" onChange="checkAnswer({qnum});" size="{size}"/>{after_text}'
+choice_answer = '<table class="question-choices">{choices}</table>{after_text}'
+input_single = '\n<input type="hidden" name="Q{qnum}hidden"/>'
+
+single_item = '''<td><input type="radio" name="Q{qnum}option"/></td>
+<td class="brown" >{choice}</td><td><div class="question-choices">{text}</div></td>
+'''
+multiple_item = '''<td><input type="checkbox" name="Q{qnum}option{optnum}"/></td>
+<td class="brown" >{choice}</td><td><div class="question-choices">{text}</div></td>
+'''
+
+tf_feedback_text = r'''
+ <div id="q{choice}{feedback}" class="feedback"><em class="dazzle">{correct_answer}</em> <em>{answer2}</em>
+ <div>{text}</div>
+ </div>'''
+single_feedback = r'''
+ <div id="q{qnum}feedback{part}" class="feedback">
+ <em>{alpha_choice} <span class="dazzle">{correct_answer}</span></em>
+ <div>{feedback}</div>
+ </div>'''
+
+multiple_feedback = r'''
+ <div id="q{qnum}feedback{part}" class="feedback">
+ <em>{one_mistake}</em><br>{multiple_choice_opener} <span class="dazzle">{correct_answer}</span>.
+ <div>{feedback}</div>
+ </div>'''
+multiple_feedback_correct = r'''
+ <div id="q{qnum}feedback0" class="feedback"><em class="dazzle">{correct}</em>
+ <ol>
+{feedback}
+ </ol>
+ </div>'''
+multiple_feedback_answer = ' <li><em>{correct_answer}</em> {reason}</li>'
+
+initialise_invite = r'''WebQuiz needs to be initialised. In order to display quiz web pages
+WebQuiz needs to copy some css and javascript files into a directory
+that is accessible from your webserver.
+
+Do you want to initialise WebQuiz now [Y/n]? '''
+
+# no script error when javascript is not enabled
+no_script = r'''<noscript>
+ <div class="warning">
+ If you are reading this message either your browser does not support
+ JavaScript or because JavaScript is not enabled. You will need to enable
+ JavaScript and then reload this page in order to use this quiz.
+ </div>
+ </noscript>'''
+
+######################################################################
+# the remaining templates prompt the user when initialising webquiz
+######################################################################
+
+initialise_introduction = r'''
+WebQuiz Initialisation
+======================
+If you want to install the web components of WebQuiz files into a "system"
+directory then you should quit this program (use control-C on unix-like
+systems) and then run
+ webquiz --initialise
+from an administrators account or, on unix-like systems, use:
+ sudo webquiz --initialise
+
+If you want to continue then WebQuiz will guide you through the
+initialisation process. For more information about the steps involved
+see Section 3.2 of the WebQuiz manual On many systems, you can open
+the webquiz manual using the command: texdoc webquiz
+'''
+
+webroot_request = r'''----
+To make files accessible from your web server WebQuiz needs:
+ o A directory, or folder, on your server that is visible from your
+ web server. This directory MUST be accessible from the web. It can
+ either be a "system" directory or in your personal web directories.
+ o The relative URL for accessing these files from the web. This is
+ the part of the URL that you have to add to your "root" URL to
+ access the files. For example, if the URL for your department is
+ http://www.maths.usyd.edu.au/
+ and the WebQuiz files can be accessed as
+ http://www.maths.usyd.edu.au/teaching/WebQuiz
+ then the relative URL for the WebQuiz files is /teaching/WebQuiz
+
+It is recommended that you create a separate directory for WebQuiz on your
+web server. The location of the files on your web server will depend on
+your operating system and system configuration. A common sysem location
+for the WebQuiz web directory on a {platform} system is
+ {webquiz_dir}
+'''
+
+not_installed = r'''
+According to kpsewhich, the TeX components of WebQuiz are not installed
+on your system. If you have downloaded the WebQuiz zip file from ctan
+then try using:
+ > webquiz --tex-install
+If the TeX components are already installed then something has gone
+horribly wrong. If you think this is a bug please report it by creating
+an issue at {}
+'''
+
+oserror_copying = r'''There was a problem copying files to {web_dir}
+Error: {err}
+
+Please give a different directory
+'''
+
+webquiz_url_message = r'''
+Please give the relative URL for the WebQuiz web directory. For example,
+if the base of your web server's directory is /var/www/html/ and the
+WebQuiz web directory is /var/www/html/courses/WebQuiz then the
+relative URL for the WebQuiz directory would be /courses/WebQuiz.
+
+WebQuiz relative URL [{}]: '''
+
+initialise_ending = r'''
+You should now be able to build web pages using webquiz! As an initial
+test you can try to build the example files from the webquiz manual
+by going to the directory
+ {web_dir}/doc/examples
+If pstricks and dvisgvm are properly configured (see Section 3.3 of
+the manual), then you can also try building the online manual, by
+going to the directory
+ {web_dir}/doc/examples
+and typing:
+ webquiz webquiz-online-manual
+
+If you want to change the default webquiz settings please use:
+ webquiz --edit-settings
+'''
+
+webquiz_url_warning = r'''
+WebQuiz has not been initialised. To remove the warning message from
+the web page please use
+ webquiz --initialise
+to install the WebQuiz javascript and css files.
+'''
+
+text_initialise_warning = r'''
+WebQuiz has not yet been initialised. To remove this warning please use
+ webquiz --initialise
+to install the WebQuiz web files onto your system.
+'''
+
+web_initialise_warning = r'''
+ <div id="initialisewarning" class="warning">
+ WebQuiz has not yet been initialised. To remove this warning box please use
+ <blockquote>
+ webquiz --initialise
+ </blockquote>
+ to install the WebQuiz web files on your system.
+ <button style="float: right" onclick="document.getElementById('initialisewarning').style.display='none'">OK</button>
+ </div>
+'''
+
+rc_permission_error = r'''
+Attempting to write the rcfile to {rcfile}
+resulted in the error:
+ {error}
+
+To write the WebQuiz rcfile into this directory you may need to quit
+and run webquiz again, either using an administrator account, or using
+sudo on linux/macosx.
+
+Press the key 1-3, followed by RETURN, to:
+ 1. Try to save to {rcfile} again
+ 2. Save to the user rcfile {alt_rcfile}
+ 3. Give a different location for the rcfile
+Press any other key to exit without saving.
+'''
+
+permission_error = r'''
+You do not have permission to write to {}.
+
+To install WebQuiz files into this directory you may need to quit and
+run webquiz using either an administrator account, or using sudo on
+linux/macosx.
+
+Alternatively, please give a different directory.
+'''
+
+insufficient_permissions = r'''
+Insufficient permissions. Try using sudo or using an admisitrator account.
+{}
+'''
+
+webquiz_url_warning = r'''
+WARNING: most of the time, but not always, the relative URL will be a
+suffix of the web directory name, which is not the case with your
+settings. Your URL may well be correct, however, if you have made a
+mistake then you can change this at any time using the command:
+ webquiz --initialise
+'''
+
+edit_settings = r'''----
+In the webquizrc file you can set global defaults for the following:
+ breadrumbs
+ colour theme
+ department
+ department_url
+ engine
+ institution
+ institution
+ language
+Leave these blank if you do not want default values. There are three
+additional "advanced: options:
+ mathjax
+ webquiz_layout
+ webquiz_mk4
+Please only change these settings if you know what you are doing
+because incorrect values for these settings will break WebQuiz.
+
+With each setting the default value is printed inside square brackets.
+For example, as [default]. Press RETURN to accept the default value.
+Except for the location of the WebQuiz web directory all of these
+settings are easy to change at any time using the command:
+ webquiz --edit-settings
+'''
+
+advanced_settings = r'''
+** The remaining settings are advanced settings that you probably **
+** do not want to change at this time. Incorrect values for these **
+** settings will break WebQuiz so accept the defaults unless you **
+** know what you are doing. **
+'''
+
+# and now for the webquiz help message
+webquiz_help_message = r'''
+WebQuiz allows you to write interactive online quizzes using latex
+'''
diff --git a/Master/texmf-dist/scripts/webquiz/webquiz_util.py b/Master/texmf-dist/scripts/webquiz/webquiz_util.py
new file mode 100755
index 00000000000..7a06108e1b0
--- /dev/null
+++ b/Master/texmf-dist/scripts/webquiz/webquiz_util.py
@@ -0,0 +1,128 @@
+#!/usr/bin/env python3
+r'''
+------------------------------------------------------------------------------
+ webquiz_util | utilty functions
+------------------------------------------------------------------------------
+ Copyright (C) Andrew Mathas, University of Sydney
+
+ Distributed under the terms of the GNU General Public License (GPL)
+ http://www.gnu.org/licenses/
+
+ This file is part of the WebQuiz system.
+
+ <Andrew.Mathas@sydney.edu.au>
+------------------------------------------------------------------------------
+'''
+
+import os
+import subprocess
+import shutil
+import stat
+import sys
+import traceback
+
+# ---------------------------------------------------------------------------------------
+# Return the full path for a file in the webquiz directory
+webquiz_file = lambda file: os.path.join(os.path.dirname(os.path.realpath(__file__)), file)
+
+def shell_command(cmd):
+ r'''
+ Short-cut for shell commands
+ '''
+ return subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True).decode('ascii').strip()
+
+def kpsewhich(search):
+ r'''
+ Short-cut to access kpsewhich output. usage: kpsewhich('-var-value=TEXMFLOCAL')
+ '''
+ return subprocess.check_output('kpsewhich ' + search, stderr=subprocess.STDOUT, shell=True).decode('ascii').strip()
+
+# ---------------------------------------------------------------------------------------
+class MetaData(dict):
+ r"""
+ A dummy class for reading, accessing and storing key-value pairs from
+ a file. Any internal spaces in the key name are replaced with underscores
+ and lines without a key-value pair are ignored.
+
+ The key-value pairs are available as both attributes and items
+
+ Usage: MetaData(filename) or MetaData(filename, key-value pairs)
+ """
+
+ def __init__(self, filename, **args):
+ dict.__init__(self)
+ # add attributes from **args
+ for key in args:
+ setattr(self, key, args[key])
+ with open(filename, 'r') as meta:
+ for line in meta:
+ if '=' in line:
+ key, val = line.strip().split('=')
+ if key.strip() != '':
+ self.__setitem__(key.strip().lower().replace(' ', '_'),
+ val.strip())
+ setattr(self,
+ key.strip().lower().replace(' ', '_'),
+ val.strip())
+
+
+#################################################################################
+def webquiz_debug(debugging, *arg):
+ if debugging:
+ sys.stderr.write(' '.join('{}'.format(a) for a in arg)+'\n')
+
+
+#################################################################################
+def webquiz_error(debugging, msg, err=None):
+ r'''
+ Consistent handling of errors in magthquiz: print the message `msg` and
+ exist with error code `err.errno` if it is available.abs
+ '''
+ print('{dash}WebQuiz error:\n {msg}\n{dash}'.format(
+ msg=msg, dash='-'*40+'\n')
+ )
+
+ if err is not None:
+ trace = traceback.extract_tb(sys.exc_info()[2])
+ filename, lineno, fn, text = trace[-1]
+ print('File: {}, line number: {}\nError {} in {}: {}'.format(
+ filename, lineno, err, fn, text))
+
+ if debugging and err is not None:
+ raise
+
+ if hasattr(err, 'errno'):
+ sys.exit(err.errno)
+
+ sys.exit(1)
+
+
+###############################################################################
+def copytree(src, dst, symlinks=False, ignore=None):
+ r''' Recursively copy directory tree, fixing shutil.copytree
+ from https://stackoverflow.com/questions/1868714
+ '''
+ if not os.path.exists(dst):
+ os.makedirs(dst)
+ shutil.copystat(src, dst)
+ lst = os.listdir(src)
+ if ignore:
+ excl = ignore(src, lst)
+ lst = [x for x in lst if x not in excl]
+ for item in lst:
+ s = os.path.join(src, item)
+ d = os.path.join(dst, item)
+ if symlinks and os.path.islink(s):
+ if os.path.lexists(d):
+ os.remove(d)
+ os.symlink(os.readlink(s), d)
+ try:
+ st = os.lstat(s)
+ mode = stat.S_IMODE(st.st_mode)
+ os.lchmod(d, mode)
+ except OSError:
+ pass # lchmod not available
+ elif os.path.isdir(s):
+ copytree(s, d, symlinks, ignore)
+ else:
+ shutil.copy2(s, d)
diff --git a/Master/texmf-dist/scripts/webquiz/webquiz_xml.py b/Master/texmf-dist/scripts/webquiz/webquiz_xml.py
new file mode 100755
index 00000000000..b1db71a2dab
--- /dev/null
+++ b/Master/texmf-dist/scripts/webquiz/webquiz_xml.py
@@ -0,0 +1,386 @@
+r'''
+-----------------------------------------------------------------------------
+ webquiz_xml | xml reader for reading the xml file generated by tex4ht
+-----------------------------------------------------------------------------
+
+ Copyright (C) Andrew Mathas and Donald Taylor, University of Sydney
+
+ Distributed under the terms of the GNU General Public License (GPL)
+ http://www.gnu.org/licenses/
+
+ This file is part of the Math_quiz system.
+
+ <Andrew.Mathas@sydney.edu.au>
+ <Donald.Taylor@sydney.edu.au>
+-----------------------------------------------------------------------------
+'''
+
+# -*- encoding: utf-8 -*-
+
+import xml.sax
+
+# imports of webquiz code
+import webquiz_util
+
+# ---------------------------------------------------------------------------------------
+def ReadWebQuizXmlFile(quizfile, defaults):
+ r'''
+ Set up, call and then return the xml parser
+ for the quiz web page
+ '''
+ parser = xml.sax.make_parser()
+ quiz = QuizHandler(defaults)
+ parser.setContentHandler(quiz)
+ parser.setErrorHandler(quiz)
+ parser.setDTDHandler(quiz) # as far as I can see this does nothing...
+ parser.parse(quizfile)
+ parser.close()
+ return quiz
+
+
+# ---------------------------------------------------------------------------------------
+class Data(object):
+ r'''
+ A wrapper object class that holds the data for the different
+ components of the quiz.
+ '''
+ def __init__(self, **args):
+ '''
+ Accepts key-value pairs, each of which is stored as an attribute
+ '''
+ self._items = args.items()
+ for key, val in args.items():
+ setattr(self, key, val)
+
+
+class QuizHandler(xml.sax.ContentHandler):
+ """
+ The content handler gives the xml tags to `startElement`, which
+ initialises the webquiz tags, and then `endElement` attaches the
+ content of each webquiz tag tothe appropriate part of `self`. Any end
+ tag that is ot special to webquiz has its contents appended to
+ `self.text`. Any tag that contains `DeFaUlT` is set to the system
+ default using the `defaults` dictionary.
+ """
+
+ def __init__(self, defaults):
+ self.defaults = defaults
+
+ # arrays for the different quiz components
+ self.discussion_list = []
+ self.question_list = []
+ self.quiz_index = []
+
+ # these will contain the link and meta elements from the xml file but they
+ # are ignored by webquiz.py
+ self.link_list = []
+ self.meta_list = []
+
+ # to add mathjs when an eval comparison is used
+ self.mathjs = False
+
+ # the following tags have defaults set by `defaults`
+ self.setting_tags = [
+ 'department',
+ 'department_url',
+ 'institution',
+ 'institution_url',
+ 'language',
+ 'theme',
+ ]
+ # quiz data
+ for tag in self.setting_tags:
+ setattr(self, tag, defaults[tag])
+ self.breadcrumb = ''
+ self.text = ''
+ self.after_text = ''
+ self.title = ''
+ self.unit_code = ''
+ self.unit_name = ''
+
+ # keep track of current tags for debugging...
+ self.current_tags=[]
+
+ def webquiz_debug(self, msg):
+ r'''
+ Customised debugging message for the xml module
+ '''
+ webquiz_util.webquiz_debug(self.defaults.debugging, 'xml: '+msg)
+
+ def webquiz_error(self, msg, err=None):
+ r'''
+ Customised error message for the xml module
+ '''
+ webquiz_util.webquiz_error(self.defaults.debugging, 'xml: '+msg, err)
+
+ def set_default_attribute(self, key, value):
+ ''' Set the attribute `key` of self, using the default value if
+ `value=='DeFaUlT'`.
+ '''
+ if value.strip() == 'DeFaUlT':
+ setattr(self, key, self.defaults[key])
+ else:
+ setattr(self, key, value)
+ self.webquiz_debug('Just set "{}" equal to "{}" from "{}"'.format(key, getattr(self, key), value))
+
+ #---- start of start elements --------------------------------------------
+ def startElement(self, tag, attributes):
+ '''
+ At the start of each webquiz xml tag we need to pull out the
+ attributes and place
+ '''
+ self.webquiz_debug('Starting tag for '+tag)
+ self.current_tags.append(tag)
+
+ if hasattr(self, 'start_'+tag):
+ getattr(self, 'start_'+tag)(attributes)
+
+ elif tag in ['department', 'institution', 'uni']:
+ for key in attributes.keys():
+ self.set_default_attribute(tag, attributes.get(key))
+
+ def start_webquiz(self, attributes):
+ r'''
+ Start element for tag="webquiz". Initialise the quix and extract
+ and process the list of attributes.
+ '''
+ for key in attributes.keys():
+ self.set_default_attribute(key, attributes.get(key))
+
+ # convert the following attibutes to booleans
+ for key in ['debugging', 'hide_side_menu', 'one_page', 'pst2pdf', 'random_order']:
+ setattr(self, key, getattr(self, key)=='true')
+
+ setattr(self, 'language', self.language.lower())
+ setattr(self, 'theme', self.theme.lower())
+
+ # set debugging mode from the latex file...from this point on
+ self.defaults.debugging = self.defaults.debugging or self.debugging
+
+ def start_link(self, attributes):
+ r'''
+ Start element for tag="link"
+ '''
+ self.link_list.append({key: attributes.get(key) for key in attributes.keys()})
+
+ def start_meta(self, attributes):
+ r'''
+ Start element for tag="meta"
+ '''
+ self.meta_list.append({key: attributes.get(key) for key in attributes.keys()})
+
+ def start_breadcrumb(self, attributes):
+ r'''
+ Start element for tag="breadcrumb"
+ '''
+ self.set_default_attribute('breadcrumbs', attributes.get('breadcrumbs'))
+
+ def start_unit_name(self, attributes):
+ r'''
+ Start element for tag="unit_name"
+ '''
+ self.set_default_attribute('unit_url', attributes.get('url'))
+ self.quizzes_url = attributes.get('quizzes_url')
+ if self.quizzes_url == 'DeFaUlT':
+ self.quizzes_url = self.unit_url + '/Quizzes'
+
+ def start_discussion(self, attributes):
+ r'''
+ Start element for tag="discussion"
+ '''
+ discussion = Data(heading = '',
+ short_heading = '',
+ text = '' # The text of the discussion
+ )
+ self.discussion_list.append(discussion)
+
+ def start_question(self, attributes):
+ r'''
+ Start element for tag="question"
+ '''
+ self.question_list.append(
+ Data(text = '', # The text of the question
+ type = None, # input, or single or multiple choice
+ after_text = '' # text at end of question
+ )
+ )
+
+ def start_answer(self, attributes):
+ r'''
+ Process the different question types, items choice and feedback
+ '''
+ if self.question_list[-1].type != None:
+ self.webquiz_error('question {} has too many question types: {} and input'.format(
+ len(self.question_list)+1, self.question_list[-1].type)
+ )
+ self.question_list[-1].type = 'input'
+ self.question_list[-1].answer = ''
+ self.question_list[-1].feedback_right = ''
+ self.question_list[-1].feedback_wrong = ''
+ self.question_list[-1].text += self.text
+ self.text = ''
+
+ self.question_list[-1].comparison = attributes.get('comparison')
+ self.question_list[-1].prompt = attributes.get('prompt')=='true'
+ if self.question_list[-1].comparison in ['complex', 'number']:
+ self.mathjs = True
+
+ def start_choice(self, attributes):
+ r'''
+ Start element for tag="choice"
+ '''
+ if self.question_list[-1].type != None:
+ self.webquiz_error('question {} has too many question types: {} and choice'.format(
+ len(self.question_list)+1, self.question_list[-1].type)
+ )
+ self.question_list[-1].type = attributes.get('type')
+ self.question_list[-1].columns = int(attributes.get('columns'))
+ self.question_list[-1].items = []
+ self.question_list[-1].correct = 0
+ self.question_list[-1].text += self.text
+ self.text = ''
+
+ def start_item(self, attributes):
+ r'''
+ Start element for tag="item"
+ '''
+ self.question_list[-1].items.append(
+ Data(correct= attributes.get('correct'),
+ symbol=attributes.get('symbol'),
+ feedback='',
+ text=''
+ )
+ )
+ if attributes.get('correct')=='true':
+ self.question_list[-1].correct += 1
+
+ def start_index_item(self, attributes):
+ r'''
+ Finally look after the index file
+ '''
+ self.quiz_index.append(Data(
+ prompt=attributes.get('prompt')=='true',
+ url=attributes.get('url'),
+ title=''
+ )
+ )
+
+ def start_when(self, attributes):
+ r'''
+ start element for tag="when"
+ '''
+ if self.text.strip() != '':
+ self.question_list[-1].after_text += ' '+self.text.strip()
+ self.webquiz_debug('After_text is now {}'.format(self.question_list[-1].after_text))
+ self.text = ''
+ self.current_tags[-1] = 'feedback_'+attributes.get('type')
+
+ #---- end of start elements ---------------------------------------------
+
+ def endElement(self, tag):
+ self.webquiz_debug('ending tag for {} (should be {})'.format(tag, self.current_tags[-1]))
+
+ reset_text = True
+ if hasattr(self, 'end_'+tag):
+ getattr(self, 'end_'+tag)()
+ self.text = ''
+
+ elif tag in self.setting_tags:
+ self.set_default_attribute(tag, self.text)
+ self.text = ''
+
+ elif tag in ['heading', 'short_heading']:
+ setattr(self.discussion_list[-1], tag, self.text.strip())
+
+ elif tag in ['breadcrumb', 'title', 'unit_code', 'unit_name']:
+ setattr(self, tag, self.text.strip())
+
+ else:
+ # self.text lives to be used another day
+ reset_text = False
+
+ if reset_text:
+ self.text = ''
+
+ # remove the last tag from the tag list
+ self.current_tags.pop()
+
+ #---- start of the end elements ------------------------------------------
+
+ def end_answer(self):
+ r'''
+ Process end tag when tag="answer"
+ '''
+ self.question_list[-1].answer = self.text.strip()
+
+ def end_discussion(self):
+ r'''
+ Process end tag when tag="discussion"
+ '''
+ self.discussion_list[-1].text = self.text.strip()
+
+ def end_item(self):
+ r'''
+ Process end tag when tag="item"
+ '''
+ self.question_list[-1].items[-1].text = self.text.strip()
+
+ def end_feedback(self):
+ r'''
+ Process end tag when tag="feedback"
+ '''
+ self.question_list[-1].items[-1].feedback = self.text.strip()
+
+ def end_question(self):
+ r'''
+ Process end tag when tag="question"
+ '''
+ # first some error checking
+ if self.question_list[-1].type == None:
+ self.webquiz_error('Question {} does not have an \\answer or choice environment'.format(
+ len(self.question_list)+1))
+
+ elif hasattr(self.question_list[-1], 'items'):
+ if len(self.question_list[-1].items)==0:
+ self.webquiz_error('question {} has no multiple choice items'.format(
+ len(self.question_list)+1))
+
+ if self.question_list[-1].type=='single' and self.question_list[-1].correct!=1:
+ self.webquiz_error('question {} is single-choice but has {} correct answers'.format(
+ len(self.question_list)+1,
+ self.question_list[-1].correct
+ )
+ )
+ elif not hasattr(self.question_list[-1], 'answer') or self.question_list[-1].answer=='':
+ self.webquiz_error('question {} does have not an \answer or multiple choice'.format(
+ len(self.question_list)+1))
+
+ if self.text.strip() != '':
+ self.question_list[-1].after_text += ' '+self.text.strip()
+
+ def end_index_item(self):
+ r'''
+ Process end tag when tag="index_item"
+ '''
+ self.quiz_index[-1].title = self.text.strip().replace('\n',' ').replace('\r',' ')
+
+ def end_when(self):
+ r'''
+ Process end tag when tag="index_item"
+ '''
+ self.webquiz_debug('WHEN: Adding text to '+self.current_tags[-1])
+ setattr(self.question_list[-1], self.current_tags[-1], self.text.strip())
+
+ #---- end of end elements -----------------------------------------------
+
+ def characters(self, text): #data,start,length):
+ r'''
+ Append everything to `self.text`
+ '''
+ self.text += text
+
+ def error(self, e):
+ self.webquiz_error('unknown error', e)
+
+ def fatalError(self, e):
+ self.webquiz_error('unknown fatal error', e)