def grades(): user = validate_user() categories = session.query(Category).all() homeworks = get_homeworks_before() update_hw_grades(user, homeworks) session.commit() gradebook, max_scores = get_gradebook() grades = [entry for entry in gradebook if entry[0] == user] if grades: grades = grades[0][1] else: grades = {hw.id: get_grade(user.stuid, hw.id) for hw in homeworks} return render_template("grades.html", homeworks=homeworks, grades=grades, max_scores=max_scores, options=options, user=user, categories=categories)
def submit(): user = validate_user() q_id = request.args.get("q_id") question = get_question(q_id) responses = request.form.getlist('responses') out = question.submit_response(user.stuid, responses) return json.dumps(out, cls=NewEncoder)
def upload(): user = validate_user() file = request.files['file'] if not file: return "No file uploaded." # extract the extension ext = file.filename.rsplit('.', 1)[1] # generate a random filename from string import ascii_lowercase, digits from random import choice filename = "".join(choice(ascii_lowercase + digits) for _ in range(40)) filename += "." + ext # determine where to save the file path = "%s/WWW/%s/%s" % (options.base_dir, options.upload_dir, filename) file.save(path) # return the URL to the file url = "%s/%s/%s" % (options.base_url, options.upload_dir, filename) return ''' <script> var input1 = top.$('.mce-btn.mce-open').parent().find('.mce-textbox').val('%s'); input1.parents(".mce-formitem").next().find(".mce-textbox").val('%s'); </script>''' % (url, url)
def to_html(self): # not good to have imports here... from queries import get_question, get_last_question_response, get_peer_tasks_for_grader, get_self_tasks_for_student from auth import validate_user self.set_metadata() user = validate_user() if user.type == "guest": return "Sorry, but only students can view peer assessment questions." vars = {"question": get_question(self.question_id)} # if peer assessment was assigned if len(self.peer_pts): peer_tasks = get_peer_tasks_for_grader(self.question_id, user.stuid) vars['peer_responses'] = [get_last_question_response(self.question_id, task.student) for task in peer_tasks] # if self assessment was assigned if self.self_pts is not None: # add the task if it hasn't been already response = get_last_question_response(self.question_id, user.stuid) if response and not get_self_tasks_for_student(self.question_id, user.stuid): session.add(GradingTask(grader=user.stuid, student=user.stuid, question_id=self.question_id)) session.commit() vars['self_response'] = response # jinja2 to get template for peer review questions from jinja2 import Environment, PackageLoader env = Environment(autoescape=True, loader=PackageLoader("ohms", "templates")) template = env.get_template("peer_review_question.html") return template.render(**vars)
def rate(): user = validate_user() question_id = request.args.get("id") tasks = get_peer_tasks_for_student(question_id, user.stuid) tasks = [t for t in tasks if t.score is not None] return render_template("rate.html", grading_tasks=tasks, options=options)
def login_handler(): if request.method == 'POST': if validate_user(request.form['username'], request.form['password']): login_user(User(request.form['username'], True)) return redirect(url_for('quiz_page')) else: return render_template( 'quiz-login.html', message="Incorrect User/Password combination") return render_template('quiz-login.html', message=None)
def cohort_file_manifest(cohort_id): """ GET: Retrieve a cohort's file manifest POST: Retrieve a cohort's file manifest with applied filters """ response_obj = None code = None try: user_info = auth_info() user = validate_user(user_info['email'], cohort_id) if not user: response_obj = { 'message': 'Encountered an error while attempting to identify this user.' } code = 500 else: file_manifest = get_file_manifest(cohort_id, user) if file_manifest: # Presence of a message means something went wrong with our request if 'message' in file_manifest: response_obj = file_manifest code = 400 else: code = 200 response_obj = { 'data': file_manifest } else: response_obj = { 'message': "Error while attempting to retrieve file manifest for cohort {}.".format(str(cohort_id)) } code = 500 except UserValidationException as e: response_obj = { 'message': str(e) } code = 403 except Exception as e: logger.exception(e) response_obj = { 'message': 'Encountered an error while attempting to identify this user.' } code = 500 finally: close_old_connections() response_obj['code'] = code response = jsonify(response_obj) response.status_code = code return response
def materials(): user = validate_user() import os files = [ f for f in os.listdir("%s/WWW/restricted/" % options.base_dir) if not f.startswith('.') ] files.sort() return render_template("materials.html", user=user, files=files, options=options)
def hw_list(): user = validate_user() homeworks = get_homework() categories = session.query(Category).all() to_do = update_hw_grades(user, homeworks) session.commit() return render_template("list.html", homeworks=homeworks, categories=categories, user=user, options=options, current_time=pdt_now(), to_do=to_do)
def signup(): try: request_body = request.get_json() user_name = request_body["user_name"] password = request_body["password"] email = request_body["email"] user_validate = validate_user(user_name, password, email) if user_validate == True: new_user = sign_up(user_name, password, email) token = jwt.encode( { 'user': new_user, 'exp': datetime.datetime.utcnow() + datetime.timedelta(days=2) }, app.config['SECRET_KEY'], 'HS256') return jsonify({'token': token.decode('UTF-8')}) else: return make_response(jsonify({"message": user_validate}), 409) except KeyError: return make_response(jsonify({"message": "missing fields"}), 409)
def hw(): user = validate_user() hw_id = request.args.get("id") hw = get_homework(hw_id) question_list = get_all_regular_questions() if user.type == "admin" else None if user.type == "admin": return render_template("hw.html", hw_list=get_homework(), homework=hw, user=user, question_list=question_list, options=options) else: if hw.start_date and hw.start_date > pdt_now(): raise Exception("This homework has not yet been released.") return render_template("hw.html", homework=hw, user=user, question_list=question_list, options=options)
def hw(): user = validate_user() hw_id = request.args.get("id") hw = get_homework(hw_id) question_list = get_all_regular_questions( ) if user.type == "admin" else None if user.type == "admin": return render_template("hw.html", hw_list=get_homework(), homework=hw, user=user, question_list=question_list, options=options) else: if hw.start_date and hw.start_date > pdt_now(): raise Exception("This homework has not yet been released.") return render_template("hw.html", homework=hw, user=user, question_list=question_list, options=options)
def rate_submit(): user = validate_user() task = get_grading_task(request.form.get('task_id')) task.rating = int(request.form.get('rating')) session.commit() return ""
def cohorts(): """ GET: Retrieve a user's list of cohorts POST: Add a new cohort """ response = None info = None code = None try: user_info = auth_info() user = validate_user(user_info['email']) if not user: response = jsonify({ 'code': 500, 'message': 'Encountered an error while attempting to identify this user.' }) response.status_code = 500 else: if request.method == 'GET': info = get_cohorts(user_info['email']) else: info = create_cohort(user) if info: response_obj = {} if 'message' in info: code = 400 else: code = 200 response_obj['data'] = info response_obj['code'] = code response = jsonify(response_obj) response.status_code = code # Lack of a valid object means something went wrong on the server else: response = jsonify({ 'code': 500, 'message': "Error while attempting to {}.".format( 'retrieve the cohort list' if request.method == 'GET' else 'create this cohort' ) }) response.status_code = 500 except UserValidationException as e: response = jsonify({ 'code': 403, 'message': str(e) }) response.status_code = 403 except Exception as e: logger.exception(e) response = jsonify({ 'code': 500, 'message': 'Encountered an error while attempting to {}.'.format( "retrieve a list of cohorts" if request.method == 'GET' else "create this cohort" ) }) response.status_code = 500 finally: close_old_connections() return response
def cohort(cohort_id): """ GET: Retrieve extended information for a specific cohort PATCH: Edit an extent cohort """ try: user_info = auth_info() user = validate_user(user_info['email'], cohort_id) response = None code = None if not user: response = jsonify({ 'code': 500, 'message': 'Encountered an error while attempting to identify this user.' }) response.status_code = 500 else: if request.method == 'GET': include_barcodes = (request.args.get('include_barcodes', default="false", type=str).lower() == "true") cohort_info = get_cohort_info(cohort_id, include_barcodes) else: cohort_info = edit_cohort(cohort_id, user, delete=(request.method == 'DELETE')) if cohort_info: response_obj = {} if 'message' in cohort_info: code = 400 else: code = 200 response_obj['data'] = cohort_info response_obj['code'] = code response = jsonify(response_obj) response.status_code = code else: response = jsonify({ 'code': 404, 'message': "Cohort ID {} was not found.".format(str(cohort_id))}) response.status_code = 404 except UserValidationException as e: response = jsonify({ 'code': 403, 'message': str(e) }) response.status_code = 403 except Exception as e: logger.exception(e) response = jsonify({ 'code': 500, 'message': 'Encountered an error while attempting to retrieve this cohort\'s information.' }) response.status_code = 500 finally: close_old_connections() return response
def load(): user = validate_user() q_id = request.args.get("q_id") question = get_question(q_id) return json.dumps(question.load_response(user), cls=NewEncoder)
def get_gradebook(): """ helper function that gets the gradebook """ user = validate_user() if user.type == "admin": homeworks = get_homework() else: homeworks = get_homeworks_before() # get all the grades, put them into a gradebook gradebook, max_scores = {}, {} for user in get_users(): if user.type == "student": gradebook[user] = {} for homework in homeworks: grades = session.query(Grade).filter_by(hw_id = homework.id).all() scores = [] for g in grades: if g.student not in gradebook: continue gradebook[g.student][homework.id] = g try: scores.append(float(g.score)) except: pass if homework.max_score is not None: max_scores[homework.id] = homework.max_score elif scores: max_scores[homework.id] = max(scores) else: max_scores[homework.id] = None gradebook = gradebook.items() gradebook.sort(key=lambda entry: convert_to_last_name(entry[0].name)) categories = session.query(Category).all() # calculate total scores by category, taking into account excused assignments for student, grades in gradebook: earned = {c: [] for c in categories} possible = {c: [] for c in categories} for hw in homeworks: if max_scores[hw.id] is None or max_scores[hw.id] == 0: continue possible[hw.category].append(max_scores[hw.id]) if hw.id in grades: if grades[hw.id].excused: # if student was excused from assignment possible[hw.category].remove(max_scores[hw.id]) # don't count it against else: try: earned[hw.category].append(float(grades[hw.id].score)) except: earned[hw.category].append(0) else: earned[hw.category].append(0) # add grades to gradebook grades["overall"] = 0. for category, poss in possible.iteritems(): if len(poss) == 0: grades[category.name] = "0 / 0" continue # sort scores by benefit to grade if dropped e, p = sum(earned[category]), sum(poss) if len(poss) > category.drops + 1: grades_sorted = sorted(zip(earned[category], poss), key=lambda x: -(e-x[0])/(p-x[1])) grades_sorted = grades_sorted[category.drops:] out = zip(*grades_sorted) else: out = earned[category], poss grades[category.name] = "%0.1f / %0.1f" % (sum(out[0]), sum(out[1])) if sum(out[1]) > 0: grades["overall"] += category.weight * sum(out[0]) / sum(out[1]) return gradebook, max_scores
def get_gradebook(): """ helper function that gets the gradebook """ user = validate_user() if user.type == "admin": homeworks = get_homework() else: homeworks = get_homeworks_before() # get all the grades, put them into a gradebook gradebook, max_scores = {}, {} for user in get_users(): if user.type == "student": gradebook[user] = {} for homework in homeworks: grades = session.query(Grade).filter_by(hw_id=homework.id).all() scores = [] for g in grades: if g.student not in gradebook: continue gradebook[g.student][homework.id] = g try: scores.append(float(g.score)) except: pass if homework.max_score is not None: max_scores[homework.id] = homework.max_score elif scores: max_scores[homework.id] = max(scores) else: max_scores[homework.id] = None gradebook = gradebook.items() gradebook.sort(key=lambda entry: convert_to_last_name(entry[0].name)) categories = session.query(Category).all() # calculate total scores by category, taking into account excused assignments for student, grades in gradebook: earned = {c: [] for c in categories} possible = {c: [] for c in categories} for hw in homeworks: if max_scores[hw.id] is None or max_scores[hw.id] == 0: continue possible[hw.category].append(max_scores[hw.id]) if hw.id in grades: if grades[ hw. id].excused: # if student was excused from assignment possible[hw.category].remove( max_scores[hw.id]) # don't count it against else: try: earned[hw.category].append(float(grades[hw.id].score)) except: earned[hw.category].append(0) else: earned[hw.category].append(0) # add grades to gradebook grades["overall"] = 0. for category, poss in possible.iteritems(): if len(poss) == 0: grades[category.name] = "0 / 0" continue # sort scores by benefit to grade if dropped e, p = sum(earned[category]), sum(poss) if len(poss) > category.drops + 1: grades_sorted = sorted(zip(earned[category], poss), key=lambda x: -(e - x[0]) / (p - x[1])) grades_sorted = grades_sorted[category.drops:] out = zip(*grades_sorted) else: out = earned[category], poss grades[category.name] = "%0.1f / %0.1f" % (sum(out[0]), sum( out[1])) if sum(out[1]) > 0: grades["overall"] += category.weight * sum(out[0]) / sum( out[1]) return gradebook, max_scores
def materials(): user = validate_user() import os files = [f for f in os.listdir("%s/WWW/restricted/" % options.base_dir) if not f.startswith('.')] files.sort() return render_template("materials.html", user=user, files=files, options=options)