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

« back to all changes in this revision

Viewing changes to ivle/worksheet.py

Give console and tutorial services security declarations.

Show diffs side-by-side

added added

removed removed

Lines of Context:
23
23
This module provides functions for tutorial and worksheet computations.
24
24
"""
25
25
 
26
 
from storm.locals import And, Asc, Desc, Store
27
 
import genshi
28
 
 
 
26
from storm.locals import And, Asc, Desc
29
27
import ivle.database
30
 
from ivle.database import ExerciseAttempt, ExerciseSave, Worksheet, \
31
 
                          WorksheetExercise, Exercise
32
28
 
33
29
__all__ = ['get_exercise_status', 'get_exercise_stored_text',
34
30
           'get_exercise_attempts', 'get_exercise_attempt',
35
31
          ]
36
32
 
37
 
def get_exercise_status(store, user, worksheet_exercise, as_of=None):
 
33
def get_exercise_status(store, user, exercise):
38
34
    """Given a storm.store, User and Exercise, returns information about
39
35
    the user's performance on that problem.
40
 
    @param store: A storm.store
41
 
    @param user: A User.
42
 
    @param worksheet_exercise: An Exercise.
43
 
    @param as_of: Optional datetime. If supplied, gets the status as of as_of.
44
36
    Returns a tuple of:
45
37
        - A boolean, whether they have successfully passed this exercise.
46
38
        - An int, the number of attempts they have made up to and
47
39
          including the first successful attempt (or the total number of
48
40
          attempts, if not yet successful).
49
41
    """
 
42
    ExerciseAttempt = ivle.database.ExerciseAttempt
50
43
    # A Storm expression denoting all active attempts by this user for this
51
44
    # exercise.
52
45
    is_relevant = ((ExerciseAttempt.user_id == user.id) &
53
 
            (ExerciseAttempt.ws_ex_id == worksheet_exercise.id) &
54
 
            (ExerciseAttempt.active == True))
55
 
    if as_of is not None:
56
 
        is_relevant &= ExerciseAttempt.date <= as_of
 
46
                   (ExerciseAttempt.exercise_id == exercise.id) &
 
47
                   (ExerciseAttempt.active == True))
57
48
 
58
49
    # Get the first successful active attempt, or None if no success yet.
59
50
    # (For this user, for this exercise).
75
66
 
76
67
    return first_success is not None, num_attempts
77
68
 
78
 
def get_exercise_stored_text(store, user, worksheet_exercise):
79
 
    """Given a storm.store, User and WorksheetExercise, returns an
 
69
def get_exercise_stored_text(store, user, exercise):
 
70
    """Given a storm.store, User and Exercise, returns an
80
71
    ivle.database.ExerciseSave object for the last saved/submitted attempt for
81
72
    this question (note that ExerciseAttempt is a subclass of ExerciseSave).
82
73
    Returns None if the user has not saved or made an attempt on this
84
75
    If the user has both saved and submitted, it returns whichever was
85
76
    made last.
86
77
    """
 
78
    ExerciseSave = ivle.database.ExerciseSave
 
79
    ExerciseAttempt = ivle.database.ExerciseAttempt
87
80
 
88
81
    # Get the saved text, or None
89
82
    saved = store.find(ExerciseSave,
90
83
                ExerciseSave.user_id == user.id,
91
 
                ExerciseSave.ws_ex_id == worksheet_exercise.id).one()
 
84
                ExerciseSave.exercise_id == exercise.id).one()
92
85
 
93
86
    # Get the most recent attempt, or None
94
87
    attempt = store.find(ExerciseAttempt,
95
88
            ExerciseAttempt.user_id == user.id,
 
89
            ExerciseAttempt.exercise_id == exercise.id,
96
90
            ExerciseAttempt.active == True,
97
 
            ExerciseAttempt.ws_ex_id == worksheet_exercise.id
98
91
        ).order_by(Asc(ExerciseAttempt.date)).last()
99
92
 
100
93
    # Pick the most recent of these two
109
102
        else:
110
103
            return None
111
104
 
112
 
def _get_exercise_attempts(store, user, worksheet_exercise, as_of=None,
 
105
def _get_exercise_attempts(store, user, exercise, as_of=None,
113
106
        allow_inactive=False):
114
107
    """Same as get_exercise_attempts, but doesn't convert Storm's iterator
115
108
    into a list."""
 
109
    ExerciseAttempt = ivle.database.ExerciseAttempt
116
110
 
117
111
    # Get the most recent attempt before as_of, or None
118
112
    return store.find(ExerciseAttempt,
119
113
            ExerciseAttempt.user_id == user.id,
120
 
            ExerciseAttempt.ws_ex_id == worksheet_exercise.id,
 
114
            ExerciseAttempt.exercise_id == exercise.id,
121
115
            True if allow_inactive else ExerciseAttempt.active == True,
122
116
            True if as_of is None else ExerciseAttempt.date <= as_of,
123
117
        ).order_by(Desc(ExerciseAttempt.date))
124
118
 
125
 
def get_exercise_attempts(store, user, worksheet_exercise, as_of=None,
 
119
def get_exercise_attempts(store, user, exercise, as_of=None,
126
120
        allow_inactive=False):
127
121
    """Given a storm.store, User and Exercise, returns a list of
128
122
    ivle.database.ExerciseAttempt objects, one for each attempt made for the
132
126
        attempts made before or at this time.
133
127
    allow_inactive: If True, will return disabled attempts.
134
128
    """
135
 
    return list(_get_exercise_attempts(store, user, worksheet_exercise, as_of,
 
129
    return list(_get_exercise_attempts(store, user, exercise, as_of,
136
130
        allow_inactive))
137
131
 
138
 
def get_exercise_attempt(store, user, worksheet_exercise, as_of=None,
 
132
def get_exercise_attempt(store, user, exercise, as_of=None,
139
133
        allow_inactive=False):
140
 
    """Given a storm.store, User and WorksheetExercise, returns an
 
134
    """Given a storm.store, User and Exercise, returns an
141
135
    ivle.database.ExerciseAttempt object for the last submitted attempt for
142
136
    this question.
143
137
    Returns None if the user has not made an attempt on this
147
141
        attempts made before or at this time.
148
142
    allow_inactive: If True, will return disabled attempts.
149
143
    """
150
 
    return _get_exercise_attempts(store, user, worksheet_exercise, as_of,
 
144
    return _get_exercise_attempts(store, user, exercise, as_of,
151
145
        allow_inactive).first()
152
146
 
153
 
def save_exercise(store, user, worksheet_exercise, text, date):
 
147
def save_exercise(store, user, exercise, text, date):
154
148
    """Save an exercise for a user.
155
149
 
156
 
    Given a store, User, WorksheetExercise, text and date, save the text to the
 
150
    Given a store, User, Exercise and text and date, save the text to the
157
151
    database. This will create the ExerciseSave if needed.
158
152
    """
159
153
    saved = store.find(ivle.database.ExerciseSave,
160
154
                ivle.database.ExerciseSave.user_id == user.id,
161
 
                ivle.database.ExerciseSave.ws_ex_id == worksheet_exercise.id
162
 
                ).one()
 
155
                ivle.database.ExerciseSave.exercise_id == exercise.id).one()
163
156
    if saved is None:
164
 
        saved = ivle.database.ExerciseSave(user=user, 
165
 
                                        worksheet_exercise=worksheet_exercise)
 
157
        saved = ivle.database.ExerciseSave(user=user, exercise=exercise)
166
158
        store.add(saved)
167
159
 
168
160
    saved.date = date
169
161
    saved.text = text
170
162
 
171
 
def calculate_score(store, user, worksheet, as_of=None):
 
163
def calculate_score(store, user, worksheet):
172
164
    """
173
165
    Given a storm.store, User, Exercise and Worksheet, calculates a score for
174
166
    the user on the given worksheet.
175
 
    @param store: A storm.store
176
 
    @param user: A User.
177
 
    @param worksheet: A Worksheet.
178
 
    @param as_of: Optional datetime. If supplied, gets the score as of as_of.
179
167
    Returns a 4-tuple of ints, consisting of:
180
168
    (No. mandatory exercises completed,
181
169
     Total no. mandatory exercises,
190
178
    # Get the student's pass/fail for each exercise in this worksheet
191
179
    for worksheet_exercise in worksheet.worksheet_exercises:
192
180
        exercise = worksheet_exercise.exercise
193
 
        worksheet = worksheet_exercise.worksheet
194
181
        optional = worksheet_exercise.optional
195
182
 
196
 
        done, _ = get_exercise_status(store, user, worksheet_exercise, as_of)
 
183
        done, _ = get_exercise_status(store, user, exercise)
197
184
        # done is a bool, whether this student has completed that problem
198
185
        if optional:
199
186
            opt_total += 1
203
190
            if done: mand_done += 1
204
191
 
205
192
    return mand_done, mand_total, opt_done, opt_total
206
 
 
207
 
def calculate_mark(mand_done, mand_total):
208
 
    """Calculate a subject mark, given the result of all worksheets.
209
 
    @param mand_done: The total number of mandatory exercises completed by
210
 
        some student, across all worksheets.
211
 
    @param mand_total: The total number of mandatory exercises across all
212
 
        worksheets in the offering.
213
 
    @return: (percent, mark, mark_total)
214
 
        percent: The percentage of exercises the student has completed, as an
215
 
            integer between 0 and 100 inclusive.
216
 
        mark: The mark the student has received, based on the percentage.
217
 
        mark_total: The total number of marks available (currently hard-coded
218
 
            as 5).
219
 
    """
220
 
    # We want to display a students mark out of 5. However, they are
221
 
    # allowed to skip 1 in 5 questions and still get 'full marks'.
222
 
    # Hence we divide by 16, essentially making 16 percent worth
223
 
    # 1 star, and 80 or above worth 5.
224
 
    if mand_total > 0:
225
 
        percent_int = (100 * mand_done) // mand_total
226
 
    else:
227
 
        # Avoid Div0, just give everyone 0 marks if there are none available
228
 
        percent_int = 0
229
 
    # percent / 16, rounded down, with a maximum mark of 5
230
 
    max_mark = 5
231
 
    mark = min(percent_int // 16, max_mark)
232
 
    return (percent_int, mark, max_mark)
233
 
 
234
 
def update_exerciselist(worksheet):
235
 
    """Runs through the worksheetstream, generating the appropriate
236
 
    WorksheetExercises, and de-activating the old ones."""
237
 
    exercises = []
238
 
    # Turns the worksheet into an xml stream, and then finds all the 
239
 
    # exercise nodes in the stream.
240
 
    worksheetdata = genshi.XML(worksheet.get_xml())
241
 
    for kind, data, pos in worksheetdata:
242
 
        if kind is genshi.core.START:
243
 
            # Data is a tuple of tag name and a list of name->value tuples
244
 
            if data[0] == 'exercise':
245
 
                src = ""
246
 
                optional = False
247
 
                for attr in data[1]:
248
 
                    if attr[0] == 'src':
249
 
                        src = attr[1]
250
 
                    if attr[0] == 'optional':
251
 
                        optional = attr[1] == 'true'
252
 
                if src != "":
253
 
                    exercises.append((src, optional))
254
 
    ex_num = 0
255
 
    # Set all current worksheet_exercises to be inactive
256
 
    db_worksheet_exercises = Store.of(worksheet).find(WorksheetExercise,
257
 
        WorksheetExercise.worksheet_id == worksheet.id)
258
 
    for worksheet_exercise in db_worksheet_exercises:
259
 
        worksheet_exercise.active = False
260
 
    
261
 
    for exerciseid, optional in exercises:
262
 
        worksheet_exercise = Store.of(worksheet).find(WorksheetExercise,
263
 
            WorksheetExercise.worksheet_id == worksheet.id,
264
 
            Exercise.id == WorksheetExercise.exercise_id,
265
 
            Exercise.id == exerciseid).one()
266
 
        if worksheet_exercise is None:
267
 
            exercise = Store.of(worksheet).find(Exercise,
268
 
                Exercise.id == exerciseid
269
 
            ).one()
270
 
            if exercise is None:
271
 
                raise NotFound()
272
 
            worksheet_exercise = WorksheetExercise()
273
 
            worksheet_exercise.worksheet_id = worksheet.id
274
 
            worksheet_exercise.exercise_id = exercise.id
275
 
            Store.of(worksheet).add(worksheet_exercise)
276
 
        worksheet_exercise.active = True
277
 
        worksheet_exercise.seq_no = ex_num
278
 
        worksheet_exercise.optional = optional
279