def __add_default_courses(app: Flask): app.app_context().push() db.create_all() if Course.query.count() == 0: course = Course( "course1", datetime.strptime("2021-01-01", "%Y-%m-%d").date(), datetime.strptime("2021-01-01", "%Y-%m-%d").date(), 1, ) db.session.add(course) course2 = Course( "course2", datetime.strptime("2019-01-01", "%Y-%m-%d").date(), datetime.strptime("2019-01-01", "%Y-%m-%d").date(), 2, ) db.session.add(course2) course3 = Course( "course3", datetime.strptime("2018-01-01", "%Y-%m-%d").date(), datetime.strptime("2018-01-01", "%Y-%m-%d").date(), 3, ) db.session.add(course3) db.session.commit()
def test_with_many_courses_and_many_students(self): alex = Student(name="Alex") alex.save() jordan = Student(name="Jordan") jordan.save() math = Course(name="Math") math.save() biology = Course(name="Biology") biology.save() alex.enroll(math) jordan.enroll(biology) alex.enroll(biology) self.assertListEqual(list(alex.get_courses()), [math, biology]) self.assertListEqual(list(jordan.get_courses()), [biology]) self.assertListEqual(list(biology.get_students()), [alex, jordan]) self.assertListEqual(list(math.get_students()), [alex]) alex.disenroll(biology) self.assertListEqual(list(alex.get_courses()), [math]) self.assertListEqual(list(biology.get_students()), [jordan]) jordan.disenroll(math) self.assertListEqual(list(jordan.get_courses()), [biology]) self.assertListEqual(list(math.get_students()), [alex])
def update(baseName): oldDF = models.Course.query.all() #oldIDs = models.Course.query.session_ID() newDF = json.load( open(app.config["FILE_UPLOADS"] + '/' + baseName + ".json", "r")) oldSessionIDs = [] for oldRecord in oldDF: oldSessionIDs.append(oldRecord.session_ID) for oldRecord in oldDF: for newRecord in newDF: if oldRecord.session_ID == newRecord[ 'SessionID'] and oldRecord != newRecord: db.session.delete(oldRecord) alternate = Course(Course_title=newRecord['CourseTitle'], Classroom=newRecord['Classroom'], Course_code=newRecord['CourseCode'], Credits=newRecord['Cr'], Format=newRecord['CourseFormat'], session_ID=newRecord['SessionID']) db.session.add(alternate) db.session.commit() elif not (newRecord['SessionID'] in oldSessionIDs): # in oldIDs new = Course(Course_title=newRecord['CourseTitle'], Classroom=newRecord['Classroom'], Course_code=newRecord['CourseCode'], Credits=newRecord['Cr'], Format=newRecord['CourseFormat'], session_ID=newRecord['SessionID']) db.session.add(new) db.session.commit()
def import_professors(df): for i in tqdm(df.iterrows()): pid, series = i pname = series.Name score = None if str(series.Score) == 'nan' else series.Score nrev = None if str(series.Num_Reviews) == 'nan' else series.Num_Reviews if series.Nugget == 'None': nuggets = None elif series.Nugget == 'Gold': nuggets = 1 else: nuggets = 0 p = Professor(pid=pid, pname=pname, nuggets=nuggets, score=score, nrev=nrev) dparsed = ast.literal_eval(series.Dept) if dparsed: if isinstance(dparsed, list): for d in dparsed: dname, did = d dquery = Department.query.filter( Department.did == did).first() if dquery: p.departments.append(dquery) else: d = Department(dname=dname, did=did) p.departments.append(d) else: dname, did = dparsed dquery = Department.query.filter(Department.did == did).first() if dquery: p.departments.append(dquery) else: d = Department(dname=dname, did=did) p.departments.append(d) cparsed = ast.literal_eval(series.Courses) if cparsed: if isinstance(cparsed, list): for c in cparsed: cname, cid = c cquery = Course.query.filter(Course.cid == cid).first() if cquery: p.courses.append(cquery) else: c = Course(cname=cname, cid=cid) p.courses.append(c) else: cname, cid = cparsed cquery = Course.query.filter(Course.cid == cid).first() if cquery: p.courses.append(cquery) else: c = Course(cname=cname, cid=cid) p.courses.append(c) db.session.add(p) db.session.commit()
def create_todo(): a1 = Course(title='Mathematics') b1 = Todo(description='Finish math homework', course=a1) db.session.add(b1) a2 = Course(title='English') b2 = Todo(description='write essay', course=a2) db.session.add(b2) db.session.commit()
def reset_db(): flash('Resetting Database: deleting old data and repopulating with dummy data') # clear all data from all tables meta = db.metadata for table in reversed(meta.sorted_tables): print('Clear table {}'.format(table)) db.session.execute(table.delete()) db.session.commit() # populate tables with dummy data users = [ User(username='******', name='Professor Pancake', email='*****@*****.**', bio='Not a professor, definitely a pancake'), User(username='******', name='Mouse Cop', email='*****@*****.**', bio='Cat no like mouse. Cat like coding WORM'), User(username='******', name='Little Russian Lady', email='*****@*****.**', bio='Please... get me some beets'), ] users[0].set_password('cat1') users[1].set_password('cat2') users[2].set_password('cat3') db.session.add_all(users) db.session.commit() users[0].send_request(users[2]) users[1].send_request(users[0]) users[2].send_request(users[1]) departments = [ Department(name='Computer Science', abbr='COMP'), Department(name='Languages', abbr='LNGS'), Department(name='Mathematics', abbr='MATH') ] db.session.add_all(departments) courses = [ Course(name='Principles of Computer Science II', number=172, department=departments[0]), Course(name='Introduction to Data Structures', number=220, department=departments[0]), Course(name='Language and the Mind', number=242, department=departments[1]), Course(name='Statistics', number=124, department=departments[2]), Course(name='Intro to WORM Programming', number=999, department=departments[0]), ] db.session.add_all(courses) associations = [ MentorToCourse(mentor=users[0], course=courses[1]), MentorToCourse(mentor=users[0], course=courses[0]), MentorToCourse(mentor=users[1], course=courses[3]), MentorToCourse(mentor=users[1], course=courses[4]), MentorToCourse(mentor=users[2], course=courses[2]), ] db.session.add_all(associations) db.session.commit() return redirect(url_for('index'))
def add_todo(): a1 = Course(title='Drafting') b1 = Todo( description='start blueprints', course=a1 ) db.session.add(b1) a2 = Course(title='Python') b2 = Todo(description='practice', todo=a2) db.session.add(b2) db.session.commit()
def create(): # TODO authenticate user form = CreateCourseForm() if form.validate_on_submit(): course = Course(number=int(form.courseNumber.data), name=form.courseName.data, description=form.courseDescription.data, prerequisites=form.coursePrereqs.data, building=form.courseBuilding.data, room=form.courseRoomNo.data) course.setVersion() course.is_core = form.isCore.data course.is_diversity = form.isDiversity.data course.is_elr = form.isELR.data course.is_wi = form.isWI.data syllabus = Syllabus(course_number=form.courseNumber.data, course_version=course.version, semester=form.semester.data, year=form.year.data, section=form.section.data) syllabus.setVersion() db.session.add(syllabus) db.session.add(course) db.session.commit() # TODO: Handle case, what if course already exists. crash cleanly flash("Course Created!") return render_template('course/create.html', title="Create Course", form=form)
def add_courses(num_courses=12): course_titles = [ 'CS', 'ARCH', 'EAS', 'MECH', 'BIOL', 'BMED', 'ECE', 'HTS', 'LMC' ] designations = [d['name'] for d in Designation.get_all()] categories = [c['name'] for c in Category.get_all()] for i in xrange(num_courses): course_number = '{} {}'.format( course_titles[randint(0, len(course_titles) - 1)], randint(1000, 9999)) instructor = 'Instructor for {}'.format(course_number) designation = designations[randint(0, len(designations) - 1)] cats = [ categories[i] for i in sample(xrange(len(categories)), randint(2, 5)) ] new_course = Course(course_number=course_number, name='Course Name for {}'.format(course_number), instructor=instructor, est_num_students=randint(0, 1000), designation_name=designation, categories=cats, is_new_course=True) new_course.save()
def setUp(self): self.app = create_app('testing') self.app_context = self.app.app_context() self.app_context.push() db.create_all() Role.insert_roles() self.client = self.app.test_client(use_cookies=True) # 新建教师 赋予加V角色 新建原课程/课程 r = Role.query.filter_by(name='Teacher_V').first() if r is None: raise Exception('没有教师角色???') self.teacher = User(username=u'桃李满园关不住', name=u'这是老师', password='******', confirmed=True, role=r) self.raw_course = RawCourse(name=u'出装、意识与走位', course_code='12345', worth='100') self.course = Course(self.teacher, self.raw_course) db.session.add(self.teacher) db.session.add(self.raw_course) db.session.add(self.course) db.session.commit()
def create_course(): from random import choice from string import ascii_uppercase as uc, digits as dg course_name = request.values['course_name'] part1 = ''.join(choice(uc) for j in range(3)) # 三个大写的英文 part2 = ''.join(choice(dg) for j in range(3)) # 三个随机数字 invitation_code = part1 + part2 search_result = Course.query.filter_by(id=invitation_code).first() while search_result is not None: part1 = ''.join(choice(uc) for j in range(3)) # 三个大写的英文 part2 = ''.join(choice(dg) for j in range(3)) # 三个随机数字 invitation_code = part1 + part2 newcourse = Course(invitation_code, course_name, g.user.id) user = User.query.filter_by(id=g.user.id).first() newcourse.creator = user db.session.add(newcourse) db.session.commit() result = session['result'] result.append((url_for('t_class_section', course_id=invitation_code), course_name)) session.pop('result', None) session['result'] = result return jsonify(invitation_code)
def add_course(request): c_names = ['大学英语', '商务英语', '线代', '高数'] for name in c_names: c = Course() c.c_name = name c.save() return HttpResponse('创建课程成功')
def test_course_with_class(self): # + 原课程 raw_course = RawCourse(name=u'Java') db.session.add(raw_course) db.session.commit() # + 从原课程指定实际课程 course = Course(User(name=u"老师"), RawCourse(name=u"没课")) # course.raw_course_id = raw_course.id course.raw_course = raw_course db.session.add(course) db.session.commit() # + 两个班级 c = _Class(name=u'14计本1') c2 = _Class(name=u'14计本2') # 将班级与课程关联起来 c.courses.append(course) # c2.courses.append(course) course.classes.append(c2) db.session.add(c) db.session.add(c2) db.session.commit() # 判断 self.assertTrue(course in c.courses) self.assertTrue(c in course.classes) self.assertTrue(course in c2.courses) self.assertTrue(c2 in course.classes) course.classes.remove(c) db.session.add(course) db.session.commit() self.assertFalse(course in c.courses) self.assertFalse(c in course.classes)
def seeds(create_database): user = User( name="Marcus Pereira", email="*****@*****.**", password=generate_password_hash("12345"), is_admin=True, ) db.session.add(user) db.session.commit() course = Course( name="Curso de test", slug="curso-de-test", description="alguma coisa...", duration=300, video_url="http://fake:4000/video", source_code_url="http://fake:4000/source", release_date=datetime.utcnow(), author_id=user.id, ) tag = Tag(name="python") tag2 = Tag(name="javascript") tag3 = Tag(name="flask") course.tags.append(tag) course.tags.append(tag2) course.tags.append(tag3) db.session.add(course) db.session.commit() db.session.add( Quote(title="1. introduction", quote_time=20, course_id=course.id)) db.session.commit()
def add_course(id): teacher = Teacher.query.filter_by(id=id).first() courseName = str(request.data.get('courseName', '')) author = teacher.firstname limit = str(request.data.get('limit', '')) if courseName and author and limit: new_course = Course(courseName=courseName, author=author, limit=limit) teacher.course_teachers.append(new_course) teacher.save() new_course.save() response = jsonify({ 'id': new_course.id, 'courseName': new_course.courseName, 'author': new_course.author, 'limit': new_course.limit, 'students': new_course.course_students }) response.status_code = 201 return response else: return { "ERROR": "Введіть всі поля courseName and author and limit", "STATUS CODE": 405 }
def add_cou(): cous = ['线代', '高数', '概论', '大学物理', '大学英语'] for cou in cous: c = Course() c.c_name = cou c.save() return '创建课程成功'
def postTaPosition(): form = PositionPostForm() if request.method == 'POST': if form.validate_on_submit(): post = PositionPost(course=request.form['course'], semester=request.form['semester'], numbersOfTA=request.form['numbersOfTA'], minGPA=request.form['minGPA'], minGrade=request.form['minGrade'], requirements=request.form['requirements'], instructor_id=current_user.instructor.id) course = Course(name=post.course, numbersOfTA=post.numbersOfTA, instructor_id=current_user.instructor.id) course.currentTA = 0 post.name = current_user.instructor.name post.phone = current_user.instructor.phone post.classes = course db.session.add(course) db.session.add(post) current_user.instructor.courses.append(course) current_user.instructor.posts.append(post) db.session.commit() flash('Posted') return redirect('/instructor') return render_template('create.html', title="Post TA-Positions", form=form)
def new_course(): form = NewCourse() if request.method == 'POST' and form.validate(): check = Course.query.filter_by( course_name=request.form.get('course_name').title(), grade=request.form.get('grade')).first() if check == None: y = Course(course_name=request.form.get('course_name').title(), grade=request.form.get('grade'), teacher_id=current_user.id) session.add(y) session.commit() data = request.form course_id = y.id for student in data: if student[:7] == 'student': # same problem as '/courses/<id>/add_students where id in not autoincramemting count = StudentCourse.query.order_by( StudentCourse.id.desc()).all() if len(count) == 0: sc_id = 1 else: sc_id = count[0].id + 1 x = StudentCourse(id=sc_id, student_id=request.form.get(student), course_id=y.id) session.add(x) session.commit() return redirect(f'/courses/{course_id}') else: flash( 'A course with that name is already being taught in that grade' ) return redirect('/courses/new') return render_template('teacher_templates/new_course.html', form=form)
def add_cou(request): cous = ['线代', '高数', '物理', '英语'] for c in cous: cou = Course() cou.c_name = c cou.save() return HttpResponse('创建课程成功')
def add_course(): cou = Course() cou.c_name = '大学英语' db.session.add(cou) db.session.commit() return '创建成功'
def parse_and_store(path): db.drop_all() db.create_all() print(path) data = json.load(open(path)) for datum in data: course = Course(course_id=datum["Course"], call_number=datum["CallNumber"], course_name=datum["CourseTitle"], bulletin_flags=datum["BulletinFlags"], division_code=datum["DivisionCode"], class_notes=datum["ClassNotes"], num_enrolled=datum["NumEnrolled"], max_size=datum["MaxSize"], min_units=datum["MinUnits"], num_fixed_units=datum["NumFixedUnits"], term=datum["Term"], campus_name=datum["CampusName"], campus_code=datum["CampusCode"], school_code=datum["SchoolCode"], school_name=datum["SchoolName"], approval=datum["Approval"], prefix_name=datum["PrefixName"], prefix_long_name=datum["PrefixLongname"], instructor_name=datum["Instructor1Name"], type_name=datum["TypeName"], type_code=datum["TypeCode"]) db.session.add(course) db.session.commit()
def main(): app, db = create_app(Config) with app.app_context(): bulk_objects = [] db.create_all() # First get a set of all the courses courses = set() # Set of sqlalchemy.util._collections.result for row in TDG.query.with_entities(TDG.campus, TDG.subject, TDG.course, TDG.detail).distinct(): courses.add(row) for row in PRG.query.with_entities( PRG.campus, PRG.subject, PRG.course, PRG.detail).filter(PRG.year < '2014').distinct(): courses.add(row) N = len(courses) for index, course in enumerate(courses): if index % 100 == 0: print(f'{index}/{N}') sections = get_sections_combined(course) averages = [ section.average for section in sections if section.average is not None ] # Compute the average and standard deviation avg, stdev = compute_average_stdev(sections, averages) avg_past_5_yrs = compute_average_past_5_years(sections) max_course_avg = max(averages) if averages else None min_course_avg = min(averages) if averages else None # Get newest metadata meta = TDG.query.with_entities(TDG.faculty_title, TDG.course_title, TDG.subject_title)\ .filter_by(campus=course.campus, subject=course.subject, course=course.course, detail=course.detail).first() if meta is None: meta = PRG.query.with_entities(PRG.faculty_title, PRG.course_title, PRG.subject_title) \ .filter_by(campus=course.campus, subject=course.subject, course=course.course, detail=course.detail).first() new_entry = Course(campus=course.campus, faculty_title=meta.faculty_title, subject=course.subject, subject_title=meta.subject_title, course=course.course, course_title=meta.course_title, detail=course.detail, average=avg, average_past_5_yrs=avg_past_5_yrs, stdev=stdev, max_course_avg=max_course_avg, min_course_avg=min_course_avg) bulk_objects.append(new_entry) db.session.bulk_save_objects(bulk_objects) db.session.commit()
def course_info(): state = request.args.get('state') holes = request.args.get('holes') course_name = request.args.get('course_name') if holes == '18 Holes': form = CourseInfoForm18() hole_numbers = [i for i in range(18)] # using this to increment throught the FieldList in CourseInfoForm_ else: form = CourseInfoForm9() hole_numbers = [i for i in range(9)] if form.validate_on_submit(): par = form.par.data # returns list [] of ints hole_numbers = [i+1 for i in hole_numbers] layout = {'Hole': hole_numbers, 'Par': par} course = Course(course=course_name, layout=layout, state=state) db.session.add(course) db.session.commit() message = "{} Added to Database".format(course_name) flash(message, 'success') return redirect(url_for('index')) return render_template('course_info.html', form=form, hole_numbers=hole_numbers)
def setUp(self): self.app = create_app('testing') self.app_context = self.app.app_context() self.app_context.push() db.create_all() db.session.add(Course(credit=1, score=90, type_id=CourseType.GENERAL)) db.session.add(Course(credit=2, score=75, type_id=CourseType.GENERAL)) db.session.add(Course(credit=1, score=80, type_id=CourseType.PRO_BASIC)) db.session.add(Course(credit=2, score=35, type_id=CourseType.PRO_BASIC)) db.session.add(Course(credit=1, score=90, type_id=CourseType.PRO_OPTIONAL)) db.session.commit()
def add_cou(request): names = ['大学英语', '大学语文', '高数', '模电', 'VHDL'] for name in names: cou = Course() cou.c_name = name cou.save() return HttpResponse('添加课程成功')
def add_class(): form = AddClassForm() if form.validate_on_submit(): course = Course(code=form.code.data, student=current_user, lec_link=form.lec_link.data, pra_link=form.pra_link.data, tut_link=form.tut_link.data) lec = Lecture(course=course) pra = Practical(course=course) tut = Tutorial(course=course) if form.lec1_start.data != '': add = 12 if form.lec1_ampm == 'am': add = 0 lec.day1 = int(form.lec1_day.data) lec.time1 = int(form.lec1_start.data) + add if form.lec2_start.data != '': add = 12 if form.lec2_ampm == 'am': add = 0 lec.day2 = int(form.lec2_day.data) lec.time2 = int(form.lec2_start.data) + add if form.lec3_start.data != '': add = 12 if form.lec3_ampm == 'am': add = 0 lec.day3 = int(form.lec3_day.data) lec.time3 = int(form.lec3_start.data) + add if form.tut_start.data != '': add = 12 if form.tut_ampm == 'am': add = 0 tut.day1 = int(form.tut_day.data) tut.time1 = int(form.tut_start.data) + add if form.pra_start.data != '': add = 12 if form.pra_ampm == 'am': add = 0 pra.day1 = int(form.pra_day.data) pra.time1 = int(form.pra_start.data) + add db.session.add(course) db.session.add(lec) db.session.add(tut) db.session.add(pra) db.session.commit() return redirect(url_for('index')) return render_template('edit.html', form=form)
def add_course(): if request.method == 'GET': courses = ['线代', '高数', '大学物理', '计算机', '英语'] for course in courses: c = Course() c.c_name = course db.session.add(c) db.session.commit() return '创建课程成功'
def seedTheCourseData(): courses = [ "Broadmoor", "Camas Meadows", "Colwood", "Heron Lakes Great Blue", "Heron Lakes Greenback", "Tri Mountain" ] for course in courses: new_course = Course(name=course) new_course.save()
def updateInformation(): form = AdminForm() if form.validate_on_submit(): course_code = form.course_code.data course_code = form.course_code.data start_time = form.start_time.data end_time = form.end_time.data start_date = form.start_date.data end_date = form.end_date.data location = form.location.data student_array = [] student_details = form.student_details.data # filename = secure_filename(student_details.filename) contents = student_details.read() # contents = contents.decode() contents_stripped = contents.rstrip("\r\n") contents_split = contents_stripped.split("\r\n") first_row = True for content in contents_split: if first_row == True: first_row = False else: data = content.split(",") new_name = data[0] new_email = data[1] if not db.session.query(db.exists().where( Student.email == new_email)).scalar(): new_student = Student(email=new_email, name=new_name) db.session.add(new_student) student_array.append(new_student) if db.session.query(Location).filter( Location.venue == location).first() == True: new_location = db.session.query(Location).filter( Location.venue == location).first() else: new_location = Location(venue=location) db.session.add(new_location) db.session.commit() new_course = Course(course_code=course_code, start_time=start_time, end_time=end_time, start_date=start_date, end_date=end_date, location_id=new_location.id, students=student_array) db.session.add(new_course) db.session.commit() flash('Course information has been updated!') return redirect(url_for('updateInformation')) return render_template('updateinformation.html', title='Admin', form=form)
def add_course(id, cname="noname"): # course_response_object = json.loads(views.get_course(course_id)) if course_in_database(id) == False: course = Course() course.course_id = id course.course_name = cname course.save() return course else: return Course.objects.get(course_id=id)