def post_grade(permission, user_id, course_id, assignment_number): user_type = get_user_type(user_id) if user_type == 'teacher': abort(404) if user_type == 'student': data = request.args try: # get the assignment_id from the course and assignment# assignment = Assignment.query.filter(Assignment.assignment_number==assignment_number)\ .filter(Assignment.course_id==course_id).one_or_none() assignment_id = assignment.id grade = Grade(assignment_id=assignment_id, user_id=user_id, points=data['points']) grade.insert() return jsonify({ 'status': 200, 'success': True, 'course_id': course_id, 'assignment_number': assignment_number, 'points': data['points'] }) except Exception as e: print(f'The following exception occured while posting grades: {e}') abort(400)
def add_grade(): if current_user.__tablename__ == 'teachers': form = GradeForm() if form.validate_on_submit(): stu = Student.query.get(form.stu_id.data) if stu is None: flash(u'没有学号为 %s 的学生,请先创建该学生的信息' % form.stu_id.data) else: stu_id = int(form.stu_id.data) course_id = form.course_id.data grade = form.grade.data new_grade = db.session.query(Grade).filter_by( course_id=course_id, stu_id=stu_id).first() if new_grade is None: new_grade = Grade(stu_id, course_id, grade) else: new_grade.grade = grade try: db.session.add(new_grade) db.session.commit() except SQLAlchemyError: flash(u'成绩添加失败,请确认输入是否正确') db.session.rollback() else: flash(u'成绩添加成功', 'success') return redirect(url_for('add_grade')) # to clear form fields return render_template('add_grade.html', form=form) else: return render_template('404.html'), 404
def importgrades(request): username = request.user.username if request.POST: form = ImportForm(request.POST, request.FILES) if form.is_valid(): try: xlsfile = request.FILES.get('grades', '') filename = xlsfile.name #创建文件存储的路径 fname = os.path.join( settings.MEDIA_ROOT, 'uploads/grades/%s' % strftime("%Y/%m/%d", localtime()), filename) if os.path.exists(fname): os.remove(fname) dirs = os.path.dirname(fname) if not os.path.exists(dirs): os.makedirs(dirs) #写入文件 if os.path.isfile(fname): os.remove(fname) content = xlsfile.read() fp = open(fname, 'wb') fp.write(content) fp.close() #格式化xls文件中数据,将其存到数据库中 book = open_workbook(fname) sheet = book.sheet_by_index(0) for row_index in range(sheet.nrows): record = sheet.row_values(row_index, 0) try: student = Student.objects.get( user__username=str(record[1]).rstrip(".0")) grade = Grade(term=record[0], student=student, score=record[2]) grade.save() except Student.DoesNotExist, e: traceback.print_stack() traceback.print_exc() print e successinfo = "上传" success = True return render_to_response( 'grade/import.html', { "title": '导入成绩单', 'form': form, 'successinfo': successinfo, 'success': success, 'username': username }, context_instance=RequestContext(request)) except Exception, e: traceback.print_stack() traceback.print_exc() print e
def addGrade(): g_name = request.form.get('g_name') g_mainteacher = request.form.get('t_id') grade = Grade.query.filter_by(g_name =g_name).first() if grade: msg = '班级名称已存在' else: newgrade = Grade(g_name,g_mainteacher) newgrade.save() msg = '添加成功' return msg
def populate_grades(): grades = [ dict(starting_percentage=0, ending_percentage=65, letter_grade="E/F", four_point_zero_grade=0.0), dict(starting_percentage=65, ending_percentage=66, letter_grade="D", four_point_zero_grade=1.0), dict(starting_percentage=67, ending_percentage=69, letter_grade="D+", four_point_zero_grade=1.3), dict(starting_percentage=70, ending_percentage=72, letter_grade="C-", four_point_zero_grade=1.7), dict(starting_percentage=73, ending_percentage=76, letter_grade="C", four_point_zero_grade=2.0), dict(starting_percentage=77, ending_percentage=79, letter_grade="C+", four_point_zero_grade=2.3), dict(starting_percentage=80, ending_percentage=82, letter_grade="B-", four_point_zero_grade=2.7), dict(starting_percentage=83, ending_percentage=86, letter_grade="B", four_point_zero_grade=3.0), dict(starting_percentage=87, ending_percentage=89, letter_grade="B+", four_point_zero_grade=3.3), dict(starting_percentage=90, ending_percentage=92, letter_grade="A-", four_point_zero_grade=3.7), dict(starting_percentage=93, ending_percentage=96, letter_grade="A", four_point_zero_grade=4.0), dict(starting_percentage=97, ending_percentage=100, letter_grade="A+", four_point_zero_grade=4.0) ] for grade in grades: g = Grade(**grade) logger.debug(g.to_dict())
def importgrades(request): username = request.user.username if request.POST: form = ImportForm(request.POST,request.FILES) if form.is_valid(): try: xlsfile = request.FILES.get('grades','') filename = xlsfile.name #创建文件存储的路径 fname = os.path.join(settings.MEDIA_ROOT,'uploads/grades/%s'%strftime("%Y/%m/%d",localtime()),filename) if os.path.exists(fname): os.remove(fname) dirs = os.path.dirname(fname) if not os.path.exists(dirs): os.makedirs(dirs) #写入文件 if os.path.isfile(fname): os.remove(fname) content = xlsfile.read() fp = open(fname, 'wb') fp.write(content) fp.close() #格式化xls文件C数据,将其存到数据库C book = open_workbook(fname) sheet = book.sheet_by_index(0) for row_index in range(sheet.nrows): record = sheet.row_values(row_index,0) try: student = Student.objects.get(user__username=str(record[1]).rstrip(".0")) grade = Grade(term=record[0],student=student,score=record[2]) grade.save() except Student.DoesNotExist,e: traceback.print_stack() traceback.print_exc() print e successinfo = "上传" success = True return render_to_response('grade/import.html',{ "title":'ImportGPAForm', 'form':form, 'successinfo':successinfo, 'success':success, 'username':username},context_instance = RequestContext(request)) except Exception,e: traceback.print_stack() traceback.print_exc() print e
def _grade_management(): action=request.args.get('action',type=str) if action=="add_grade": grade=request.args.get('grade',type=unicode) if not Grade.query.filter(Grade.grade_name==grade).first(): g=Grade(grade_name=grade) else: return u"该年级已经存在" try: db.session.add(g) db.session.commit() #重新生成grade.json文件 generateGradeJson() return u"添加成功" except : return u"发生未知错误" elif action=="del_grade": grade=request.args.get('grade',type=unicode) g=Grade.query.filter(Grade.grade_name==grade).first() try: db.session.delete(g) generateGradeJson() db.session.commit() return u"删除成功" except : return u"发生未知错误"
def api_classes(): classes = [] grades = Grade.query.all() for grade in grades: grade_id = grade.id class_name = grade.gradename stu_number = grade.stunumber manageId = grade.manage_id grade_info = { "id": grade_id, "className": class_name, "studentNumber": stu_number, "manageId": manageId } classes.append(grade_info) dic = {"classes": classes} if request.method == "GET": return jsonify(dic), 201 elif request.method == "POST": data = request.get_json() grade_name = data.get('className') manageId = session.get('stuid') grade = Grade(gradename=grade_name, manage_id=manageId) db.session.add(grade) db.session.commit() manager = User.query.filter(User.id == manageId).first() manager.grade = grade db.session.commit() return "success", 201
def add_grade_submission(): try: new_grade = Grade( num=request.form['num'] ) print(new_grade) Grade.insert(new_grade) flash('Grade ' + request.form['num'] + ' was successfully listed!') except: db.session.rollback() print(sys.exc_info()) flash('An error occurred. Grade ' + request.form['num'] + ' could not be listed.') finally: db.session.close() query = Grade.query.all() return render_template('pages/grades.html', data=query, userinfo=session['profile'])
def post(self): """Create new grade""" student = request.get_json()['student'] reportid = request.get_json()['reportid'] points = request.get_json()['points'] feedback = request.get_json()['feedback'] needsgrading = request.get_json()['needsgrading'] new_grade = Grade(student=student, reportid=reportid, points=points, feedback=feedback, needsgrading=needsgrading) try: new_grade.save() except UniqueViolatedError: return jsonify(error="Grade for this report already exists"), 409 return jsonify(message="ok")
def add_grades(cid, period): course = db.GqlQuery("SELECT * FROM Course WHERE cid=:1", cid).fetch(1)[0] grades = simplejson.loads(course.grades) for grade in grades: new_grade = Grade() new_grade.cid = cid new_grade.cname = course.name new_grade.grade = grade["grade"] new_grade.sid = grade["sid"] new_grade.period = grade["period"] new_grade.put()
def patch(self, id): grade = Grade.fetchone(id=id) grade.student = request.get_json()['student'] grade.reportid = request.get_json()['reportid'] grade.points = request.get_json()['points'] grade.feedback = request.get_json()['feedback'] grade.needsgrading = request.get_json()['needsgrading'] try: grade.save() except UniqueViolatedError: return jsonify(errors=["Duplicated email address"]), 409 return jsonify(message='ok')
def add_grade(student_id, subject_id, value): id_grade = max_grade_id().one().max_id val = float(value) if 6 < val or val < 1: return False grade = Grade(grade_id=id_grade + 1, student_id=student_id, subject_id=subject_id, value=float(val)) session.add(grade) session.commit() return True
def add(): if request.method == "GET": course_num = request.args['courseNum'] return render_template("addAssignment.html", course_num=course_num) name = request.form.get('assignment') course_num = request.form.get('courseNum') newAssignment = Assignment(name=name, class_id=course_num) db_session.add(newAssignment) db_session.commit() db_session.add(Grade(grade=0, assignment_id=newAssignment.id)) db_session.commit() return redirect(url_for('search', courseNum=course_num))
def index(self): grades = Grade.fetchall() ret = [] for grade in grades: ret.append({ 'id': grade.id, 'student': grade.student, 'reportid': grade.reportid, 'points': grade.points, 'feedback': grade.feedback, 'needsgrading': grade.needsgrading }) return jsonify(sorted(ret, key=lambda i: i['id'], reverse=True))
def get(self, reportid): repid = int(reportid) grade = Grade.fetchone(reportid=repid) try: return jsonify({ 'id': grade.id, 'student': grade.student, 'reportid': grade.reportid, 'points': grade.points, 'feedback': grade.feedback, 'needsgrading': grade.needsgrading }) except: return jsonify("None")
def generateGradeJson(): try: grade_dict={ "grade":[] } grade_list=Grade.get_grades() for i in grade_list: grade_dict["grade"].append(i) with open(__StaticDir__+"grade.json",'w') as f: f.write(json.dumps(grade_dict))#把json格式的内容写入文件 except StandardError,e: #print e raise
def grade_list(): print g.user.priv if g.user.priv == 'student': q = Grade.getByUserId(g.user.id) else: q = Grade.getByTeacherId(g.user.id) print q.count() subj = request.args.get('subject', None) if subj: grades = q.filter( or_(Grade.subject.like("%" + subj + "%"), Grade.name.like("%" + subj + "%"))).all() else: grades = q.all() resp = [] for grade in grades: res = {} res['id'] = grade.student_id res['teacher'] = u'无' res['name'] = u'数据缺失' u = User.getById(grade.student_id) if u: res['name'] = u.name else: print grade.student_id u = User.getById(grade.teacher_id) if u: res['teacher'] = u.name res['subject'] = grade.subject res['contest_time'] = str(grade.contest_time) res['semester'] = grade.semester res['score'] = grade.score resp.append(res) return render_template('grade.html', user=g.user, grades=resp, cur_page='grade')
def get_grade_data(): g_id = request.form.get('student_id') subject = request.form.get('subject') grades = Grade.getByUserId(g_id).filter(Grade.subject==subject).\ order_by(Grade.contest_time).all() resp = make_response() resp.headers['Access-Control-Allow-Origin'] = '*' resp.headers['Access-Control-Allow-Methods'] = 'POST' resp.headers[ 'Access-Control-Allow-Headers'] = 'x-requested-with,content-type' data = {} data_name = [] data_value = [] for x in grades: data_value.append(x.score) data_name.append(str(x.contest_time)) u = User.getById(g_id) data['code'] = 0 data['value'] = data_value data['name'] = data_name data['title'] = User.getById(g_id).name + u"的" + subject + u"成绩曲线" resp.data = json.dumps(data) return resp
def grade_update(): data = request.get_json() subject_id = data['subject_id'] student_id = data['student_id'] stage = data['stage'] value = data[stage].strip() grade = Grade.query.filter_by(subject_id=subject_id, student_id=student_id, stage=stage).first() if grade: if value == '': db.session.delete(grade) else: grade.value = value else: if value == '': return jsonify(status="fail") grade = Grade(subject_id=subject_id, student_id=student_id, stage=stage, value=value) db.session.add(grade) db.session.commit() return jsonify(status="success")
def addgrade(): if g.user.priv == 'student': return render_template('error.html', user=g.user, error=u'haha') m = Grade() m.title = request.form.get('title', None) m.subject = request.form.get('subject', None) m.contest_time = request.form.get('contest_time', None) m.user_id = request.form.get('user_id', None) m.teacher_id = g.user.id m.student_id = request.form.get('student_id', None) m.semester = request.form.get('semester', None) if m.student_id: m.name = User.getById(m.student_id) score = request.form.get('score', None) if score: m.score = int(score) resp = make_response() resp.headers['Access-Control-Allow-Origin'] = '*' resp.headers['Access-Control-Allow-Methods'] = 'POST' resp.headers[ 'Access-Control-Allow-Headers'] = 'x-requested-with,content-type' print 'start add' try: sess.add(m) sess.commit() print '=========================' resp.data = json.dumps({'code': 0, 'msg': u'发布成功'}) except Exception, ex: print "------------------------" print ex resp.data = json.dumps({'code': -1, 'reason': ex})
def saveGrade(): assignId = request.form.get('assignmentId') newGrade = request.form.get('newGrade') db_session.add(Grade(grade=newGrade, assignment_id=assignId)) db_session.commit() return redirect(url_for('search', courseNum=request.form.get('course')))
def awarding_grade(course_id: int, student_id: int, grade: int, session=None): session.add(Grade(student_id=student_id, course_id=course_id, grade=grade))
def performance_review(submission: models.Submission): exam = submission.question.exam exam_questions = select(q for q in Question if q.exam == exam)[:] total_marks, total_number_of_questions = 0, 0 for exam_question in exam_questions: total_marks += exam_question.marks total_number_of_questions += 1 learner_submissions = select( s for s in Submission if s.question.exam == exam and s.user == submission.user)[:] ticks = 0 crosses = 0 unmarked = 0 marks_obtained = 0 for s in learner_submissions: if s.mark == Mark.tick or s.mark == Mark.auto_tick: ticks += 1 marks_obtained += s.marks_obtained elif s.mark == Mark.cross or s.mark == Mark.auto_cross: crosses += 1 elif s.mark == Mark.unmarked: unmarked += 1 else: pass percentage = int(marks_obtained / total_marks * 100) grade = Grade.get(lambda g: percentage >= g.starting_percentage and percentage <= g.ending_percentage) performance = Performance.get(user=submission.user, exam=exam) if not performance: performance_data = dict( ticks=ticks, crosses=crosses, unmarked=unmarked, marks_obtained=marks_obtained, total_marks=total_marks, total_number_of_questions=total_number_of_questions, percentage=percentage, grade=grade, exam=exam, user=submission.user) performance = Performance(**performance_data) else: performance.ticks = ticks performance.crosses = crosses performance.unmarked = unmarked performance.marks_obtained = marks_obtained performance.total_marks = total_marks performance.percentage = percentage performance.grade = grade logger.debug(performance.to_dict()) return performance
def import_grade(request, filter_id): ''' Импорт классов. ''' render = {} if request.user.type == 'EduAdmin': if request.user.school.id != int(filter_id): raise Http404 render['school'] = school = get_object_or_404(School, id=filter_id) if request.method == 'GET': render['form'] = form = ImportForm() else: render['form'] = form = ImportForm(request.POST, request.FILES) if form.is_valid(): render['errors'] = errors = [] grades = [] rows = csv.reader(form.cleaned_data['file'], delimiter=';') i = 0 try: for row in rows: i += 1 if len(row) < 3: errors.append({ 'line': i, 'column': 0, 'error': u'недостаточное количество столбцов' }) continue try: int(row[0]) except ValueError: errors.append({ 'line': i, 'column': 1, 'error': u'это не число' }) continue try: row[1], row[2] = row[1].decode( 'cp1251'), row[2].decode('cp1251') except UnicodeError: errors.append({ 'line': i, 'column': 0, 'error': u'некорректное значение (невозможно определить кодировку)' }) continue grades.append( Grade(number=row[0], long_name=row[1], small_name=row[2], school=school)) except csv.Error: pass if len(errors) == 0: for grade in grades: grade.save() messages.success(request, u'Классы импортированы') return HttpResponseRedirect('..') return render_to_response('~userextended/gradeImport.html', render, context_instance=RequestContext(request))
def shuffle(self, grades_per_submission): # make sure grades_per_projects is positive if grades_per_submission <= 0: return None # get number of hackers number_of_hackers = Hacker.query.count() hackers = Hacker.query.all() # make sure there are more hackers than grades_per_project if not number_of_hackers > grades_per_submission: return None # get number of submissions number_of_submissions = Submission.query.count() submissions = Submission.query.all() # total number of grades total_grades = number_of_submissions * grades_per_submission # approximate amount of grades per hacker grades_per_hacker = math.ceil(total_grades / number_of_hackers) # The following vars are only for testing purposes: set_up = {} for hacker in hackers: set_up[hacker.name] = [0, hacker] # loop over each project for submission in submissions: # loop over grades_per_project for index in range(grades_per_submission): # set list of possible hackers to choose from, only those with less grades than grades_per_hacker hackers_to_choose = {key: value for (key, value) in set_up.items() if value[0] < grades_per_hacker} # Times over the while loop while_times = 0 # times try again try_again_times = 0 # grab a hacker that is not part of this submission while True: while_times += 1 # get random hacker from list hacker_key = random.choice(list(hackers_to_choose.keys())) hacker_dict = hackers_to_choose[hacker_key] hacker = hacker_dict[1] num_of_grades = hacker_dict[0] # check that hacker is not of current project if hacker.team_id != submission.team.id: # check that this hacker is not already grading this submission if num_of_grades == 0 or self.hackerNotGradingThis(hacker, submission): num_of_grades += 1 # create the grade object grade = Grade() # add the new grade to the hacker and the submission hacker.grades.append(grade) submission.grades.append(grade) # need to set list items to the edited items hacker_dict[1] = hacker hacker_dict[0] = num_of_grades break # if we have gone over the entire list once, then re do the list with more hackers if while_times > len(hackers_to_choose): try_again_times += 1 hackers_to_choose = {key: value for (key, value) in set_up.items() if value[0] < grades_per_hacker + try_again_times} while_times = 0 # grab the hackers with the most and least grades and try to balance them out by moving grades between the two # order the hackers by number of grades in them sets = {} for key, value in set_up.items(): if sets.get(value[0]): sets[value[0]].append(value) else: sets[value[0]] = [value, ] # grab max number of grades in hacker max_num = sorted(sets.keys())[-1] # add numbers 0 to man_num to sets if it does not exist for index in range(max_num): if index not in sets.keys(): sets[index] = [] # we want to sort the dict by the int keys, we receive a tuple sets = sorted(sets.items()) print(self.getDistribution(sets)) # here key is number of grade, value is list of hackers with that number of grades for key, value in sets: list_to_fix = value # we want to bring these hackers one less than the optimal grades per hacker times_to_fix = grades_per_hacker - key - 1 # only proceed if we need to fix hackers in this range of grades if times_to_fix > 0: for index in range(len(list_to_fix)): # the list of number of grades and the hacker we are working with num_grades_hacker_list = list_to_fix[0] ttf = times_to_fix # highest set, set of optimal value highest_set = sets[grades_per_hacker] # second highest set, set of one less than optimal value second_highest_set = sets[grades_per_hacker - 1] # loop over the number of times we need to fix this hacker while ttf > 0: # choose a random hacker that will help us random_num_grades_hacker_list = random.choice(highest_set[1]) # iterate of grades of random hacker for grade in random_num_grades_hacker_list[1].grades: # make sure the grade is not of the hacker's team if grade.submission.team_id is not num_grades_hacker_list[1].team_id: # make grade switch grade = random_num_grades_hacker_list[1].grades.pop() num_grades_hacker_list[1].grades.append(grade) # add one grade to hacker num_grades_hacker_list[0] += 1 # remove one from random hacker and switch him to next list below highest_set[1].remove(random_num_grades_hacker_list) second_highest_set[1].append(random_num_grades_hacker_list) random_num_grades_hacker_list[0] -= 1 # fix was complete so remove a time to fix and break out of for each loop ttf -= 1 break # if all the grades from the random hacker can't be added to this hacker than choose a different # random hacker next round # if the num_grade_hacker_list number of grades is different from the key then we remove it # from the current list and add it to a new list depending on the number of grades if num_grades_hacker_list[0] is not key: # remove num_grades_hacker_list we are fixing from its list value.remove(num_grades_hacker_list) # add the num_grade_hacker_list we are fixing to its new list sets[num_grades_hacker_list[0]][1].append(num_grades_hacker_list) # this is to fix hackers with too many grades if times_to_fix < -1: for index in range(len(list_to_fix)): # the list of number of grades and the hacker we are working with num_grades_hacker_list = list_to_fix[0] ttf = times_to_fix # lowest set, the time to fix minus one more lowest_set = sets[(times_to_fix - 1)] # second lowest set second_lowest_set = sets[times_to_fix] # loop over the number of times we need to fix this hacker while ttf < -1: # choose a random hacker that will help us random_num_grades_hacker_list = random.choice(lowest_set[1]) # iterate of grades of hacker with too many grades for grade in num_grades_hacker_list[1].grades: # make sure the grade is not of the random hacker's team if grade.submission.team_id is not num_grades_hacker_list[1].team_id: # make grade switch grade = num_grades_hacker_list[1].grades.pop() random_num_grades_hacker_list[1].grades.append(grade) # remove one from the hacker num_grades_hacker_list[0] -= 1 # add one to random hacker and bump him one list up lowest_set[1].remove(random_num_grades_hacker_list) second_lowest_set[1].append(random_num_grades_hacker_list) random_num_grades_hacker_list[0] += 1 # fix was complete so remove a time to fix and break out of for each loop ttf += 1 break # if all the grades from the random hacker can't be added to this hacker than choose a different # random hacker next round # if the num_grade_hacker_list number of grades is different from the key then we remove it # from the current list and add it to a new list depending on the number of grades if num_grades_hacker_list[0] is not key: # remove num_grades_hacker_list we are fixing from its list value.remove(num_grades_hacker_list) sets[num_grades_hacker_list[0]][1].append(num_grades_hacker_list) dis = self.getDistribution(sets) print(dis) # commit db changes db.session.commit() return dis
from models import Grade, Person p1 = Person("Linda", "passkeylinda") p2 = Person("Lennon", "Yorika") persons = [p1, p2] g1 = Grade("11b", persons) g1.print_persons() print(g1)