~azzar1/unity/add-show-desktop-key

1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
1
#!/usr/bin/env python
2
# IVLE - Informatics Virtual Learning Environment
1195.1.17 by Matt Giuca
ivle-marks: Updated copyright to 2009.
3
# Copyright (C) 2007-2009 The University of Melbourne
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
4
#
5
# This program is free software; you can redistribute it and/or modify
6
# it under the terms of the GNU General Public License as published by
7
# the Free Software Foundation; either version 2 of the License, or
8
# (at your option) any later version.
9
#
10
# This program is distributed in the hope that it will be useful,
11
# but WITHOUT ANY WARRANTY; without even the implied warranty of
12
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
# GNU General Public License for more details.
14
#
15
# You should have received a copy of the GNU General Public License
16
# along with this program; if not, write to the Free Software
17
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
18
19
# Program: Marks
20
# Author:  Matt Giuca
21
22
# Script to calculate the marks for all students for a particular subject.
23
# Requires root to run.
24
25
import sys
26
import os
27
import csv
1195.1.18 by Matt Giuca
ivle.worksheet.utils: Can now calculate exercise and worksheet marks as of a
28
import datetime
1195.1.2 by Matt Giuca
Added optparse - proper options parsing.
29
import optparse
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
30
1195.1.3 by Matt Giuca
ivle-marks: Move root-check earlier so it runs BEFORE the program crashes due
31
if os.getuid() != 0:
32
    print >>sys.stderr, "Must run %s as root." % os.path.basename(sys.argv[0])
33
    sys.exit()
34
1201 by William Grant
ivle.database.get_store() now takes a configuration object.
35
import ivle.config
1080.1.60 by Matt Giuca
ivle.worksheet: Added calculate_score. This is a nice clean Storm port of
36
import ivle.database
1099.1.220 by Nick Chadwick
Merged from trunk
37
import ivle.worksheet.utils
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
38
39
def get_userdata(user):
40
    """
41
    Given a User object, returns a list of strings for the user data which
42
    will be part of the output for this user.
43
    (This is not marks, it's other user data).
44
    """
45
    last_login = (None if user.last_login is None else
1080.1.71 by William Grant
bin/ivle-marks: Fix, and remove dependency on ivle.db. Use Storm to list
46
                    user.last_login.strftime("%d/%m/%y"))
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
47
    return [user.studentid, user.login, user.fullname, last_login]
1195.1.9 by Matt Giuca
ivle-marks: Fixed up header and actual body calculation (now uses the database
48
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
49
userdata_header = ["Student ID", "Login", "Full name", "Last login"]
1195.1.9 by Matt Giuca
ivle-marks: Fixed up header and actual body calculation (now uses the database
50
def get_header(worksheets):
51
    """
52
    Given a list of Worksheet objects (the assessable worksheets), returns a
53
    list of strings -- the column headings for the marks section of the CSV
54
    output.
55
    """
56
    return (userdata_header + [ws.name for ws in worksheets]
57
            + ["Total %", "Mark"])
58
1195.1.18 by Matt Giuca
ivle.worksheet.utils: Can now calculate exercise and worksheet marks as of a
59
def get_marks_user(worksheets, user, as_of=None):
1195.1.9 by Matt Giuca
ivle-marks: Fixed up header and actual body calculation (now uses the database
60
    """Gets marks for a particular user for a particular set of worksheets.
61
    @param worksheets: List of Worksheet objects to get marks for.
62
    @param user: User to get marks for.
1195.1.18 by Matt Giuca
ivle.worksheet.utils: Can now calculate exercise and worksheet marks as of a
63
    @param as_of: Optional datetime. If supplied, gets the marks as of as_of.
1195.1.9 by Matt Giuca
ivle-marks: Fixed up header and actual body calculation (now uses the database
64
    @returns: The user's percentage for each worksheet, overall, and
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
65
    their final mark, as a list of strings, in a manner which corresponds to
66
    the headings produced by get_marks_header.
67
    """
68
    worksheet_pcts = []
69
    # As we go, calculate the total score for this subject
70
    # (Assessable worksheets only, mandatory problems only)
71
    problems_done = 0
72
    problems_total = 0
73
1195.1.9 by Matt Giuca
ivle-marks: Fixed up header and actual body calculation (now uses the database
74
    for worksheet in worksheets:
1080.1.60 by Matt Giuca
ivle.worksheet: Added calculate_score. This is a nice clean Storm port of
75
        # We simply ignore optional exercises here
76
        mand_done, mand_total, _, _ = (
1195.1.18 by Matt Giuca
ivle.worksheet.utils: Can now calculate exercise and worksheet marks as of a
77
            ivle.worksheet.utils.calculate_score(store, user, worksheet,
78
                                                 as_of))
1195.1.15 by Matt Giuca
ivle-marks, ivle.worksheet.utils: Fixed Divide-by-zero exception if there are
79
        if mand_total > 0:
80
            worksheet_pcts.append(float(mand_done) / mand_total)
81
        else:
82
            # Avoid Div0, just give everyone 0 marks if there are none
83
            worksheet_pcts.append(0.0)
1080.1.60 by Matt Giuca
ivle.worksheet: Added calculate_score. This is a nice clean Storm port of
84
        problems_done += mand_done
85
        problems_total += mand_total
1195.1.13 by Matt Giuca
ivle.worksheet.utils: Added calculate_mark, which is from the duplicated code
86
    percent, mark, _ = (
87
        ivle.worksheet.utils.calculate_mark(problems_done, problems_total))
88
    return worksheet_pcts + [float(percent)/100, mark]
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
89
1195.1.18 by Matt Giuca
ivle.worksheet.utils: Can now calculate exercise and worksheet marks as of a
90
def writeuser(worksheets, user, csvfile, cutoff=None):
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
91
    userdata = get_userdata(user)
1195.1.18 by Matt Giuca
ivle.worksheet.utils: Can now calculate exercise and worksheet marks as of a
92
    marksdata = get_marks_user(worksheets, user, cutoff)
1195.1.11 by Matt Giuca
ivle-marks: Fix up error trying to print Unicode strings with non-ASCII
93
    data = userdata + marksdata
94
    # CSV writer can't handle non-ASCII characters. Encode to UTF-8.
95
    data = [unicode(x).encode('utf-8') for x in data]
96
    csvfile.writerow(data)
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
97
1195.1.4 by Matt Giuca
ivle-marks: Moved all of the various code outside any functions into a main
98
def main(argv=None):
99
    global store
100
    if argv is None:
101
        argv = sys.argv
102
103
    usage = """usage: %prog [options] subject
104
    (requires root)
105
    Reports each student's marks for a given subject offering."""
106
107
    # Parse arguments
108
    parser = optparse.OptionParser(usage)
109
    parser.add_option("-s", "--semester",
110
        action="store", dest="semester", metavar="YEAR/SEMESTER",
111
        help="Semester of the subject's offering (eg. 2009/1). "
1195.1.18 by Matt Giuca
ivle.worksheet.utils: Can now calculate exercise and worksheet marks as of a
112
             "Defaults to the currently active semester.",
113
        default=None)
114
    parser.add_option("-c", "--cutoff",
115
        action="store", dest="cutoff", metavar="DATE",
116
        help="Cutoff date (calculate the marks as of this date). "
117
             "YYYY-MM-DD H:M:S.",
1195.1.4 by Matt Giuca
ivle-marks: Moved all of the various code outside any functions into a main
118
        default=None)
119
    (options, args) = parser.parse_args(argv[1:])
120
121
    if len(args) < 1:
122
        parser.print_help()
123
        parser.exit()
124
1195.1.5 by Matt Giuca
ivle-marks: Now gets a subject object from the db (doesn't yet use it),
125
    subject_name = unicode(args[0])
126
1195.1.4 by Matt Giuca
ivle-marks: Moved all of the various code outside any functions into a main
127
    if options.semester is None:
128
        year, semester = None, None
129
    else:
130
        try:
131
            year, semester = options.semester.split('/')
132
            if len(year) == 0 or len(semester) == 0:
133
                raise ValueError()
134
        except ValueError:
135
            parser.error('Invalid semester (must have form "year/semester")')
136
1195.1.18 by Matt Giuca
ivle.worksheet.utils: Can now calculate exercise and worksheet marks as of a
137
    if options.cutoff is not None:
138
        try:
139
            cutoff = datetime.datetime.strptime(options.cutoff,
140
                                                "%Y-%m-%d %H:%M:%S")
141
        except ValueError:
142
            parser.error("Invalid date format: '%s' "
143
                         "(must be YYYY-MM-DD H:M:S)." % options.cutoff)
144
    else:
145
        cutoff = None
146
1246 by Matt Giuca
ivle.marks: No longer loads all of the plugins via config.Config.
147
    store = ivle.database.get_store(ivle.config.Config(plugins=False))
1195.1.5 by Matt Giuca
ivle-marks: Now gets a subject object from the db (doesn't yet use it),
148
149
    # Get the subject from the DB
150
    subject = store.find(ivle.database.Subject,
151
                     ivle.database.Subject.short_name == subject_name).one()
152
    if subject is None:
153
        print >>sys.stderr, "No subject with short name '%s'" % subject_name
154
        return 1
155
1195.1.7 by Matt Giuca
ivle-marks: Added code to get an offering from the DB (either the semester
156
    # Get the offering from the DB
157
    if semester is None:
158
        # None specified - get the current offering from the DB
159
        offerings = list(subject.active_offerings())
160
        if len(offerings) == 0:
161
            print >>sys.stderr, ("No active offering for subject '%s'"
162
                                 % subject_name)
163
            return 1
164
        elif len(offerings) > 1:
165
            print >>sys.stderr, ("Multiple active offerings for subject '%s':"
166
                                 % subject_name)
167
            print >>sys.stderr, "Please use one of:"
168
            for offering in offerings:
169
                print >>sys.stderr, ("    --semester=%s/%s"
170
                    % (offering.semester.year, offering.semester.semester))
171
            return 1
172
        else:
173
            offering = offerings[0]
174
    else:
175
        # Get the offering for the specified semester
176
        offering = subject.offering_for_semester(year, semester)
177
        if offering is None:
178
            print >>sys.stderr, (
179
                "No offering for subject '%s' in semester %s/%s"
180
                % (subject_name, year, semester))
181
            return 1
182
1195.1.8 by Matt Giuca
ivle-marks: Now gets the list of assessable worksheets from the database
183
    # Get the list of assessable worksheets
1195.1.14 by Matt Giuca
ivle-marks: Do not list() the lookup for worksheets (since it doesn't need to
184
    worksheets = offering.worksheets.find(assessable=True)
1195.1.8 by Matt Giuca
ivle-marks: Now gets the list of assessable worksheets from the database
185
1195.1.4 by Matt Giuca
ivle-marks: Moved all of the various code outside any functions into a main
186
    # Start writing the CSV file - header
187
    csvfile = csv.writer(sys.stdout)
1195.1.9 by Matt Giuca
ivle-marks: Fixed up header and actual body calculation (now uses the database
188
    csvfile.writerow(get_header(worksheets))
1195.1.4 by Matt Giuca
ivle-marks: Moved all of the various code outside any functions into a main
189
1195.1.16 by Matt Giuca
ivle-marks: Now only displays users who are enrolled in the given offering.
190
    # Get all users enrolled in this offering
191
    users = store.find(ivle.database.User,
192
                   ivle.database.User.id == ivle.database.Enrolment.user_id,
193
                   offering.id == ivle.database.Enrolment.offering).order_by(
194
                        ivle.database.User.login)
1195.1.4 by Matt Giuca
ivle-marks: Moved all of the various code outside any functions into a main
195
    for user in users:
1195.1.18 by Matt Giuca
ivle.worksheet.utils: Can now calculate exercise and worksheet marks as of a
196
        writeuser(worksheets, user, csvfile, cutoff)
1195.1.4 by Matt Giuca
ivle-marks: Moved all of the various code outside any functions into a main
197
198
if __name__ == "__main__":
199
    sys.exit(main(sys.argv))