-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmkt.py
More file actions
executable file
·1329 lines (1092 loc) · 54.8 KB
/
mkt.py
File metadata and controls
executable file
·1329 lines (1092 loc) · 54.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import os, sys, argparse, errno
import tempfile
import shutil
import subprocess
import random
import uuid
import hashlib
from configobj import ConfigObj
class MKT:
# set to True when the master settings are read. This is done so we only
# have to do it once
mainSettingsStored = False
# config structure for the master settings
config = None
# default number of points for questions that don't have it set
defaultPoints = 2
# default space for the solution, for questions that don't have it set
defaultSolutionSpace = None
# current indent level
indent = 0
# Enable test mode
testMode = False
# quiz mode has no cover page
quiz = False
# whether to split multiple choice questions into multiple columns (this is a default for quizzes)
splitMultipleChoice = False
# add an ID to the test
id = False
# Enable draft mode
draftMode = False
# Total points is used for maxPercent calculations
totalPoints = None
# use a bubble sheet for T/F and MC question
bubbleSheet = False
# For maxPercent to work, we need to make two passes. This will be set to
# true if we encounter a maxPercent keyword
needSecondPass = False
currentPass = 1
multipartSkipKeys = ['type', 'points', 'showPoints', 'question', 'solutionSpace', 'key']
# hash used for duplicate question detection. Since we want to keep track
# of ALL questions, regardless of whether we use it in a test or not, we
# can make it a member variable
qHash = {}
###########################################
# __init__
##########################################
def __init__(self, args):
# If the user specifies 1 versions, it's the same as none specified
if not args.versions:
pass
elif args.versions < 1:
fatal("-v <#> must be 1, or greater")
elif args.versions > 10:
fatal("-v <#> must be 10, or less")
if args.versions == 1:
args.versions = None
try:
with open(args.configFile, encoding='utf-8'):
pass
except IOError:
fatal("Could not open %s" % (args.configFile))
# List of questions
questions = []
# Name of the file for the answer key
answerFilename = ''
# output file pointer
of = None
# keyfile points
kf = None
# Initialize RNG
if not args.uuid:
args.uuid = uuid.uuid1()
print("New UUID: %s" % args.uuid)
random.seed(str(args.uuid))
self.testMode = args.test
if self.testMode:
print(">>> TEST MODE ENABLED <<<")
self.draftMode = args.draft
# Read in the ini file specified on the command line
print("Reading %s" % (args.configFile))
path = os.path.dirname(args.configFile)
config = ConfigObj(args.configFile)
if "quiz" in config and config["quiz"].lower() == "true":
self.quiz = True
self.splitMultipleChoice = True
if "bubbleSheet" in config and config["bubbleSheet"].lower() == "true":
self.bubbleSheet = True
if "splitMultipleChoice" in config:
if config["splitMultipleChoice"].lower() == "true":
self.splitMultipleChoice = True
else:
self.splitMultipleChoice = False
if "includeID" in config and config["includeID"].lower() == "true":
self.id = True
questions_list = {}
points = 0
while True:
questions = []
self.qHash = {}
questions = self.parseConfig('File', args.configFile, config, root=path)
if self.needSecondPass:
self.currentPass = 2
self.qHash = {}
self.totalPoints = 0
for q in questions:
self.totalPoints += int(q["points"])
print("-------------------------------------------------------")
print("Encounted maxPercent.. reparsing.")
print(("Total points: %d" % (self.totalPoints)))
print("-------------------------------------------------------")
# Reseed with the same UUID so we get the same questionsList
random.seed(str(args.uuid))
questions = self.parseConfig('File', args.configFile, config, root=path)
key = 0
for q in questions:
key += int(q["points"])
print("*************************************")
print(key)
print("*************************************")
if not key in questions_list:
questions_list[key] = [questions]
else:
questions_list[key].append(questions)
if not args.versions:
points = key
break
if len(questions_list[key]) >= int(args.versions):
points = key
break
if args.versions:
for v in range(0, int(args.versions)):
self.writeTest(args, questions_list[points][v], chr(v + ord('A')))
else:
self.writeTest(args, questions_list[points][0])
print("")
print("If you have the same config file and question set, you can regenerate")
print("this test with by specifing the following argument to mkt:")
print("\t-u %s" % args.uuid)
print("")
##########################################
# writeTest
##########################################
def writeTest(self, args, questions, version=None):
# invert this so it makes it easy to use
answerKey = not args.noAnswerKey
fileName, fileExtension = os.path.splitext(args.configFile)
baseName = os.path.basename(fileName)
if args.dest:
destDir = args.dest + "/"
else:
destDir = fileName + "/"
try:
os.makedirs(destDir, 0o700)
except OSError as e:
if e.errno == errno.EEXIST and os.path.isdir(destDir):
pass
else:
fatal("Can not create destination direction %s" % (destDir))
if version:
baseName += "." + version
outFilename = destDir + baseName + ".tex"
answerFilename = destDir + baseName + ".key.tex"
# Check if the files exist
if not args.force and os.path.exists(outFilename):
fatal("%s: file already exists" % (outFilename))
of = open(outFilename, 'w', encoding='utf-8')
if answerKey:
if not args.force and os.path.exists(answerFilename):
fatal("%s: file already exists" % (answerFilename))
kf = open(answerFilename, 'w', encoding='utf-8')
# Generate the test once
tempFile = tempfile.TemporaryFile(mode='w+')
self.generateTest(tempFile, questions)
self.writeHeader(of, '', args, version)
# Now we write copy from the temp file to the test file
tempFile.seek(0, 0)
shutil.copyfileobj(tempFile, of)
self.writeFooter(of)
print(("\nTest file written: %s" % (outFilename)))
if answerKey:
self.writeHeader(kf, 'answers,', args, version)
# Write the same test contents
tempFile.seek(0, 0)
shutil.copyfileobj(tempFile, kf)
self.writeFooter(kf)
print(("Answer key file written: %s" % (answerFilename)))
of.close()
kf.close()
tempFile.close()
if args.pdf:
self.createPDF(outFilename, answerFilename)
##########################################
# createPDF
##########################################
def createPDF(self, outFile, answerFilename):
# TODO: This could stand to be reworked. It's ugly
print("Generating PDFs...")
fileName, fileExtension = os.path.splitext(outFile)
oldpath = os.getcwd()
newpath = os.path.dirname(outFile)
os.chdir(newpath)
logFile = open("%s.log" % (os.path.basename(fileName)), "wb+")
if len(newpath) == 0:
newpath = "."
executable = ["pdflatex", "-halt-on-error", os.path.basename(outFile)]
for i in range(0, 3):
process = subprocess.Popen(executable, stdout=subprocess.PIPE)
for line in process.stdout.readlines():
logFile.write(line)
if process.wait() != 0:
logFile.close()
os.chdir(oldpath)
fatal("Error running pdflatex. Check logs.")
if len(answerFilename) > 0:
executable = ["pdflatex", "-halt-on-error", os.path.basename(answerFilename)]
for i in range(0, 3):
process = subprocess.Popen(executable, stdout=subprocess.PIPE)
for line in process.stdout:
logFile.write(line)
if process.wait() != 0:
logFile.close()
os.chdir(oldpath)
fatal("Error running pdflatex. Check logs.")
logFile.close();
os.chdir(oldpath)
##########################################
# writeHeader
##########################################
def writeHeader(self, of, answerKey, args, version):
print("% This document generated with mkt", file=of)
print("%% uuid: %s" % args.uuid, file=of)
print("%% configFile: %s" % args.configFile, file=of)
if version:
print("%% version: %s" % version, file=of)
if answerKey:
print("\\documentclass[10pt,answers,addpoints]{exam}\n", file=of)
else:
print("\\documentclass[10pt,addpoints]{exam}\n", file=of)
print("\\usepackage{amssymb}\n" \
"\\usepackage{graphicx}\n" \
"\\usepackage{listings}\n" \
"\\usepackage{tabularx}\n" \
"\\usepackage{mathtools}\n" \
"\\usepackage{wasysym }\n"\
"\\usepackage{color}\n\n", file=of)
if args.draft:
print("\\usepackage{draftwatermark}\n", file=of)
print("\\SetWatermarkText{DRAFT}\n", file=of)
print("\\SetWatermarkScale{7}\n", file=of)
print("\\makeatletter", file=of)
print("\\ifcase \\@ptsize \\relax % 10pt", file=of)
print("\\newcommand{\\miniscule}{\\@setfontsize\\miniscule{4}{5}}% \\tiny: 5/6", file=of)
print("\\or% 11pt", file=of)
print("\\newcommand{\\miniscule}{\\@setfontsize\\miniscule{5}{6}}% \\tiny: 6/7", file=of)
print("\\or% 12pt", file=of)
print("\\newcommand{\\miniscule}{\\@setfontsize\\miniscule{5}{6}}% \\tiny: 6/7", file=of)
print("\\fi", file=of)
print("\\makeatother", file=of)
print("\\pagestyle{headandfoot}", file=of)
if self.quiz:
if self.id:
print("\\firstpageheader{ Name: \\makebox[3in]{\\hrulefill}} {\\hspace{3in}ID: \\makebox[1.5in]{\\hrulefill}} {%s}" % (self.config["test"]), file=of)
print("\\runningheader{} {} {%s}" % (self.config["test"]), file=of)
else:
print("\\firstpageheader{ Name: \\makebox[5in]{\\hrulefill}} {} {%s}" % (self.config["test"]), file=of)
print("\\runningheader{} {} {%s}" % (self.config["test"]), file=of)
if answerKey:
print("\\firstpageheader{Name: \\textcolor{red}{KEY} } {} {%s}" % (self.config["test"]), file=of)
print("\\runningheader{} { \\textcolor{red}{KEY} } {%s}" % (self.config["test"]), file=of)
else:
if answerKey:
print("\\firstpageheader{%s} {} { \\textcolor{red}{KEY} }" % (self.config["test"]), file=of)
print("\\runningheader{%s} {} { \\textcolor{red}{KEY} }" % (self.config["test"]), file=of)
else:
if "nameOnEveryPage" in self.config and self.config["nameOnEveryPage"].lower() == "true":
print("\\firstpageheader{%s} {} { Name: \\makebox[3.5in]{\\hrulefill}}" % (self.config["test"]), file=of)
print("\\runningheader{%s} {} { Name: \\makebox[3.5in]{\\hrulefill}}" % (self.config["test"]), file=of)
else:
print("\\firstpageheader{%s} {} {}" % (self.config["test"]), file=of)
print("\\runningheader{%s} {} {}" % (self.config["test"]), file=of)
print("\\firstpagefooter{%s} {Page \\thepage\\ of \\numpages} {\\makebox[.5in]{\\hrulefill}/\\pointsonpage{\\thepage}}" % (
self.config["courseNumber"]), file=of)
print("\\runningfooter{%s} {Page \\thepage\\ of \\numpages} {\\makebox[.5in]{\\hrulefill}/\\pointsonpage{\\thepage}}" % (
self.config["courseNumber"]), file=of)
#print("\\CorrectChoiceEmphasis{\color{red}}", file=of)
print("\\checkedchar{\\textcolor{red}{$\\CIRCLE$}}", file=of)
print("\\SolutionEmphasis{\\color{red}}", file=of)
print("\\renewcommand{\\questionshook}{\\setlength{\\itemsep}{.35in}}", file=of)
print("\\bonuspointpoints{bonus point}{bonus points}", file=of)
print("\\colorsolutionboxes", file=of)
print("\\definecolor{SolutionBoxColor}{gray}{1.0}", file=of)
if not self.quiz:
print("\n", file=of)
#print("\\checkboxchar{$\\Box$}", file=of)
print("\\CorrectChoiceEmphasis{\\color{red}}", file=of)
print("\\SolutionEmphasis{\\color{red}}", file=of)
print("\\renewcommand{\\questionshook}{\\setlength{\\itemsep}{.35in}}", file=of)
print("\\bonuspointpoints{bonus point}{bonus points}", file=of)
print("\\colorsolutionboxes", file=of)
print("\\definecolor{SolutionBoxColor}{gray}{1.0}", file=of)
print("\n", file=of)
print("\\begin{document}", file=of)
print("\\begin{coverpages}", file=of)
print("\\begin{center}", file=of)
print("\\vspace*{1in}", file=of)
print("\n", file=of)
print("\\textsc{\\LARGE %s \\\\%s }\\\\[1.5cm]" % (self.config["school"], self.config["department"]), file=of)
print("\\textsc{\\LARGE %s}\\\\[1cm]" % (self.config["courseName"]), file=of)
print("\\textsc{\\LARGE %s}\\\\[1cm]" % (self.config["term"]), file=of)
print(self.config["instructor"], file=of)
print("\\textsc{\\Huge %s}\\\\[1cm]" % (self.config["test"]), file=of)
if version:
print("\\textsc{\\LARGE Version: %s}\\\\[1cm]" % (version), file=of)
print("%s" % (self.config["note"]), file=of)
print("\\vfill", file=of)
print("\n", file=of)
if answerKey:
print("{\\Large { Score: \\makebox[1in]{\\underline{\\hspace{5mm}\\textcolor{red}{KEY} \\hspace{5mm}}} / \\numpoints }} \\\\[4cm]", file=of)
else:
print("{\\Large { Score: \\makebox[1in]{\\hrulefill} / \\numpoints }} \\\\[4cm]", file=of)
print("\\end{center}", file=of)
if answerKey:
print("\\makebox[\\textwidth]{\\textcolor{red}{KEY}}", file=of)
else:
if "includeID" in self.config and self.config["includeID"].lower() == "true":
print("\\makebox[0.60\\textwidth]{Name: \\enspace\\hrulefill}", file=of)
print("\\makebox[0.40\\textwidth]{ID: \\enspace\\hrulefill}", file=of)
else:
print("\\makebox[\\textwidth]{Name: \\enspace\\hrulefill}", file=of)
if args.draft:
print("\\covercfoot{ Exam ID: %s}" % args.uuid, file=of)
else:
print("\\covercfoot{\\miniscule{ Exam ID: %s}}" % args.uuid, file=of)
print("\\end{coverpages}", file=of)
print("\n", file=of)
else:
print("\\begin{document}", file=of)
if (self.config["note"]) != "":
print("%s" % (self.config["note"]), file=of)
###########################################
# writeFooter
##########################################
def writeFooter(self, of):
print("\\end{questions}", file=of)
print("\\end{document}", file=of)
###########################################
# getQuestions
##########################################
def getQuestions(self, path):
for parent, ldirs, lfiles in os.walk(path):
lfiles = [nm for nm in lfiles if not nm.startswith('.')]
ldirs[:] = [nm for nm in ldirs if not nm.startswith('.')] # in place
lfiles.sort()
for nm in lfiles:
nm = os.path.join(parent, nm)
yield nm
###########################################
# shuffle
##########################################
def shuffle(self, items): # returns new list
if self.testMode:
return items
if type(items) is dict:
fatal("Cannot shuffle dictionaries")
else:
return [t[1] for t in sorted((random.random(), i) for i in items)]
###########################################
# processInclude
##########################################
def processInclude(self, config, root=None):
rval = []
# If there is only one thing in out list, make it a list so we can
# reuse the same code below
if isinstance(config, str):
config = [config]
for inc in config:
self.indent += 1
# If it's a directory, read all the files in the directory
if root:
inc = "%s/%s" % (root, inc)
if os.path.isdir(inc):
files = self.getQuestions(inc)
# If it's a file, read it in
elif os.path.isfile(inc):
files = [inc]
else:
fatal("%s: directory or file does not exist" % (inc))
for f in files:
rval += self.parseConfig('File', f, ConfigObj(f, interpolation=True))
self.indent -= 1
return rval
###########################################
# parseTestSettings
##########################################
def parseTestSettings(self, c, config):
if c in ["test", "instructor", "courseName", "courseNumber", "term", "note",
"school", "department", "nameOnEveryPage", "defaultPoints",
"defaultSolutionSpace", "useCheckboxes", "defaultLineLength",
"includeID", "useClassicTF", "quiz", "splitMultipleChoice", "bubbleSheet"]:
if not self.mainSettingsStored:
self.mainSettingsStored = True
self.config = config
# Set up some defaults of the keys aren't found
if "useCheckboxes" not in self.config:
self.config["useCheckboxes"] = "false"
if "useClassicTF" not in self.config:
self.config["useClassicTF"] = "false"
if "defaultLineLength" not in self.config:
self.config["defaultLineLength"] = "1in"
# We need to do this once here because when we add questions, it
# we want to add the default points settings. Everything else is
# used on page genreation so it can be saved in the struct for
# later
if "defaultPoints" in config:
self.defaultPoints = config["defaultPoints"]
# Same for defaultSolutionSpace
if "defaultSolutionSpace" in config:
self.defaultSolutionSpace = config["defaultSolutionSpace"]
# We did consumer this key
return True
# We did NOT consume this key
return False
###########################################
# parseConfig
##########################################
def parseConfig(self, descriptor, name, config, root=None):
sys.stdout.write(" " * self.indent)
qList = []
maxQuestions = None
maxPoints = None
maxPercent = None
showSummary = True
#Scott ADDED
maxLongPoints = None
maxTFPoints = None
maxShortPoints = None
maxMCPoints = None
#Scott ADDED end
# found a question. Add it!
if "question" in config:
if (("examOnly" in config) and (self.quiz)):
print("%s: %s - Skipping question for quiz mode" % (descriptor, os.path.basename(name)))
elif (("quizOnly" in config) and (not self.quiz)):
print("%s: %s - Skipping question for exam mode" % (descriptor, os.path.basename(name)))
else:
print("%s: %s - Adding question" % (descriptor, os.path.basename(name)))
# If points is not set, set it here
if not "points" in config and config["type"].lower() != "multipart":
config["points"] = self.defaultPoints
# If it's a long answer question, make sure there is a solution
# space defined
if "type" not in config:
fatal("'type' not defined for question")
if (config["type"].lower() == "longanswer") and not "solutionSpace" in config:
if self.defaultSolutionSpace:
config["solutionSpace"] = self.defaultSolutionSpace
else:
fatal(
"'solutionSpace' and 'defaultSolutionSpace' cannot both be undefined for short answer questions")
if config["type"].lower() == "multipart":
if "points" in config:
fatal("Multipart questions must have points set in sub parts")
mppoints = 0
for k in config.keys():
if k not in self.multipartSkipKeys:
mppoints += int(config[k]['points'])
if not "solutionSpace" in config[k]:
if self.defaultSolutionSpace:
config[k]["solutionSpace"] = self.defaultSolutionSpace
else:
fatal("'solutionSpace' and 'defaultSolutionSpace' cannot both be undefined for short answer questions")
config["points"] = mppoints
# Check for dupes. Strip out all whitespace in the string and
# then get an md5 hash. It's less to store and fairly quick to
# compute
s = "".join(config["question"].split())
m = hashlib.md5(s.encode('utf-8')).hexdigest()
if m in self.qHash:
print("\nFATAL ERROR!! Duplication questions detected!", file=sys.stderr)
print(" Question: \"%s\"" % config["question"], file=sys.stderr)
print(" Initially processed in '%s'" % (self.qHash[m]), file=sys.stderr)
print(" Also processed in '%s'" % (name), file=sys.stderr)
sys.exit(2)
else:
self.qHash[m] = name
# Append the question to the question List
config["key"] = name
qList.append(config)
else: # Not a question
print("%s: '%s' - Parsing" % (descriptor, os.path.basename(name)))
# No questions at this level. Need to recursive look for them
for c in config:
if c.lower() == "maxquestions":
if not self.testMode:
maxQuestions = int(config[c])
elif c.lower() == "maxpoints":
if not self.testMode:
maxPoints = int(config[c])
elif c.lower() == "maxpercent":
maxPercent = int(config[c])
self.needSecondPass = True
elif c.lower() == "maxlongpoints": #Scott ADDED
maxLongPoints = int(config[c])
elif c.lower() == "maxtfpoints": #Scott ADDED
maxTFPoints = int(config[c])
elif c.lower() == "maxmcpoints": #Scott ADDED
maxMCPoints = int(config[c])
elif c.lower() == "maxshortpoints": #Scott ADDED
maxShortPoints = int(config[c])
elif c == "include":
qList += self.processInclude(config["include"], root=root)
elif self.parseTestSettings(c, config):
continue
elif not isinstance(config[c], str):
self.indent += 1
try:
qList += self.parseConfig('Section', "%s/%s" % (name, c), config[c], root=root)
except Exception as e:
print("Error: ")
print(e)
print(("Section %s/%s" % (name, c)))
sys.exit(0)
self.indent -= 1
else:
fatal("Unknown token: %s" % c)
# This is needed to correctly fetch maxPoints and maxQuestions from the
# "config" section of the ini file
if "config" in config and "maxPoints" in config["config"]:
maxPoints = (int)(config["config"]["maxPoints"])
print("Max points:", maxPoints)
if "config" in config and "maxQuestions" in config["config"]:
maxQuestions = (int)(config["config"]["maxQuestions"])
if maxPoints and maxPercent:
fatal("maxPoints and maxPercent cannot be specified for the same section!")
#Scott ADDED
tempQList = []
altQList = []
currLongPoints = 0
currShortPoints = 0
currMCPoints = 0
currTFPoints = 0
qList = self.shuffle(qList)
for q in qList:
# If the question is required, move it to the front of the list
if ("required" in q and (q["required"].lower() == "true")):
qList.remove(q)
qList.insert(0, q)
for q in qList:
if maxLongPoints and q['type'].lower() == "multipart":
if int(q['points']) + currLongPoints <= maxLongPoints:
tempQList.append(q)
currLongPoints = currLongPoints + int(q['points'])
if maxLongPoints and q['type'].lower() == "longanswer":
if int(q['points']) + currLongPoints <= maxLongPoints:
tempQList.append(q)
currLongPoints = currLongPoints + int(q['points'])
elif maxShortPoints and q['type'].lower() == "shortanswer":
if int(q['points']) + currShortPoints <= maxShortPoints:
tempQList.append(q)
currShortPoints = currShortPoints + int(q['points'])
elif maxTFPoints and q['type'].lower() == "tf":
if int(q['points']) + currTFPoints <= maxTFPoints:
tempQList.append(q)
currTFPoints = currTFPoints + int(q['points'])
elif maxMCPoints and q['type'].lower() == "multiplechoice":
if int(q['points']) + currMCPoints <= maxMCPoints:
tempQList.append(q)
currMCPoints = currMCPoints + int(q['points'])
else:
altQList.append(q)
qList = tempQList[:]
#Scott ADDED end
# Cut the list down to get the max points requested
sectionPoints = 0
altPoints = 0
oldLen = len(qList)
for p in qList:
sectionPoints += int(p["points"])
for p in altQList:
altPoints += int(p["points"])
oldLen = len(qList) + len(altQList)
oldSectionPoints = sectionPoints + altPoints
if maxPoints and oldSectionPoints < maxPoints:
qList.extend(altQList)
sectionPoints = oldSectionPoints
elif maxPoints and sectionPoints < maxPoints:
showSummary = False
altQList = self.shuffle(altQList)
for q in altQList:
# If the question is required, move it to the front of the list
if ("required" in q and (q["required"].lower() == "true")):
altQList.remove(q)
altQList.insert(0, q)
for p in altQList:
if sectionPoints + int(p["points"]) <= maxPoints:
sectionPoints += int(p["points"])
qList.append(p)
sys.stdout.write(" " * self.indent)
print("%s: '%s': maxPoints set to %d" % (descriptor, os.path.basename(name), maxPoints))
sys.stdout.write(" " * self.indent)
print(" old total: %d old # of questions: %d" % (oldSectionPoints, oldLen))
sys.stdout.write(" " * self.indent)
print(" new total: %d new # of questions: %d" % (sectionPoints, len(qList)))
elif maxPoints:
pass
else:
qList.extend(altQList)
sectionPoints = sectionPoints + altPoints
if maxQuestions and len(qList) > maxQuestions:
showSummary = False
qList = self.shuffle(qList)
qList = qList[:maxQuestions]
sys.stdout.write(" " * self.indent)
print("%s: '%s': maxQuestions set to %d" % (descriptor, os.path.basename(name), maxQuestions))
# Cut the list down to get the maxPercent requested. This should happen
# after maxQuestions since it's possible maxQuestions was used to pick 1
# of 3 identical type questions.
if self.totalPoints and maxPercent: # if we didn't get through the first pass yet, this won't work
percentPoints = (int)(maxPercent / 100.0 * self.totalPoints)
if sectionPoints >= percentPoints:
showSummary = False
qList = self.shuffle(qList)
newList = []
# In this case, we want to get one MORE question than what is
# required for maxPoints since we are just going for rough
# percentages
newPoints = 0
for p in qList:
newPoints += int(p["points"])
newList.append(p)
if newPoints > percentPoints:
break
sys.stdout.write(" " * self.indent)
print(" %s: '%s': maxPercent set to %d%%" % (descriptor, os.path.basename(name), maxPercent))
sys.stdout.write(" " * self.indent)
print(" old total: %d old # of questions: %d" % (sectionPoints, len(qList)))
sys.stdout.write(" " * self.indent)
print(" new total: %d new # of questions: %d" % (newPoints, len(newList)))
sys.stdout.write(" " * self.indent)
print(" actual percentage: %d%%" % (newPoints * 100 / self.totalPoints))
qList = newList
sectionPoints = newPoints
else:
sys.stdout.write(" " * self.indent)
print(" !! %s: '%s': maxPercent set to %d" % (descriptor, os.path.basename(name), maxPercent))
sys.stdout.write(" " * self.indent)
print(" !! We required at least %d points to meet this requirement, " % (percentPoints))
sys.stdout.write(" " * self.indent)
print(" !! but only %d points were available." % (sectionPoints))
sys.stdout.write(" " * self.indent)
print(" !! actual percentage: %d%%" % (sectionPoints * 100 / self.totalPoints))
# if we didn't already show a summary
# AND
# We are in a section with at least 2 elements
# OR
# We are a file
if showSummary and ((len(qList) > 1 and descriptor == 'Section') or
descriptor == 'File'):
sys.stdout.write(" " * self.indent)
print("%s: '%s' - Adding %d questions worth %d points" % (descriptor,
os.path.basename(name), len(qList), sectionPoints))
return qList
###########################################
# beginMinipage
##########################################
def beginMinipage(self, of):
if self.config["useCheckboxes"].lower() == "true":
space = .25
else:
space = .10
of.write("\\par\\vspace{%fin}\\begin{minipage}{\\linewidth}\n" % (space))
###########################################
# endMinipage
##########################################
def endMinipage(self, of):
of.write("\\end{minipage}\n")
of.write("\n\n")
###########################################
# createTrueFalseQuestions
##########################################
def createTrueFalseQuestions(self, of, questions, bonus=None):
for m in self.shuffle(questions):
self.beginMinipage(of)
if bonus:
of.write("\\bonusquestion[%d]\n" % (int(m["points"])))
else:
of.write("\\question[%d]\n" % int(m["points"]))
if self.config["useCheckboxes"].lower() == "true":
if False:
of.write("%s\n" % (m["question"]))
of.write("\n ")
of.write("\\ifprintanswers\n")
if m["solution"].lower() == "true":
of.write("\\hspace{0.9\\textwidth}\\textbf{$\\CIRCLE$ True} \n\n")
of.write("\\hspace{0.9\\textwidth}\\textbf{$\\ocircle$ False} ")
else:
of.write("\\hspace{0.9\\textwidth}\\textbf{$\\ocircle$ True} \n\n")
of.write("\\hspace{0.9\\textwidth}\\textbf{$\\CIRCLE$ False} ")
of.write("\\else\n")
of.write("\\hspace{0.9\\textwidth}\\textbf{$\\ocircle$ True} \n\n")
of.write("\\hspace{0.9\\textwidth}\\textbf{$\\ocircle$ False} ")
of.write("\\fi\n ")
else:
of.write("%s\n" % (m["question"]))
of.write("\n ")
of.write("\\ifprintanswers\n")
if m["solution"].lower() == "true":
of.write("\\hfill\\textbf{\\textcolor{red}{$\\CIRCLE$} True ")
of.write("\\hspace{2mm}$\\ocircle$ False} ")
else:
of.write("\\hfill\\textbf{$\\ocircle$ True ")
of.write("\\hspace{2mm}\\textcolor{red}{$\\CIRCLE$} False} ")
of.write("\\else\n")
of.write("\\hfill\\textbf{$\\ocircle$ True ")
of.write("\\hspace{2mm}$\\ocircle$ False} ")
of.write("\\fi\n ")
elif self.config["useClassicTF"].lower() == "true":
if m["solution"].lower() == "true":
correctAnswer = "True"
else:
correctAnswer = "False"
of.write("%s\n" % (m["question"]))
of.write("\\setlength\\answerlinelength{1in}\n")
of.write("\\answerline[%s]\n\n" % (correctAnswer))
else:
of.write("\\ifprintanswers\n")
if m["solution"].lower() == "true":
of.write("\\textbf{[ \\textcolor{red}{True} / False ]} ")
else:
of.write("\\textbf{[ True / \\textcolor{red}{False} ]} ")
of.write("\\else\n")
of.write("\\textbf{[ True / False ]} ")
of.write("\\fi\n")
of.write("%s\n" % (m["question"]))
of.write("\\medskip\n")
self.endMinipage(of)
###########################################
# createMultipleChoiceQuestions
##########################################
def createMultipleChoiceQuestions(self, of, questions, bonus=None):
for m in self.shuffle(questions):
self.beginMinipage(of)
if bonus:
of.write("\\bonusquestion[%d]\n" % (int(m["points"])))
else:
of.write("\\question[%d]\n" % int(m["points"]))
of.write("%s\n" % (m["question"]))
of.write("\\medskip\n")
try:
answers = {m["correctAnswer"]: "CorrectChoice"}
except TypeError:
fatal("correctAnswer not defined for %s" % (m))
try:
answers.update({v: "choice" for v in m["wrongAnswers"]})
except KeyError:
fatal("'wrongAnswers' not defined for %s" % (m))
answers = self.shuffle(list(answers.items()))
if self.config["useCheckboxes"].lower() == "true":
if self.splitMultipleChoice:
of.write("\\\\ \\begin{oneparcheckboxes}\n")
else:
of.write("\\begin{checkboxes}\n")
count=0
align = "\\makebox[5cm][l]{"
lineBreakOnEach = False
for a, b in answers:
if len(a) > 30:
lineBreakOnEach = True
for a, b in answers:
count+=1
of.write("\\%s %s %s}\n" % (b, align, a))
if (count % 2==0 or lineBreakOnEach) and not count == len(answers) and (self.splitMultipleChoice):
of.write("\\\\")
if self.splitMultipleChoice:
of.write("\\end{oneparcheckboxes}\n")
else:
of.write("\\end{checkboxes}\n\n\n")
else:
if self.quiz:
of.write("\\begin{oneparchoices}\n")
else:
of.write("\\begin{choices}\n")
currentAnswer = 'A'
for a, b in answers:
of.write("\\%s %s\n" % ("choice", a))
if b == "CorrectChoice":
correctAnswer = currentAnswer
currentAnswer = chr(ord(currentAnswer) + 1)
if "lineLength" in m:
lineLength = m["lineLength"]
else:
lineLength = self.config["defaultLineLength"]
if self.quiz:
of.write("\\end{oneparchoices}\n")
else:
of.write("\\end{choices}\n")
# Answer lines for multiple choice questions are always 1in
of.write("\\setlength\\answerlinelength{1in}\n")
of.write("\\answerline[%s]\n\n" % (correctAnswer))
self.endMinipage(of)
###########################################
# createShortAnswerQuestions
##########################################
def createShortAnswerQuestions(self, of, questions, bonus=None):
for m in self.shuffle(questions):
self.beginMinipage(of);
of.write("\\vspace{.35cm}")
if bonus:
of.write("\\bonusquestion[%d]\n" % (int(m["points"])))
else:
of.write("\\question[%d]\n" % int(m["points"]))
of.write("%s\n" % (m["question"]))
of.write("\\vspace{.25cm}")
# Write out the solution
if "lineLength" in m:
lineLength = m["lineLength"]
else:
lineLength = self.config["defaultLineLength"]