示例#1
0
def student_page():  # student sign in page
    if request.method == "POST":
        user = Student("", "", "", "", "")
        user.email = request.form['email']
        user.password = request.form['password']
        result = db.get_student(user.email)

        if result:
            password2 = result['student_password']
            if hasher.verify(user.password, password2):
                session['logged_in'] = True
                session['s-email'] = user.email
                session['s-name'] = result['student_name']
                session['s-surname'] = result['student_surname']
                session['s-id'] = result['student_id']
                flash('You are now logged in', 'success')  #??
                return redirect(
                    url_for('student_main_page', name=result['student_name']))
            else:
                error = " Wrong password!"
                return render_template('student_sign.html', error=error)

        else:
            error = " Email not found!"
            return render_template('student_sign.html', error=error)

    return render_template('student_sign.html')
示例#2
0
class TestStudent(TestCase):
    def setUp(self):
        self.student = Student(name='ramadan')
        self.quiz = Quiz()

    def test_created(self):
        self.assertEqual('ramadan', self.student.name)
        self.assertEqual([], self.student.assigned_classes)
        self.assertEqual([], self.student.quizzes)

    @patch('classes.Quiz.solve_question', autospec=True)
    def test_solve_question(self, solve):
        # no quizzes
        self.assertFalse(self.student.solve_question('', '', ''))

        self.student.quizzes.append(self.quiz)

        # wrong quiz id
        self.assertFalse(self.student.solve_question('', '', ''))
        self.assertFalse(solve.called)

        # correct quiz id
        self.assertTrue(
            self.student.solve_question(self.quiz.id, 'question_id',
                                        'solution'))
        solve.assert_called_with(self.quiz, 'question_id', 'solution')

    @patch('classes.Quiz.get_grade', autospec=True)
    def test_get_total_grade(self, get_grade):
        # no quizzes
        get_grade.return_value = 10
        self.assertEqual(0, self.student.get_total_grade())
        self.student.quizzes.append(self.quiz)
        self.assertEqual(10, self.student.get_total_grade())
    def generate_students(self):
        """
        Generate students, giving a level of ability in each subject
        """
        student = Student()
        self.students = student.generate_students()

        print('\033[44m' + '***********STUDENTS*************' + '\033[0m')
        pprint(self.students)
示例#4
0
 def load_students(self):
     students = []
     with self.connection.cursor() as cur:
         cur.execute(
             "select concat(ucase(surname), ' ', givenname) as name, level, prioritized_list from students"
         )
         index = 0
         for row in cur:
             student = Student(index, row['name'].strip(),
                               row['prioritized_list'].strip())
             student.level = row['level'].strip()
             students.append(student)
             index += 1
     return students
示例#5
0
 def ld_students(cls, file_name):
     """Загрузка данных об учащихся"""
     with codecs.open(file_name, encoding='utf-8') as fl:
         data = fl.readlines()
     for student in data:
         full_name, birthday = student.strip().split(';')
         student = Student(full_name, birthday)
         cls.lst_students.append(student)
示例#6
0
 def load_students(self):
     students = []
     lines = default_read_and_filter_csv('students.txt')
     index = 0
     for line in lines:
         students.append(
             Student(index, line['name'].strip(),
                     line['prioritized_list'].strip()))
         index += 1
     return students
示例#7
0
def sudents_page():
    if request.method == 'POST':
        new_student_id = request.form.get('student_id', "")
        new_student_name= request.form.get('name', '')
        new_student_last_name= request.form.get('last-name', '')

        new_student = Student(name=new_student_name, student_id = new_student_id)
        students.append(new_student)

        return redirect(url_for('student_page'))
    return render_template('index.html', students=students)
示例#8
0
    def test_assign_quiz_to_student(self):
        self.student = Student(name='ramadan')
        self.quiz1 = Quiz()
        self.quiz2 = Quiz()

        self.assertEqual([], self.student.quizzes)

        Teacher.assign_quiz_to_student(self.student, self.quiz1)
        self.assertEqual([self.quiz1], self.student.quizzes)

        Teacher.assign_quiz_to_student(self.student, self.quiz2)
        self.assertEqual([self.quiz1, self.quiz2], self.student.quizzes)
示例#9
0
    def download_list(self):
        """
        Devuelve una lista de Student con todos los estudiantes en el servidor
        """

        students = []
        #############
        estudiantes = requests.get(
            "http://assistance-py.herokuapp.com/students")
        for i in estudiantes.json()["students"]:
            students.append(
                Student(i["name"], i["username"], i["assistance"], i["id"]))

        return students
示例#10
0
    def download_list(self):
        """
        Devuelve una lista de Student con todos los estudiantes en el servidor
        """

        # Solucion ------------------------------------------------------------
        students = []
        request = requests.get(url="{}/students".format(self.url))
        for dic in request.json()['students']:
            students.append(
                Student(id=dic['id'],
                        name=dic['name'],
                        username=dic['username'],
                        assistance=dic['assistance']))
        # -----------------------------------------------------------------------

        return students
示例#11
0
def initial_frame(img):
    """initializes student object

    Args:
       img: first image in directory

    Returns:
        list of student objects

    """
    student_list = []
    faces = find_faces(img)
    for i in range(len(faces)):
        student_list.append(Student(faces[i], str(i)))

    for student in student_list:
        get_pose_direction(student, img)
        get_angle(student)
    return student_list
示例#12
0
def signUp():
    if request.method == "POST":
        form_name = request.form["fname"]
        form_surname = request.form["lname"]
        form_id = request.form["ownid"]
        form_email = request.form["Email"]
        form_password = hasher.hash(request.form["password"])
        form_person = request.form["person"]
        db = current_app.config["db"]
        if request.form["password"] != request.form[
                "confirm_password"]:  #for error
            password_error = "Passwords not matching! Try Again"
            return render_template('signup.html',
                                   password_error=password_error)

        if db.check_exists_student_id(form_id) or db.check_exists_teacher_id(
                form_id):  #for error
            error = "The ID exists! Try Again"
            return render_template('signup.html', error=error)

        if db.check_exists_student_email(
                form_email) or db.check_exists_teacher_email(
                    form_email):  #for error
            error = "The email has already used!"
            return render_template('signup.html', error=error)

        if form_person == "teacher":
            teacher = Teacher(form_id, form_name, form_surname, form_email,
                              form_password)
            teacher_key = db.add_teacher(teacher)
            return redirect(url_for("successful", teacher_key=teacher_key))

        elif form_person == "student":
            student = Student(form_id, form_name, form_surname, form_email,
                              form_password)
            student_key = db.add_student(student)
            return redirect(url_for("successful", student_key=student_key))
        else:
            return "person is not chosen!"
    else:
        return render_template('signup.html')
示例#13
0
def create_student():
    """
    Function to create a student
    """
    name = input('Name of new student: \n').title()
    course = input('Which course is taking: \n').title()
    working = input('Is this student working? (y/n) \n').lower()

    if working == 'y':
        job = input("What's his job: \n")
        try:
            pay = int(input("Yearly Payment: \n"))
            working_st = Working_student(name, course, job, pay)
            students.append(working_st)
            return print(f'\nStudent added!')
        except ValueError:
            return print(value_error_message)

    new_student = Student(name, course)
    students.append(new_student)
    return print(f'\nStudent added!')
示例#14
0
def find_new_students(student_list, next_frame, index):
    """looks for new students and appends them to student_list

    Args:
       student_list: list of objects
       next_frame: next image
       index: the index of the frame

    Returns:
        student_list

    """
    faces = find_faces(next_frame)
    for face in faces:

        found = False
        top_left = face['keypoints']['left_eye']
        bottom_right = face['keypoints']['mouth_right']
        box = utils.extend_box(top_left, bottom_right, 50)

        for student in student_list:
            test_point = student.face_points['nose']

            # img = next_frame.copy()
            # cv2.circle(img, test_point,1,(0,0,255),2)
            # cv2.rectangle(img, box[0], box[1], (255,255,0),1)
            # utils.show_image(img)

            if utils.point_in_box(box, test_point):
                found = True
                break

        if not found:
            max_name = max([int(x.name) + 1 for x in student_list])
            attention_list = [random.randint(1, 359) for i in range(index + 1)]
            student_list.append(Student(face, max_name))
            student_list[-1].attention_angle_list = attention_list
示例#15
0
def get_mentees(sheetname="CovEd student form (New)"):
    mentees = []

    #variables containing the headings of columns in google forms.
    name_head = 'Full Name:'
    email_head = 'Email Address'
    grade_head = "What is your age group? (Repeaters in any particular stream please select the 11-12 option in the corresponding stream)"
    foreignuniv_head = "Some mentors have experience with College Applications for foreign universities (like essays and other stuff). Do you require some help with that? (Please select yes only if you are really considering applying to a foreign university soon)"
    subjects_head = "What subjects do you specifically need help with?"
    extracurricular_head = "Would you be interested in receiving extra curricular support from your mentor (Answer the next question only if your response to this question is Yes):"
    feedback_head = "If you are filling this form for the second time and have already been assigned a mentor, are you happy with the mentor assigned to you?"
    emotype_head = "Please select all the box pertaining to the area that you need support with with (once again please be considerate and only select something if you genuinely need help with it):"
    gender_head = "What is your gender? (Note that we are providing this facility only in the case of students requiring emotional support as some issues can be sensitive. For general academic help this option will not be taken into account)"
    assigned_mentor_head = "Mentor"

    #fetch data from sheet
    records, mentee_sheet = get_data_from_sheet(sheetname)

    row_no = 1

    for row in records:
        row_no += 1
        #For some cases, the values do not match what is given in the dictionary.
        try:

            if row[assigned_mentor_head].replace(' ', '') == '':
                assigned_mentor = None
            else:
                assigned_mentor = row[assigned_mentor_head]

            feedback = classes_model.feedback[row[feedback_head]]

            ## Appending only the unassigned students to save time
            if assigned_mentor != None and feedback != 2:
                continue

            if feedback == 1 or feedback == 4:
                continue

            name = row[name_head]
            email = row[email_head]
            classes = classes_model.class_ids[row[grade_head]]
            foreignuniv = classes_model.bool_dict[
                row[foreignuniv_head] if row[foreignuniv_head] != '' else
                'No']  #some entries were blank in forms.
            subjects = row[subjects_head].split(
                ",")  #Assumed list in assignmentor
            extracurricular = classes_model.bool_dict[
                row[extracurricular_head]]
            if extracurricular:
                emotype = [
                    classes_model.emotype[y.strip()]
                    for y in row[emotype_head].split(",")
                ]  #split- assignmentor assumes list. strip- google forms appends whitespaces which can be difficult to keep in account
                if 0 not in emotype:
                    emotype.append(0)
            else:
                emotype = [0]

            # print("Student", extracurricular, emotype)

            try:  #Made like this because some people have not filled gender even after saying Yes to support
                gender = classes_model.gender[row[gender_head]]
            except:
                gender = None

            #Initialise mentee object
            student_object = Student(name,
                                     email,
                                     classes,
                                     foreignuniv,
                                     subjects,
                                     extracurricular,
                                     emotype=emotype,
                                     gender=gender,
                                     feedback_type=feedback,
                                     assigned_mentor=assigned_mentor,
                                     row_no=row_no)
            mentees.append(student_object)

        except:
            print("Some Error Occured : Student")
            print(row[name_head], row[email_head])
            print("\n#############################################\n")
            continue

    return mentees, mentee_sheet
示例#16
0
def students_subroutine(student_list):
    """
    Subroutine for working with student list.
    """
    while True:
        pretty.print_bar(PROGRAM_WIDTH)
        print(
            "What would you like to do? (type either option number or [keyword])"
        )
        pretty.print_options("[View] students", "[Add] student",
                             "[Remove] student", "[Update] student info",
                             "[Return]")
        inp = input().lower()

        if inp == "1" or inp == "view":
            start = end = None
            start_inp = input(
                "First letter to start at? (Leave blank to start at beginning)\n"
            )
            if start_inp and valid.is_letter(start_inp):
                start = start_inp
            else:
                start = "a"
            end_inp = input(
                "First letter to end at? (Leave blank to go until end)\n")
            if end_inp and valid.is_letter(end_inp):
                end = end_inp
            else:
                end = "z"
            print()
            pretty.print_bar(PROGRAM_WIDTH)
            try:
                student_list.print_table(start, end)
            except ValueError as e:
                print(e)
            print()
            input("Press enter to return.")

        elif inp == "2" or inp == "add":
            # Add new student to student list.
            # Basic flow: ask for all arguments in a try/except block listening
            # for KeyboardInterrupts. If any are raised, exit add subroutine
            # and continue looping. Otherwise, create a new Student with given
            # parameters and add to students list. Report success.
            print("Press CTRL+C at any time to cancel.")
            args = []
            try:
                # Got all of the arguments at once in a list and then just expanded them
                # into the parameters for new Student. Less readable, but more compact.
                args.append(input("First name?\n").strip(' '))
                args.append(input("Last name?\n").strip(' '))
                args.append(input("Phone number?\n"))
                args.append(input("Email address?\n"))
                args.append(input("Class or subject?\n"))
                args.append(input("Notes?\n"))
            except KeyboardInterrupt:
                pass
            else:
                pretty.print_bar(PROGRAM_WIDTH, ALERT_SYM)
                student_list.add(Student(*args))
                print("Student {0} added successfully.".format(args[0] + " " +
                                                               args[1]))
                save(student_list, transaction_record=None)

        elif inp == "3" or inp == "remove":
            # Remove student by name from student list.
            # Basic flow: Ask for name of student to remove in try/except block
            # listening for KeyboardInterrupts. If any are raised, exit remove
            # subroutine and continue looping. Else use StudentList method to
            # remove student with given name and report success or failure
            # (returned by method).
            print("Press CTRL+C at any time to cancel.")
            try:
                name = input("Full name of student to remove?\n")
            except KeyboardInterrupt:
                pass
            else:
                pretty.print_bar(PROGRAM_WIDTH, ALERT_SYM)
                removed = student_list.remove(name)
                if removed:
                    print("Student {0} removed successfully.".format(name))
                    save(student_list, transaction_record=None)
                else:
                    print("Student {0} not found (check spelling?).".format(
                        name))

        elif inp == "4" or inp == "update":
            # Update student info in student list.
            # Basic flow: Ask for name of student to update in try/except block
            # listening for KeyboardInterrupts. If any are raised, exit remove
            # subroutine and continue looping. Else use StudentList method to
            # update student with given name. Ask for field and new value to update
            # to. Report success or failure (returned by method). Student field
            # updates have no type checking for values.
            print("Press CTRL+C at any time to cancel.")
            try:
                name = input("Full name of student to update?\n")
                print("Field to update? (type by [keyword])")
                pretty.print_options("[First] name", "[Last] name",
                                     "[Phone] number", "[Email] address",
                                     "[Subject] or class", "[Notes]")
                field = input().lower()
                newval = input("New value of field?\n")
            except KeyboardInterrupt:
                pass
            else:
                pretty.print_bar(PROGRAM_WIDTH, ALERT_SYM)
                #  This works because update method returns True or False for successful update or not.
                updated = student_list.update(name, field, newval)
                if updated:
                    #  A little magic in format to make update to field "first" or "last" show as "first name" or "last name."
                    print(
                        "Student {0} {1} successfully updated to {2}.".format(
                            name, field + ("name" if field == "first"
                                           or name == "last" else ""), newval))
                    save(student_list, transaction_record=None)
                else:
                    print(
                        "Student {0} or field {1} not found (check spelling?)."
                        .format(name, field))

        elif inp == "5" or inp == "return":
            # Finishes method and returns to place in main() stack loop.
            return
        else:
            pass
示例#17
0
    "Lecturer": [["lecture", "phone number", "profession", "password"]],
    "Coordinator": [["coordinator", "phone number", "password"]]
}

"Database of questions using dictionary"


def add_user(obj: Student or Lecturer or Coordinator):
    if type(obj) == Student:
        user_list["Student"].append((obj.get_name(), obj.get_password()))
    elif type(obj) == Lecturer:
        user_list.update({
            "Lecturer": [obj.name, obj.phone_number, obj.topic, obj.password]
        })
    else:
        user_list.update(
            {"Coordinator": [obj.name, obj.phoneNumber, obj.password]})


def del_user(string: str):
    for lec in user_list["Lecturer"]:
        if lec == user_list["Lecturer"][0]:
            user_list["Lecturer"].pop(0)


stu = Student("eliran", "123")
add_user(stu)
print(user_list["Student"])
del_user("full name")
print(user_list["Lecturer"])
示例#18
0
from classes import HighSchoolStudent, Student

jess = Student("Jessica", "Monteiro")
print(jess)
示例#19
0
from classes import Student

student1 = Student("Vipin", "B.tech", 3.0, False)
student2 = Student("Savi", "MBA", 5.0, True)
print(student1.name + " is honor:" + str(student1.on_honor_roll()))
print(student2.name + " is honor:" + str(student2.on_honor_roll()))


示例#20
0
from classes import Student

student1 = Student("Jim", "Computer science", 3.5, False)
student2 = Student("Kim", "Arts", 2.5, True)
print(student1.gpa)

print(student2.on_honor_rol())
示例#21
0
def student():
    return Student("bruce")
示例#22
0
Методы:
    create_homework - текст задания и количество дней на это задание,
    возвращает экземпляр Homework
    Обратите внимание, что для работы этого метода не требуется сам объект.

PEP8 соблюдать строго, проверку делаю автотестами и просмотром кода.
Всем перечисленным выше атрибутам и методам классов сохранить названия.
К названием остальных переменных, классов и тд. подходить ответственно -
давать логичные подходящие имена.
"""

from classes import Student, Teacher

if __name__ == '__main__':
    teacher = Teacher('Daniil', 'Shadrin')
    student = Student('Roman', 'Petrov')
    teacher.last_name  # Shadrin
    student.first_name  # Roman

    expired_homework = teacher.create_homework('Learn functions', 0)
    expired_homework.created  # Example: 2019-05-26 16:44:30.688762
    expired_homework.deadline  # 0:00:00
    expired_homework.text  # 'Learn functions'

    # create function from method and use it
    create_homework_too = teacher.create_homework
    oop_homework = create_homework_too('create 2 simple classes', 5)
    oop_homework.deadline  # 5 days, 0:00:00

    student.do_homework(oop_homework)
    student.do_homework(expired_homework)  # You are late
示例#23
0
def create_students_from_input(file, config):
	'''
		There is a check for how many columns are in the student data input file.
		If the data does not have all of the following information, this function
		will fail.
		Currently assumes:
			- 1 column for ID
			- 1 column for degree_pursuing
			- 1 column for business_ability
			- 1 column for coding_ability
			- 1 column for work experience
			- classes.number_project_rankings columns for project rankings
			- 1 column for first name
			- 1 column for last name
                        - 1 column for a binary field (fill with 0 if not needed)
	'''
	try:
		data = pd.read_csv(file)
		data_array = np.array(data)
		shape = data_array.shape
		num_rows = shape[0]

		students_lst = []
                configParser = ConfigParser.ConfigParser()
                configParser.read(config)
                use_binary_raw = configParser.getboolean("valid_values", "use_binary")
                if use_binary_raw == True:
                        use_binary = 1
                else :
                        use_binary = 0
		# Extract rows and create students
		for i in range(0, num_rows):
			student = data_array[i,:]
			if (not(len(student) == classes.number_project_rankings + 7 + use_binary)):
				error = "Row " + str(i) + " in " + str(file) + " does not have"
				error += "the number of fields required by the config file."
				raise InputError(error)

			ID 	= student[0]
			if (ID in student_ids):
				raise CompError("Student IDs must be unique.")
			student_ids.append(ID)
			 
			degree_pursuing = student[1]
			business_ability = student[2]
			coding_ability = student[3]
			num_yrs_work_exp = student[4]

			# Only take the desired number of project rankings that we want.
			rankings = student[5:(5 + classes.number_project_rankings)]
			first_name = student[5 + classes.number_project_rankings]
			last_name = student[5 + classes.number_project_rankings + 1]
                        name = first_name + " " + last_name
			a = Student(name, ID, degree_pursuing, business_ability, coding_ability, 
				num_yrs_work_exp, rankings)
                        if (use_binary_raw):
                                bin_field = student[5 + classes.number_project_rankings + 2]
                                a.set_bin_field(bin_field)
			students_lst.append(a)

		return students_lst

	except(IOError):
		if (len(file) == 0):
			error = "Please enter a valid filename."
			raise InputError(error)
		else:
			error = "Error with reading the file for student data."
			raise InputError(error)
示例#24
0
 def setUp(self):
     self.student = Student(name='ramadan')
     self.quiz = Quiz()
示例#25
0
from classes import Teacher, Student, Course

compsci = Course("Computer Science 101", "CS101")
maria = Student("Maria", "Martinez")
joe = Student("Joe", "Smith")
ashven = Student("Ashven", "Matthew")

imani = Teacher("Imani", "Matthews")

compsci.add([maria, joe, ashven])
compsci.set_teacher(imani)

print(compsci.teacher, compsci.students)

joe.addgrade(compsci, 80)
joe.addgrade(compsci, 89)
joe.addgrade(compsci, 100)

print()
print("GPA for {} is {:.2f}.".format(joe, joe.gpa_for(compsci)))
示例#26
0
from functions import *
from classes import Employee, Student

a()
b()
c()

e1 = Employee(101, "Payal", 22, 1000000, "CEO")
e1.display()

s1 = Student(11, "ranu", 12)
s1.display()
示例#27
0
def self_vs_instructor_repeater(repeaters, course):
    self_paced_run = course.self_paced_run
    index_of_self_paced = course.semester_names.index(self_paced_run)
    test_in = Cohort()
    test_out = Cohort()
    test = Cohort()
    control = Cohort()

    retook_dic = defaultdict(list)

    for userid in repeaters.get_keys():
        student = repeaters.get(userid)
        if repeaters.get_num_semesters(userid) >= 2:
            if student.is_in_semester(self_paced_run):
                # add to test_in
                entity = student.get(self_paced_run)
                new_student = Student(student.userid)
                new_student.add(self_paced_run, entity)
                test_in.add(userid, new_student)
                # add to test_out
                new_student = student.deep_copy()
                # print(new_student.get_keys())
                test.add(userid, new_student)
                new_student.delete(self_paced_run)
                test_out.add(userid, new_student)
            else:
                control.add(userid, student.deep_copy())

            for sem_name in student.get_keys():
                if course.is_first_or_last_semester(sem_name):
                    continue
                retook_dic[sem_name].append(
                    0 if sem_name ==
                    student.get_last_semester(course.semester_names) else 1)

    print()
    print('REPEATERS WHO DIDNT TAKE SELF-PACED:')
    print('completion % overall: ', control.get_completion_rate())
    print('average grade overall: ', control.get_average('overall', True))
    print('average grade overall: ', control.get_average('overall_1', True))
    print('ever completed:', control.get_ever_completed_rate())

    print()
    print('REPEATERS IN SELF-PACED DURING SELF-PACED SEM:')
    print('completion % overall: ', test_in.get_completion_rate())
    print('average grade overall: ', test_in.get_average('overall', True))
    print('average grade overall: ', test_in.get_average('overall_1', True))
    print('ever completed:', test_in.get_ever_completed_rate())

    print()
    print('REPEATERS IN SELF-PACED DURING INSTRUCTOR-LED SEM:')
    print('completion % overall: ', test_out.get_completion_rate())
    print('average grade overall: ', test_out.get_average('overall', True))
    print('average grade overall: ', test_out.get_average('overall_1', True))
    print('ever completed:', test_out.get_ever_completed_rate())

    print()
    print('RETAKING COURSE')
    ls = []
    for key in retook_dic:
        if key == self_paced_run:
            print("self paced", statistics.mean(retook_dic[key]))
        else:
            ls.append(statistics.mean(retook_dic[key]))
    print("instructor ", statistics.mean(ls))

    x = [0, 1, 2, 4, 5]
    x_labels = [
        'ever', 'self\n\n\nGroup A', 'instuctor', 'ever', '\n\n\nGroup B',
        'instuctor'
    ]
    y = [
        test.get_ever_completed_rate(),
        test_in.get_completion_rate(),
        test_out.get_completion_rate(),
        control.get_ever_completed_rate(),
        control.get_completion_rate()
    ]
    plt.bar(x, y, align='center')
    plt.ylabel('% of learners who complete', fontsize=12)
    plt.xticks([0, 1, 2, 4, 4.5, 5], x_labels, fontsize=12)
    plt.savefig("anything" + ("1x" if course.is_1x else "2x") + ".png",
                bbox_inches='tight')
    plt.clf()
示例#28
0
from classes import Student

student = Student(input("How many questions?"), input("What difficultly do you want?"))
if "easy" in student.get_level():
    student.easy_test()
elif "medium" in student.get_level():
    student.medium_test()
elif "hard" in student.get_level():
    student.hard_test()
示例#29
0
#Create instances of cohorts
cohort_37 = Cohort("Cohort 37")
cohort_38 = Cohort("Cohort 38")
cohort_39 = Cohort("Cohort 39")

#Create Instances of instructors
instructor_andy = Instructor("Andy", "Collins", "*****@*****.**", cohort_38,
                             "JavaScript")
instructor_jisie = Instructor("Jisie", "David", "*****@*****.**", cohort_38,
                              "Python")
instructor_steve = Instructor("Steve", "Brownlee", "*****@*****.**",
                              cohort_37, "JavaScript")

#Create instances of students
student_matt = Student("Matt", "Crook", "*****@*****.**", cohort_38)
student_mike = Student("Mike", "Pence", "*****@*****.**", cohort_38)
student_kub = Student("Kub", "Docker", "*****@*****.**", cohort_38)
student_sara = Student("Sara", "Vue", "*****@*****.**", cohort_37)
student_bruce = Student("Bruce", "Brown", "*****@*****.**", cohort_39)

# Have the instructors assign an exercise to a student
instructor_andy.add_exercise(student_matt, list_exercise)
instructor_jisie.add_exercise(student_bruce, interface_exercise)
instructor_steve.add_exercise(student_kub, function_currying)
instructor_andy.add_exercise(student_mike, multiple_inheritance_exercise)
instructor_jisie.add_exercise(student_sara, classes_exercise)
instructor_andy.add_exercise(student_matt, classes_exercise)

# Create a list of students. Add all of the student instances to it.
students = list()
示例#30
0
文件: answer.py 项目: neskoc/oopython
# attribute "courses_grades".
# Create the method **average_grade**. Calculate and return the students
# average grade. Ignore grades with "-" in the calculation.
#
# Create a new instance of the class Student. Initiate it with the name
# `Zimba` and ssn `516518-3442`.
# Use the add_course_grade method to add the following courses, `htmlphp`
# with grade `2`, `design` with grade `-` and `linux` with grade `5`.
#
#
# Answer with the Student object's "average_grade" method.
#
# Write your code below and put the answer into the variable ANSWER.
#

student = Student("Zimba", "516518-3442")
student.add_course_grade("html", 2)
student.add_course_grade("design", "-")
student.add_course_grade("linux", 5)

ANSWER = student.average_grade()

# I will now test your answer - change false to true to get a hint.
dbwebb.assert_equal("1.4", ANSWER, False)

# """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
# Exercise 1.5 (1 points)
#
# In Teacher, create the *classmethod* **from_json**. This shall take one
# argument, `filename`.
# The *filename* is a json -file that contains data to create and return a
示例#31
0
 def import_students_from_json(self) -> typing.Iterable[Student]:
     with open(self.students_path, 'r') as students_file:
         for student in json.load(students_file):
             yield Student(**student)