def new_assignment_from_form(form): if form.assignment_task_file.data is not None: file = form.assignment_task_file.data random_filename = app.files.models.save_file(file) original_filename = app.files.models.get_secure_filename(file.filename) assignment_task_file = AssignmentTaskFile( original_filename=original_filename, filename=random_filename, user_id=current_user.id) db.session.add(assignment_task_file) db.session.flush() # Access the assignment_task_file.id field from db for turma_id in form.target_turmas.data: assignment = Assignment( title=form.title.data, description=form.description.data, due_date=form.due_date.data, target_turma_id=turma_id, created_by_id=current_user.id, peer_review_necessary=form.peer_review_necessary.data, peer_review_form_id=form.peer_review_form_id.data) if form.assignment_task_file.data is not None: assignment.assignment_task_file_id = assignment_task_file.id db.session.add(assignment) db.session.commit()
def setUpModule(): app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://' db.create_all() a1 = Assignment(title='Some assignment 1', course_id=1, outcome_id=123) a2 = Assignment(title='Some assignment 2', course_id=1, outcome_id=456) db.session.add_all([a1, a2]) db.session.commit()
def add_assignment(course_id): course = Course.query.filter_by(id=course_id).first_or_404() if request.method == 'POST': existing_assignment = Assignment.query.filter_by( title=request.form["title"]).first() if existing_assignment is not None: flash("Use different title") return redirect(url_for('assignments.add_assignment', course_id=course.id)) assignment = Assignment() assignment.title = request.form['title'] assignment.course = course assignment.description = request.form['description'] assignment.sample_input = request.form['sample_input'] assignment.sample_output = request.form['sample_output'] assignment.test_data = request.form['test_data'] if request.form['time_limit'] != '' and is_number(request.form['time_limit']): assignment.time_limit = request.form['time_limit'] db.session.add(assignment) db.session.commit() flash("Successfully added new assignment to {}".format(course.title)) return redirect(url_for("assignments.assignment", id=assignment.id)) return render_template("assignments/add_assignment.html", title="Add assignment", course=course)
def create_assignment(cid): course = Course.query.get_or_404(cid) form = AssignmentCreateForm().validate_for_api() with db.auto_commit(): assignment = Assignment() form.populate_obj(assignment) assignment.course_cid = cid if 'file' in request.files: file = request.files['file'] if file and file.filename != '': create_file(file, assignment) db.session.add(assignment) return jsonify({'id': assignment.id})
def _process_assignments(self, user: Account, assignments: dict): """ Processes the user's WaniKani assignments and stores it in the database to be easily accessible. Parameters ---------- user : Account The user's Account ORM object. assignments : dict The JSON containing the review info. Returns ------- None """ for assignment in assignments['data']: id = assignment['id'] subject_id = assignment['data']['subject_id'] subject = Subject.query.filter_by(id=subject_id).first().characters srs_stage_name = assignment['data']['srs_stage_name'] srs_stage_id = assignment['data']['srs_stage'] start_date = assignment['data']['started_at'] pass_date = assignment['data']['passed_at'] end_date = assignment['data']['burned_at'] asmt = Assignment.query.filter_by(id=id).first() if asmt: asmt.srs_stage = srs_stage_id asmt.started_at = start_date asmt.passed_at = pass_date asmt.burned_at = end_date else: asmt = Assignment() asmt.id = id asmt.user_id = user.id asmt.srs_stage = srs_stage_id asmt.started_at = start_date asmt.passed_at = pass_date asmt.burned_at = end_date asmt.subject_id = subject_id database.session.add(asmt) # Hack to properly pad UTF-8 Japanese characters. # Python does not handle multi-byte characters that well, especially considering full vs half width. if 'Radical' not in subject: padding_to_remove = len(subject) - 1 subject = f'{subject:>15}'.replace(' ', '', padding_to_remove) else: subject = f'{subject:>16}' print( f'ID: {id:>10} | Subject ID: {subject_id:>8} | Subject: {subject} | SRS stage: {srs_stage_name:>14} ({srs_stage_id}) | Start date: {start_date or "N/A":>27} | Pass date: {pass_date or "N/A":>27} | Completion date: {end_date or "N/A":>27}' )
def test_align_outcome_to_assignment(self): a1 = Assignment(id=123456, title='Some assignment', course_id=999) db.session.add(a1) db.session.commit() o1 = Outcome.query.filter_by(outcome_id=123).first() o1.align(a1)
def populate(): date_object = request.get_json() year = date_object[2] response_list = [] for i in range(7): response_list.append([]) month = date_object[0][i] day = date_object[1][i] assignments = Assignment.query.filter( Assignment.user_id == current_user.id).filter( Assignment.classification == 'requested').filter( Assignment.month == month).filter( Assignment.day == day).filter( Assignment.year == year).all() for assignment in assignments: # here is where we duplicate each assignment into an 'assigned' one assigned_assignment = Assignment( month=assignment.month, day=assignment.day, year=assignment.year, classification='assigned', employee_id=assignment.employee.id, user_id=current_user.id) db.session.add(assigned_assignment) response_list[i].append([ assignment.employee.first_name, assignment.employee.last_name ]) db.session.commit() json_response = json.dumps(response_list) return json_response
def save_assignment_data(canvas, course_id, assignment_group_id): """ Save course assignments to the database. :param canvas: canvasapi Canvas object :ptype canvas: object :param course_id: Canvas course ID :ptype course_id: int :param assignment_group_id: Canvas assignment group ID :ptype assignment_group_id: int """ assignment_commits = [] course = canvas.get_course(course_id) assignment_group = course.get_assignment_group(assignment_group_id, include=["assignments"]) for a in assignment_group.assignments: query = Assignment.query.get(a["id"]) if query is None: assignment = Assignment(id=a["id"], title=a["name"], course_id=course_id) assignment_commits.append(assignment) db.session.bulk_save_objects(assignment_commits) db.session.commit()
def test_build_submission_dict(self): o1 = Outcome(id=1, title='Test Outcome', course_id=39775, outcome_id=123) a1 = Assignment(id=190128, title='Test Assignment', course_id=39775) db.session.add_all([o1, a1]) db.session.commit() o1.align(a1) db.session.commit() course = self.canvas.get_course(self.course_id) enrollments = [31874, 31875] assignment_list = [190128] submissions = [] all_submissions = course.get_multiple_submissions( assignment_ids=assignment_list, student_ids=enrollments, include=("user", "assignment"), grouped=True, ) for student in all_submissions: items = student.submissions for item in items: submissions.append( Assignments.process_enrollment_submissions(item)) self.assertIsInstance(submissions, list)
def setUp(self): app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://' db.create_all() o2 = Outcome(outcome_id=123, course_id=999, title="Some Outcome") a2 = Assignment(id=999, course_id=999, title="Some Assignment") db.session.add_all([o2, a2]) db.session.commit()
def new_assignment_from_form (form): if form.assignment_task_file.data is not None: file = form.assignment_task_file.data random_filename = app.files.models.save_file(file) original_filename = app.files.models.get_secure_filename(file.filename) assignment_task_file = AssignmentTaskFile ( original_filename=original_filename, filename = random_filename, user_id = current_user.id ) db.session.add(assignment_task_file) db.session.flush() # Access the assignment_task_file.id field from db db.session.commit() for turma_id in form.target_turmas.data: assignment = Assignment( title=form.title.data, description=form.description.data, due_date=form.due_date.data, target_turma_id=turma_id, created_by_id=current_user.id, peer_review_necessary= form.peer_review_necessary.data, open_peer_review= form.open_peer_review.data, peer_review_form_id=form.peer_review_form_id.data) if form.assignment_task_file.data is not None: assignment.assignment_task_file_id=assignment_task_file.id db.session.add(assignment) db.session.flush() if form.email_students: users = app.classes.models.get_class_enrollment_from_class_id(turma_id) assignment_url = url_for('assignments.view_assignments', _external=True) usernames_and_emails = [] assignment_title = assignment.title for enrollment, turma, user in users: usernames_and_emails.append ({ 'username': user.username, 'email': user.email }) app_name = current_app.config['APP_NAME'] thr = Thread( target=send_async_assignment_notification_to_class, args=[current_app._get_current_object(), usernames_and_emails, turma_id, assignment_title, assignment_url, app_name]) thr.start() db.session.commit()
def test_publish(mocker, student_repository, assignment_scraper, notifier): cases = [{ 'scraper': [{ '00002401': [Assignment(date.today(), 'bla bla')] }], 'repository': [ Student('00002401', 'Filippo', 'Branca', [], '2020-01-26T09:05:35.692104', '2020-01-26T09:05:35.692104') ], 'result': """ Ecco i compiti in scadenza oggi per Filippo: - 2020-04-26: bla bla """ }] mocker.patch.object(assignment_scraper, "all") mocker.patch.object(student_repository, "all") mocker.patch.object(notifier, "send") for case in cases: # reset mock objects assignment_scraper.all.reset_mock() student_repository.all.reset_mock() notifier.send.reset_mock() # set side effects assignment_scraper.all.side_effect = case['scraper'] student_repository.all.side_effect = [case['repository']] notifier.send.side_effect = None # execute publisher = PublishAssignmentsHandler(student_repository, assignment_scraper, notifier) event = { "account": "123456789012", "region": "us-east-2", "detail": {}, "detail-type": "Scheduled Event", "source": "aws.events", "time": "2019-03-01T01:23:45Z", "id": "cdc73f9d-aea9-11e3-9d5a-835b769c0d9c", "resources": ["arn:aws:events:us-east-1:123456789012:rule/my-schedule"] } context = {} publisher.handle(event, context) notifier.send.assert_called_with(case['result'])
def setUpModule(): app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://' db.create_all() o1 = Outcome(title='Some outcome 1', course_id=999, outcome_id=123) o2 = Outcome(title='Some outcome 1', course_id=888, outcome_id=123) a1 = Assignment(title="Some assignment", course_id=999, id=111) db.session.add_all([o1, o2, a1]) db.session.commit()
def seed_assignments(): for i in range(500): new_assignment = Assignment(professional_id=fake.pyint(min_value=1, max_value=200), patient_id=fake.pyint(min_value=1, max_value=1000)) db.session.add(new_assignment) db.session.commit()
def saveAddAssignment(): name = request.form['name'] date = request.form['date'] points = request.form['points'] newassignment = Assignment(name, date, points) assignments.append(newassignment) return redirect(url_for('index'))
def assignment_fixture(course: Course, session: Session) -> Assignment: assignment = Assignment( name="Big Exam", description="Huge Exam", status="completed", due=datetime.date(2021, 12, 12), course_id=course.id, weight=50, mark=100, outcome="pass", ) session.add(assignment) session.commit() yield assignment
def test_align_assignment_to_outcome(self): o3 = Outcome(outcome_id=1, course_id=999, title="Test Outcome 1") a1 = Assignment(title='Some Assignment', course_id=999, id=1) db.session.add_all([o3, a1]) db.session.commit() outcome_id = 1 assignment_id = 1 course_id = 999 Outcomes.align_assignment_to_outcome(course_id, outcome_id, assignment_id) outcome = Outcome.query.filter_by(outcome_id=1).first() self.assertIsNotNone(outcome.assignment_id)
def newassignment(code): # form = NewAssignment() user = current_user course = Course.query.filter_by(code=code).first_or_404() if request.method == "POST": assignment = Assignment(title=request.form.get("title"), body=request.form.get("body")) course.assignments.append(assignment) db.session.add(assignment) db.session.commit() flash('Congratulations, you have added a new question!') return redirect(url_for('opencourse', code=code))
def create_assignment(*, session: Session = Depends(get_session), course_id: int, assignment: AssignmentCreate, current_user: User = Depends(deps.get_current_user)): # check that the user is authorized to get this course get_course(session, course_id, current_user) # create the assignment assignment_db = Assignment.from_orm(assignment) assignment_db.course_id = course_id # assign to this course session.add(assignment_db) session.commit() session.refresh(assignment_db) return assignment_db
def add(): form = AssignmentForm() if request.method == 'POST': if form.validate_on_submit(): assignment = Assignment(name=form.name.data, due_date=form.due_date.data, description=form.description.data, course_id=form.course.data) db.session.add(assignment) db.session.commit() flash('Assignment Added', 'success') return redirect(url_for('assignments.index')) else: print(form.errors) flash('Assignment is invalid', 'danger') context = {'form': form} return render_template('assignments/add.html', **context)
def addAssignment(): addStudentForm = StudentForm() addAssignmentForm = AssignmentForm() if addAssignmentForm.validate_on_submit(): newassignment = Assignment(addAssignmentForm.name.data.strip(), addAssignmentForm.date.data.strip(), addAssignmentForm.points.data.strip()) assignments.append(newassignment) # anything you print here gets printed to your terminal print(newassignment.name, newassignment.date, newassignment.points) return redirect(url_for('index')) return render_template('gradebook.html', addStudentForm=addStudentForm, addAssignmentForm=addAssignmentForm, students=students, assignments=assignments)
def create_assignment(): form = AssignmentForm() if form.validate_on_submit(): dt = time_convert(str(form.due_date.data), str(form.due_time.data)) assignment = Assignment(class_name=form.class_name.data, title=form.title.data, summary=form.summary.data, due=dt, creator=current_user) db.session.add(assignment) db.session.commit() flash('Your assignment is posted!') return redirect(url_for('index')) return render_template('assignment.html', title='New Assignment', form=form)
def add_assignment(): # create the Assignment row in the table assignment_list = request.get_json() username, month, day, year, classification = assignment_list[ 0], assignment_list[1], assignment_list[2], assignment_list[ 3], assignment_list[4] employee = Employee.query.filter( Employee.user_id == current_user.id).filter( Employee.username == username).first() # month, day, year, shift_type, employee_id new_assignment = Assignment(month=month, day=day, year=year, classification=classification, employee_id=employee.id, user_id=current_user.id) db.session.add(new_assignment) db.session.commit() return f'add assignment route run'
def create_course(*, session: Session = Depends(get_session), course: CourseCreate, current_user: User = Depends(deps.get_current_user)): db_course = Course.from_orm(course, {"user_id": current_user.id}) session.add(db_course) session.commit() session.refresh(db_course) new_assignments = [] for assignment in course.assignments: new_assignment = Assignment.from_orm(assignment, {"course_id": db_course.id}) new_assignments.append(new_assignment) session.add_all(new_assignments) db_course.assignments = new_assignments session.commit() session.refresh(db_course) return db_course
def extract_assisgnments(page: str) -> List[Assignment]: """ Parses and extract student's assignment from the 'registro di classe' HTML page. """ tree = html.fromstring(page) trs = tree.xpath('//*[@id="content-comunicazioni"]/table/tbody/tr') assignments = [] for tr in trs: tds = tr.xpath('td') # print('when', tds[0].xpath('string()')) # print('when', tds[0].xpath('text()')) date_text = tds[0].xpath('i')[0].tail when = datetime.strptime(date_text, '%d/%m/%Y').date() homework = tds[2].text_content() assignments.append(Assignment(when, homework)) return assignments
def new_assignment(): teacher = Teacher.query.filter_by(id=current_user.id).first() blocks = teacher.blocks weeks = Week.query.filter(Week.block.has(teacher_id=current_user.id)).all() form = AssignmentForm() form.block.choices = [( block.id, f'{block.subject.title} {block.title}', ) for block in teacher.blocks] if form.validate_on_submit(): week = Week.query.filter_by( block_id=form.block.data, week_number=form.week_number.data, ).first() if form.end_of_week.data: due_date = week.end_date else: due_date = form.due_date.data assignment = Assignment( week_id=form.week_number.data, due_date=due_date, title=form.title.data, description=form.description.data, ) week.assignments.append(assignment) db.session.commit() return redirect(url_for('new_assignment')) return render_template( 'assignments/new_assignment.html', blocks=blocks, weeks=weeks, form=form, )
def deploy(): ''' Run deployment tasks. ''' # migrate database to latest revision from flask_migrate import upgrade upgrade() # insert data from app.models import Color Color.insert_entries() from app.models import Permission Permission.insert_entries() from app.models import Role Role.insert_entries() from app.models import IDType IDType.insert_entries() from app.models import Gender Gender.insert_entries() from app.models import Relationship Relationship.insert_entries() from app.models import PurposeType PurposeType.insert_entries() from app.models import ReferrerType ReferrerType.insert_entries() from app.models import BookingState BookingState.insert_entries() from app.models import AssignmentScoreGrade AssignmentScoreGrade.insert_entries() from app.models import GREAWScore GREAWScore.insert_entries() from app.models import ScoreLabel ScoreLabel.insert_entries() from app.models import InvitationType InvitationType.insert_entries() from app.models import EducationType EducationType.insert_entries() from app.models import ScoreType ScoreType.insert_entries() from app.models import CourseType CourseType.insert_entries() from app.models import iPadCapacity iPadCapacity.insert_entries() from app.models import iPadState iPadState.insert_entries() from app.models import Room Room.insert_entries() from app.models import Lesson Lesson.insert_entries() from app.models import Section Section.insert_entries() from app.models import Assignment Assignment.insert_entries() from app.models import Test Test.insert_entries() from app.models import AnnouncementType AnnouncementType.insert_entries() from config import basedir data = raw_input(u'Enter data identifier (e.g.: initial or 20160422): ') datadir = os.path.join(basedir, 'data', data) if os.path.exists(datadir): from app.models import User User.insert_entries(data=data, basedir=basedir) from app.models import UserCreation UserCreation.insert_entries(data=data, basedir=basedir) from app.models import Punch Punch.insert_entries(data=data, basedir=basedir) from app.models import Tag Tag.insert_entries(data='initial', basedir=basedir) from app.models import Product Product.insert_entries(data='initial', basedir=basedir) from app.models import Course Course.insert_entries(data='initial', basedir=basedir) from app.models import Period Period.insert_entries(data='initial', basedir=basedir) from app.models import iPad iPad.insert_entries(data='initial', basedir=basedir) from app.models import iPadContent iPadContent.insert_entries(data='initial', basedir=basedir) from app.models import NotaBene NotaBene.insert_entries(data='initial', basedir=basedir) from app.models import Feed Feed.insert_entries(data=data, basedir=basedir) else: print u'---> Invalid data identifier: %s' % data
def readPubSub(message): try: print('***********************Reading Message***********************') if message["collection"] == "courses.courseWork": if message['eventType'] == "CREATED": service = build_service() assignment = service.courses().courseWork().get( courseId=message['resourceId']['courseId'], id=message['resourceId']['id']).execute() print("Adding new assignment") a = Assignment(name=assignment.get('title'), courseWorkId=message['resourceId']['id']) db.session.add(a) db.session.commit() elif message["collection"] == "courses.courseWork.studentSubmissions": service = build_service() submission = service.courses().courseWork().studentSubmissions( ).get(courseId=message['resourceId']['courseId'], courseWorkId=message['resourceId']['courseWorkId'], id=message['resourceId']['id']).execute() if message['eventType'] == "MODIFIED" and submission[ 'state'] == 'TURNED_IN': student = get_student(service, submission["userId"]) print("Received a submission from ") attachments = submission['assignmentSubmission']['attachments'] errorFiles = [] for file in attachments: fileTitle = file['driveFile']['title'] # File Format: Firstname Lastname, Event, Topic, test/key if re.match( r'^\w+\s\w+\s*,\s*.*,\s*.*,\s*([Tt]est|[Kk]ey)', fileTitle.strip()): fileDetails = fileTitle.split(',') if Event.query.filter_by( event_name=fileDetails[1].strip().lower( )).first() is not None: print("<b>Filename:</b> " + fileTitle + ", <b>Error:</b> None") else: print("<b>Filename:</b> " + fileTitle + ", <b>Error:</b> Incorrect Event Name") errorFiles.append( "<b>Filename:</b> " + fileTitle + ", <b>Error:</b> Incorrect Event Name") else: print("<b>Filename:</b> " + fileTitle + ", <b>Error:</b> Incorrect Filename Format") errorFiles.append( "<b>Filename:</b> " + fileTitle + ", <b>Error:</b> Incorrect Filename Format") if errorFiles != []: print("Sending Error Email") # return_work(service,submission["courseId"], submission["courseWorkId"], submission["id"]) assignment = Assignment.query.filter_by( courseWorkId=submission['courseWorkId']).first() sendCheckFilename(student["emailAddress"], assignment.name, submission["alternateLink"], errorFiles) else: print("Sending Received Submission Email") assignment = Assignment.query.filter_by( courseWorkId=submission['courseWorkId']).first() sendReceivedSubmission(student["emailAddress"], assignment.name, submission["alternateLink"]) else: print("No action on last message") else: print("No action on last message") except Exception as e: print("Error reading message:", e)
def update_assignment(title, email, score): assignment = Assignment.find(title.strip()) assignment.add_to_db(email, score) return 'Assignment updated', 204
from app.models import User, Student, Assignment import sqlite3 import sys import csv # initialize students and arrays students = [] # eventually we will get these via SQL queries instead dummystudent1 = Student('John', 'Doe', '*****@*****.**') dummystudent2 = Student('Kanye', 'West', '*****@*****.**') students.append(dummystudent1) students.append(dummystudent2) assignments = [] # eventually we will get these via SQL queries instead dummyassignment1 = Assignment('HW 1', '01-01-2020', 5) dummyassignment2 = Assignment('HW 2', '01-02-2020', 10) assignments.append(dummyassignment1) assignments.append(dummyassignment2) @app.route('/') #@app.route('/index') #@login_required def index(): addStudentForm = StudentForm() addAssignmentForm = AssignmentForm() return render_template('gradebook.html', addStudentForm=addStudentForm, addAssignmentForm=addAssignmentForm, students=students,