/
c_teams.py
520 lines (396 loc) · 13.7 KB
/
c_teams.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
#!/bin/env python
import os, sys, csv, sr, re
import mailer
def get_team(num):
return sr.group( "team%i" % num )
def get_college(num):
return sr.group( "college-%i" % num )
def search_colleges(s):
"Search through the colleges to find one with s its name"
groups = sr.groups.list("college-*")
res = []
for gname in groups:
group = sr.group(gname)
if s.upper() in group.desc.upper():
res.append(group)
return res
def college_find( numsub ):
colnum = None
try:
colnum = int(numsub)
except ValueError:
pass
if colnum == None:
cols = search_colleges(numsub)
else:
return get_college(colnum)
if len(cols) > 1:
# TODO: prompt the user
print "\"%s\" matches more than one college." % numsub
sys.exit(1)
if len(cols) == 0:
print "\"%s\" matches no colleges." % numsub
sys.exit(1)
return cols[0]
def new_username( fname, lname, tmpset = [] ):
prefix = "%s%s" % (fname[0], lname[0])
prefix = prefix.lower()
def c(i):
return "%s%i" % (prefix, i)
n = 1
u = sr.user( c(n) )
while u.in_db or u.username in tmpset:
n += 1
u = sr.user( c(n) )
return u.username
def new_team():
i = 1
tg = get_team(i)
while tg.in_db:
i += 1
tg = get_team(i)
return i
def print_table( rows ):
widths = []
for colnum in range(0, len(rows[0])):
w = 0
for row in rows:
w = max(w, len(row[colnum]))
widths.append(w)
for row in rows:
for colnum in range(0, len(row)):
v = row[colnum]
sys.stdout.write( v )
sys.stdout.write( " " * (4 + widths[colnum] - len(v)) )
sys.stdout.write( "\n" )
class CmdBase:
def __init__(self, args):
abort = False
if hasattr(self, "min_args") and len(args) < self.min_args:
print "Too few arguments to command."
abort = True
if hasattr(self, "max_args") and len(args) > self.max_args:
print "Too many arguments to command"
abort = True
if abort:
if hasattr(self, "usage"):
print "Usage: %s" % self.usage
sys.exit(1)
class CmdTeamList(CmdBase):
desc = "List the teams"
max_args = 0
def __init__(self, args):
CmdBase.__init__(self, args)
glist = sr.groups.list()
for gname in glist:
if re.match( "^team[0-9]+$", gname ) == None:
continue
print gname
class CmdTeamCreateCSV(CmdBase):
desc = "Create a new team from a CSV file"
usage = "COLLEGE_(NUMBER|SUBSTR) CSV_FILE [lang=LANG] [team=TEAMNO]"
min_args, max_args = 2, 4
def __init__(self, args):
CmdBase.__init__(self, args)
CDESC, CSV_FNAME = args[0], args[1]
college_group = college_find( CDESC )
newusers = self.form_new_users( CSV_FNAME )
print
print "Will create %i users" % len(newusers)
disp = [["username", "fname", "lname", "email"]]
disp += [ [u.username, u.cname, u.sname, u.email] for u in newusers ]
print_table( disp )
teamno = None
lang = "english"
for arg in args[2:]:
name, val = arg.split("=")
if name == "team":
teamno = int(val)
elif name == "lang":
lang = val
else:
raise Exception("Unsupported argument \"%s\"", arg)
if teamno == None:
teamno = new_team()
print
print "They will form team %i." % teamno
print "And will be associated with %s: %s." % ( college_group.name, college_group.desc )
students_group = sr.group("students")
team_group = get_team(teamno)
print "Is this OK? (yes/no)",
resp = raw_input()
resp = resp.lower().strip()
if resp == "yes":
print "Creating users..."
for u in newusers:
print "\t", u.username
passwd = sr.users.GenPasswd()
# Password has to be set after user is in db
u.save()
u.set_passwd( new = passwd )
u.set_lang( lang )
mailer.send_template( "welcome", u, { "PASSWORD": passwd } )
print "Saving groups."
for g in students_group, team_group, college_group:
g.user_add(newusers)
g.save()
def form_new_users(self, csv_fname):
"Create the new user objects -- not in db yet."
rows = self.read_csv( csv_fname )
# Returns dictionary
# keys are columns, values are column numbers
colmap = self.discover_columns(rows)
newusers = []
for row in rows:
fname, lname, email = [row[colmap[x]] for x in ["fname", "lname", "email"]]
u = sr.user( new_username(fname, lname, tmpset = [x.username for x in newusers]) )
u.cname = fname.strip().capitalize()
u.sname = lname.strip().capitalize()
u.email = email.strip().lower()
newusers.append(u)
return newusers
def score_fname(self, col):
fname = os.path.join( os.path.dirname(__file__), "data/yob2009.txt" )
census = csv.reader( open(fname, "r") )
census_fnames = set()
for row in census:
census_fnames.add( row[0].upper() )
s = 0
col = [x.upper() for x in col]
for val in col:
if val in census_fnames:
s += 1
return s
def score_lname(self, col):
fname = os.path.join( os.path.dirname(__file__), "data/surnames.txt" )
census = open(fname, "r")
census_lnames = set()
for row in census.readlines():
census_lnames.add( row.strip().upper() )
s = 0
col = [x.strip().upper() for x in col]
for val in col:
if val in census_lnames:
s += 1
return s
def score_email(self, col):
s = 0
for val in col:
if '@' in val:
s += 1
return s
def discover_columns(self, rows):
"Return a map of columns to use given csv rows"
score_funcs = { "fname": self.score_fname,
"lname": self.score_lname,
"email": self.score_email }
cols = { "fname":0, "lname":0, "email":0 }
max_cols = max([len(row) for row in rows])
scores = [dict(cols) for x in range(0, max_cols)]
for colnum in range(0, max_cols):
col = []
for row in rows:
try:
col.append( row[colnum] )
except IndexError:
pass
for field, fn in score_funcs.iteritems():
scores[colnum][field] += fn(col)
for colname in cols.keys():
colscores = [x[colname] for x in scores]
cols[colname] = self.find_max_score(colscores)[0]
while True:
print "*" * 40
print "Column arrangement:"
print cols
print
print " y = yes, create this team."
print " change COLNAME colnum"
print " q = quit this utility"
print " e = show an example line"
print "Command:",
resp = raw_input()
if len(resp) == 0:
continue
if resp[0] == "y":
break
if resp == "q":
sys.exit(1)
if resp == "e":
print rows[0]
continue
ss = resp.split()
if ss[0] == "change":
if len(ss) < 3:
print "Please specify a column name and number"
continue
colname, num = ss[1], int(ss[2])
if not cols.has_key(colname):
print "Invalid field name \"%s\"." % colname
continue
if num >= max_cols or num < 0:
print "Invalid column number."
continue
cols[colname] = num
return cols
def find_max_score(self, colscores):
m = max(colscores)
n = 0
cols = []
for score in colscores:
if score == m:
cols.append(n)
n += 1
return cols
def read_csv(self, fname):
csvfile = open( fname, "r" )
r = csv.reader(csvfile)
rows = []
for row in r:
rows.append([x.strip() for x in row])
return rows
class CmdTeamInfo(CmdBase):
desc = "Show information about a team"
usage = "TEAM_NUMBER"
min_args, max_args = 1, 1
def __init__(self, args):
CmdBase.__init__(self, args)
tg = get_team(int(args[0]))
if not tg.in_db:
print "Team %i do not exist" % int(args[0])
sys.exit(1)
# Group people into teachers, students, mentors and misc:
g = ["teachers", "students", "mentors"]
groups = {}
team_grouped = {}
for gname in g:
groups[gname] = sr.group(gname)
team_grouped[gname] = []
for uname in tg.members:
for gname, g in groups.iteritems():
if uname in g.members:
team_grouped[gname].append(uname)
if hasattr(tg, "desc"):
print "Team %i: %s" % (int(args[0]), tg.desc)
else:
print "Team", int(args[0]), "(no description)"
print
for status, ulist in team_grouped.iteritems():
if len(ulist):
print len(ulist), "%s:" % status
ulist.sort()
for u in ulist:
print "\t%s" % u
print
else:
print "No %s." % status
# Work out what college they're from
college_gnames = set()
for uname in team_grouped["students"] + team_grouped["teachers"]:
u = sr.user(uname)
assert u.in_db
for gname in u.groups():
if re.match( "^college-[0-9]+$", gname ) != None:
college_gnames.add( gname )
college_gnames = list(college_gnames)
college_gnames.sort()
if len(college_gnames):
print "Colleges:"
for gname in college_gnames:
print "\t%s" % gname
else:
print "No associated college."
class CmdCollegeList(CmdBase):
desc = "List colleges"
max_args = 0
def __init__(self, args):
CmdBase.__init__(self, args)
glist = sr.groups.list()
for gname in glist:
if re.match( "^college-[0-9]+$", gname ) == None:
continue
g = sr.group(gname)
if hasattr(g, "desc"):
desc = g.desc
else:
desc = "(no description)"
print "%s: %s" % (gname, desc)
print "\t %i members." % len(g.members)
teams = set()
for uname in g.members:
u = sr.user(uname)
assert u.in_db
for gname in u.groups():
if re.match( "^team[0-9]+$", gname ) != None:
teams.add(gname)
print "\t %i teams: %s" % (len(teams),
", ".join([x[4:] for x in teams]) )
print
class CmdCollegeInfo(CmdBase):
desc = "Show information about a college"
usage = "COLLEGE_(NUMBER|SUBSTR)"
min_args, max_args = 1,1
def __init__(self, args):
CmdBase.__init__(self, args)
CDESC = args[0]
college = college_find( CDESC )
print "%s: %s" % (college.name , college.desc)
teams = set()
for uname in college.members:
u = sr.user(uname)
for g in u.groups():
if re.match( "^team[0-9]+$", g ) != None:
teams.add(g)
print "Teams:"
for team in teams:
print "\t -", team
class CmdCollegeCreate(CmdBase):
desc = "Create a new college"
usage = "colleges create DESCRIPTION"
min_args, max_args = 1,1
def __init__(self, args):
CmdBase.__init__(self, args)
desc = args[0]
g = self.next_free_college()
g.desc = desc
g.save()
print "Created college group \"%s\"" % g.name
def next_free_college(self):
i = 1
while True:
cg = get_college(i)
if not cg.in_db:
return cg
i += 1
class CmdTeams:
desc = "Team management commands"
cmds = { "list": CmdTeamList,
"from-csv": CmdTeamCreateCSV,
"info": CmdTeamInfo }
def __init__(self, args):
if len(args) < 1 or args[0] not in self.cmds:
if len(args):
print "Invalid command"
else:
print "Manage teams.\n"
print "Valid subcommands:"
for cmd_name, cmdf in self.cmds.iteritems():
print " - %s: %s" % ( cmd_name, cmdf.desc )
sys.exit(1)
self.cmds[args[0]](args[1:])
class CmdColleges:
desc = "Team management commands"
cmds = { "info" : CmdCollegeInfo,
"list": CmdCollegeList,
"create": CmdCollegeCreate }
def __init__(self, args):
if len(args) < 1 or args[0] not in self.cmds:
if len(args):
print "Invalid command"
else:
print "Manage college groups.\n"
print "Valid subcommands:"
for cmd_name, cmdf in self.cmds.iteritems():
print " - %s: %s" % ( cmd_name, cmdf.desc )
sys.exit(1)
self.cmds[args[0]](args[1:])