Esempio n. 1
0
def view_Booking_Page():
    bookings = root.child('bookings').get()
    list = []  #store booking objects
    for typeid in bookings:

        eachbooking = bookings[typeid]

        if eachbooking['type'] == 'idoctor':
            doctor = Doctor(eachbooking['name'], eachbooking['age'],
                            eachbooking['phoneNumber'], eachbooking['email'],
                            eachbooking['startingDateAndTime'],
                            eachbooking['type'],
                            eachbooking['specialization1'])
            doctor.set_typeid(typeid)
            print(doctor.get_typeid())
            list.append(doctor)
        elif eachbooking['type'] == 'iinstructor':
            instructor = Instructor(eachbooking['name'], eachbooking['age'],
                                    eachbooking['phoneNumber'],
                                    eachbooking['email'],
                                    eachbooking['startingDateAndTime'],
                                    eachbooking['type'],
                                    eachbooking['specialization2'])
            instructor.set_typeid(typeid)
            print(instructor.get_typeid())
            list.append(instructor)
        else:
            flash("You have no appointments.")
    return render_template('viewBookingPage.html', bookings=list)
Esempio n. 2
0
def instructor_cp():
    user = current_user
    username = user.get_id()
    instructor = Instructor(username)
    course_data = instructor.show_courses(
    )  # Can use this to show course data for instructor
    #student_list = instructor.show_students('cid1')
    #assignment_list = instructor.show_assignments('cid1')
    #ta_list = instructor.show_tas('cid1')
    #resource_list = instructor.show_resources('cid1')
    # submission_list = instructor.show_submissions('cid1')
    return render_template('instructor_cp.html',
                           user=user,
                           course_data=course_data)
Esempio n. 3
0
 def load_instructors(self, file):
     '''Load the instructors data from the specified file.'''
     try:
         for i in line_values(file, 3, "\t"):
             self._instructors[i[0]] = Instructor(i[0], i[1], i[2])
     except FileNotFoundError:
         print("Error: Instructors file {} was not found.".format(file))
Esempio n. 4
0
def signin():
    studentid = 1000
    in1 = input(
        " select your status 1-student  2-instructor  3-esducation secretary ")
    name = input("enter your name : ")

    lastname = input("enter your last name: ")
    fathersname = input("enter your fathersname")
    username = input("enter your user name: ")
    password = input("enter your password:"******"1":
        studentid += 1
        print("your studentid is: " + str(studentid))
        student = Student(name, lastname, fathersname, username, password,
                          studentid)
        members.append(student)

    if in1 == "2":
        instructor = Instructor(name, lastname, fathersname, username,
                                password)
        members.append(instructor)

    if in1 == "3":
        educationsecretary = Educationsecretary(name, lastname, fathersname,
                                                username, password)
        members.append(educationsecretary)
Esempio n. 5
0
def remove_submission():
    # URL requested will look like /control/instructor_cp/modify_course/?cid=some-value
    course_id = request.args.get('cid')
    id = request.args.get('id')
    assign_id = request.args.get('assign_id')
    assign_id = int(assign_id)
    user = current_user
    username = user.get_id()
    instructor = Instructor(username)
    course_data = instructor.get_course_data(course_id)
    sub_list = instructor.show_submissions(course_id)
    sub_ids = []
    for sub in sub_list:
        sub_ids.append(sub[3])

    student_list = instructor.show_students(course_id)
    student_ids = []
    for student in student_list:
        student_ids.append(student[0])

    if sub_ids.__contains__(assign_id) and student_ids.__contains__(id):
        instructor.remove_submission(id, assign_id, course_id)
        return redirect(url_for('instructor_cp'))
    else:
        return redirect(url_for('instructor_cp'))
    return render_template('instructor_cp.html',
                           user=user,
                           course_data=course_data)
Esempio n. 6
0
def edit_grade():
    # URL requested will look like /control/instructor_cp/modify_course/?cid=some-value
    course_id = request.args.get('cid')
    id = request.args.get('id')
    assign_id = request.args.get('assign_id')
    file_path = request.args.get('file_path')
    user = current_user
    username = user.get_id()
    instructor = Instructor(username)

    if request.method == 'POST':
        grade = request.form['grade']
        if grade > 0:
            instructor.grade_submission(id, assign_id, file_path, grade,
                                        course_id)
            return redirect(url_for('instructor_cp'))
        else:
            return redirect(url_for('instructor_cp'))
    return render_template('instr_edit_grade.html')
Esempio n. 7
0
def enroll_ta():
    # URL requested will look like /control/instructor_cp/modify_course/?cid=some-value
    course_id = request.args.get('cid')
    user = current_user
    username = user.get_id()
    instructor = Instructor(username)

    user2 = current_user
    username2 = user2.get_id()
    admin = Admin(username2)

    course_data = instructor.get_course_data(course_id)
    ta_list = instructor.show_tas(course_id)
    ta_ids = []
    for ta in ta_list:
        ta_ids.append(ta[0])

    user_list = admin.show_all_users()
    user_ids = []
    for use in user_list:
        user_ids.append(use[0])

    if request.method == 'POST':
        taID = request.form['taID']
        if taID not in ta_ids and len(taID) < 7 and taID in user_ids:
            instructor.enroll_ta_in_course(taID, course_id)
            return redirect(url_for('instructor_cp'))
        else:
            return redirect(url_for('instructor_cp'))
    return render_template('instr_enroll_ta.html')
Esempio n. 8
0
 def setUp(self):
     i = Instructor(1)
     squad = Squadron()
     stud = Student(2, squad)
     q = Qual('C-172')
     stud.quals.append(q)
     e = Event(1)
     r = Rule('onwing')
     e.rules.append(r)
     ss = StudentSortie()
     ss.student = stud
     ss.event = e
     sor = Sortie()
     sor.studentSorties.append(ss)
     sor.instructor = i
     return sor
Esempio n. 9
0
def read_instructors(path):
    '''
    this reads instructors.txt with help of file_reader() from HW0802.py
    '''
    instructor_list = list()
    try:
        for file in os.listdir(path):
            if os.path.isfile(os.path.join(path, file)):
                if file == "instructors.txt" :
                    completepath=os.path.join(path+"\\"+file)
                    for value in file_reader(completepath, num_fields=3, sep='\t', header=False):
                        instructor_list.append(Instructor(value[0],value[1],value[2]))
    except Exception as e: 
        print(f"Exception while reading instructors data : {e}")
        return list()    
    return instructor_list
Esempio n. 10
0
 def test_instructor(self):
     '''Test the Instructor class'''
     i1 = Instructor()
     self.assertEqual(i1._cwid, '')
     self.assertEqual(i1._name, '')
     self.assertEqual(i1._department, '')
     self.assertEqual(i1._courses, {})
     i2 = Instructor('123456', 'Martin, Marty', 'MATH')
     i2.increment_student_count('SSW-540')
     i2.increment_student_count('SSW-555')
     i2.increment_student_count('SSW-555')
     self.assertEqual(i2._cwid, '123456')
     self.assertEqual(i2._name, 'Martin, Marty')
     self.assertEqual(i2._department, 'MATH')
     self.assertEqual(i2._courses, {'SSW-540':1, 'SSW-555':2})
Esempio n. 11
0
 def crewrest_pairs(self, day, resource_type):
     pairs = []
     if resource_type == "Student":
         s = Student(id="Sample", squadron=self)
     elif resource_type == "Instructor":
         s = Instructor(id="Sample")
     else:
         s = Flyer(id="Sample")
     for wave1 in self.schedules[day].waves.values():
         rest = Sniv()
         rest.begin = wave1.times[resource_type].end
         rest.end = rest.begin + s.crewRest()
         s.snivs[0] = rest
         if day + 1 in self.schedules:
             for wave2 in self.schedules[day + 1].waves.values():
                 if not s.available(self.schedules[day + 1].day, wave2):
                     pairs.append((wave1, wave2))
     return pairs
Esempio n. 12
0
 def generateCrewrestExclusion(self,day1,day2,resourceType):
     w={}
     if resourceType=="Student":
         s=Student("Sample",self)
     elif resourceType=="Instructor":
         s=Instructor("Sample")
     else:
         s=Flyer("Sample")
     for w1 in self.schedules[day1].waves:
         w[w1]=[]
         wave1=self.schedules[day1].waves[w1]
         rest=Sniv()
         rest.begin = wave1.times[resourceType].end
         rest.end = rest.begin + s.crewRest
         s.snivs[0]=rest
         for w2 in self.schedules[day2].waves:
             wave2=self.schedules[day2].waves[w2]
             if not s.available(self.schedules[day2].date,wave2):
                 w[w1].append(w2)
     return w
Esempio n. 13
0
def modify_course():
    # URL requested will look like /control/instructor_cp/modify_course/?cid=some-value
    course_id = request.args.get('cid')
    user = current_user
    username = user.get_id()
    instructor = Instructor(username)
    course_data = instructor.get_course_data(course_id)
    student_list = instructor.show_students(course_id)
    ta_list = instructor.show_tas(course_id)
    assignment_list = instructor.show_assignments(course_id)
    resource_list = instructor.show_resources(course_id)
    submission_list = instructor.show_submissions(course_id)

    if course_id is not None:
        return render_template('instr_view_course.html',
                               user=user,
                               course_id=course_id,
                               course_data=course_data,
                               student_list=student_list,
                               ta_list=ta_list,
                               assignment_list=assignment_list,
                               resource_list=resource_list,
                               submission_list=submission_list)
    return 'Error: No query string.'
Esempio n. 14
0
def add_resource():
    # URL requested will look like /control/instructor_cp/modify_course/?cid=some-value
    course_id = request.args.get('cid')
    user = current_user
    username = user.get_id()
    instructor = Instructor(username)
    course_data = instructor.get_course_data(course_id)
    res_list = instructor.show_resources(course_id)
    res_ids = []
    for res in res_list:
        res_ids.append(res[0])

    if request.method == 'POST':
        resName = request.form['resName']
        filepath = request.form['filepath']
        if resName not in res_ids:
            instructor.create_resource(course_id, resName, filepath)
            return redirect(url_for('instructor_cp'))
        else:
            return redirect(url_for('instructor_cp'))
    return render_template('instr_add_resource.html')
Esempio n. 15
0
def add_assignment():
    # URL requested will look like /control/instructor_cp/modify_course/?cid=some-value
    course_id = request.args.get('cid')
    user = current_user
    username = user.get_id()
    instructor = Instructor(username)
    course_data = instructor.get_course_data(course_id)
    assign_list = instructor.show_assignments(course_id)
    assign_ids = []
    for assign in assign_list:
        assign_ids.append(assign[0])

    if request.method == 'POST':
        assignID = request.form['assignID']
        filepath = request.form['filepath']
        if assignID not in assign_ids:
            instructor.create_assignment(assignID, course_id, filepath)
            return redirect(url_for('instructor_cp'))
        else:
            return redirect(url_for('instructor_cp'))
    return render_template('instr_add_assignment.html')
Esempio n. 16
0
def unenroll_ta():
    # URL requested will look like /control/instructor_cp/modify_course/?cid=some-value
    course_id = request.args.get('cid')
    ta_id = request.args.get('id')
    user = current_user
    username = user.get_id()
    instructor = Instructor(username)
    course_data = instructor.get_course_data(course_id)
    ta_list = instructor.show_tas(course_id)
    ta_ids = []
    for ta in ta_list:
        ta_ids.append(ta[0])

    if ta_id in ta_ids:
        instructor.unenroll_ta_in_course(ta_id, course_id)
        return redirect(url_for('instructor_cp'))
    else:
        return redirect(url_for('instructor_cp'))
    return render_template('instructor_cp.html',
                           user=user,
                           course_data=course_data)
Esempio n. 17
0
def load(vtna, config):

    con = mdb.connect(host=config['host'],
                      port=config['port'],
                      user=config['user'],
                      passwd=config['password'],
                      db=config['database'])
    with con:
        # cur = con.cursor()
        # cur = con.cursor(dictionary=True)
        cur = con.cursor(mdb.cursors.DictCursor)
        days = config['days']
        if days > 3:
            vtna.calculateMaintenance = True

        # Loop over schedule table where not published and flight_day != NULL and add schedules for each flight_day
        # Ought to sort by date and not pull past schedules - day >= date.today()!
        query = "SELECT * FROM schedule WHERE published = FALSE ORDER BY day ASC LIMIT %d" % days
        cur.execute(query)  # AND NOT flight_day = NULL
        i = 1
        rows = cur.fetchall()  # .fetchmany(size=days)

        for row in rows:
            sked = Schedule(row)
            sked.flyDay = i
            # Set priority
            sked.priority = i**(-0.5)  # priorities[i]
            if verbose:
                print 'Computing schedule for schedule ID %d, flight day %d, day %s, with priority %s' % (
                    sked.id, sked.flyDay, sked.day, sked.priority)
            vtna.schedules[i] = sked
            i += 1

        vtna.days = len(rows)

        #Find waves
        cur.execute("SELECT * FROM wave")
        rows = cur.fetchall()
        waves = {}
        for row in rows:
            waves[int(row["wave_ID"])] = row

        #Create waves for each schedule
        for d in vtna.schedules:
            sked = vtna.schedules[d]
            if not sked.blank:
                sked.waves = {}  # %(emp_no)s"
                # cursor.execute(select_stmt, { 'emp_no': 2 })
                cur.execute(
                    "SELECT * FROM schedule_wave WHERE schedule_ID = %(schedule_ID)s",
                    {'schedule_ID': sked.id})
                rows = cur.fetchall()
                createWaves(sked, rows, waves)
        if verbose:
            print "Waves loaded"

        #Create events for squadron
        cur.execute("SELECT * FROM event")
        rows = cur.fetchall()
        for row in rows:
            i = int(row["event_ID"])
            e = Event(event_ID=i)
            if row["check_instructor_req"]:
                e.check = True
            if row["onwing_req"]:
                e.onwing = True
            elif row["not_onwing_req"]:
                e.offwing = True
            e.flightHours = float(row["dual_flight_hours"]) + float(
                row["solo_flight_hours"])
            e.planeHours = float(row["ground_plane_hours"])
            total_inst = float(
                row["ground_nonplane_hours"]) + e.planeHours + e.flightHours
            e.instructionalHours = total_inst
            e.syllabus = int(row["syllabus_ID"])
            e.max_students = int(row["max_students"])
            if row["follows_immediately"] != None and int(
                    row["follows_immediately"]) == 1:
                e.followsImmediately = True
            vtna.syllabus[i] = e

            #Set event precedence and following
        cur.execute("SELECT * FROM event_precedence")
        rows = cur.fetchall()
        for row in rows:
            i = int(row["following_event_ID"])
            j = int(row["preceding_event_ID"])
            if verbose:
                print i, ' follows ', j
            vtna.syllabus[i].precedingEvents.add(vtna.syllabus[j])
            vtna.syllabus[j].followingEvents.add(vtna.syllabus[i])
        if verbose:
            print "Events loaded"

        #Loop over planes
        cur.execute("SELECT * FROM plane WHERE active=TRUE")
        rows = cur.fetchall()
        for row in rows:
            # if verbose:
            #   print row["tail_number"],row["plane_type_ID"],row["max_cargo"]
            p = row["tail_number"]
            plane = Plane(id=p)
            plane.planetype = row["plane_type_ID"]
            ni = None
            tach = None
            if row["next_inspection"] != None:
                ni = float(row["next_inspection"])
            if row["tach"] != None:
                tach = float(row["tach"])
            if ni != None and tach != None and ni >= tach:
                plane.hours = ni - tach
            if ni != None and tach != None and ni < tach:
                plane.hours = 0.0
            if (row["max_cargo"] != 0 and row["max_cargo"] != None):
                plane.maxWeight = row["max_cargo"]
            if row["priority"] != None:
                plane.priority = row["priority"]
            vtna.planes[p] = plane

            #Add plane types

        #Add plane availability
        cur.execute(
            "SELECT * FROM plane_unavail WHERE (end >= %s and start <= %s)",
            (vtna.schedules[1].day.strftime('%Y-%m-%d'),
             (vtna.schedules[vtna.days].day +
              timedelta(days=1)).strftime('%Y-%m-%d')))
        rows = cur.fetchall()
        i = 1
        for row in rows:
            p = row["plane_tail_number"]
            #if verbose: print p,row["start"],row["end"]
            if p in vtna.planes:
                plane = vtna.planes[p]
                s = Sniv()
                s.begin = row["start"]
                s.end = row["end"]
                plane.snivs[i] = s
                i = i + 1
        if verbose:
            print "Planes loaded"

        #Loop over instructors, adding them
        cur.execute("SELECT * FROM cfi WHERE active = TRUE")
        rows = cur.fetchall()
        for row in rows:
            c = int(row["CFI_ID"])
            if verbose:
                print c
            inst = Instructor(id=c)
            inst.max_events = row["max_events"]
            if row["C990"]:
                inst.check = True
            if row["paid"]:
                inst.paid = 1

            vtna.instructors[c] = inst
        if verbose:
            print "Instructors loaded"

        #Loop over students, adding them
        cur.execute("SELECT * FROM student WHERE status = 'active'")
        rows = cur.fetchall()
        for row in rows:
            s = int(row["student_ID"])
            if verbose:
                print 'Student id ', s
            stud = Student(id=s, squadron=vtna)
            stud.crewRestHours = 12
            # stud.crewRest = timedelta(hours=12)
            stud.syllabus = int(row["syllabus_ID"])
            if row["priority"] is not None:
                stud.priority = float(row["priority"])
            if row["last_flight"] is not None:
                stud.last_flight = row["last_flight"]
            cfi = row["onwing_CFI_ID"]
            if cfi in vtna.instructors:
                #if verbose: print "Add instructor",cfi
                stud.onwing = vtna.instructors[cfi]
            elif cfi != None:
                print 'CFI %d onwing for student %d not in instructors!' % (
                    cfi, s)
            else:
                print 'no cfi for student %d' % (s)
            vtna.students[s] = stud
            # print vtna.students[s].__dict__
            partner_ID = row["partner_student_ID"]
            if partner_ID in vtna.students:
                #if verbose: print "Add partners",s,partner_ID
                stud.partner = vtna.students[partner_ID]
                vtna.students[partner_ID].partner = stud
        if verbose:
            print "Students loaded"

        #Add weight for students & CFIs
        cur.execute("SELECT * FROM user")
        rows = cur.fetchall()
        for row in rows:
            id = row["user_ID"]
            if row["weight"] != None:
                if id in vtna.students:
                    vtna.students[id].weight = int(row["weight"])
                elif id in vtna.instructors:
                    vtna.instructors[id].weight = int(row["weight"])
        if verbose:
            print "Weights loaded"

        #Add plane quals for students & CFIs
        cur.execute("SELECT * FROM plane_quals")
        rows = cur.fetchall()
        for row in rows:
            id = row["user_ID"]
            if id in vtna.students:
                vtna.students[id].quals.append(row["plane_type_ID"])
            elif id in vtna.instructors:
                vtna.instructors[id].quals.append(row["plane_type_ID"])
        if verbose:
            print "Quals loaded"

        #Add snivs for students & CFIs
        cur.execute(
            "SELECT * FROM sniv WHERE (end >= %s and start <= %s and approval=TRUE)",
            (vtna.schedules[1].day.strftime('%Y-%m-%d'),
             (vtna.schedules[vtna.days].day +
              timedelta(days=1)).strftime('%Y-%m-%d')))
        rows = cur.fetchall()
        i = 1
        for row in rows:
            id = row["user_ID"]
            if verbose:
                print id, row["start"], row["end"]
            s = Sniv(row)
            if id in vtna.students:
                vtna.students[id].snivs[i] = s
                i += 1
            elif id in vtna.instructors:
                vtna.instructors[id].snivs[i] = s
                i += 1

        if verbose:
            print "Snivs loaded"

        #Load most recent published schedule as schedule.today()
        cur.execute(
            "SELECT * FROM schedule WHERE published=TRUE ORDER BY day DESC LIMIT 1"
        )
        row = cur.fetchone()
        vtna.today.id = int(row["schedule_ID"])
        vtna.today.day = row["day"]
        midnight = datetime.combine(vtna.today.day, time(0))
        query = "SELECT * FROM schedule_wave WHERE schedule_ID = %d" % vtna.today.id
        cur.execute(query)
        rows = cur.fetchall()
        createWaves(vtna.today, rows, waves)
        query = "SELECT * FROM sortie WHERE schedule_ID = %s" % vtna.today.id
        cur.execute(query)
        rows = cur.fetchall()
        for row in rows:
            s = Sortie()
            id = int(row["sortie_ID"])
            if verbose:
                print id, row["CFI_ID"]
            s.brief = row["brief"]
            cfi_id = int(row["CFI_ID"])
            if cfi_id in vtna.instructors and row["wave_ID"] != None:
                s.instructor = vtna.instructors[cfi_id]  #Instructor
                s.studentSorties = []
                s.takeoff = row["scheduled_takeoff"]
                s.land = row["scheduled_land"]
                if row["wave_ID"] in vtna.today.waves:
                    s.wave = vtna.today.waves[int(
                        row["wave_ID"])]  #Wave ojbect
                vtna.today.sorties[id] = s

        #Create sorties and studentSorties from the entries in those table corresponding to the most recent published sked
        cur.execute(
            "SELECT * FROM student_sortie WHERE (status = 'pass' OR status = 'marginal' OR status = 'scheduled')"
        )
        rows = cur.fetchall()
        for row in rows:
            if row["student_ID"] != None:
                s = int(row["student_ID"])
                if s in vtna.students:
                    stud = vtna.students[s]
                    event = vtna.syllabus[int(row["event_ID"])]
                    if row["status"] == "scheduled":
                        stud.scheduledEvents.add(event)
                    else:
                        stud.completedEvents.add(event)
                    if row["sortie_ID"] in vtna.today.sorties:
                        sortie = vtna.today.sorties[row["sortie_ID"]]
                        ss = StudentSortie()
                        ss.student = vtna.students[s]
                        ss.event = event
                        if row["plane_tail_number"] in vtna.planes:
                            sortie.plane = vtna.planes[
                                row["plane_tail_number"]]
                        sortie.studentSorties.append(ss)
                        if vtna.today.day == (vtna.schedules[1].day -
                                              timedelta(days=1)):
                            #print "happy dance", stud.id, sortie.wave.id
                            takeoff = row["actual_takeoff"]
                            if not takeoff:
                                takeoff = midnight + sortie.takeoff
                            land = row["actual_land"]
                            if not land:
                                land = midnight + sortie.land
                            sniv = Sniv()
                            sniv.begin = takeoff
                            sniv.end = land + timedelta(
                                hours=event.debrief_hours) + stud.crewRest()
                            stud.snivs[0] = sniv
                            instructor_sniv = Sniv()
                            instructor_sniv.begin = takeoff
                            instructor_sniv.end = land + timedelta(
                                hours=event.debrief_hours
                            ) + sortie.instructor.crewRest()
                            sortie.instructor.snivs['crewrest' + str(
                                row['student_sortie_ID'])] = instructor_sniv
            p = row["plane_tail_number"]
            if row["status"] == 'scheduled' and p in vtna.planes and row[
                    "sked_flight_hours"] != None:
                if (vtna.planes[p].hours -
                        float(row["sked_flight_hours"])) >= 0:
                    vtna.planes[p].hours -= float(row["sked_flight_hours"])
                else:
                    vtna.planes[p].hours = 0.0
        """for s in vtna.students:
            stud = vtna.students[s]
            print 'Student: ', stud.id
            if stud.findPossible(1,True):
                print 'Next event: ', stud.getNextEvent()
            for event in stud.findPossible(1,True):
                if verbose:
                    print 'student ', s, 'possible event ', event.id"""

        #Loop over instructor preferences
        cur.execute(
            "SELECT * FROM instructor_preference LEFT JOIN cfi ON instructor_preference.cfi_CFI_ID = cfi.CFI_ID WHERE cfi.active = TRUE"
        )
        rows = cur.fetchall()
        for row in rows:
            c = int(row["cfi_CFI_ID"])
            pref = row["preference"]
            inst = vtna.instructors[c]
            begin = row["start"]
            end = row["end"]
            for d, sked in vtna.schedules.iteritems():
                midnight = datetime.combine(sked.day, time(0))
                start_time = midnight + begin
                end_time = midnight + end
                s = Sniv()
                s.begin = start_time
                s.end = end_time
                r = Instructor(id='sample')
                r.snivs[0] = s
                for w, wave in sked.waves.iteritems():
                    if not r.available(sked.day, wave):
                        inst.setPreference(d, w, pref)
                        if verbose:
                            print "Set preference for instructor %d, day %d, wave %d for value %d" % (
                                c, d, w, pref)
Esempio n. 18
0
 def instructor_setup(self, squadron, count):
     for i in range(-count, 0):
         squadron.instructors[i] = Instructor(i)
         squadron.instructors[i].quals.append(Qual('C-172'))
Esempio n. 19
0
def AddInstructor(self, args):
    s = Instructor()
    s.idx = len(self.instructors)
    if "infoName" in args:
        s.infoName = args["infoName"]
    if "subjectAssign" in args:
        s.subjectAssign = args["subjectAssign"]
    if "subjectEnroll" in args:
        s.subjectEnroll = args["subjectEnroll"]
    if "timeImpossible" in args:
        s.timeImpossible = args["timeImpossible"]
    if "timePrefer1st" in args:
        s.timePrefer1st = args["timePrefer1st"]
    if "timePrefer2nd" in args:
        s.timePrefer2nd = args["timePrefer2nd"]
    if "timePrefer3rd" in args:
        s.timePrefer3rd = args["timePrefer3rd"]
    s.parent = self
    self.instructors.append(s)
Esempio n. 20
0
def update_bookings(id):
    form = bookingPage(request.form)
    if request.method == 'POST' and form.validate():
        if form.type.data == "idoctor":
            name = form.name.data
            age = form.age.data
            phoneNumber = form.phoneNumber.data
            email = form.email.data
            specialization1 = form.specialization1.data
            startingDateAndTime = form.startingDateAndTime.data
            type = form.type.data

            doctor = Doctor(name, age, phoneNumber, email, startingDateAndTime,
                            type, specialization1)

            book_db = root.child('bookings/' + id)

            book_db.set({
                'name': doctor.get_name(),
                'age': doctor.get_age(),
                'phoneNumber': doctor.get_phoneNumber(),
                'email': doctor.get_email(),
                'startingDateAndTime': doctor.get_startingDateAndTime(),
                'type': doctor.get_type(),
                'specialization1': doctor.get_specialization1(),
            })

            flash("Your appointment has been rescheduled", 'success')

        elif form.type.data == "iinstructor":
            name = form.name.data
            age = form.age.data
            phoneNumber = form.phoneNumber.data
            email = form.email.data
            specialization2 = form.specialization2.data
            startingDateAndTime = form.startingDateAndTime.data
            type = form.type.data

            instructor = Instructor(name, age, phoneNumber, email,
                                    startingDateAndTime, type, specialization2)

            book_db = root.child('bookings/' + id)

            book_db.set({
                'name':
                instructor.get_name(),
                'age':
                instructor.get_age(),
                'phoneNumber':
                instructor.get_phoneNumber(),
                'email':
                instructor.get_email(),
                'startingDateAndTime':
                instructor.get_startingDateAndTime(),
                'type':
                instructor.get_type(),
                'specialization2':
                instructor.get_specialization2(),
            })

            flash('Your appointment has been rescheduled.', 'success')

        return redirect(url_for('view_Booking_Page'))
    else:
        url = 'bookings/' + id
        eachbook = root.child(url).get()

        if eachbook['type'] == 'idoctor':
            doctor = Doctor(eachbook['name'], eachbook['age'],
                            eachbook['phoneNumber'], eachbook['email'],
                            eachbook['startingDateAndTime'], eachbook['type'],
                            eachbook['specialization1'])
            doctor.set_typeid(id)
            form.name.data = doctor.get_name()
            form.age.data = doctor.get_age()
            form.phoneNumber.data = doctor.get_phoneNumber()
            form.email.data = doctor.get_email()
            form.specialization1.data = doctor.get_specialization1()
            form.startingDateAndTime.data = doctor.get_startingDateAndTime()
            form.type.data = doctor.get_type()

        else:
            instructor = Instructor(eachbook['name'], eachbook['age'],
                                    eachbook['phoneNumber'], eachbook['email'],
                                    eachbook['startingDateAndTime'],
                                    eachbook['type'],
                                    eachbook['specialization2'])
            instructor.set_typeid(id)
            form.name.data = instructor.get_name()
            form.age.data = instructor.get_age()
            form.phoneNumber.data = instructor.get_phoneNumber()
            form.email.data = instructor.get_email()
            form.specialization2.data = instructor.get_specialization2()
            form.startingDateAndTime.data = instructor.get_startingDateAndTime(
            )
            form.type.data = instructor.get_type()
        return render_template('updateBookingPage.html', form=form)
Esempio n. 21
0
# instructor,course,matrix lecture*course wi element hours array in array
from Course import Course
from Instructor import Instructor
from department import Department

instructors_hours = {'ahmed':{"network": 2, "electronics": 6, "selected": 4},'mohamed': {"operating_system": 2, "database2": 6, "selected": 4},'ali': {"operating_system": 4, "network": 4, "ethics": 4}}
instructor_names=['ahmed','ali','mohamed']
instructors_hours_empty = {'ahmed':{"network": 0, "electronics": 0, "selected": 0},'mohamed': {"operating_system": 0, "database2": 0, "selected": 0},'ali': {"operating_system": 0, "network": 0, "ethics": 0}}
ahmed = Instructor(0, "ahmed", instructors_hours.get("ahmed"))
mohamed = Instructor(1, "mohamed", instructors_hours.get("mohamed"))
ali = Instructor(2, "ali", instructors_hours.get("ali"))
network = Course(0, "network")
electronics = Course(1, "electronics")
database2 = Course(2, "database2")
ethics = Course(3, "ethics")
selected = Course(4, "selected")
operating_system = Course(5, "operating_system")

network.set_instructors(ahmed)
electronics.set_instructors(ahmed)
selected.set_instructors(ahmed)
operating_system.set_instructors(mohamed)
database2.set_instructors(mohamed)
selected.set_instructors(mohamed)
operating_system.set_instructors(ali)
network.set_instructors(ali)
ethics.set_instructors(ali)

sum_hours=sum(instructors_hours.get('ahmed').values())+sum(instructors_hours.get('mohamed').values())+sum(instructors_hours.get('ali').values())

Esempio n. 22
0
def main():
    config = {}
    execfile(sys.argv[1], config)
    with open(sys.argv[2]) as csvfile:
        reader = csv.DictReader(csvfile)
        con = mysql.connector.connect(host=config['host'],
                                      port=config['port'],
                                      user=config['user'],
                                      passwd=config['password'],
                                      db=config['database'])
        cur = con.cursor(dictionary=True)
        print '4'
        for crow in reader:
            print(crow['first_name'], crow['last_name'])
            #  Look for instructor in user db, return instructor_ID
            cur.execute("SELECT user_ID FROM user WHERE last_name = %(last_name)s "
                        "AND (middle_name = %(middle_name)s OR middle_name IS NULL) "
                        "AND first_name = %(first_name)s "
                        "AND title = %(title)s "
                        "LIMIT 1", crow)
            row = cur.fetchone()
            print row
            if row is None:
                #  Create resource entries
                cur.execute("INSERT INTO resource(`created_at`, `type`, `airfield_ID`) VALUES "
                            "(NOW(),'user',4)")
                instructor_ID = cur.lastrowid
            else:
                instructor_ID = row['user_ID']

            print instructor_ID
            instructor = Instructor(instructor_ID=instructor_ID)
            # Enter user information
            cur.execute("SELECT count(1) FROM user WHERE user_ID = %(id)s;", {'id': instructor_ID})
            row = cur.fetchone()
            if row['count(1)'] == 0:
                crow['id'] = instructor_ID
                cur.execute("INSERT INTO user(user_ID, last_name, first_name, middle_name, title, role) VALUES ("
                            "%(id)s, %(last_name)s, %(first_name)s, %(middle_name)s, %(title)s, 'instructor')", crow)

            # Enter instructor information
            cur.execute("SELECT count(1) FROM instructor WHERE instructor_ID = %(id)s;", {'id': instructor_ID})
            row = cur.fetchone()
            if row['count(1)'] == 0:
                cur.execute("INSERT INTO instructor(instructor_ID, active) VALUES (%(id)s, 1)", {'id': instructor_ID})

            # Associate instructor with VT-35
            cur.execute("SELECT count(1) FROM hierarchy WHERE child = %(id)s LIMIT 1;", {'id': instructor_ID})
            row = cur.fetchone()
            if row['count(1)'] == 0:
                cur.execute("INSERT INTO hierarchy(parent, child) VALUES (5, %(id)s)", {'id': instructor_ID})

            # Insert resource_tags

            cur.execute("SELECT count(1) FROM resource_tag WHERE resource_ID = %(id)s LIMIT 1;", {'id': instructor_ID})
            row = cur.fetchone()
            if row['count(1)'] == 0:
                cur.execute("""INSERT INTO resource_tag(resource_ID, tag_ID) VALUES (%(id)s, 1), (%(id)s, 3),
(%(id)s, 4), (%(id)s, 5), (%(id)s, 7),  (%(id)s, 8), (%(id)s, 10)""", {'id': instructor_ID})

        con.commit()
        con.close()
Esempio n. 23
0
File: main.py Progetto: DiazzzU/ATT
courses.append([])
while len(s) > 0:
    s = s.split(', ')
    s[len(s) - 1] = s[len(s) - 1][:-1]
    courseName = s[0][0:s[0].find('{') - 1]
    sessionName = s[0][s[0].find('{') + 1:s[0].find('}')]
    groups = s[2].split('/')

    for x in groups:
        if x not in allGroups:
            allGroups.append(x)

    A = findInstructor(s[1])
    if A == None:
        A = Instructor(instructorIDS, s[1])
        instructorIDS = instructorIDS + 1
        instructors.append(A)

    C = findCourse(courseName, 0)
    if C == None:
        C = Course(courseIDS, courseName, "core")
        courseIDS = courseIDS + 1
        courses[0].append(C)

    session = Session(sessionIDS, sessionName, C, A.id)
    sessionIDS = sessionIDS + 1

    A.addSession(session)
    C.addSession(session)
Esempio n. 24
0
imgaug.seed(RANDOM_SEED)
torch.manual_seed(RANDOM_SEED)
torch.cuda.manual_seed_all(RANDOM_SEED)
np.random.seed(RANDOM_SEED)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False

if __name__ == '__main__':
    # timestamp = "20201205-030029"
    timestamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
    model_name = "Resnet50-BS32-BigLR-MoreFC-Dropout-Noised-WeightedLoss-Epoch50-Version-27"
    model_name = timestamp + '-' + model_name
    use_model = 'cbam_resnet'  # 'svm' or 'resnet' or 'cbam_resnet'

    from Instructor import Instructor
    instructor = Instructor(model_name, args)
    if use_model == 'svm':
        instructor.trainAutoEncoder()
        instructor.generateAutoEncoderTestResultSamples(sample_cnt=20)
        instructor.trainSVM(load=False)
        instructor.genTestResult(from_svm=True)
    elif use_model == 'cbam_resnet':
        from run_cbam_resnet import run_cbam_resnet, genTestResult
        cbam_resnet_ckpt_path = run_cbam_resnet(args.CBAM_CONFIG_PATH)
        # cbam_resnet_ckpt_path = "saved/checkpoints/cbam_resnet50__n_2020Dec15_01.31"
        genTestResult(args.CBAM_CONFIG_PATH, cbam_resnet_ckpt_path, args=args)
    elif use_model == 'resnet':
        instructor.trainResnet()
        instructor.loadResnet(epoch=args.epochs)
        instructor.genTestResult(from_svm=False)
Esempio n. 25
0
parser.add_argument('--eps', default=EPS, type=float)
parser.add_argument('--epoch', default=EPOCH, type=int)
parser.add_argument('--batch_size', default=BATCH_SIZE, type=int)
parser.add_argument('--num_workers', default=NUM_WORKERS, type=int)
parser.add_argument('--disp_period', default=DISP_PERIOD, type=int)
parser.add_argument('--max_norm', default=MAX_NORM, type=float)
parser.add_argument('--cumul_batch', default=CUMUL_BATCH, type=int)
parser.add_argument('--warmup_rate', default=WARMUP_RATE, type=int)

args = parser.parse_args()

args.DATA_PATH = DATA_PATH
args.RAW_PATH = RAW_PATH
args.CKPT_PATH = CKPT_PATH
args.LOG_PATH = LOG_PATH

args.DEVICE = torch.device(
    'cuda:0' if args.cuda and torch.cuda.is_available() else 'cpu')
torch.cuda.set_device(args.DEVICE)

random.seed(RANDOM_SEED)
np.random.seed(RANDOM_SEED)

if __name__ == '__main__':
    # timestamp = "20201225-171648"
    timestamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
    model_name = timestamp + '-' + "RoBERTa-large-Cumulbatch-Alldata-Warmup-Batchlarger-MoreEpoch"
    instructor = Instructor(model_name, args)
    instructor.trainModel(use_all=True)
    instructor.testModel(load_pretrain=True, epoch=args.epoch)
Esempio n. 26
0
def load(vtna, config):

    con = mdb.connect(host=config['host'],
                      port=config['port'],
                      user=config['user'],
                      passwd=config['password'],
                      db=config['db'])
    with con:
        cur = con.cursor()
        cur.execute("SELECT VERSION()")

        ver = cur.fetchone()

        if verbose:
            print "Database version : %s " % ver

        cur = con.cursor(mdb.cursors.DictCursor)

        #Loop over schedule table where not published and flight_day != NULL and add schedules for each flight_day
        cur.execute("SELECT * FROM schedule WHERE (published = FALSE)"
                    )  # AND NOT flight_day = NULL
        rows = cur.fetchall()

        i = 1
        priorities = {}
        priorities[1] = 1.0
        priorities[2] = 0.5
        priorities[3] = 0.3
        priorities[4] = 0.2
        priorities[5] = 0.2
        priorities[6] = 0.2
        priorities[7] = 0.2

        days = config['days']
        for row in rows:
            if i <= days:
                #i = int(row["flight_day"])
                day = row["day"]
                sked = Schedule(day)
                sked.flyDay = i
                sked.id = int(row["schedule_ID"])

                #Set priority
                """if row["priority"]!=None:
                    sked.priority = float(row["priority"])"""
                sked.priority = priorities[i]
                if verbose:
                    print 'Computing schedule for schedule ID %d, flight day %d, day %s, with priority %s ' % (
                        sked.id, sked.flyDay, day, sked.priority)
                vtna.schedules[i] = sked
                i = i + 1
        vtna.totalFlightDays = days

        #Find waves
        cur.execute("SELECT * FROM wave")
        rows = cur.fetchall()
        waves = {}
        for row in rows:
            waves[int(row["wave_ID"])] = row

        #Create waves for each schedule. Having no waves makes the schedule blank.
        for d in vtna.schedules:
            sked = vtna.schedules[d]
            sked.waves = {}
            cur.execute("SELECT * FROM schedule_wave WHERE schedule_ID = %s",
                        (sked.id))
            rows = cur.fetchall()
            createWaves(sked, rows, waves)
        if verbose:
            print "Waves loaded"

        #Create events for squadron
        cur.execute("SELECT * FROM event")
        rows = cur.fetchall()
        for row in rows:
            i = int(row["event_ID"])
            e = Event(i)
            if row["check_instructor_req"]:
                e.check = True
            if row["onwing_req"]:
                e.onwing = True
            elif row["not_onwing_req"]:
                e.offwing = True
            e.flightHours = float(row["dual_flight_hours"]) + float(
                row["solo_flight_hours"])
            e.planeHours = float(row["ground_plane_hours"])
            total_inst = float(
                row["ground_nonplane_hours"]) + e.planeHours + e.flightHours
            e.instructionalHours = total_inst
            e.syllabus = int(row["syllabus_ID"])
            e.maxStudents = int(row["max_students"])
            if row["follows_immediately"]:
                e.followsImmediately = True
            vtna.syllabus[i] = e

            #Set event precedence and following
        cur.execute("SELECT * FROM event_precedence")
        rows = cur.fetchall()
        for row in rows:
            i = int(row["following_event_ID"])
            j = int(row["preceding_event_ID"])
            if verbose:
                print i, ' follows ', j
            vtna.syllabus[i].precedingEvents.add(vtna.syllabus[j])
            vtna.syllabus[j].followingEvents.add(vtna.syllabus[i])
        if verbose:
            print "Events loaded"

        #Loop over planes
        cur.execute("SELECT * FROM plane WHERE active=TRUE")
        rows = cur.fetchall()
        for row in rows:
            #if verbose: print row["tail_number"],row["plane_type_ID"],row["max_cargo"]
            p = row["tail_number"]
            plane = Plane(p)
            plane.planetype = row["plane_type_ID"]
            if row["next_inspection"] != None and row["tach"] != None:
                plane.hours = float(row["next_inspection"]) - float(
                    row["tach"])
            if (row["max_cargo"] != 0 and row["max_cargo"] != None):
                plane.maxWeight = row["max_cargo"]
            if row["priority"] != None:
                plane.priority = row["priority"]
            vtna.planes[p] = plane

            #Add plane types

        #Add plane availability
        cur.execute(
            "SELECT * FROM plane_unavail WHERE (end >= %s and start <= %s)",
            (vtna.schedules[1].date.strftime('%Y-%m-%d'),
             vtna.schedules[vtna.totalFlightDays].date.strftime('%Y-%m-%d')))
        rows = cur.fetchall()
        i = 1
        for row in rows:
            p = row["plane_tail_number"]
            #if verbose: print p,row["start"],row["end"]
            if p in vtna.planes:
                plane = vtna.planes[p]
                s = Sniv()
                s.begin = row["start"]
                s.end = row["end"]
                plane.snivs[i] = s
                i = i + 1
        if verbose:
            print "Planes loaded"

        #Loop over instructors, adding them
        cur.execute("SELECT * FROM cfi WHERE active = TRUE")
        rows = cur.fetchall()
        for row in rows:
            c = int(row["CFI_ID"])
            if verbose:
                print c
            inst = Instructor(c)
            inst.maxEvents = row["max_events"]
            if row["C990"]:
                inst.check = True
            vtna.instructors[c] = inst
        if verbose:
            print "Instructors loaded"

        #Loop over students, adding them
        cur.execute("SELECT * FROM student WHERE status = 'active'")
        rows = cur.fetchall()
        for row in rows:
            s = int(row["student_ID"])
            if verbose:
                print 'Student id ', s
            stud = Student(s, vtna)
            stud.syllabus = int(row["syllabus_ID"])
            if row["priority"] != None:
                stud.priority = float(row["priority"])
            cfi = row["onwing_CFI_ID"]
            if cfi in vtna.instructors:
                #if verbose: print "Add instructor",cfi
                stud.onwing = vtna.instructors[cfi]
            elif cfi != None:
                print 'CFI %d onwing for student %d not in instructors!' % (
                    cfi, s)
            else:
                print 'no cfi for student %d' % (s)
            vtna.students[s] = stud
            partner_ID = row["partner_student_ID"]
            if partner_ID in vtna.students:
                #if verbose: print "Add partners",s,partner_ID
                stud.partner = vtna.students[partner_ID]
                vtna.students[partner_ID].partner = stud
        if verbose:
            print "Students loaded"

        #Add weight for students & CFIs
        cur.execute("SELECT * FROM user")
        rows = cur.fetchall()
        for row in rows:
            id = row["user_ID"]
            if row["weight"] != None:
                if id in vtna.students:
                    vtna.students[id].weight = int(row["weight"])
                elif id in vtna.instructors:
                    vtna.instructors[id].weight = int(row["weight"])
        if verbose:
            print "Weights loaded"

        #Add plane quals for students & CFIs
        cur.execute("SELECT * FROM plane_quals")
        rows = cur.fetchall()
        for row in rows:
            id = row["user_ID"]
            if id in vtna.students:
                vtna.students[id].quals.append(row["plane_type_ID"])
            elif id in vtna.instructors:
                vtna.instructors[id].quals.append(row["plane_type_ID"])
        if verbose:
            print "Quals loaded"

        #Add snivs for students & CFIs
        cur.execute(
            "SELECT * FROM sniv WHERE (end >= %s and start <= %s and approval=TRUE)",
            (vtna.schedules[1].date.strftime('%Y-%m-%d'),
             vtna.schedules[vtna.totalFlightDays].date.strftime('%Y-%m-%d')))
        rows = cur.fetchall()
        i = 1
        for row in rows:
            id = row["user_ID"]
            if verbose:
                print id, row["start"], row["end"]
            if id in vtna.students:
                s = Sniv()
                s.begin = row["start"]
                s.end = row["end"]
                vtna.students[id].snivs[i] = s
                i = i + 1
            elif id in vtna.instructors:
                s = Sniv()
                s.begin = row["start"]
                s.end = row["end"]
                vtna.instructors[id].snivs[i] = s
                i = i + 1

        if verbose:
            print "Snivs loaded"

        #Load most recent published schedule as schedule.today()
        cur.execute(
            "SELECT * FROM schedule WHERE published=TRUE ORDER BY day DESC")
        row = cur.fetchone()
        vtna.today.id = int(row["schedule_ID"])
        vtna.today.date = row["day"]
        cur.execute("SELECT * FROM schedule_wave WHERE schedule_ID = %s",
                    (vtna.today.id))
        rows = cur.fetchall()
        createWaves(vtna.today, rows, waves)

        cur.execute("SELECT * FROM sortie WHERE schedule_ID = %s",
                    (vtna.today.id))
        rows = cur.fetchall()
        for row in rows:
            s = Sortie()
            id = int(row["sortie_ID"])
            if verbose:
                print id, row["CFI_ID"]
            s.brief = row["brief"]
            cfi_id = int(row["CFI_ID"])
            if cfi_id in vtna.instructors and row["wave_ID"] != None:
                s.instructor = vtna.instructors[cfi_id]  #Instructor
                s.studentSorties = []
                s.takeoff = row["scheduled_takeoff"]
                s.land = row["scheduled_land"]
                if row["wave_ID"] != None:
                    s.wave = vtna.today.waves[int(
                        row["wave_ID"])]  #Wave ojbect
                else:
                    s.wave = vtna.today.waves[
                        1]  #This is a bad hack. Ought to use a function to determine nearest wave in today's set of waves
                vtna.today.sorties[id] = s

        #Create sorties and studentSorties from the entries in those table corresponding to the most recent published sked
        cur.execute(
            "SELECT * FROM student_sortie WHERE (status = 'pass' OR status = 'marginal' OR status = 'scheduled')"
        )
        rows = cur.fetchall()
        for row in rows:
            if row["student_ID"] != None:
                s = int(row["student_ID"])
                if s in vtna.students:
                    stud = vtna.students[s]
                    event = vtna.syllabus[int(row["event_ID"])]
                    if row["status"] == "scheduled":
                        stud.scheduledEvents.add(event)
                    else:
                        stud.completedEvents.add(event)
                    if row["sortie_ID"] in vtna.today.sorties:
                        sortie = vtna.today.sorties[row["sortie_ID"]]
                        ss = StudentSortie()
                        ss.student = vtna.students[s]
                        ss.event = event
                        if row["plane_tail_number"] in vtna.planes:
                            sortie.plane = vtna.planes[
                                row["plane_tail_number"]]
                        sortie.studentSorties.append(ss)
                        if vtna.today.date == vtna.schedules[
                                1].date + timedelta(days=1):
                            sniv = Sniv()
                            sniv.begin = sortie.brief
                            sniv.end = sortie.wave.times[
                                "Flyer"].end + stud.crewRest
                            stud.snivs[0] = sniv
            p = row["plane_tail_number"]
            if row["status"] == 'scheduled' and p in vtna.planes and row[
                    "sked_flight_hours"] != None:
                vtna.planes[p].hours -= float(row["sked_flight_hours"])

        for s in vtna.students:
            stud = vtna.students[s]
            i = 1
            for event in stud.findPossible(1, True):
                if verbose:
                    print 'student ', s, 'possible event ', event.id
                if i == 1:
                    stud.nextEvent = event
                i = i + 1

        #Loop over instructor preferences
        cur.execute(
            "SELECT * FROM instructor_preference LEFT JOIN cfi ON instructor_preference.cfi_CFI_ID = cfi.CFI_ID WHERE cfi.active = TRUE"
        )
        rows = cur.fetchall()
        for row in rows:
            c = int(row["cfi_CFI_ID"])
            pref = row["preference"]
            inst = vtna.instructors[c]
            begin = row["start"]
            end = row["end"]
            for d, sked in vtna.schedules.iteritems():
                midnight = datetime.combine(sked.date, time(0))
                start_time = midnight + begin
                end_time = midnight + end
                s = Sniv()
                s.begin = start_time
                s.end = end_time
                r = Instructor(0)
                r.snivs[0] = s
                for w, wave in sked.waves.iteritems():
                    if not r.available(sked.date, wave):
                        inst.setPreference(d, w, pref)
                        if verbose:
                            print "Set preference for instructor %d, day %d, wave %d for value %d" % (
                                c, d, w, pref)
Esempio n. 27
0
def main():
    config = {}
    execfile(sys.argv[1], config)
    vt = TrainingSquadron(config)
    vtSqlScheduler.load(vt, config)

    #  Load csv
    with open(sys.argv[2]) as csvfile:
        reader = csv.DictReader(csvfile)
        con = mysql.connector.connect(host=config['host'],
                                      port=config['port'],
                                      user=config['user'],
                                      passwd=config['password'],
                                      db=config['database'])
        cur = con.cursor(dictionary=True)
        #  Create validation sortie
        s = Sortie(instructor=Instructor(instructor_ID=11))
        s.schedule_ID = 113
        s.takeoff = datetime.now()
        s.land = datetime.now()
        s.brief = datetime.now()
        s.wave = Wave(1)

        for crow in reader:
            progressing = set()
            print(crow['first_name'], crow['last_name'])
            #  Look for student in user db, return student_ID
            cur.execute(
                "SELECT user_ID FROM user WHERE last_name = %(last_name)s "
                "AND (middle_name = %(middle_name)s OR middle_name IS NULL) "
                "AND first_name = %(first_name)s "
                "AND title = %(title)s "
                "LIMIT 1", crow)
            row = cur.fetchone()
            if row is None:
                #  Create resource entries
                cur.execute(
                    "INSERT INTO resource(`created_at`, `type`, `airfield_ID`) VALUES "
                    "(NOW(),'user',4)")
                student_ID = cur.lastrowid
            else:
                student_ID = row['user_ID']

            student = Student(student_ID=student_ID)
            # Enter user information
            cur.execute("SELECT count(1) FROM user WHERE user_ID = %(id)s;",
                        {'id': student_ID})
            row = cur.fetchone()
            if row['count(1)'] == 0:
                crow['id'] = student_ID
                cur.execute(
                    "INSERT INTO user(user_ID, last_name, first_name, middle_name, title) VALUES ("
                    "%(id)s, %(last_name)s, %(first_name)s, %(middle_name)s, %(title)s)",
                    crow)

            # Enter student information
            cur.execute(
                "SELECT count(1) FROM student WHERE student_ID = %(id)s;",
                {'id': student_ID})
            row = cur.fetchone()
            if row['count(1)'] == 0:
                cur.execute(
                    "INSERT INTO student(student_ID, status, training_end_date) VALUES ("
                    "%(id)s, 'active', %(end)s)", {
                        'id': student_ID,
                        'end': crow['training_end_date']
                    })
                cur.execute(
                    "INSERT INTO student_syllabus(student_ID, syllabus_ID) "
                    "VALUES (%(id)s, %(syll)s)", {
                        'id': student_ID,
                        'syll': int(crow['syllabus_ID'])
                    })
                student_syllabus_ID = cur.lastrowid
            else:
                cur.execute(
                    "SELECT student_syllabus_ID FROM student_syllabus WHERE student_ID = %(id)s LIMIT 1;",
                    {'id': student_ID})
                row = cur.fetchone()
                student_syllabus_ID = row['student_syllabus_ID']
            student.student_syllabus_ID = student_syllabus_ID

            # Create class if not there
            cur.execute(
                "SELECT count(1), organization_ID FROM organization WHERE name = %(class_name)s LIMIT 1;",
                {'class_name': "Class " + crow['class']})
            row = cur.fetchone()
            if row['count(1)'] == 0:
                cur.execute(
                    "INSERT INTO resource(`created_at`, `type`, `airfield_ID`) VALUES "
                    "(NOW(),'organization',4)")
                class_ID = cur.lastrowid
                cur.execute(
                    """INSERT INTO organization(organization_ID, name, scheduling) VALUES
                (%(id)s, %(class_name)s, 0)""", {
                        'id': class_ID,
                        'class_name': "Class " + crow['class']
                    })
                cur.execute(
                    "INSERT INTO hierarchy(parent, child) VALUES (5, %(id)s)",
                    {'id': class_ID})
            else:
                class_ID = row['organization_ID']

            # Associate student with VT-35
            cur.execute(
                "SELECT count(1) FROM hierarchy WHERE child = %(id)s LIMIT 1;",
                {'id': student_ID})
            row = cur.fetchone()
            if row['count(1)'] == 0:
                cur.execute(
                    "INSERT INTO hierarchy(parent, child) VALUES (5, %(id)s)",
                    {'id': student_ID})

            # Insert resource_tags

            cur.execute(
                "SELECT count(1) FROM resource_tag WHERE resource_ID = %(id)s LIMIT 1;",
                {'id': student_ID})
            row = cur.fetchone()
            if row['count(1)'] == 0:
                cur.execute(
                    """INSERT INTO resource_tag(resource_ID, tag_ID) VALUES (%(id)s, 1),
                    (%(id)s, 2),
                    (%(id)s, 3),
                    (%(id)s, 4),
                    (%(id)s, 5),
                    (%(id)s, 7),
                    (%(id)s, 8),
                    (%(id)s, 9),
                    (%(id)s, 10)""", {'id': student_ID})
            """# Pull progressing events
            cur.execute("SELECT * FROM student_sortie "
                "LEFT JOIN student ON student.student_ID = student_sortie.student_ID "
                "LEFT JOIN hierarchy ON student.student_ID = child "
                "LEFT JOIN student_syllabus "
                "ON student_sortie.student_syllabus_ID = student_syllabus.student_syllabus_ID "
                "LEFT JOIN sortie ON sortie.sortie_ID = student_sortie.sortie_ID "
                "LEFT JOIN schedule ON schedule.schedule_ID = student_sortie.schedule_ID "
                "WHERE student.student_ID = %(id)s "
                "AND (hierarchy.stop > NOW() OR hierarchy.stop IS NULL) "
                "AND student_syllabus.outcome IS NULL AND student_sortie.progressing_event = 1 "
                "AND schedule.published = TRUE",
                {'id': student_ID})"""

            # Create student sorties for each ancestor event
            event = vt.events[int(crow['latest_event_ID'])]
            ss = StudentSortie()
            ss.student = student
            ss.event = event
            s.studentSorties.append(ss)
            for a, syllabus in vt.syllabus[int(
                    crow['syllabus_ID'])].ancestors(event):
                ss = StudentSortie()
                ss.student = student
                ss.event = a
                s.studentSorties.append(ss)
                print ss

            for i in range(1, 4):
                ss = StudentSortie()
                ss.student = Student(student_ID=student_ID)
                ss.event = vt.events[i]
                s.studentSorties.append(ss)
                print ss

        write(s, cur)
        con.commit()
        con.close()
Esempio n. 28
0
def load(vtna,importName):

    book = xlrd.open_workbook(importName)
    sh = book.sheet_by_name("Multi")

    #vtna = Squadron() #Create a squadron object to hold the data

    dates = [date(2015,3,27),date(2015,3,28),date(2015,3,29)] #Dates to write schedules for. Should be passed via sys.argv Assume unlisted gap dates are blank schedules.

    #Dealing with blank schedules needs more work. Schedules need to know if crew rests constraints apply from the previous day
    i=1
    for day in dates:
        sked=Schedule(day)
        sked.flyDay = i
        vtna.schedules[i]=sked
        i=i+1
    vtna.totalFlightDays = len(dates)

    #Creates the events in the syllabus. Would be replaced by call to data if necessary.
    for i in range(-3,11):
        e = Event(i)
        if i > -3:
            vtna.syllabus[i-1].followingEvents.add(e)
            e.precedingEvents.add(vtna.syllabus[i-1])
        if i>0:
            e.flightHours=1.0
            if i != 5 and i !=9:
                e.onwing=True
        vtna.syllabus[i]=e

    vtna.syllabus[5].offwing=True
    vtna.syllabus[9].offwing=True
    vtna.syllabus[9].check=True
    vtna.syllabus[10].followsImmediately=True
    #Could modify any schedule data for any day as necessary

    """days = range(1,numdays+1)
    events = range(-3,11)
    numwaves = int(sh.cell_value(0,1))
    waves = range(1,numwaves+1)
    maxstuds = int(sh.cell_value(3,1))
    maxweight = int(sh.cell_value(4,1))
    limitweight = int(sh.cell_value(5,2))
    dcoeff = {}
    wcoeff = {}
    icoeff = {}

    for d in days:
        dcoeff[d]=float(sh.cell_value(7+d,8))
    for w in waves:
        wcoeff[w]=float(sh.cell_value(7+w,5))
    #maxstuds = {}
    #i=8
    #for e in events:
    #    maxstuds[e] = int(sh.cell_value(i,2))
    #    i = i+1"""

    sh = book.sheet_by_name("pavail")
    """planes = []
    pavail = {}
    planetype = {}"""
    j=2
    while True:
            try:
                plane = sh.cell_value(j,0)
                plane = plane.encode('utf8')
                #planes.append(plane)
                p = Plane(plane)
                p.planetype = sh.cell_value(j,1).encode('utf8')
                vtna.planes[plane]=p
                j = j+1
            except IndexError:
                break

    print "Planes loaded"
    i=2
    for p in vtna.planes:
        plane = vtna.planes[p]
        d=0
        for day in vtna.schedules:
            plane._available[day]={}
            j=2
            for w in vtna.schedules[day].waves:
                wave = vtna.schedules[day].waves[w]
                if int(sh.cell_value(i,5*d+j)) == 1:
                    plane._available[day][wave]=True
                else:
                    plane._available[day][wave]=False
                j=j+1
            d=d+1
        i=i+1
                #pavail[planes[i],days[d],waves[j]]=int(sh.cell_value(i+2,5*d+j+2))
    print "Plane availability loaded"

    sh = book.sheet_by_name("inst")
    """insts = []
    imax = {}
    check = {}
    iweight = {}
    iqual = {}
    itype = {}"""
    i = 1
    while True:
        try:
            inst = sh.cell_value(i, 0)
            inst = inst.encode('utf8')
            #insts.append(inst)
            vtna.instructors[inst]=Instructor(inst)
            #imax[inst]= int(sh.cell_value(i,1))
            vtna.instructors[inst].maxEvents=int(sh.cell_value(i,1))
            #check[inst]=int(sh.cell_value(i,2))
            vtna.instructors[inst].check = int(sh.cell_value(i,2))
            #iweight[inst]=int(sh.cell_value(i,3))
            vtna.instructors[inst].weight = int(sh.cell_value(i,3))
            if (int(sh.cell_value(i,4))==1):
                vtna.instructors[inst].quals.append('C-172-N')
                vtna.instructors[inst].quals.append('C-172-SP')
                vtna.instructors[inst].quals.append('C-172')
            if (int(sh.cell_value(i,5))==1):
                vtna.instructors[inst].quals.append('PA-28')
            """
            itype[inst,'C-172-SP'] = int(sh.cell_value(i,4))
            itype[inst,'C-172-N'] = int(sh.cell_value(i,4))
            itype[inst,'PA-28'] = int(sh.cell_value(i,5))
            #pc = 4
            for p in planes:
                if itype[inst,planetype[p]]==1:
                    iqual[inst,p] = 1
                else:
                    iqual[inst,p] = 0
            #    pc = pc+1"""
            i = i + 1
        except IndexError:
            break

    print "Instructors loaded"
    sh = book.sheet_by_name("stud")
    """
    studs = []
    syll = {}
    sweight = {}
    squal = {}
    sprior = {}"""
    i = 1
    while True:
        try:
            stud = sh.cell_value(i,0)
            stud = stud.encode('utf8')
            #studs.append(stud)
            vtna.students[stud]=Student(stud,vtna)
            #syll[stud]=int(sh.cell_value(i,1))
            eventID = int(sh.cell_value(i,1))
            vtna.students[stud].syllabus = 1
            vtna.students[stud].nextEvent = vtna.syllabus[eventID]
            if eventID > -3:
                vtna.students[stud].scheduledEvents.add(vtna.syllabus[eventID-1])
            for x in range(-3,eventID-1):
                vtna.students[stud].completedEvents.add(vtna.syllabus[x])
            #sweight[stud]=int(sh.cell_value(i,2))
            vtna.students[stud].weight = int(sh.cell_value(i,2))
            vtna.students[stud].quals.append(sh.cell_value(i,3).encode('utf8'))
            """stype = sh.cell_value(i,3)
            stype = stype.encode('utf8')
            sprior[stud] = int(sh.cell_value(i,4))
            for p in planes:
                #print p
                if planetype[p]==stype:
                    squal[stud,p] = 1
                else:
                    squal[stud,p] = 0
            #    pc = pc+1"""
            i=i+1
        except IndexError:
            break

    print "Students loaded"

    """
    sh = book.sheet_by_name("iavail")
    iavail = {}
    for i in range(len(insts)):
        for d in range(len(days)):
            for w in range(len(waves)):
                iavail[insts[i],days[d],waves[w]] = int(sh.cell_value(i+2,5*d+w+1))



    sh = book.sheet_by_name("ipref")
    for i in range(len(insts)):
        for d in range(len(days)):
            for w in range(len(waves)):
                icoeff[insts[i],days[d],waves[w]] = int(sh.cell_value(i+2,5*d+w+1))

    sh = book.sheet_by_name("savail")
    savail = {}
    for s in range(len(studs)):
        for d in range(len(days)):
            for w in range(len(waves)):
                savail[studs[s], days[d], waves[w]]= int(sh.cell_value(s+2,5*d+w+1))


    stud1 = []
    onwingpair = {}
    onwinginst = {}
    """
    sh = book.sheet_by_name("onwing")
    i = 1
    while True:
        try:
            stud = sh.cell_value(i,0)
            stud=stud.encode('utf8')
            #stud1.append(stud)
            pair = sh.cell_value(i,1)
            pair = pair.encode('utf8')
            instructor = sh.cell_value(i,3).encode('utf8')
            #onwinginst[stud] = instructor
            #onwinginst[pair] = instructor
            vtna.students[stud].onwing = vtna.instructors[instructor]
            #onwingpair[stud]=pair
            if (pair != ''):
                vtna.students[stud].partner = vtna.students[pair]
                vtna.students[pair].partner = vtna.students[stud]
                vtna.students[pair].onwing = vtna.instructors[instructor]
            #t = sh.cell_value(i,2)
            #t = t.encode('utf8')
            #squal[stud]=t
            #squal[pair]=t
            i=i+1
        except IndexError:
            break

    #istart = []
    #sstart = []
    sh = book.sheet_by_name("start")
    i=0
    while True:
        try:
            wave = int(sh.cell_value(i,0))
            plane = sh.cell_value(i,4).encode('utf8')
            inst = sh.cell_value(i,6).encode('utf8')
            stud = sh.cell_value(i,7).encode('utf8')
            event = int(sh.cell_value(i,9))
            #istart.append((inst,plane,wave))
            #sstart.append((stud,plane,wave,event))
            vtna.students[stud].last['wave']=wave
            vtna.students[stud].last['plane']=plane
            vtna.instructors[inst].last['wave']=wave
            vtna.instructors[inst].last['plane']=plane
            s = Sortie()
            s.instructor = vtna.instructors[inst]
            s.plane = vtna.planes[plane] #Plane id
            s.wave = vtna.today.waves[wave] #Wave id
            ss = StudentSortie
            ss.student=vtna.students[stud]
            ss.event=event
            s.studentSorties.append(ss)
            vtna.today.sorties[i]=s
            i=i+1
        except IndexError:
            break

    print "Ending load"
    """
Esempio n. 29
0
def bookingpage():
    form = bookingPage(request.form)
    if request.method == 'POST' and form.validate():
        if form.type.data == "idoctor":
            name = form.name.data
            age = form.age.data
            phoneNumber = form.phoneNumber.data
            email = form.email.data
            specialization1 = form.specialization1.data
            startingDateAndTime = form.startingDateAndTime.data
            type = form.type.data

            doctor = Doctor(name, age, phoneNumber, email, startingDateAndTime,
                            type, specialization1)

            book_db = root.child('bookings')

            book_db.push({
                'name':
                doctor.get_name(),
                'age':
                doctor.get_age(),
                'phoneNumber':
                doctor.get_phoneNumber(),
                'email':
                doctor.get_email(),
                'startingDateAndTime':
                doctor.get_startingDateAndTime(),
                'type':
                doctor.get_type(),
                'specialization1':
                doctor.get_specialization1(),
            })
            flash("Your appointment is registered.", 'success')

        elif form.type.data == "iinstructor":
            name = form.name.data
            age = form.age.data
            phoneNumber = form.phoneNumber.data
            email = form.email.data
            specialization2 = form.specialization2.data
            startingDateAndTime = form.startingDateAndTime.data
            type = form.type.data

            instructor = Instructor(name, age, phoneNumber, email,
                                    startingDateAndTime, type, specialization2)

            book_db = root.child('bookings')
            book_db.push({
                'name':
                instructor.get_name(),
                'age':
                instructor.get_age(),
                'phoneNumber':
                instructor.get_phoneNumber(),
                'email':
                instructor.get_email(),
                'startingDateAndTime':
                instructor.get_startingDateAndTime(),
                'type':
                instructor.get_type(),
                'specialization2':
                instructor.get_specialization2()
            })

            flash('Your appointment is registered.', 'success')

        return redirect(url_for('view_Booking_Page'))
        # return render_template('view_Booking_Page.html',form=form)
    return render_template('BookingPage.html', form=form)
def main():

    debug = False
    root = Tk()
    root.withdraw()
    run_time = datetime.now().strftime('%Y%m%d%H%M') # used for file extensions, makes sorting easy
    print("\nMathnasium Scheduler Launched")
    default_directory = "C:\\ProgramData\\MathnasiumScheduler"
    FILEOPENOPTIONS = dict(defaultextension='.csv', filetypes=[('XLSX', '*.xlsx'), ('CSV file', '*.csv')])
    # Todo-jerry add center name picklist, get center names from configuraton file
    center_name = simpledialog.askstring("Name prompt", "Enter Center Name")
    schedule_start_date = simpledialog.askstring("Schedule Start Prompt", "Enter Schedule Start Date (MM/DD/YY)")
    # center_name = "aaaa.TestRun" #Eliminates need to select files for successive test runs
    importer = Importer().import_all(run_time, default_directory, center_name, FILEOPENOPTIONS)

    #Create Schedule Workbook
    # Create Run Workbook
    run_wb_path = default_directory + "\\" + center_name + "." + run_time + ".xlsx"
    run_wb = Workbook()
    run_wb.save(run_wb_path)
    schedule_by_name_ws = run_wb.create_sheet("Schedule By Name", index=0)
    schedule_by_day_ws = run_wb.create_sheet("Schedule By Day", index=1)
    forecast_summary_ws = run_wb.create_sheet("Summary Forecast", index=2)
    forecast_detailed_ws = run_wb.create_sheet("Detailed Forecast", index=3)
    run_log_ws = run_wb.create_sheet("Runlog", index=4)
    #ToDo Write run_log to run_log_ws
    run_log = []
    instructors = Instructor.create_instructors(run_log)
    students = Student.initialize_students(importer.attendance_ws, importer.student_data_ws, run_log)

    #Create Events
    print("\nCreating events from student arrivals and departures\n")
    events = []
    for each_student in Student.students:
        events.append(Event('Arrival', each_student.arrival_time, each_student))
        events.append(Event('Departure', each_student.departure_time, each_student))
    events.sort()

    #Executing Events
    print("Executing events and collecting information")
    # Gather events by week day
    #ToDo refactor this into Common and use common
    # define days consistent with datetime.weekday()
    mon = 0
    tue = 1
    wed = 2
    thu = 3
    fri = 4
    sat = 5
    sun = 6

    # Group events by day
    event_groups = {sun: [], mon: [], tue: [], wed: [], thu: [], fri: [], sat: []}
    for each_event in events:
        event_groups[each_event.event_time.weekday()].append(each_event)

    print("\tDetermining cost of each day")
    costsOfEventGroups = {}
    for each_day in event_groups.keys():
        cost = 0.0
        for each_event in event_groups[each_day]:
            if each_event.is_arrival_event: cost = cost + each_event.cost()
        costsOfEventGroups[each_day] = round(cost, 1)
        print("\t\tDay: ", each_day, "Cost: ", costsOfEventGroups[each_day])

    # Sort and process each group of events
    for each_day in event_groups.keys():
        print("\n\tProcessing Day: ", str(each_day))
        event_groups[each_day].sort()
        instructorsMinimum = 2.0  # ToDo remove hard coded variable the minimum staffing level
        instructorsRequired = 0.0  # actual number of instructors required to meet student demand
        event_number = 1  # first event number
        student_count = 0  # start with zero students
        for each_event in event_groups[each_day]:
            # Set event number
            each_event.event_number = event_number
            # Set event's previous and next events
            if event_number != 1: each_event.prev = events[events.index(each_event) - 1]
            if event_number != len(event_groups[each_day]): each_event.next = event_groups[each_day][
                event_groups[each_day].index(each_event) + 1]
            event_number = event_number + 1  # next event number
            # Maintain student count
            if (each_event.is_arrival_event):
                student_count = student_count + 1
            elif (each_event.is_departure_event):
                student_count = student_count - 1
            each_event.student_count = student_count
            # Compute/maintain the actual number of instructors required
            instructorsRequired = instructorsRequired + each_event.cost()
            # Compute/maintain the number of instructors to staff (minimum is instructorsMinimum)
            each_event.instructor_count = max(instructorsMinimum, math.ceil(instructorsRequired))

        print("\t\tCollecting Instructor Change Events")
        instructor_change_events = []
        for each_event in event_groups[each_day]:
            if each_event.is_instructor_change_event():
                instructor_change_events.append(each_event)

        print("\t\tMarking Churn Events")
        tolerance = 360  # seconds (6 minutes)
        for i in range(len(instructor_change_events) - 1):
            event = instructor_change_events[i]
            next_event = instructor_change_events[i + 1]
            event.isChurnEvent = event.is_peak_event() and next_event.is_valley_event() \
                                 and (next_event.event_time - event.event_time).seconds < tolerance

        print("\t\tScheduling Instructors")
#        instructors = Instructor.instructors
        instructors.sort()
        if debug:
            for eachInstructor in instructors: print(eachInstructor)
        inactive_instructors = instructors
        active_instructors = []
        dateChangeEvents = 0

        for each_event in event_groups[each_day]:
            if each_event.is_date_change_event():
                dateChangeEvents = dateChangeEvents + 1
                # Activate minimum number of instructors needed to open if necessary
                active_instructor_count = 0
                inactive_instructors.sort()
                instructors_changed = []
                for this_instructor in inactive_instructors:
                    if this_instructor.isAvailableToOpen(each_event) and (active_instructor_count < instructorsMinimum):
                        active_instructor_count = active_instructor_count + 1
                        this_instructor.startWorkWhenOpen(each_event)
                        active_instructors.append(this_instructor)
                        # save pointers to instructors for removal from unscheduled list
                        instructors_changed.append(this_instructor)
                for i in instructors_changed: inactive_instructors.remove(i)

            # Check for and remove departing Instructors
            departed_instructors = []
            for this_instructor in active_instructors:
                departed = False
                if this_instructor.mustDepart(each_event):
                    this_instructor.departWork(each_event)
                    departed_instructors.append(this_instructor)

            instructor_change_needed = each_event.instructor_count - len(active_instructors)
            if not each_event.is_churn_event and instructor_change_needed > 0:
                # Schedule available instructors
                # print("\t\t\tActivate Instructor")
                active_instructor_count = 0
                inactive_instructors.sort()
                # print("Inactive Instructors: " + str(len(inactive_instructors)))
                while (active_instructor_count < instructor_change_needed):
                    # print('while')
                    # Find instructor and schedule instructor
                    instructors_changed = [] #ToDo inside the while loop (inconsistent see line 215)
                    for this_instructor in inactive_instructors:
                        if this_instructor.isAvailable(each_event) and (active_instructor_count < instructor_change_needed):
                            active_instructor_count = active_instructor_count + 1
                            this_instructor.startWork(each_event)
                            active_instructors.append(this_instructor)
                            # Save pointers to newly scheduled instructors for removal from unscheduled list
                            instructors_changed.append(this_instructor)
                # Remove newly activated (scheduled) instructors from inactive list
                for i in instructors_changed: inactive_instructors.remove(i)

            if not each_event.is_churn_event and instructor_change_needed < 0:
                # Deactivate instructors
                # print("\t\t\tDeactivate Instructor")
                deactivated_instructor_count = 0
                instructors_deactivated = [] #ToDo outside the while loop (inconsistent see line 200)
                active_instructors.sort()
                # print("Printing Reversed Rank List")
                # for this in reversed(active_instructors):
                #     print(this.name, this.rank)
                while deactivated_instructor_count < abs(instructor_change_needed):
                    for this_instructor in reversed(active_instructors):
                          if deactivated_instructor_count < abs(instructor_change_needed):
                            deactivated_instructor_count = deactivated_instructor_count + 1
                            this_instructor.stopWork(each_event)
                            inactive_instructors.append(this_instructor)
                            instructors_deactivated.append(this_instructor)
                for i in instructors_deactivated: active_instructors.remove(i)

            # Finalize schedules after last departure or final event of the day
            if (each_event == event_groups[each_day][len(event_groups[each_day]) - 1]) or each_event.next.is_date_change_event():
                instructors_changed = []
                for this_instructor in active_instructors:
                    this_instructor.isScheduled = False
                    inactive_instructors.append(this_instructor)
                    instructors_changed.append(this_instructor)
                for i in instructors_changed: active_instructors.remove(i)
                for i in inactive_instructors: i.finalizeSchedule()

    Reporter().write_all(events, instructors, forecast_detailed_ws, forecast_summary_ws, schedule_by_name_ws)

    print("\nReview, edit, and approve schedules")
    # Todo code to review, edit, and approve schedules

    print("\nFormating and Closing Workbooks")
    Importer().close_workbooks()
    Reporter().format_sheets(run_wb)
    run_wb.save(run_wb_path)
    run_wb.close()

    print("\nLaunching Excel")
    os.system("start excel " + run_wb_path )

    # Todo code up individual schedule emails including mapping to email addresses and instructor first names.
    print("\nEmailing Schedules to Instructors")
#    Gmailer().send_instructor_schedules(instructors)

    # Todo code up scheduling individual work events on master schedule calendar and instructor calendars.
    print("\nAdding Work Events to Instructor Google Calendars")
#    GoogleEventScheduler().insert_events(instructors)

    print("\nScheduler Run Completed")
def main():

    print("This tests instructor class\n")

    MAXINSTRUCTORS = 4

    #create instructors
    instructors = []
    for i in range(MAXINSTRUCTORS):
        info = makePersonInfo()
        officeHrs = makeHours()
        instructors.append(
            Instructor(info[0], info[1], info[2], info[3], officeHrs))

    print("Faculty ")
    print(
        " shoud show 4 instructors with names, ages, Lnumbers, and office hours\n"
    )
    print("     Name       Age  LNumber       Office Hours ")
    for i in range(MAXINSTRUCTORS):
        fName = instructors[i].getFirstName()
        lName = instructors[i].getLastName()
        age = instructors[i].getAge()
        lNum = instructors[i].getLNumber()
        officeHrs = instructors[i].getOfficeHours()
        print(f'{fName:7}' + f'{lName:8}' + f'{age:3}' + "  " + f'{lNum:12}' +
              f'{officeHrs:10}')

    print("\nThis tests student class")

    MAXSTUDENTS = 8

    #create students
    students = []
    for i in range(MAXSTUDENTS):
        info = makePersonInfo()
        gpa = makeGPA()
        students.append(Student(info[0], info[1], info[2], info[3], gpa))

    print("Students ")
    print(" should show 8 students with names, ages, Lnumbers, and GPAS\n")
    print("     Name          Age  LNumber    GPA ")
    for i in range(MAXSTUDENTS):
        fName = students[i].getFirstName()
        lName = students[i].getLastName()
        age = students[i].getAge()
        lNum = students[i].getLNumber()
        gpa = students[i].getGPA()
        print(f'{fName:7} {lName:8} {age:4}   {lNum:10} {gpa:.2f}')

    print("\nThis displays polymorphism of getJob")

    # create three persons
    MAXPERSONS = 3
    persons = []

    print("Showing jobs ")
    print(
        "should output Test One Undefined, Test Two Instructor, Test Three Student"
    )

    persons.append(Person("Test", "One", 42, "L00000001"))
    persons.append(Instructor("Test", "Two", 55, "L00000002"))
    persons.append(Student("Test", "Three", 21, "L00000003"))

    for person in persons:
        print(person.getFirstName() + " " + person.getLastName() + " " +
              person.getJob())