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

1080.1.56 by Matt Giuca
Added new module: ivle.worksheet. This will contain general functions for
1
# IVLE - Informatics Virtual Learning Environment
2
# Copyright (C) 2007-2009 The University of Melbourne
3
#
4
# This program is free software; you can redistribute it and/or modify
5
# it under the terms of the GNU General Public License as published by
6
# the Free Software Foundation; either version 2 of the License, or
7
# (at your option) any later version.
8
#
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
# GNU General Public License for more details.
13
#
14
# You should have received a copy of the GNU General Public License
15
# along with this program; if not, write to the Free Software
16
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
17
18
# Author: Matt Giuca
19
20
"""
21
Worksheet Utility Functions
22
23
This module provides functions for tutorial and worksheet computations.
24
"""
25
1394.2.8 by William Grant
Factor out console-based exercise testing into ivle.worksheet.test_exercise_submission().
26
import os.path
27
1102 by William Grant
Move ivle.webapp.tutorial.service.generate_exerciselist() to ivle.worksheet,
28
from storm.locals import And, Asc, Desc, Store
29
import genshi
30
1080.1.56 by Matt Giuca
Added new module: ivle.worksheet. This will contain general functions for
31
import ivle.database
1102 by William Grant
Move ivle.webapp.tutorial.service.generate_exerciselist() to ivle.worksheet,
32
from ivle.database import ExerciseAttempt, ExerciseSave, Worksheet, \
33
                          WorksheetExercise, Exercise
1394.2.8 by William Grant
Factor out console-based exercise testing into ivle.worksheet.test_exercise_submission().
34
import ivle.webapp.tutorial.test
1080.1.56 by Matt Giuca
Added new module: ivle.worksheet. This will contain general functions for
35
1384.1.10 by William Grant
Display a nice error message if a worksheet attempts to reference a non-existent exercise.
36
__all__ = ['ExerciseNotFound', 'get_exercise_status',
37
           'get_exercise_stored_text', 'get_exercise_attempts',
1394.2.8 by William Grant
Factor out console-based exercise testing into ivle.worksheet.test_exercise_submission().
38
           'get_exercise_attempt', 'test_exercise_submission',
1080.1.59 by Matt Giuca
ivle.worksheet, ivle.database: Added/updated __all__.
39
          ]
40
1384.1.10 by William Grant
Display a nice error message if a worksheet attempts to reference a non-existent exercise.
41
class ExerciseNotFound(Exception):
42
    pass
43
1195.1.18 by Matt Giuca
ivle.worksheet.utils: Can now calculate exercise and worksheet marks as of a
44
def get_exercise_status(store, user, worksheet_exercise, as_of=None):
1080.1.56 by Matt Giuca
Added new module: ivle.worksheet. This will contain general functions for
45
    """Given a storm.store, User and Exercise, returns information about
46
    the user's performance on that problem.
1195.1.18 by Matt Giuca
ivle.worksheet.utils: Can now calculate exercise and worksheet marks as of a
47
    @param store: A storm.store
48
    @param user: A User.
49
    @param worksheet_exercise: An Exercise.
50
    @param as_of: Optional datetime. If supplied, gets the status as of as_of.
1080.1.56 by Matt Giuca
Added new module: ivle.worksheet. This will contain general functions for
51
    Returns a tuple of:
52
        - A boolean, whether they have successfully passed this exercise.
53
        - An int, the number of attempts they have made up to and
54
          including the first successful attempt (or the total number of
55
          attempts, if not yet successful).
56
    """
57
    # A Storm expression denoting all active attempts by this user for this
58
    # exercise.
59
    is_relevant = ((ExerciseAttempt.user_id == user.id) &
1099.1.180 by Nick Chadwick
This commit changes the tutorial service, which now almost exclusively
60
            (ExerciseAttempt.ws_ex_id == worksheet_exercise.id) &
61
            (ExerciseAttempt.active == True))
1195.1.18 by Matt Giuca
ivle.worksheet.utils: Can now calculate exercise and worksheet marks as of a
62
    if as_of is not None:
63
        is_relevant &= ExerciseAttempt.date <= as_of
1080.1.56 by Matt Giuca
Added new module: ivle.worksheet. This will contain general functions for
64
65
    # Get the first successful active attempt, or None if no success yet.
66
    # (For this user, for this exercise).
67
    first_success = store.find(ExerciseAttempt, is_relevant,
68
            ExerciseAttempt.complete == True
69
        ).order_by(Asc(ExerciseAttempt.date)).first()
70
71
    if first_success is not None:
72
        # Get the total number of active attempts up to and including the
73
        # first successful attempt.
74
        # (Subsequent attempts don't count, because the user had already
75
        # succeeded by then).
76
        num_attempts = store.find(ExerciseAttempt, is_relevant,
77
                ExerciseAttempt.date <= first_success.date).count()
78
    else:
79
        # User has not yet succeeded.
80
        # Get the total number of active attempts.
81
        num_attempts = store.find(ExerciseAttempt, is_relevant).count()
82
83
    return first_success is not None, num_attempts
1080.1.57 by Matt Giuca
ivle.worksheet: Added get_exercise_stored_text, ported from
84
1099.1.180 by Nick Chadwick
This commit changes the tutorial service, which now almost exclusively
85
def get_exercise_stored_text(store, user, worksheet_exercise):
86
    """Given a storm.store, User and WorksheetExercise, returns an
1080.1.58 by Matt Giuca
ivle.worksheet: Added get_exercise_attempts and get_exercise_attempt.
87
    ivle.database.ExerciseSave object for the last saved/submitted attempt for
88
    this question (note that ExerciseAttempt is a subclass of ExerciseSave).
1080.1.57 by Matt Giuca
ivle.worksheet: Added get_exercise_stored_text, ported from
89
    Returns None if the user has not saved or made an attempt on this
90
    problem.
91
    If the user has both saved and submitted, it returns whichever was
92
    made last.
93
    """
94
95
    # Get the saved text, or None
96
    saved = store.find(ExerciseSave,
97
                ExerciseSave.user_id == user.id,
1099.1.180 by Nick Chadwick
This commit changes the tutorial service, which now almost exclusively
98
                ExerciseSave.ws_ex_id == worksheet_exercise.id).one()
1080.1.57 by Matt Giuca
ivle.worksheet: Added get_exercise_stored_text, ported from
99
100
    # Get the most recent attempt, or None
101
    attempt = store.find(ExerciseAttempt,
102
            ExerciseAttempt.user_id == user.id,
103
            ExerciseAttempt.active == True,
1099.1.180 by Nick Chadwick
This commit changes the tutorial service, which now almost exclusively
104
            ExerciseAttempt.ws_ex_id == worksheet_exercise.id
1080.1.57 by Matt Giuca
ivle.worksheet: Added get_exercise_stored_text, ported from
105
        ).order_by(Asc(ExerciseAttempt.date)).last()
106
107
    # Pick the most recent of these two
108
    if saved is not None:
109
        if attempt is not None:
110
            return saved if saved.date > attempt.date else attempt
111
        else:
112
            return saved
113
    else:
114
        if attempt is not None:
115
            return attempt
116
        else:
117
            return None
1080.1.58 by Matt Giuca
ivle.worksheet: Added get_exercise_attempts and get_exercise_attempt.
118
1099.1.180 by Nick Chadwick
This commit changes the tutorial service, which now almost exclusively
119
def _get_exercise_attempts(store, user, worksheet_exercise, as_of=None,
1080.1.58 by Matt Giuca
ivle.worksheet: Added get_exercise_attempts and get_exercise_attempt.
120
        allow_inactive=False):
121
    """Same as get_exercise_attempts, but doesn't convert Storm's iterator
122
    into a list."""
123
124
    # Get the most recent attempt before as_of, or None
125
    return store.find(ExerciseAttempt,
126
            ExerciseAttempt.user_id == user.id,
1099.1.180 by Nick Chadwick
This commit changes the tutorial service, which now almost exclusively
127
            ExerciseAttempt.ws_ex_id == worksheet_exercise.id,
1080.1.58 by Matt Giuca
ivle.worksheet: Added get_exercise_attempts and get_exercise_attempt.
128
            True if allow_inactive else ExerciseAttempt.active == True,
129
            True if as_of is None else ExerciseAttempt.date <= as_of,
130
        ).order_by(Desc(ExerciseAttempt.date))
131
1099.1.180 by Nick Chadwick
This commit changes the tutorial service, which now almost exclusively
132
def get_exercise_attempts(store, user, worksheet_exercise, as_of=None,
1080.1.58 by Matt Giuca
ivle.worksheet: Added get_exercise_attempts and get_exercise_attempt.
133
        allow_inactive=False):
134
    """Given a storm.store, User and Exercise, returns a list of
135
    ivle.database.ExerciseAttempt objects, one for each attempt made for the
136
    exercise, sorted from latest to earliest.
137
138
    as_of: Optional datetime.datetime object. If supplied, only returns
139
        attempts made before or at this time.
140
    allow_inactive: If True, will return disabled attempts.
141
    """
1099.1.180 by Nick Chadwick
This commit changes the tutorial service, which now almost exclusively
142
    return list(_get_exercise_attempts(store, user, worksheet_exercise, as_of,
1080.1.58 by Matt Giuca
ivle.worksheet: Added get_exercise_attempts and get_exercise_attempt.
143
        allow_inactive))
144
1099.1.180 by Nick Chadwick
This commit changes the tutorial service, which now almost exclusively
145
def get_exercise_attempt(store, user, worksheet_exercise, as_of=None,
1080.1.58 by Matt Giuca
ivle.worksheet: Added get_exercise_attempts and get_exercise_attempt.
146
        allow_inactive=False):
1099.1.198 by William Grant
Fix retrieval of old exercise attempts.
147
    """Given a storm.store, User and WorksheetExercise, returns an
1080.1.58 by Matt Giuca
ivle.worksheet: Added get_exercise_attempts and get_exercise_attempt.
148
    ivle.database.ExerciseAttempt object for the last submitted attempt for
149
    this question.
150
    Returns None if the user has not made an attempt on this
151
    problem.
152
153
    as_of: Optional datetime.datetime object. If supplied, only returns
154
        attempts made before or at this time.
155
    allow_inactive: If True, will return disabled attempts.
156
    """
1099.1.198 by William Grant
Fix retrieval of old exercise attempts.
157
    return _get_exercise_attempts(store, user, worksheet_exercise, as_of,
1080.1.58 by Matt Giuca
ivle.worksheet: Added get_exercise_attempts and get_exercise_attempt.
158
        allow_inactive).first()
1080.1.60 by Matt Giuca
ivle.worksheet: Added calculate_score. This is a nice clean Storm port of
159
1099.1.180 by Nick Chadwick
This commit changes the tutorial service, which now almost exclusively
160
def save_exercise(store, user, worksheet_exercise, text, date):
1080.1.88 by William Grant
ivle.worksheet: Add a save_exercise function.
161
    """Save an exercise for a user.
162
1099.1.180 by Nick Chadwick
This commit changes the tutorial service, which now almost exclusively
163
    Given a store, User, WorksheetExercise, text and date, save the text to the
1080.1.88 by William Grant
ivle.worksheet: Add a save_exercise function.
164
    database. This will create the ExerciseSave if needed.
165
    """
166
    saved = store.find(ivle.database.ExerciseSave,
167
                ivle.database.ExerciseSave.user_id == user.id,
1099.1.180 by Nick Chadwick
This commit changes the tutorial service, which now almost exclusively
168
                ivle.database.ExerciseSave.ws_ex_id == worksheet_exercise.id
1099.1.150 by Nick Chadwick
Modified worksheets to properly link attempts to worksheets and
169
                ).one()
1080.1.88 by William Grant
ivle.worksheet: Add a save_exercise function.
170
    if saved is None:
1099.1.180 by Nick Chadwick
This commit changes the tutorial service, which now almost exclusively
171
        saved = ivle.database.ExerciseSave(user=user, 
172
                                        worksheet_exercise=worksheet_exercise)
1080.1.88 by William Grant
ivle.worksheet: Add a save_exercise function.
173
        store.add(saved)
174
175
    saved.date = date
176
    saved.text = text
177
1195.1.18 by Matt Giuca
ivle.worksheet.utils: Can now calculate exercise and worksheet marks as of a
178
def calculate_score(store, user, worksheet, as_of=None):
1080.1.60 by Matt Giuca
ivle.worksheet: Added calculate_score. This is a nice clean Storm port of
179
    """
180
    Given a storm.store, User, Exercise and Worksheet, calculates a score for
181
    the user on the given worksheet.
1195.1.18 by Matt Giuca
ivle.worksheet.utils: Can now calculate exercise and worksheet marks as of a
182
    @param store: A storm.store
183
    @param user: A User.
184
    @param worksheet: A Worksheet.
185
    @param as_of: Optional datetime. If supplied, gets the score as of as_of.
1080.1.60 by Matt Giuca
ivle.worksheet: Added calculate_score. This is a nice clean Storm port of
186
    Returns a 4-tuple of ints, consisting of:
187
    (No. mandatory exercises completed,
188
     Total no. mandatory exercises,
189
     No. optional exercises completed,
190
     Total no. optional exercises)
191
    """
192
    mand_done = 0
193
    mand_total = 0
194
    opt_done = 0
195
    opt_total = 0
196
197
    # Get the student's pass/fail for each exercise in this worksheet
198
    for worksheet_exercise in worksheet.worksheet_exercises:
199
        exercise = worksheet_exercise.exercise
1099.4.3 by Nick Chadwick
Updated the tutorial service, to now allow users to edit worksheets
200
        worksheet = worksheet_exercise.worksheet
1080.1.60 by Matt Giuca
ivle.worksheet: Added calculate_score. This is a nice clean Storm port of
201
        optional = worksheet_exercise.optional
202
1195.1.18 by Matt Giuca
ivle.worksheet.utils: Can now calculate exercise and worksheet marks as of a
203
        done, _ = get_exercise_status(store, user, worksheet_exercise, as_of)
1080.1.60 by Matt Giuca
ivle.worksheet: Added calculate_score. This is a nice clean Storm port of
204
        # done is a bool, whether this student has completed that problem
205
        if optional:
206
            opt_total += 1
207
            if done: opt_done += 1
208
        else:
209
            mand_total += 1
210
            if done: mand_done += 1
211
212
    return mand_done, mand_total, opt_done, opt_total
1102 by William Grant
Move ivle.webapp.tutorial.service.generate_exerciselist() to ivle.worksheet,
213
1195.1.13 by Matt Giuca
ivle.worksheet.utils: Added calculate_mark, which is from the duplicated code
214
def calculate_mark(mand_done, mand_total):
215
    """Calculate a subject mark, given the result of all worksheets.
216
    @param mand_done: The total number of mandatory exercises completed by
217
        some student, across all worksheets.
218
    @param mand_total: The total number of mandatory exercises across all
219
        worksheets in the offering.
220
    @return: (percent, mark, mark_total)
221
        percent: The percentage of exercises the student has completed, as an
222
            integer between 0 and 100 inclusive.
223
        mark: The mark the student has received, based on the percentage.
224
        mark_total: The total number of marks available (currently hard-coded
225
            as 5).
226
    """
227
    # We want to display a students mark out of 5. However, they are
228
    # allowed to skip 1 in 5 questions and still get 'full marks'.
229
    # Hence we divide by 16, essentially making 16 percent worth
230
    # 1 star, and 80 or above worth 5.
1195.1.15 by Matt Giuca
ivle-marks, ivle.worksheet.utils: Fixed Divide-by-zero exception if there are
231
    if mand_total > 0:
232
        percent_int = (100 * mand_done) // mand_total
233
    else:
234
        # Avoid Div0, just give everyone 0 marks if there are none available
235
        percent_int = 0
1195.1.13 by Matt Giuca
ivle.worksheet.utils: Added calculate_mark, which is from the duplicated code
236
    # percent / 16, rounded down, with a maximum mark of 5
237
    max_mark = 5
238
    mark = min(percent_int // 16, max_mark)
239
    return (percent_int, mark, max_mark)
240
1102 by William Grant
Move ivle.webapp.tutorial.service.generate_exerciselist() to ivle.worksheet,
241
def update_exerciselist(worksheet):
242
    """Runs through the worksheetstream, generating the appropriate
243
    WorksheetExercises, and de-activating the old ones."""
244
    exercises = []
245
    # Turns the worksheet into an xml stream, and then finds all the 
246
    # exercise nodes in the stream.
1099.1.220 by Nick Chadwick
Merged from trunk
247
    worksheetdata = genshi.XML(worksheet.get_xml())
1102 by William Grant
Move ivle.webapp.tutorial.service.generate_exerciselist() to ivle.worksheet,
248
    for kind, data, pos in worksheetdata:
249
        if kind is genshi.core.START:
250
            # Data is a tuple of tag name and a list of name->value tuples
251
            if data[0] == 'exercise':
252
                src = ""
253
                optional = False
254
                for attr in data[1]:
255
                    if attr[0] == 'src':
256
                        src = attr[1]
257
                    if attr[0] == 'optional':
258
                        optional = attr[1] == 'true'
259
                if src != "":
260
                    exercises.append((src, optional))
261
    ex_num = 0
262
    # Set all current worksheet_exercises to be inactive
263
    db_worksheet_exercises = Store.of(worksheet).find(WorksheetExercise,
264
        WorksheetExercise.worksheet_id == worksheet.id)
265
    for worksheet_exercise in db_worksheet_exercises:
266
        worksheet_exercise.active = False
267
    
268
    for exerciseid, optional in exercises:
269
        worksheet_exercise = Store.of(worksheet).find(WorksheetExercise,
270
            WorksheetExercise.worksheet_id == worksheet.id,
271
            Exercise.id == WorksheetExercise.exercise_id,
272
            Exercise.id == exerciseid).one()
273
        if worksheet_exercise is None:
274
            exercise = Store.of(worksheet).find(Exercise,
275
                Exercise.id == exerciseid
276
            ).one()
277
            if exercise is None:
1384.1.10 by William Grant
Display a nice error message if a worksheet attempts to reference a non-existent exercise.
278
                raise ExerciseNotFound(exerciseid)
1102 by William Grant
Move ivle.webapp.tutorial.service.generate_exerciselist() to ivle.worksheet,
279
            worksheet_exercise = WorksheetExercise()
280
            worksheet_exercise.worksheet_id = worksheet.id
281
            worksheet_exercise.exercise_id = exercise.id
282
            Store.of(worksheet).add(worksheet_exercise)
283
        worksheet_exercise.active = True
284
        worksheet_exercise.seq_no = ex_num
285
        worksheet_exercise.optional = optional
286
1394.2.8 by William Grant
Factor out console-based exercise testing into ivle.worksheet.test_exercise_submission().
287
288
def test_exercise_submission(config, user, exercise, code):
289
    """Test the given code against an exercise.
290
291
    The code is run in a console process as the provided user.
292
    """
293
    # Start a console to run the tests on
294
    jail_path = os.path.join(config['paths']['jails']['mounts'],
295
                             user.login)
296
    working_dir = os.path.join("/home", user.login)
297
    cons = ivle.console.Console(config, user.unixid, jail_path,
298
                                working_dir)
299
300
    # Parse the file into a exercise object using the test suite
301
    exercise_obj = ivle.webapp.tutorial.test.parse_exercise_file(
302
        exercise, cons)
303
304
    # Run the test cases. Get the result back as a JSONable object.
305
    # Return it.
306
    test_results = exercise_obj.run_tests(code)
307
308
    # Close the console
309
    cons.close()
310
311
    return test_results
1442.1.26 by William Grant
Factor the real DB worksheet -> fake mark worksheet translation into ivle.worksheet.util, so we can use it elsewhere.
312
313
314
class FakeWorksheetForMarks:
315
    """This class represents a worksheet and a particular students progress
316
    through it.
317
    
318
    Do not confuse this with a worksheet in the database. This worksheet
319
    has extra information for use in the output, such as marks."""
320
    def __init__(self, id, name, assessable):
321
        self.id = id
322
        self.name = name
323
        self.assessable = assessable
324
        self.complete_class = ''
325
        self.optional_message = ''
326
        self.total = 0
327
        self.mand_done = 0
328
    def __repr__(self):
329
        return ("Worksheet(id=%s, name=%s, assessable=%s)"
330
                % (repr(self.id), repr(self.name), repr(self.assessable)))
331
332
333
# XXX: This really shouldn't be needed.
334
def create_list_of_fake_worksheets_and_stats(store, user, offering):
335
    """Take an offering's real worksheets, converting them into stats.
336
337
    The worksheet listing views expect special fake worksheet objects
338
    that contain counts of exercises, whether they've been completed,
339
    that sort of thing. A fake worksheet object is used to contain
340
    these values, because nobody has managed to refactor the need out
341
    yet.
342
    """
343
    new_worksheets = []
344
    problems_done = 0
345
    problems_total = 0
346
347
    # Offering.worksheets is ordered by the worksheets seq_no
348
    for worksheet in offering.worksheets:
349
        new_worksheet = FakeWorksheetForMarks(
350
            worksheet.identifier, worksheet.name, worksheet.assessable)
351
        if new_worksheet.assessable:
352
            # Calculate the user's score for this worksheet
353
            mand_done, mand_total, opt_done, opt_total = (
354
                ivle.worksheet.utils.calculate_score(store, user, worksheet))
355
            if opt_total > 0:
356
                optional_message = " (excluding optional exercises)"
357
            else:
358
                optional_message = ""
359
            if mand_done >= mand_total:
360
                new_worksheet.complete_class = "complete"
361
            elif mand_done > 0:
362
                new_worksheet.complete_class = "semicomplete"
363
            else:
364
                new_worksheet.complete_class = "incomplete"
365
            problems_done += mand_done
366
            problems_total += mand_total
367
            new_worksheet.mand_done = mand_done
368
            new_worksheet.total = mand_total
369
            new_worksheet.optional_message = optional_message
370
        new_worksheets.append(new_worksheet)
371
372
    return new_worksheets, problems_total, problems_done