-
Notifications
You must be signed in to change notification settings - Fork 2
/
bootcamp.py
executable file
·1369 lines (1258 loc) · 55.5 KB
/
bootcamp.py
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
#!/bin/env python3
## by Ralf Brown, Carnegie Mellon University
## last edit: 15sep2020
import csv
import datetime
import dateutil.parser
import math
import os
import pytz
import random
import re
import sys
import urllib, urllib.request
from itertools import chain
from urllib.error import HTTPError
from statistics import mean # requires Python 3.4+
from canvaslms import Course, Grade, CanvasCSV
from canvascmu import Institution
try:
from hackerrank import HackerRank
have_HR = True
except ImportError:
have_HR = False
######################################################################
## configuration
COURSE_NAME = "Coding Boot Camp"
HOST = "canvas.cmu.edu"
MAIL = "@andrew.cmu.edu"
TEST_STUDENT = 57945 # uid of the Test Student for the course
## People whose comments should be ignored when processing peer reviews. Use the display_name for each.
COURSE_STAFF = []
TIMEZONE = pytz.timezone('America/New_York')
## for very skewed grades, we may want to compute standard deviation separately for grades above and below the mean
SPLIT_STDDEV = True
## configuration of late penalty: percent per day and maximum days late accepted
LATE_PERCENTAGE = 10
LATE_DAYS = 7
## configuration of points for the shuffle
SHUFFLE_ASSESSMENT_POINTS = 60
SHUFFLE_FEEDBACK_POINTS = 40
SHUFFLE_SUBMISSION_POINTS = 50
INCOMPLETE_RUBRIC_PENALTY = 0.50
## 20% penalty for not submitting a photo along with the interviewee assessment
NO_PHOTO_PENALTY = 0.20
## should HackerRank assignment links be posted as assignment comments?
POST_LINK = False
######################################################################
def add_bootcamp_flags(parser):
'''
add the flags specific to 11-601 to the given argument parser
'''
parser.add_argument("-I","--inclass",action="store_true",help="interpret CSV file as an in-class exercise")
parser.add_argument("-H","--homework",action="store_true",help="interpret CSV file as a homework assignment")
parser.add_argument("-E","--exam",action="store_true",help="treat assignment as an exam, use actual points as grade")
parser.add_argument("-S","--shuffle",metavar="NAME",help="use assignment NAME as source of grades for shuffle assessment")
parser.add_argument("-F","--feedback",metavar="NAME",help="use assignment NAME as source of grades for shuffle feedback")
parser.add_argument("--makecurve",action="store_true",help="compute curve for mean of 85%% and stdev of 5%%")
parser.add_argument("--targetmean",default=None,metavar="N",help="set target mean for --makecurve to N%%")
parser.add_argument("--makeshuffle",action="store_true",help="create interview shuffle among the enrolled students")
parser.add_argument("--shufflegroups",metavar="GRPLIST",help="split shuffle to match only within comma-separated GRPLIST")
parser.add_argument("--prevshuffles",metavar="FILE",help="avoid assigning a matching present in FILE from prior shuffles")
parser.add_argument("--reassign",action="store_true",help="assign a new interviewee to an interviewer")
parser.add_argument("--force",action="store_true",help="force grade upload even if student has already been graded")
parser.add_argument("-Q","--questions",metavar="FILE",help="load list of shuffle questions from FILE")
parser.add_argument("--students",metavar="FILE",help="use list of students in FILE instead of current roster for --makeshuffle")
parser.add_argument("--addreviewer")
parser.add_argument("--old",action="store_true",help="use .csv files for shuffle scores instead of rubric")
if have_HR:
parser.add_argument("--invite",metavar="TESTID",help="invite students on roster to HackerRank test TESTID (use --message for the custom text in the invitation email)")
parser.add_argument("--copyscores",metavar="TESTIDLIST",help="copy scores from HackerRank tests listed in TESTIDLIST")
parser.add_argument("--autoprocess",action="store_true",help="run unattended --invite and --copyscores processes")
return
######################################################################
def setup_course(args):
course = Course(HOST, COURSE_NAME, verbose=args.verbose)
course.simulate(args.dryrun)
course.mail_address(MAIL)
course.use_raw_points(args.use_raw_points)
course.set_points(args.points)
course.set_late_percentage(LATE_PERCENTAGE,LATE_DAYS)
course.set_due_day(args.due_day)
course.find_assignment(args.assignment)
return course
######################################################################
def build_feedback(partnum, total, mcq, coding, subscores):
subscores = [x for x in subscores if 'Not Applicable' not in str(x)]
comment = 'Part {}: '.format(partnum+1) if partnum >= 0 else ''
if mcq is None:
comment += '{} points'.format(int(total))
else:
comment += '{}mcq+{}code'.format(Grade.drop_decimals(mcq),Grade.drop_decimals(coding))
if sum(1 for x in subscores if x is not None) > 1:
subs = (Grade.drop_decimals(x) if x is not None else '-' for x in subscores)
comment += '; per-Q: ' + ':'.join(subs)
return comment
######################################################################
def parse_hackerrank(course, csv, grades, partnum, verbose=False):
## extract the column numbers of interest from the first row
row = csv.next_row()
idx_date = csv.get_index('Date taken')
idx_email = csv.get_index('Login ID')
idx_andrew = csv.get_index('Andrew')
if idx_andrew == -1:
idx_andrew = csv.get_index('AndrewID')
if idx_andrew == -1:
idx_andrew = csv.get_index('Andrew ID')
idx_mcq = csv.get_index('MCQ')
idx_coding = csv.get_index('Coding')
idx_score = csv.get_index('Total score')
idx_date = csv.get_index('Date taken') # was the assignment late?
idx_qs = [csv.get_index('Question '+str(num)) for num in range(1,100)]
while not csv.eof:
row = csv.next_row()
if not row:
break
submit_date = csv.get_field(idx_date)
email = csv.get_field(idx_email)
andrew = csv.get_field(idx_andrew)
mcq = csv.get_field(idx_mcq)
coding = csv.get_field(idx_coding)
total = csv.get_field(idx_score)
subscores = [csv.get_field(i) for i in idx_qs if i >= 0]
uid = course.get_student_id(email,andrew)
if uid is None:
continue # non-existent or dropped student
comment = build_feedback(partnum,total,mcq,coding,subscores)
if uid in grades:
gr = grades[uid]
else:
gr = Grade()
grades[uid] = gr
if verbose:
print(' adding',uid,partnum,email,total,comment)
if total is not None:
pn = partnum if partnum >= 0 else 0
gr.add(total,comment,pn,course.late_penalty(submit_date))
return
######################################################################
def extract_andrew_from_filename(filename,what='feedback'):
if '/' in filename:
filename = filename.split('/')[-1]
return filename.rsplit('_{}'.format(what),-1)[0]
######################################################################
def normalize_q_value(val):
if val is None or val == '' or val[0] == 'n':
return 'na'
return val
######################################################################
def validate_shuffle_assessment(course,csv_filename):
with open(csv_filename,"r") as f:
csvfile = CanvasCSV(f)
# read header line
try:
row = csvfile.next_row()
except Exception as e:
print('Invalid data in file',csv_filename)
return False
interviewer = extract_andrew_from_filename(csv_filename,'assessment')
# skip second header line
csvfile.next_row()
# read interviewee AndrewID
row = csvfile.next_row()
andrew = email_to_AndrewID(row[1])
if andrew is None or andrew == '' or interviewer == andrew:
return None
if course.get_id_for_student(andrew) is not None:
return interviewer
return None
######################################################################
def parse_shuffle_assessment(course,csv,filename,grades,verbose = False):
# read header line
row = csv.next_row()
interviewer = extract_andrew_from_filename(filename,'assessment')
if "Feedback" in row[0]:
print('*',interviewer,"submitted an Interviewer Feedback")
return
# skip second header line
csv.next_row()
# read AndrewIDs and Q1/Q2/Q3/Overall scores
row = csv.next_row()
andrew = email_to_AndrewID(row[1])
##FIXME: massage AndrewID
try:
totalscore = float(row[17])
except:
print('Bad totalscore in',filename)
totalscore = -1
had_error = True
if interviewer == andrew:
print('*',interviewer,'gave own AndrewID as interviewee')
return
# skip empty line
csv.next_row()
# skip header line
csv.next_row()
# skip second header line
csv.next_row()
q1 = []
q2 = []
q3 = []
had_error = False
for i in range(7):
# get rubric score i for the three questions
row = csv.next_row()
if row is None:
print('Bad data in',filename)
had_error = True
q1 += ['?']
q2 += ['?']
q3 += ['?']
else:
q1 += [normalize_q_value(row[0])]
q2 += [normalize_q_value(row[1])]
q3 += [normalize_q_value(row[2])]
# skip empty line
csv.next_row()
# skip header line
csv.next_row()
# skip second header line
csv.next_row()
overall = []
for i in range(5):
row = csv.next_row()
if row is None:
had_error = True
else:
overall += [row[0]]
# skip empty line
csv.next_row()
# skip header line
csv.next_row()
# read feedback text
row = csv.next_row()
if row is None:
had_error = True
feedback = ''
else:
feedback = row[3]
try:
# strip decimal part of total score
base_score = int(totalscore)
except:
base_score = 0
if base_score == 0:
print('-',filename,'gives zero score')
# validity checks
if andrew is None or andrew == '':
print('*',filename,"does not include interviewee's Andrew ID")
return
uid = course.get_id_for_student(andrew)
if uid is None:
print('*',filename,'contains an unknown Andrew ID:',andrew)
return
if uid in grades:
print('=',filename,"contains an Andrew ID we've already seen:",andrew)
return
# reformat the information into a comment for the gradebook
comment = 'Q1: {}/{}/{}/{}/{}/{}/{}'.format(q1[0],q1[1],q1[2],q1[3],q1[4],q1[5],q1[6])
if ''.join(q2) != '' and ''.join(q2) != 'nanananananana':
comment += '\nQ2: {}/{}/{}/{}/{}/{}/{}'.format(q2[0],q2[1],q2[2],q2[3],q2[4],q2[5],q2[6])
if ''.join(q3) != '' and ''.join(q2) != 'nanananananana':
comment += '\nQ3: {}/{}/{}/{}/{}/{}/{}'.format(q3[0],q3[1],q3[2],q3[3],q3[4],q3[5],q3[6])
comment += '\nOverall: {}/{}/{}/{}/{}'.format(overall[0],overall[1],overall[2],overall[3],overall[4])
comment += '\nFeedback: {}'.format(feedback)
## insert score and comment into 'grades'
if had_error:
print('Bad data in',filename,', best guess is:')
print(' ',andrew,totalscore,comment)
if verbose:
print(" adding",uid,andrew,totalscore,comment)
grades[uid] = Grade(totalscore,comment)
return
######################################################################
def email_to_AndrewID(login, default_id=None):
login = login.lower()
if MAIL in login:
login, m, rest = login.rpartition(MAIL)
if '@' in login and default_id:
# non-Andrew email, so use provided Andrew ID
login = default_id
return login.strip().lower()
######################################################################
def parse_shuffle_feedback(course, csv, filename, grades, verbose = False):
if '_feedback' in filename:
user = filename.rsplit('_feedback',-1)[0]
else:
user = None
## extract the column numbers of interest from the first row
row = csv.next_row()
if "Interviewee:" in row or "Location" in row[3]:
print('*',extract_andrew_from_filename(filename),"submitted an Interviewee Assessment")
return
# skip the second row, which contains user instructions
row = csv.next_row()
if 'Andrew' in row:
# file format error? Possibly shifted contents of spreadsheet
print(filename,"is an unrecognized file")
return
# third row contains interviewer's AndrewID and overall criterion scores + final average
row = csv.next_row()
andrew = row[0]
# massage Andrew ID
andrew = email_to_AndrewID(andrew)
overall_score = row[14]
# skip empty row
csv.next_row()
# skip header line
csv.next_row()
crit = [0]*4
for i in range(4):
row = csv.next_row()
if row[0] == '':
print('!',filename,' contains blank entry in rubric')
crit[i] = 0
else:
try:
crit[i] = float(row[0])
except:
print('*',filename,' contains invalid entry in rubric')
return
# skip next header line
csv.next_row()
# read comments line
row = csv.next_row()
comment = '(no comment given)' if row is None else ''.join(row)
## validity checks
if andrew is None or andrew == "":
print('*',filename," does not contain an Interviewer ID")
return
if andrew == user:
print("= user",andrew,"entered own ID as interviewer")
return
uid = course.get_id_for_student(andrew)
if uid is None:
print('*',filename,"contains an unknown Andrew ID:",andrew)
return
if uid in grades:
print('+',filename,"contains an Andrew ID we've already seen:",andrew)
return
## OK, we've got a good feedback form, so massage the data
## we're changing the score in Canvas to be 0-40 to be compatible with an upcoming switch to rubric scoring,
## so just add up the subscores
overall_score = sum(crit)
feedback = 'Subscores: {}/{}/{}/{}, Feedback: {}'.format(crit[0],crit[1],crit[2],crit[3],comment)
if verbose:
print(" adding",uid,andrew,overall_score,feedback)
grades[uid] = Grade(overall_score,feedback)
return
######################################################################
def process_grades(course, flags, csv_files):
grades = {}
for (i, csv_file) in enumerate(csv_files):
with open(csv_file,"r") as f:
csvfile = CanvasCSV(f)
if flags.inclass:
print('processing',csv_file)
parse_hackerrank(course,csvfile,grades,-1,flags.verbose)
elif flags.homework or flags.exam:
print('processing',csv_file)
parse_hackerrank(course,csvfile,grades,i,flags.verbose)
elif flags.shuffle:
parse_shuffle_assessment(course,csvfile,csv_file,grades,flags.verbose)
elif flags.feedback:
parse_shuffle_feedback(course,csvfile,csv_file,grades,flags.verbose)
if flags.inclass or flags.homework:
numparts = len(csv_files)
else:
numparts = 1
course.batch_upload_grades(grades,numparts)
if flags.inclass:
course.zero_missing_assignment()
return
######################################################################
def process_shuffle_assessment(submissions, rubric_def, rubric_grades, submit_grades, assessors,
submit_points, course, verbose = False, require_complete = False):
if verbose:
print(len(submissions),'total submissions retrieved')
for sub in submissions:
if sub['id'] not in assessors:
continue
pts = submit_points
incomplete = False
remarks = ''
attachments = []
if 'submission_comments' in sub:
for com in sub['submission_comments']:
if 'attachments' in com and com['attachments'] and com['author']['display_name'] not in COURSE_STAFF:
for a in com['attachments']:
ctype = 'unknown'
if 'content-type' in a:
ctype = a['content-type']
attachments += (a['filename'],ctype,a['mime_class'],a['url'])
if verbose:
print('Attachments:',attachments)
uid = sub['user_id']
reviewer, _, criteria = assessors[sub['id']]
crit_points = {}
for crit in criteria:
if require_complete:
if 'points' not in crit or 'criterion_id' not in crit:
if not incomplete and rubric_def.criterion_points(crit['criterion_id']) > 0:
pts = pts - (INCOMPLETE_RUBRIC_PENALTY * submit_points)
remarks += ('Incomplete rubric (-{})'
.format(Grade.drop_decimals(INCOMPLETE_RUBRIC_PENALTY*submit_points)))
incomplete = True
continue
elif 'points' not in crit or 'criterion_id' not in crit or crit['points'] < 0.0:
continue # N/A or non-scored criterion
points = crit['points']
c_id = crit['criterion_id']
name = rubric_def.get_name(c_id)
if not name:
continue
if name[0] == 'Q' and name[2] == ':':
name = name[4:]
if 'Suggestions' in name:
if len(crit['comments']) < 8:
pts = pts - (0.05 * submit_points)
remarks += 'Did not provide suggested improvements (-{})\n' \
.format(Grade.drop_decimals(0.05*submit_points))
continue
if 'Location' in name:
if len(crit['comments']) < 8:
pts = pts - (0.05 * submit_points)
remarks += 'Did not specify location/time (-{})\n'.format(Grade.drop_decimals(0.05*submit_points))
continue
if name in crit_points:
crit_points[name] = crit_points[name] + [points]
else:
crit_points[name] = [points]
total_points = 0
possible = 0
if verbose:
print('crit_points:',crit_points)
for itemname, pointlist in crit_points.items():
total_points += mean(pointlist)
possible += 5
if total_points == 0:
print('! {} ({}) received a zero score'.format(course.student_login(uid),uid))
if possible > 0:
grade = SHUFFLE_ASSESSMENT_POINTS * (total_points / possible)
rubric_grades[uid] = SHUFFLE_ASSESSMENT_POINTS * (total_points / possible)
else:
grade = None
print('empty rubric for {} ({})'.format(course.student_login(uid),uid))
if reviewer is not None:
if attachments == []: ##FIXME
pts = pts - (NO_PHOTO_PENALTY * submit_points)
remarks += 'Did not upload photo (-{})'.format(Grade.drop_decimals(NO_PHOTO_PENALTY*submit_points))
submit_grades[reviewer] = Grade(pts,remarks)
if verbose:
print(' ',course.student_login(reviewer),'entered',grade,'for',course.student_login(uid))
return
######################################################################
def process_shuffle_rubric(course, flags):
if flags.feedback:
submit_assign_id = course.find_assignment_id(flags.feedback)
return course.confirm_peer_review_scores(course.assignment_id,submit_assign_id,None,SHUFFLE_SUBMISSION_POINTS,
require_complete=True)
submit_assign_id = course.find_assignment_id(flags.shuffle)
return course.confirm_peer_review_scores(course.assignment_id,submit_assign_id,process_shuffle_assessment,
SHUFFLE_SUBMISSION_POINTS)
######################################################################
def process_shuffle_csv(course, flags):
if flags.feedback:
what = 'feedback'
submit_assign = flags.feedback
else:
what = 'assessment'
submit_assign = flags.shuffle
submit_assign_id = course.find_assignment_id(submit_assign)
if submit_assign_id is None:
return
# get both current and former students, since someone may have uploaded feedback before dropping the course
submissions = course.fetch_assignment_submissions(submit_assign_id)
spreadsheets = []
submit_grades = {}
have_spreadsheet = {}
validated = {}
have_photo = {}
# start by downloading all of the attachments
for sub in submissions:
if sub['workflow_state'] != 'submitted' and (not flags.force or sub['workflow_state'] != 'graded'):
continue
uid = sub['user_id']
late_seconds = sub['seconds_late']
late_days = (late_seconds + 86100) // 86400
login = course.student_login(uid)
attachments = sub['attachments'] if 'attachments' in sub else []
spreadsheet_url = None
filename = None
suffix = None
for attach in attachments:
if 'filename' not in attach or 'content-type' not in attach or 'url' not in attach:
continue
mimetype = attach['content-type']
if 'spreadsheet' in mimetype:
spreadsheet_url = attach['url']
filename = attach['filename']
(base, period, suffix) = filename.rpartition('.')
if 'image' in mimetype:
have_photo[uid] = True
if spreadsheet_url:
destfile = '{}/{}_{}.{}'.format(flags.dir,login,what,suffix)
print('Downloading',what,'by',login)
try:
urllib.request.urlretrieve(spreadsheet_url,filename=destfile)
except Exception as err:
print(err)
else:
spreadsheets += [destfile]
have_spreadsheet[uid] = True
if flags.verbose:
print(spreadsheet_url,'->',destfile)
else:
print('-',login,'did not upload',what,'spreadsheet')
# convert spreadsheets to CSV and validate
csv_files = CanvasCSV.convert_files_to_csv(spreadsheets,flags.dir)
for filename in csv_files:
interviewer = validate_shuffle_assessment(course,filename)
if interviewer:
validated[interviewer] = True
# now build up the grades
for sub in submissions:
if sub['workflow_state'] != 'submitted' and (not flags.force or sub['workflow_state'] != 'graded'):
continue
uid = sub['user_id']
login = course.student_login(uid)
late_seconds = sub['seconds_late']
late_days = (late_seconds + 86100) // 86400
if uid in have_spreadsheet:
uid = course.get_id_for_student(login)
gr = Grade()
points = SHUFFLE_SUBMISSION_POINTS
## dock student for incorrect interviewee AndrewID
if login not in validated:
gr.add(0,'unknown/missing interviewee AndrewID -- please reupload',1)
points = 0
print('-',login,'had invalid/missing interviewee AndrewID')
## dock student for missing photo upload
elif uid not in have_photo and what == 'assessment':
gr.add(0,'-10 points for not uploading a photo',1)
points -= 10
print('-',login,'did not upload interview photo')
gr.add(points,'',0,course.late_penalty_by_days(late_days))
submit_grades[uid] = gr
print('')
print('Uploading grades for submitting',what)
course.batch_upload_grades(submit_grades,1,submit_assign_id)
print('')
process_grades(course,flags,csv_files)
return
######################################################################
def autodetect(flags,filename):
with open(filename,'r') as f:
pass
## FIXME
return False
######################################################################
def load_indirect_text(text):
if text and len(text) > 1 and text[0] == '@':
## read text from the named file
filename = text[1:]
text = None
try:
with open(filename,'r') as f:
text = f.read()
except Exception as err:
print(err)
return None
return text
######################################################################
if have_HR:
def HR_invite(course,args):
hr = HackerRank(verbose=args.verbose)
hr.simulate(args.dryrun)
test_id = args.invite
msg = load_indirect_text(args.message)
if msg is None or msg == '':
print('No message specified with --message. If you really want to use the\ndefault template, specify a message of "="')
return True
if msg == '=':
msg = None
if args.student:
students = args.student.split(',')
else:
students = course.fetch_active_students()
success = 0
failure = 0
comments = {}
for st in students:
if type(students) == dict:
name = course.student_name(students[st])
else:
name = course.student_name(course.get_id_for_student(st))
email = st if '@' in st else st + MAIL
response = hr.invite_test_candidate(test_id,name,email,msg)
if args.dryrun and not response:
response = {'id': 1, 'test_link': 'foo://bar'}
if response and 'test_link' in response:
if args.verbose:
print('{}: {}'.format(email,response['id']))
success += 1
if type(students) == dict:
uid = students[st]
else:
uid = course.get_id_for_student(email)
if uid and type(uid) == int and uid > 0 and POST_LINK:
## upload a comment with the test link
link_info = 'The link for this assignment is\n{}\n(see the email for full instructions)' \
.format(response['test_link'])
comments[uid] = (0,link_info)
else:
print('{}: failed'.format(email))
failure += 1
print('{} invitations sent, {} errors'.format(success,failure))
if len(comments) > 0:
print('Uploading test links to Canvas')
course.batch_upload_grades(comments,0)
return True
else:
def HR_invite(course,args):
print('Please install hackerrank.py to use this feature')
return False
######################################################################
def HR_submit_day_time(timestamp):
if not timestamp or 'T' not in timestamp:
return None, None
try:
dt = dateutil.parser.parse(timestamp)
dt = dt.astimezone(TIMEZONE)
except:
print('Error parsing',timestamp)
quit()
day = Course.day_of_year(Course.normalize_date('{}/{}/{}'.format(dt.year,dt.month,dt.day)))
return day, dt.hour
######################################################################
def HR_late_penalty(due_day, submit_day, submit_hour):
if not due_day or submit_day <= due_day:
return 0.0
late = (submit_day - due_day) * LATE_PERCENTAGE
if submit_hour == 0:
late -= (LATE_PERCENTAGE/2) # only 5% penalty instead of 10% if submitted before 1am
if late > (LATE_DAYS * LATE_PERCENTAGE): # no submissions accepted more than 7 days late
late = 100
return late / 100
######################################################################
def collect_scores(raw):
'''
convert a list of scores for the parts of an assignment into a map
from student to score on each part
'''
scores = {}
which = 0
for rawsc in raw:
for sc in rawsc:
email = sc['email']
andrew = sc['andrew'] if sc['andrew'] != '' else None
user = email_to_AndrewID(email,andrew)
s = scores[user] if user in scores else []
for _ in range(len(s),which):
s.append(None)
s.append((sc['score'],sc['questions'],HR_submit_day_time(sc['endtime'])))
scores[user] = s
which += 1
# ensure that any students who missed the last part get a null
for email in scores:
s = scores[email]
for _ in range(len(s),which):
s.append(None)
return scores
######################################################################
if have_HR:
def copy_HR_scores(course, args):
hr = HackerRank(verbose = args.verbose)
t_ids = args.copyscores.split(',')
raw_scores = []
for t_id in t_ids:
print('Fetching scores for test',t_id)
raw_scores.append(hr.get_all_test_scores(t_id,all_questions=(len(t_ids) != 1)))
# reshuffle the scores so that we have one list per student, containing the scores from all parts
scores = collect_scores(raw_scores)
grades = {}
today = Course.day_of_year()
for user in scores:
uid = course.get_student_id(user)
if uid is None:
continue
if course.due_day >= today and None in scores[user]:
# not yet due and there are missing parts, so skip
if args.verbose:
print('skipping',user,'because parts missing')
continue
total = 0.0
numparts = len(scores[user])
msg = ''
for part, sc in enumerate(scores[user]):
if numparts > 1:
msg += 'Part {}:'.format(part+1)
if not sc:
msg += hr.feedback(None,0.0)
msg += '\n'
else:
late = HR_late_penalty(course.due_day,sc[2][0],sc[2][1])
total += hr.late_score(sc[0],late)
msg += hr.feedback(sc[1],late)
msg += '\n'
if numparts > 1:
overall = args.points
if not overall or int(overall) <= 0:
overall = 100
if total == int(total):
total = int(total)
msg += 'Sum:\t{}/{} points'.format(total,overall)
grades[uid] = (total, msg)
if args.verbose:
print('{} ({})'.format(user,uid))
print(msg)
else:
print('{}: {}'.format(user,total))
course.batch_upload_grades(grades)
return True
else:
def copy_HR_scores(course, args):
print('Please install hackerrank.py to use this feature')
return False
######################################################################
def date_matches(datespec,mindate,maxdate):
if not datespec or datespec[0] == '#' or not mindate:
return False
datespec = datespec.split(':')[0]
date = datetime.date(year=mindate.year,month=int(datespec[0:2]),day=int(datespec[2:4]))
if maxdate:
return date >= mindate and date < maxdate ## for homeworks, don't start scoring until after due
else:
return date == mindate
######################################################################
def matching_dates(lines,mindate,maxdate=None):
return [line for line in lines if date_matches(line,mindate,maxdate)]
######################################################################
def autoprocess_invite(args,spec):
if type(spec) != list:
spec = [spec]
for inclass in spec:
dt, hr_id, assign_name, msg = inclass.split(':')
args.invite = hr_id
args.assignment = assign_name
args.message = msg
course = setup_course(args)
if not course.assignment_id:
print('Assignment',assign_name,'not found')
continue
HR_invite(course,args)
return
######################################################################
def autoprocess_score(args,spec):
if type(spec) != list:
spec = [spec]
orig_points = args.points
today = datetime.date.today()
year = today.year
for inclass in spec:
fields = inclass.split(':')
if len(fields) < 4:
fields.append((4-len(fields))*[''])
dt, hr_id, assign_name, msg = fields
args.due_day = Course.day_of_year(int(str(year)+dt))
args.points = orig_points
if '/' in hr_id:
hr_id, points = hr_id.split('/')
try:
args.points = int(points)
except:
args.points = 100
args.copyscores = hr_id
args.assignment = assign_name
course = setup_course(args)
copy_HR_scores(course, args)
if args.inclass:
course.zero_missing_assignment()
return
######################################################################
def autoprocess(args, remargs):
if not have_HR:
print('Please install hackerrank.py to use this feature')
return False
today = datetime.date.today()
hour = datetime.datetime.now().hour
## send out invites for, or score, in-class exercises
try:
with open('inclass.txt','r') as f:
lines = matching_dates(f.read().split('\n'),today)
if hour < 12:
autoprocess_invite(args,lines)
elif hour >= 13:
args.inclass = True
autoprocess_score(args,lines)
args.inclass = False
except Exception as err:
print('Skipping processing of in-class exercises')
if args.verbose:
print(' ',err)
## send out invites for homework assignments
if hour < 12:
try:
with open('homework.txt','r') as f:
lines = matching_dates(f.read().split('\n'),today)
autoprocess_invite(args,lines)
except Exception as err:
print('Skipping processing of homework invitations')
if args.verbose:
print(' ',err)
## copy scores for homework assignments
try:
with open('hw-scores.txt','r') as f:
lastweek = today - datetime.timedelta(days=8)
lines = matching_dates(f.read().split('\n'),lastweek,today)
if lines:
autoprocess_score(args,lines)
else:
print('No homework assignments due or within late window')
except Exception as err:
print('Skipping processing of homework scoring')
if args.verbose:
print(' ',err)
return True
######################################################################
def split_interviewers_into_groups(course, interviewers, grouplist, student_ids):
grouplist = grouplist.split(',')
grouped = []
for group in grouplist:
members = course.fetch_group_members(group)
if members:
members = [m['login_id'] for m in members if m['login_id'] in student_ids]
grouped += [members]
return grouped
######################################################################
def add_ungrouped(groups, student_ids):
longest = groups[0]
all_grouped = set()
for g in groups:
if len(g) > len(longest):
longest = g
for stu in g:
all_grouped.add(stu)
for stu in student_ids:
if stu not in all_grouped:
longest.append(stu)
return groups
######################################################################
def make_interview(interviewers, i, questions):
if i+1 < len(interviewers):
interviewee = interviewers[i+1]
else:
interviewee = interviewers[0]
if i > 0:
rev_interviewer = interviewers[i-1]
else:
rev_interviewer = interviewers[len(interviewers)-1]
for it in range(32):
random.shuffle(questions)
# extract the chapter numbers of the first three shuffled questions
f3chap = list(map(lambda x: int(x.split('.')[0]), questions[:3]))
# try to get questions from three different chapters
if it < 24 and (f3chap[0] == f3chap[1] or f3chap[1] == f3chap[2] or f3chap[0] == f3chap[2]):
continue # try again
# after the 24th try, we'll accept anything except all three questions from the same chapter
if sum(f3chap) != (3 * f3chap[0]):
break
return [interviewee,rev_interviewer] + questions[:3]
######################################################################
def swap_partners(interviewers, idx1, idx2):
tmp = interviewers[idx1]
interviewers[idx1] = interviewers[idx2]
interviewers[idx2] = tmp
# print('swapped',interviewers[idx1],'and',interviewers[idx2]) ##DEBUG
return
######################################################################
def is_repeat_interview(interviewers, partner1, partner2, prev_matches, exact = False):
partner1 = interviewers[partner1]
partner2 = interviewers[partner2]
return ((partner1, partner2) in prev_matches) or (not exact and (partner2, partner1) in prev_matches)
######################################################################
def have_repeat_interviewer(interviewers, prev_matches):
l = len(interviewers)
for i in range(l):
if is_repeat_interview(interviewers,i,(i+1)%l,prev_matches):
return True
return False
######################################################################
def repeated_partners(interviewers, partner1, partner2, partner3, prev_matches, exact = False):
partner1 = interviewers[partner1]
partner2 = interviewers[partner2]
partner3 = interviewers[partner3]
if ((partner1, partner2) in prev_matches) or ((partner2, partner3) in prev_matches):
return True
if exact:
return False
return ((partner2, partner1) in prev_matches) or ((partner3, partner2) in prev_matches)
######################################################################
def remove_repeat_interviewers(interviewers, prev_matches):
l = len(interviewers)
if prev_matches and l > 4:
#print('remove_repeat_interviewers',interviewers) ##DEBUG
for _ in range(8):
if not have_repeat_interviewer(interviewers, prev_matches):
return
random.shuffle(interviewers)
## first pass: eliminate repeats, avoiding swapping with any repeats
for i in chain(range(l),range(l)):
cur = (i+1) % l
if is_repeat_interview(interviewers,i,cur,prev_matches):
for j in range(2,l-2):
alt = (i+j) % l
if (not repeated_partners(interviewers,(alt-1)%l,cur,(alt+1)%l,prev_matches,False) and
not repeated_partners(interviewers,i,alt,(i+2)%l,prev_matches,False)):