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

« back to all changes in this revision

Viewing changes to ivle/worksheet.py

Remove www/apps/help. Replaced by ivle.webapp.help.

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
 
import os.path
27
 
 
28
 
from storm.locals import And, Asc, Desc, Store
29
 
import genshi
30
 
 
 
26
from storm.locals import And, Asc, Desc
31
27
import ivle.database
32
 
from ivle.database import ExerciseAttempt, ExerciseSave, Worksheet, \
33
 
                          WorksheetExercise, Exercise, User
34
 
import ivle.webapp.tutorial.test
35
28
 
36
 
__all__ = ['ExerciseNotFound', 'get_exercise_status',
37
 
           'get_exercise_statistics',
38
 
           'get_exercise_stored_text', 'get_exercise_attempts',
39
 
           'get_exercise_attempt', 'test_exercise_submission',
 
29
__all__ = ['get_exercise_status', 'get_exercise_stored_text',
 
30
           'get_exercise_attempts', 'get_exercise_attempt',
40
31
          ]
41
32
 
42
 
class ExerciseNotFound(Exception):
43
 
    pass
44
 
 
45
 
def get_exercise_status(store, user, worksheet_exercise, as_of=None):
 
33
def get_exercise_status(store, user, exercise):
46
34
    """Given a storm.store, User and Exercise, returns information about
47
35
    the user's performance on that problem.
48
 
    @param store: A storm.store
49
 
    @param user: A User.
50
 
    @param worksheet_exercise: An Exercise.
51
 
    @param as_of: Optional datetime. If supplied, gets the status as of as_of.
52
36
    Returns a tuple of:
53
37
        - A boolean, whether they have successfully passed this exercise.
54
38
        - An int, the number of attempts they have made up to and
55
39
          including the first successful attempt (or the total number of
56
40
          attempts, if not yet successful).
57
41
    """
 
42
    ExerciseAttempt = ivle.database.ExerciseAttempt
58
43
    # A Storm expression denoting all active attempts by this user for this
59
44
    # exercise.
60
45
    is_relevant = ((ExerciseAttempt.user_id == user.id) &
61
 
            (ExerciseAttempt.ws_ex_id == worksheet_exercise.id) &
62
 
            (ExerciseAttempt.active == True))
63
 
    if as_of is not None:
64
 
        is_relevant &= ExerciseAttempt.date <= as_of
 
46
                   (ExerciseAttempt.exercise_id == exercise.id) &
 
47
                   (ExerciseAttempt.active == True))
65
48
 
66
49
    # Get the first successful active attempt, or None if no success yet.
67
50
    # (For this user, for this exercise).
83
66
 
84
67
    return first_success is not None, num_attempts
85
68
 
86
 
def get_exercise_statistics(store, worksheet_exercise):
87
 
    """Return statistics about an exercise (with respect to a given
88
 
    worksheet).
89
 
    (number of students completed, number of students attempted)."""
90
 
    # Count the set of Users whose ID matches an attempt in this worksheet
91
 
    num_completed = store.find(User, User.id == ExerciseAttempt.user_id,
92
 
        ExerciseAttempt.ws_ex_id == worksheet_exercise.id,
93
 
        ExerciseAttempt.complete == True).config(distinct=True).count()
94
 
    num_attempted = store.find(User, User.id == ExerciseAttempt.user_id,
95
 
        ExerciseAttempt.ws_ex_id == worksheet_exercise.id,
96
 
        ).config(distinct=True).count()
97
 
    return num_completed, num_attempted
98
 
 
99
 
def get_exercise_stored_text(store, user, worksheet_exercise):
100
 
    """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
101
71
    ivle.database.ExerciseSave object for the last saved/submitted attempt for
102
72
    this question (note that ExerciseAttempt is a subclass of ExerciseSave).
103
73
    Returns None if the user has not saved or made an attempt on this
105
75
    If the user has both saved and submitted, it returns whichever was
106
76
    made last.
107
77
    """
 
78
    ExerciseSave = ivle.database.ExerciseSave
 
79
    ExerciseAttempt = ivle.database.ExerciseAttempt
108
80
 
109
81
    # Get the saved text, or None
110
82
    saved = store.find(ExerciseSave,
111
83
                ExerciseSave.user_id == user.id,
112
 
                ExerciseSave.ws_ex_id == worksheet_exercise.id).one()
 
84
                ExerciseSave.exercise_id == exercise.id).one()
113
85
 
114
86
    # Get the most recent attempt, or None
115
87
    attempt = store.find(ExerciseAttempt,
116
88
            ExerciseAttempt.user_id == user.id,
 
89
            ExerciseAttempt.exercise_id == exercise.id,
117
90
            ExerciseAttempt.active == True,
118
 
            ExerciseAttempt.ws_ex_id == worksheet_exercise.id
119
91
        ).order_by(Asc(ExerciseAttempt.date)).last()
120
92
 
121
93
    # Pick the most recent of these two
130
102
        else:
131
103
            return None
132
104
 
133
 
def _get_exercise_attempts(store, user, worksheet_exercise, as_of=None,
 
105
def _get_exercise_attempts(store, user, exercise, as_of=None,
134
106
        allow_inactive=False):
135
107
    """Same as get_exercise_attempts, but doesn't convert Storm's iterator
136
108
    into a list."""
 
109
    ExerciseAttempt = ivle.database.ExerciseAttempt
137
110
 
138
111
    # Get the most recent attempt before as_of, or None
139
112
    return store.find(ExerciseAttempt,
140
113
            ExerciseAttempt.user_id == user.id,
141
 
            ExerciseAttempt.ws_ex_id == worksheet_exercise.id,
 
114
            ExerciseAttempt.exercise_id == exercise.id,
142
115
            True if allow_inactive else ExerciseAttempt.active == True,
143
116
            True if as_of is None else ExerciseAttempt.date <= as_of,
144
117
        ).order_by(Desc(ExerciseAttempt.date))
145
118
 
146
 
def get_exercise_attempts(store, user, worksheet_exercise, as_of=None,
 
119
def get_exercise_attempts(store, user, exercise, as_of=None,
147
120
        allow_inactive=False):
148
121
    """Given a storm.store, User and Exercise, returns a list of
149
122
    ivle.database.ExerciseAttempt objects, one for each attempt made for the
153
126
        attempts made before or at this time.
154
127
    allow_inactive: If True, will return disabled attempts.
155
128
    """
156
 
    return list(_get_exercise_attempts(store, user, worksheet_exercise, as_of,
 
129
    return list(_get_exercise_attempts(store, user, exercise, as_of,
157
130
        allow_inactive))
158
131
 
159
 
def get_exercise_attempt(store, user, worksheet_exercise, as_of=None,
 
132
def get_exercise_attempt(store, user, exercise, as_of=None,
160
133
        allow_inactive=False):
161
 
    """Given a storm.store, User and WorksheetExercise, returns an
 
134
    """Given a storm.store, User and Exercise, returns an
162
135
    ivle.database.ExerciseAttempt object for the last submitted attempt for
163
136
    this question.
164
137
    Returns None if the user has not made an attempt on this
168
141
        attempts made before or at this time.
169
142
    allow_inactive: If True, will return disabled attempts.
170
143
    """
171
 
    return _get_exercise_attempts(store, user, worksheet_exercise, as_of,
 
144
    return _get_exercise_attempts(store, user, exercise, as_of,
172
145
        allow_inactive).first()
173
146
 
174
 
def save_exercise(store, user, worksheet_exercise, text, date):
 
147
def save_exercise(store, user, exercise, text, date):
175
148
    """Save an exercise for a user.
176
149
 
177
 
    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
178
151
    database. This will create the ExerciseSave if needed.
179
152
    """
180
153
    saved = store.find(ivle.database.ExerciseSave,
181
154
                ivle.database.ExerciseSave.user_id == user.id,
182
 
                ivle.database.ExerciseSave.ws_ex_id == worksheet_exercise.id
183
 
                ).one()
 
155
                ivle.database.ExerciseSave.exercise_id == exercise.id).one()
184
156
    if saved is None:
185
 
        saved = ivle.database.ExerciseSave(user=user, 
186
 
                                        worksheet_exercise=worksheet_exercise)
 
157
        saved = ivle.database.ExerciseSave(user=user, exercise=exercise)
187
158
        store.add(saved)
188
159
 
189
160
    saved.date = date
190
161
    saved.text = text
191
162
 
192
 
def calculate_score(store, user, worksheet, as_of=None):
 
163
def calculate_score(store, user, worksheet):
193
164
    """
194
165
    Given a storm.store, User, Exercise and Worksheet, calculates a score for
195
166
    the user on the given worksheet.
196
 
    @param store: A storm.store
197
 
    @param user: A User.
198
 
    @param worksheet: A Worksheet.
199
 
    @param as_of: Optional datetime. If supplied, gets the score as of as_of.
200
167
    Returns a 4-tuple of ints, consisting of:
201
168
    (No. mandatory exercises completed,
202
169
     Total no. mandatory exercises,
211
178
    # Get the student's pass/fail for each exercise in this worksheet
212
179
    for worksheet_exercise in worksheet.worksheet_exercises:
213
180
        exercise = worksheet_exercise.exercise
214
 
        worksheet = worksheet_exercise.worksheet
215
181
        optional = worksheet_exercise.optional
216
182
 
217
 
        done, _ = get_exercise_status(store, user, worksheet_exercise, as_of)
 
183
        done, _ = get_exercise_status(store, user, exercise)
218
184
        # done is a bool, whether this student has completed that problem
219
185
        if optional:
220
186
            opt_total += 1
224
190
            if done: mand_done += 1
225
191
 
226
192
    return mand_done, mand_total, opt_done, opt_total
227
 
 
228
 
def calculate_mark(mand_done, mand_total):
229
 
    """Calculate a subject mark, given the result of all worksheets.
230
 
    @param mand_done: The total number of mandatory exercises completed by
231
 
        some student, across all worksheets.
232
 
    @param mand_total: The total number of mandatory exercises across all
233
 
        worksheets in the offering.
234
 
    @return: (percent, mark, mark_total)
235
 
        percent: The percentage of exercises the student has completed, as an
236
 
            integer between 0 and 100 inclusive.
237
 
        mark: The mark the student has received, based on the percentage.
238
 
        mark_total: The total number of marks available (currently hard-coded
239
 
            as 5).
240
 
    """
241
 
    # We want to display a students mark out of 5. However, they are
242
 
    # allowed to skip 1 in 5 questions and still get 'full marks'.
243
 
    # Hence we divide by 16, essentially making 16 percent worth
244
 
    # 1 star, and 80 or above worth 5.
245
 
    if mand_total > 0:
246
 
        percent_int = (100 * mand_done) // mand_total
247
 
    else:
248
 
        # Avoid Div0, just give everyone 0 marks if there are none available
249
 
        percent_int = 0
250
 
    # percent / 16, rounded down, with a maximum mark of 5
251
 
    max_mark = 5
252
 
    mark = min(percent_int // 16, max_mark)
253
 
    return (percent_int, mark, max_mark)
254
 
 
255
 
def update_exerciselist(worksheet):
256
 
    """Runs through the worksheetstream, generating the appropriate
257
 
    WorksheetExercises, and de-activating the old ones."""
258
 
    exercises = []
259
 
    # Turns the worksheet into an xml stream, and then finds all the 
260
 
    # exercise nodes in the stream.
261
 
    worksheetdata = genshi.XML(worksheet.data_xhtml)
262
 
    for kind, data, pos in worksheetdata:
263
 
        if kind is genshi.core.START:
264
 
            # Data is a tuple of tag name and a list of name->value tuples
265
 
            if data[0] == 'exercise':
266
 
                src = ""
267
 
                optional = False
268
 
                for attr in data[1]:
269
 
                    if attr[0] == 'src':
270
 
                        src = attr[1]
271
 
                    if attr[0] == 'optional':
272
 
                        optional = attr[1] == 'true'
273
 
                if src != "":
274
 
                    exercises.append((src, optional))
275
 
    ex_num = 0
276
 
    # Set all current worksheet_exercises to be inactive
277
 
    db_worksheet_exercises = Store.of(worksheet).find(WorksheetExercise,
278
 
        WorksheetExercise.worksheet_id == worksheet.id)
279
 
    for worksheet_exercise in db_worksheet_exercises:
280
 
        worksheet_exercise.active = False
281
 
    
282
 
    for exerciseid, optional in exercises:
283
 
        worksheet_exercise = Store.of(worksheet).find(WorksheetExercise,
284
 
            WorksheetExercise.worksheet_id == worksheet.id,
285
 
            Exercise.id == WorksheetExercise.exercise_id,
286
 
            Exercise.id == exerciseid).one()
287
 
        if worksheet_exercise is None:
288
 
            exercise = Store.of(worksheet).find(Exercise,
289
 
                Exercise.id == exerciseid
290
 
            ).one()
291
 
            if exercise is None:
292
 
                raise ExerciseNotFound(exerciseid)
293
 
            worksheet_exercise = WorksheetExercise()
294
 
            worksheet_exercise.worksheet_id = worksheet.id
295
 
            worksheet_exercise.exercise_id = exercise.id
296
 
            Store.of(worksheet).add(worksheet_exercise)
297
 
        worksheet_exercise.active = True
298
 
        worksheet_exercise.seq_no = ex_num
299
 
        worksheet_exercise.optional = optional
300
 
 
301
 
 
302
 
def test_exercise_submission(config, user, exercise, code):
303
 
    """Test the given code against an exercise.
304
 
 
305
 
    The code is run in a console process as the provided user.
306
 
    """
307
 
    # Start a console to run the tests on
308
 
    jail_path = os.path.join(config['paths']['jails']['mounts'],
309
 
                             user.login)
310
 
    working_dir = os.path.join("/home", user.login)
311
 
    cons = ivle.console.Console(config, user, jail_path,
312
 
                                working_dir)
313
 
 
314
 
    # Parse the file into a exercise object using the test suite
315
 
    exercise_obj = ivle.webapp.tutorial.test.parse_exercise_file(
316
 
        exercise, cons)
317
 
 
318
 
    # Run the test cases. Get the result back as a JSONable object.
319
 
    # Return it.
320
 
    test_results = exercise_obj.run_tests(code)
321
 
 
322
 
    # Close the console
323
 
    cons.close()
324
 
 
325
 
    return test_results
326
 
 
327
 
 
328
 
class FakeWorksheetForMarks:
329
 
    """This class represents a worksheet and a particular students progress
330
 
    through it.
331
 
    
332
 
    Do not confuse this with a worksheet in the database. This worksheet
333
 
    has extra information for use in the output, such as marks."""
334
 
    def __init__(self, id, name, assessable, published):
335
 
        self.id = id
336
 
        self.name = name
337
 
        self.assessable = assessable
338
 
        self.published = published
339
 
        self.complete_class = ''
340
 
        self.optional_message = ''
341
 
        self.total = 0
342
 
        self.mand_done = 0
343
 
    def __repr__(self):
344
 
        return ("Worksheet(id=%s, name=%s, assessable=%s)"
345
 
                % (repr(self.id), repr(self.name), repr(self.assessable)))
346
 
 
347
 
 
348
 
# XXX: This really shouldn't be needed.
349
 
def create_list_of_fake_worksheets_and_stats(config, store, user, offering,
350
 
    as_of=None):
351
 
    """Take an offering's real worksheets, converting them into stats.
352
 
 
353
 
    The worksheet listing views expect special fake worksheet objects
354
 
    that contain counts of exercises, whether they've been completed,
355
 
    that sort of thing. A fake worksheet object is used to contain
356
 
    these values, because nobody has managed to refactor the need out
357
 
    yet.
358
 
    """
359
 
    new_worksheets = []
360
 
    problems_done = 0
361
 
    problems_total = 0
362
 
 
363
 
    # Offering.worksheets is ordered by the worksheets seq_no
364
 
    worksheets = offering.worksheets
365
 
 
366
 
    # Unless we can edit worksheets, hide unpublished ones.
367
 
    if 'edit_worksheets' not in offering.get_permissions(user, config):
368
 
        worksheets = worksheets.find(published=True)
369
 
 
370
 
    for worksheet in worksheets:
371
 
        new_worksheet = FakeWorksheetForMarks(
372
 
            worksheet.identifier, worksheet.name, worksheet.assessable,
373
 
            worksheet.published)
374
 
        if new_worksheet.assessable:
375
 
            # Calculate the user's score for this worksheet
376
 
            mand_done, mand_total, opt_done, opt_total = (
377
 
                ivle.worksheet.utils.calculate_score(store, user, worksheet,
378
 
                                                     as_of=as_of))
379
 
            if opt_total > 0:
380
 
                optional_message = " (excluding optional exercises)"
381
 
            else:
382
 
                optional_message = ""
383
 
            if mand_done >= mand_total:
384
 
                new_worksheet.complete_class = "complete"
385
 
            elif mand_done > 0:
386
 
                new_worksheet.complete_class = "semicomplete"
387
 
            else:
388
 
                new_worksheet.complete_class = "incomplete"
389
 
            problems_done += mand_done
390
 
            problems_total += mand_total
391
 
            new_worksheet.mand_done = mand_done
392
 
            new_worksheet.total = mand_total
393
 
            new_worksheet.optional_message = optional_message
394
 
        new_worksheets.append(new_worksheet)
395
 
 
396
 
    return new_worksheets, problems_total, problems_done