Пример #1
0
class TestSection(unittest.TestCase):
    def setUp(self):
        self.room1 = Classroom("PB001", 120)
        self.room2 = Classroom("A110",100)

    def test_name(self):
        self.assertEqual(self.room1.name,'PB001')
        self.assertEqual(self.room2.name,'A110')
        
    def test_capacity(self):
        self.assertEqual(self.room1.capacity,120)
        self.assertEqual(self.room2.capacity,100)
    
    def test_can_accomodate(self):
        self.assertEqual(self.room1.can_accommodate(120), True)
        self.assertEqual(self.room1.can_accommodate(130), False)
        self.assertEqual(self.room1.can_accommodate(130, 10), True)
    
    def test___eq__(self):
        self.assertEqual((self.room1==self.room2),False)
        self.assertEqual((self.room1 == self.room1),True)
        self.assertEqual((self.room1=='room1'),False)

    def test___ne__(self):
        self.assertEqual((self.room1!=self.room2),True)
        self.assertEqual((self.room1 != self.room1),False)
        self.assertEqual((self.room1 !='room1'),True)
Пример #2
0
 def test_remove_time_table_slot(self):
     self.timetable.remove_time_table_slot(Classroom('LT ', 45, 'PBOO2'),TimeSlot('8:00','9:00'))
     self.timetable.remove_time_table_slot(Classroom('LT ', 45, 'PBOO2'),TimeSlot('9:00','10:00'))
     self.timetable.remove_time_table_slot(Classroom('LT ', 45, 'PBOO2'),TimeSlot('10:00','11:00'))
     self.timetable.remove_time_table_slot(Classroom('LT ', 45, 'PBOO2'),TimeSlot('11:00','12:00'))
     print('-------------------------Remove time table slot ------------------')
     print(self.timetable)
def collect_repos(auth, university, course, get_repos_filepath):

    call_dir = os.getcwd()
    repos_filepath = os.path.join(call_dir, get_repos_filepath,
                                  "%s_all_repos" % course)
    if not os.path.isdir(repos_filepath):
        os.mkdir(repos_filepath)
    #else:
    # TODO: check if there are student repos here allready

    org = "%s-%s" % (university, course)
    url_orgs = 'https://api.github.com/orgs/%s' % (org)
    url_repos = 'https://api.github.com/repositories/'
    classroom = Classroom(auth, url_orgs)
    repos = classroom.get_repos()
    #SSH_base = "[email protected]:%s/" % org

    # Create the SSH links
    SSH_links = []
    for repo in repos:
        if course in repo['name'].encode('utf-8'):
            r = get(url_repos + str(repo['id']), auth=auth)
            SSH_links.append(r.json()['ssh_url'])

    # Change to destination folder
    os.chdir(repos_filepath)

    # Clone into the repos
    for SSH_link in SSH_links:
        result = os.system('git clone ' + SSH_link)
        print(result)

    # Change back to call dir
    os.chdir(call_dir)
def end_group(org):
    """Deletes all teams on the form Team-<number>"""
    auth = get_password()
    url_orgs = 'https://api.github.com/orgs/%s' % (org)    

    number_deleted = 0

    classroom = Classroom(auth, url_orgs)
    teams = classroom.get_teams()

    number_not_deleted = 0
    not_deleted = ''
    for team in teams:
        if 'Team-' in team['name']:
            r = delete("https://api.github.com/teams/" + str(team['id']), auth=auth)
            if r.status_code != 204:
                number_not_deleted += 1
                not_deleted += '\n' + team['name']
            else:
                number_deleted += 1

    if number_not_deleted == 0:
        print('Deleted all teams related to the group session (%d teams deleted)' % \
                number_deleted)
    else:
        print('Delted %s teams, but there were %s teams that where not deleted:%s' % \
               (number_deleted, number_not_deleted, not_deleted))
Пример #5
0
def collect_repos(auth, university, course, get_repos_filepath):

    call_dir = os.getcwd()
    repos_filepath = os.path.join(call_dir, get_repos_filepath, "%s_all_repos" % course)
    if not os.path.isdir(repos_filepath):
        os.makedirs(repos_filepath)
    else:
        if os.listdir(repos_filepath) != []:
            print "There are already repos in this folder, pleace \
                    remove them before cloning new into this folder"
            sys.exit(0)

    org = "%s-%s" % (university, course)
    url_orgs = 'https://api.github.com/orgs/%s' % (org)
    url_repos = 'https://api.github.com/repositories/'
    classroom = Classroom(auth, url_orgs)
    repos = classroom.get_repos()

    # Create the SSH links
    SSH_links = []
    for repo in repos:
        if course in repo['name'].encode('utf-8'):
            r = get(url_repos + str(repo['id']), auth=auth)
            SSH_links.append(r.json()['ssh_url'])

    # Change to destination folder
    os.chdir(repos_filepath)

    # Clone into the repos
    for SSH_link in SSH_links:
        result = os.system('git clone ' + SSH_link)
        #print(result)

    # Change back to call dir
    os.chdir(call_dir)
Пример #6
0
    def test_section_is_free(self):
        lecturer = Lecturer('Benjamin Kommey',4564541,'Mr')
        course = Course('Embedded Systems','COE 361')

        section = Section('ED CoE',25,3,'Electrical and Electronics Engineering','Computer Engineering')
        c_item = CurriculumItem(section,course,lecturer)

        lecture = Lecture(c_item,60)

        ttslot =  TimetableSlot('Mon', Classroom('LT ', 45, 'PBOO2'),TimeSlot('8:00', '9:00'))
        ttslot1 =TimetableSlot('Mon', Classroom('LT ', 45, 'PBOO2'),TimeSlot('9:00', '10:00'))
        ttslot2 = TimetableSlot('Mon', Classroom('LT ', 45, 'PBOO2'),TimeSlot('10:00', '11:00'))
        ttslot3 = TimetableSlot('Mon', Classroom('LT ', 45, 'PBOO2'),TimeSlot('11:00', '12:00'))
        self.assertTrue(self.timetable.add_lecture(lecture,ttslot))
        self.assertTrue(self.timetable.add_lecture(lecture,ttslot1))
        self.assertTrue(self.timetable.add_lecture(lecture,ttslot2))
        self.assertTrue(self.timetable.add_lecture(lecture,ttslot3))

        self.assertFalse(self.timetable.section_is_free(section,ttslot.time_slot))
        self.assertFalse(self.timetable.section_is_free(section,ttslot1.time_slot))
        self.assertFalse(self.timetable.section_is_free(section,ttslot2.time_slot))
        self.assertFalse(self.timetable.section_is_free(section,ttslot3.time_slot))

        self.assertTrue(self.timetable.section_is_free(section,TimeSlot('15:00', '16:00')))
        self.assertTrue(self.timetable.section_is_free(section,TimeSlot('12:00', '13:00')))
        self.assertTrue(self.timetable.section_is_free(section,TimeSlot('16:00', '17:00')))
        self.assertTrue(self.timetable.section_is_free(section,TimeSlot('7:00', '8:00')))
Пример #7
0
def end_group(org):
    """Deletes all teams on the form Team-<number>"""
    auth = get_password()
    url_orgs = 'https://api.github.com/orgs/%s' % (org)

    number_deleted = 0

    classroom = Classroom(auth, url_orgs)
    teams = classroom.get_teams()

    number_not_deleted = 0
    not_deleted = ''
    for team in teams:
        if 'Team-' in team['name']:
            r = delete("https://api.github.com/teams/" + str(team['id']),
                       auth=auth)
            if r.status_code != 204:
                number_not_deleted += 1
                not_deleted += '\n' + team['name']
            else:
                number_deleted += 1

    if number_not_deleted == 0:
        print('Deleted all teams related to the group session (%d teams deleted)' % \
                number_deleted)
    else:
        print('Delted %s teams, but there were %s teams that where not deleted:%s' % \
               (number_deleted, number_not_deleted, not_deleted))
Пример #8
0
    def test_has_right_neighbour(self):
        #TODO
        #Test for timetableslots that are occupied with lectures

        #test for edge cases

        #test for extreme left condition
        #test for left index out of bounds
        self.assertTrue(self.timetable.has_right_neighbour(
             TimetableSlot('Mon', Classroom('PB001', 100, 'Petroleum building'),TimeSlot('8:00', '9:00'))))

        #test for slot with right neighbour
        self.assertTrue(self.timetable.has_right_neighbour(
             TimetableSlot('Mon', Classroom('PB001', 100, 'Petroleum building'),TimeSlot('9:00', '10:00'))))
        
        #test for extreme right
        #should lack right neighbour
        self.assertFalse(self.timetable.has_right_neighbour(
             TimetableSlot('Mon', Classroom('PB001', 100, 'Petroleum building'),TimeSlot('16:00', '17:00'))))
        
        #test for slot not in timetable 
        self.assertFalse(self.timetable.has_right_neighbour(
             TimetableSlot('Tues', Classroom('PB001', 100, 'Petroleum building'),TimeSlot('9:00', '10:00'))))
        
        #test for slot not in timetable
        self.assertFalse(self.timetable.has_right_neighbour(
             TimetableSlot('Mon',  Classroom('PB001', 50, 'Petroleum building'),TimeSlot('16:00', '17:00'))))
Пример #9
0
    def test_all_slots(self):
        lecturer = Lecturer('Benjamin Kommey', 4564541, 'Mr')
        course = Course('Embedded Systems', 'COE 361')

        section = Section('ED CoE', 25, 3,
                          'Electrical and Electronics Engineering',
                          'Computer Engineering')
        c_item = CurriculumItem(section, course, lecturer)

        lecture = Lecture(c_item, 60)

        ttslot = TimetableSlot('Monday', Classroom('LT ', 45, 'PBOO2'),
                               TimeSlot('8:00', '9:00'))
        ttslot1 = TimetableSlot('Tuesday', Classroom(' A110', 300, 'Libary'),
                                TimeSlot('9:00', '10:00'))
        ttslot2 = TimetableSlot('Thursday', Classroom('Room C', 67, 'N1'),
                                TimeSlot('10:00', '11:00'))
        ttslot3 = TimetableSlot('Friday', Classroom('LT ', 45, 'PBOO2'),
                                TimeSlot('11:00', '12:00'))
        ttslot4 = TimetableSlot('Monday', Classroom('LT ', 45, 'PBOO2'),
                                TimeSlot('10:00', '11:00'))

        #print(self.timetable)
        self.assertTrue(self.timetable.add_lecture('Monday', lecture, ttslot))
        self.assertTrue(self.timetable.add_lecture('Tuesday', lecture,
                                                   ttslot1))
        self.assertTrue(
            self.timetable.add_lecture('Thursday', lecture, ttslot2))
        self.assertTrue(self.timetable.add_lecture('Friday', lecture, ttslot3))
        print("############ Testing All Slots##############################")
        slots = self.timetable.all_slots()

        for slot in slots:
            print(slot)
def collect_repos(auth, university, course, get_repos_filepath):

    call_dir = os.getcwd()
    repos_filepath = os.path.join(call_dir, get_repos_filepath, "%s_all_repos" % course)
    if not os.path.isdir(repos_filepath):
        os.mkdir(repos_filepath)
    #else:
        # TODO: check if there are student repos here allready

    org = "%s-%s" % (university, course)
    url_orgs = 'https://api.github.com/orgs/%s' % (org)
    url_repos = 'https://api.github.com/repositories/'
    classroom = Classroom(auth, url_orgs)
    repos = classroom.get_repos()
    #SSH_base = "[email protected]:%s/" % org

    # Create the SSH links
    SSH_links = []
    for repo in repos:
        if course in repo['name'].encode('utf-8'):
            r = get(url_repos + str(repo['id']), auth=auth)
            SSH_links.append(r.json()['ssh_url'])

    # Change to destination folder
    os.chdir(repos_filepath)
    
    # Clone into the repos
    for SSH_link in SSH_links:
        result = os.system('git clone ' + SSH_link)
        print(result)

    # Change back to call dir
    os.chdir(call_dir)
Пример #11
0
    def test_swap_lectures(self):
        pass
        #Test later, not called in generator at the moment
        lecturer = Lecturer('Benjamin Kommey', 4564541, 'Mr')
        course = Course('Embedded Systems', 'COE 361')

        section = Section('ED CoE', 25, 3,
                          'Electrical and Electronics Engineering',
                          'Computer Engineering')
        c_item = CurriculumItem(section, course, lecturer)

        lecture = Lecture(c_item, 60)

        ttslot = TimetableSlot('Monday', Classroom('LT ', 45, 'PBOO2'),
                               TimeSlot('8:00', '9:00'))
        ttslot1 = TimetableSlot('Tuesday', Classroom(' A110', 300, 'Libary'),
                                TimeSlot('9:00', '10:00'))
        ttslot2 = TimetableSlot('Thursday', Classroom('Room C', 67, 'N1'),
                                TimeSlot('10:00', '11:00'))
        ttslot3 = TimetableSlot('Friday', Classroom('LT ', 45, 'PBOO2'),
                                TimeSlot('11:00', '12:00'))
        self.assertTrue(self.timetable.add_lecture('Monday', lecture, ttslot))
        self.assertTrue(self.timetable.add_lecture('Tuesday', lecture,
                                                   ttslot1))
        self.assertTrue(
            self.timetable.add_lecture('Thursday', lecture, ttslot2))
        self.assertTrue(self.timetable.add_lecture('Friday', lecture, ttslot3))
        print(self.timetable)
Пример #12
0
    def setUp(self):
        #create an empty timetable of 5 days
        classrooms = [
            Classroom('LT ', 45, 'PBOO2'),
            Classroom('PB001', 100, 'Petroleum building'),
            Classroom('Main Library ', 60, 'Admiss'),
            Classroom('Room C', 67, 'N1'),
            Classroom(' A110', 300, 'Libary')
        ]

        timeslots = [
            TimeSlot('8:00', '9:00'),
            TimeSlot('9:00', '10:00'),
            TimeSlot('10:00', '11:00'),
            TimeSlot('11:00', '12:00'),
            TimeSlot('12:00', '13:00'),
            TimeSlot('13:00', '14:00')
        ]

        days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
        day_tables = []

        self.days = days
        for day in days:
            day_tables.append(DayTimetable(classrooms, timeslots, day))

        self.timetable = Timetable(days, day_tables)
Пример #13
0
    def setUp(self) -> None:
        # self.classrooms = factory.generate_batch(ClassRoomFactory, size=20, strategy="build")
        # self.slots = slots
        # self.day_tt = DayTimetable(classrooms=self.classrooms, time_slots=self.slots)

        classrooms = [
            Classroom('LT ', 45, 'PBOO2'),
            Classroom('PB001', 100, 'Petroleum building'),
            Classroom('PBOO2 ', 45, 'Petroleum building'),
            # Classroom('Pb103', 67, 'Petroleum Building'),
            # Classroom('PB119', 150, 'Petroluem'),
            # Classroom(' A110', 300, 'Libary'),
            # Classroom('Computer lab', 67, 'vodafone'),
            # Classroom('LAB-12', 40, 'vodafone'),
            # Classroom('Room A', 100, 'tyeh'),
            # Classroom('Room B ', 45, 'PBOO2'),
            # Classroom('Main Library ', 60, 'Admiss'),
            Classroom('Room C', 67, 'N1')]

        timeslots = [
            TimeSlot('8:00','9:00'),
            TimeSlot('9:00','10:00'),
            TimeSlot('10:00', '11:00'),
            TimeSlot('11:00', '12:00'),
            TimeSlot('12:00', '13:00'),
            TimeSlot('13:00', '14:00'),
            TimeSlot('14:00', '15:00'),
            TimeSlot('15:00', '16:00'),
            TimeSlot('16:00', '17:00')
        ]

        self.timetable = DayTimetable(classrooms, timeslots,'Mon')
Пример #14
0
    def test_remove_lecture(self):
        #test for removing a lecture from a slot that exists and is occupied
        
        lecturer = Lecturer('Benjamin Kommey',4564541,'Mr')
        course = Course('Embedded Systems','COE 361')

        section = Section('ED CoE',25,3,'Electrical and Electronics Engineering','Computer Engineering')
        c_item = CurriculumItem(section,course,lecturer)

        lecture = Lecture(c_item,60)

        print(self.timetable)
        print('--------TEST - REMOVE-------------------After Adding Lecture-----------------')
        ttslot =  TimetableSlot('Mon', Classroom('LT ', 45, 'PBOO2'),TimeSlot('8:00', '9:00'))
        self.assertTrue(self.timetable.add_lecture(lecture,ttslot))
        print(self.timetable)
        self.assertTrue(self.timetable.remove_lecture(ttslot))
        print('-----TEST REMOVE-----------------------After removing Lecture---------------')
        print(self.timetable)

        #test for removing a lecture from a slot that is empty
        self.assertFalse(self.timetable.remove_lecture(ttslot))

        #test for removing a lecture from a slot that does not exists
        self.assertFalse(self.timetable.remove_lecture( TimetableSlot('Mon', Classroom('LT ', 45, 'PBOO2'),TimeSlot('7:00', '8:00'))))
def setup_for_test():
    new_classroom = Classroom("CS1", "Mike Kane", "Tu/Th 4-6pm PST")
    new_student_1 = Student("John Doe", 1)
    new_student_2 = Student("Jane Doe", 2)
    new_classroom.next_available_student_number = 3
    new_classroom.roster[1] = new_student_1
    new_classroom.roster[2] = new_student_2
    return new_classroom
Пример #16
0
    def __init__(self, name, username, university, course, email, auth,
                 send_email, rank):
        """When initialized it testes if the information is correct and if the
           student has been initialized before. If not it calles create_repository()
        """
        self.name = name
        try:
            self.rank = int(rank)
            if rank > 3 or rank < 1:
                print("%s has a rank out of bound(%s) is has to be," % self.name, self.rank + \
                       "from 1 to 3. It is now set to 2.")
                self.rank = 2
        except:
            print("%s has wrong format on his/her rank," % self.name + \
                  " it has to be an integer. It is now set to 2.")
            self.rank = 2

        self.email = email
        self.username = username
        self.course = course
        self.university = university
        self.auth = auth
        self.send_email = send_email

        # Create useful strings
        self.org = "%s-%s" % (university, course)
        self.url_orgs = 'https://api.github.com/orgs/%s' % (self.org)
        self.url_teams = 'https://api.github.com/teams'

        Classroom.__init__(self, self.auth, self.url_orgs)

        # Check that there is an user with the given username
        if self.is_user():
            # Check if user have a team
            if not self.has_team():
                self.create_repository()

            # Get repo name
            else:
                teams = self.get_teams()
                for team in teams:
                    if team['name'].encode('utf-8') == self.name:
                        self.team_id = team['id']
                        r = get(self.url_teams + "/" + str(self.team_id) +
                                "/repos",
                                auth=auth)
                        for repo in r.json():
                            # Assumes that the student has not created a new
                            # repository containing the name of the course-<firstname>
                            base_name = "%s-%s" % (self.course, \
                                            self.strip_accents(self.name.split(" ")[0]))

                            if base_name in repo['name'].encode('utf-8'):
                                self.repo_name = repo['name'].encode('utf-8')
                                break
                        break
Пример #17
0
    def __init__(self, name, username, university, course,
                 email, auth, send_email, rank):
        """When initialized it testes if the information is correct and if the
           student has been initialized before. If not it calles create_repository()
        """
        self.name = name
        try:
            self.rank = int(rank)
            if rank > 3 or rank < 1:
                print("%s has a rank out of bound(%s) is has to be," % self.name, self.rank + \
                       "from 1 to 3. It is now set to 2.")
                self.rank = 2
        except:
            print("%s has wrong format on his/her rank," % self.name + \
                  " it has to be an integer. It is now set to 2.")
            self.rank = 2

        self.email = email
        self.username = username
        self.course = course
        self.university = university
        self.auth = auth
        self.send_email = send_email

        # Create useful strings
        self.org = "%s-%s" % (university, course)
        self.url_orgs = 'https://api.github.com/orgs/%s' % (self.org)
        self.url_teams = 'https://api.github.com/teams'

        Classroom.__init__(self, self.auth, self.url_orgs)

        # Check that there is an user with the given username
        if self.is_user():
            # Check if user have a team
            if not self.has_team():
                self.create_repository()

            # Get repo name
            else:
                teams = self.get_teams()
                for team in teams:
                    if team['name'].encode('utf-8') == self.name:
                        self.team_id = team['id']
                        r = get(self.url_teams + "/" + str(self.team_id) + "/repos", auth=auth)
                        for repo in r.json():
                            # Assumes that the student has not created a new
                            # repository containing the name of the course-<firstname>
                            base_name = "%s-%s" % (self.course, \
                                            self.strip_accents(self.name.split(" ")[0]))

                            if base_name in repo['name'].encode('utf-8'):
                                self.repo_name = repo['name'].encode('utf-8')
                                break
                        break
Пример #18
0
    def test_timetableslot(self):
        lecturer = Lecturer('Benjamin Kommey',4564541,'Mr')
        course = Course('Embedded Systems','COE 361')

        section = Section('ED CoE',25,3,'Electrical and Electronics Engineering','Computer Engineering')
        c_item = CurriculumItem(section,course,lecturer)

        lecture = Lecture(c_item,60)

        ttslot =  TimetableSlot('Mon', Classroom('LT ', 45, 'PBOO2'),TimeSlot('8:00', '9:00'))
        self.assertTrue(self.timetable.add_lecture(lecture,ttslot))
        self.assertEqual(self.timetable.timetableslot(ttslot.room,ttslot.time_slot),ttslot)
        ttslot1 = TimetableSlot('Mon', Classroom('LT ', 45, 'PBOO2'),TimeSlot('9:00', '10:00'))
        self.assertEqual(self.timetable.timetableslot(ttslot1.room,ttslot1.time_slot),ttslot1)
Пример #19
0
 def get_classroom_by_door_and_faculty(self, faculty_id, door_number):
     with dbapi2.connect(self.dbfile) as connection:
         cursor = connection.cursor()
         query = "select * from classroom where(faculty_id = %s and door_number = %s);"
         cursor.execute(query, (faculty_id, door_number))
         if cursor.rowcount == 0:
             return None
         return Classroom(*cursor.fetchone())
Пример #20
0
 def get_all_classrooms(self):
     classrooms = []
     with dbapi2.connect(self.dbfile) as connection:
         cursor = connection.cursor()
         cursor.execute("select * from classroom order by (id);")
         for row in cursor:
             classrooms.append(Classroom(*row))
     return classrooms
Пример #21
0
    def test_right_neighbours(self):
        #TODO
        #test for cases with lectures assigned to timetableslots
        
        #test for edge cases
        ttslot1 =   TimetableSlot('Mon', Classroom('PB001', 100, 'Petroleum building'),TimeSlot('14:00', '15:00'))
        neighbours = [TimetableSlot('Mon', Classroom('PB001', 100, 'Petroleum building'),TimeSlot('15:00', '16:00')),
        TimetableSlot('Mon', Classroom('PB001', 100, 'Petroleum building'),TimeSlot('16:00', '17:00'))]
        self.assertEqual(self.timetable.right_neighbours(ttslot1),neighbours)

        #leftmmost slot with no right neighours
        ttslot1 =   TimetableSlot('Mon', Classroom('PB001', 100, 'Petroleum building'),TimeSlot('16:00', '17:00'))
        self.assertEqual(self.timetable.right_neighbours(ttslot1),[])

        #slot not in timetable has no neighbours
        ttslot1 =   TimetableSlot('Fri', Classroom('PB001', 100, 'Petroleum building'),TimeSlot('8:00', '9:00'))
        self.assertEqual(self.timetable.right_neighbours(ttslot1),[])
Пример #22
0
    def test_remove_lecture(self):
        print(
            '################################### Test Removing Lectures ###############################'
        )
        lecturer = Lecturer('Benjamin Kommey', 4564541, 'Mr')
        course = Course('Embedded Systems', 'COE 361')

        section = Section('ED CoE', 25, 3,
                          'Electrical and Electronics Engineering',
                          'Computer Engineering')
        c_item = CurriculumItem(section, course, lecturer)

        lecture = Lecture(c_item, 60)

        ttslot = TimetableSlot('Monday', Classroom('LT ', 45, 'PBOO2'),
                               TimeSlot('8:00', '9:00'))
        ttslot1 = TimetableSlot('Tuesday', Classroom(' A110', 300, 'Libary'),
                                TimeSlot('9:00', '10:00'))
        ttslot2 = TimetableSlot('Thursday', Classroom('Room C', 67, 'N1'),
                                TimeSlot('10:00', '11:00'))
        ttslot3 = TimetableSlot('Friday', Classroom('LT ', 45, 'PBOO2'),
                                TimeSlot('11:00', '12:00'))
        ttslot4 = TimetableSlot('Monday', Classroom('LT ', 45, 'PBOO2'),
                                TimeSlot('10:00', '11:00'))
        print(self.timetable)
        self.assertTrue(self.timetable.add_lecture('Monday', lecture, ttslot))
        self.assertTrue(self.timetable.add_lecture('Tuesday', lecture,
                                                   ttslot1))
        self.assertTrue(
            self.timetable.add_lecture('Thursday', lecture, ttslot2))
        self.assertTrue(self.timetable.add_lecture('Friday', lecture, ttslot3))
        print(self.timetable)
        self.assertTrue(self.timetable.remove_lecture(ttslot.day, ttslot))
        self.assertTrue(self.timetable.remove_lecture(ttslot1.day, ttslot1))
        self.assertTrue(self.timetable.remove_lecture(ttslot2.day, ttslot2))
        self.assertTrue(self.timetable.remove_lecture(ttslot3.day, ttslot3))
        self.assertFalse(self.timetable.remove_lecture(ttslot4.day, ttslot4))
        print(self.timetable)

        print(
            '####################################################################'
        )
        print(self.timetable)
        self.timetable.timetable['Monday'].move_lecture(ttslot, ttslot4)
Пример #23
0
 def get_classroom(self, id):
     with dbapi2.connect(self.dbfile) as connection:
         cursor = connection.cursor()
         query = "select * from classroom where (id = %s)"
         cursor.execute(query, (id, ))
         if cursor.rowcount == 0:
             return None
     classroom = Classroom(
         *cursor.fetchone())  # Inline unpacking of a tuple
     return classroom
Пример #24
0
 def get_all_classrooms_by_faculty(self, faculty_id):
     classrooms = []
     with dbapi2.connect(self.dbfile) as connection:
         cursor = connection.cursor()
         cursor.execute(
             "select * from classroom where (faculty_id = %s) order by (id);",
             (faculty_id, ))
         for row in cursor:
             classrooms.append(Classroom(*row))
     return classrooms
Пример #25
0
def collect_repos(auth, university, course, get_repos_filepath):
    """ Clone (download) all repositories of a course """

    call_dir = os.getcwd()
    repos_filepath = os.path.join(call_dir, get_repos_filepath,
                                  "%s_all_repos" % course)
    if not os.path.isdir(repos_filepath):
        os.makedirs(repos_filepath)
    else:
        if os.listdir(repos_filepath) != []:
            print "There are already repos in this folder, please \
                    remove them before cloning new into this folder"

            sys.exit(0)

    org = "%s-%s" % (university, course)
    url_orgs = 'https://api.github.com/orgs/%s' % (org)
    url_repos = 'https://api.github.com/repositories/'
    classroom = Classroom(auth, url_orgs)
    print "Getting list of repositories..."
    repos = classroom.get_repos()
    print "Found {} repositories.".format(len(repos))

    # Create the SSH links
    SSH_links = []
    for i, repo in enumerate(repos):
        print "Getting repository links: {}%".format((100 * i) / len(repos))
        if course in repo['name'].encode('utf-8'):
            r = get(url_repos + str(repo['id']), auth=auth)
            SSH_links.append(r.json()['ssh_url'])

    # Change to destination folder
    os.chdir(repos_filepath)

    # Clone into the repos
    for i, SSH_link in enumerate(SSH_links):
        print "Cloning repositories {}%".format((100 * i) / len(SSH_links))
        result = os.system('git clone ' + SSH_link)
        print "done."

    # Change back to call dir
    os.chdir(call_dir)
Пример #26
0
 def test_remove_slot(self):
     print(
         '##################################### TEST_REMOVE_SLOT##############################'
     )
     self.timetable.remove_slot('Monday', Classroom('LT ', 45, 'PBOO2'),
                                TimeSlot('8:00', '9:00'))
     self.timetable.remove_slot('Monday', Classroom('LT ', 45, 'PBOO2'),
                                TimeSlot('9:00', '10:00'))
     self.timetable.remove_slot('Wednesday', Classroom('LT ', 45, 'PBOO2'),
                                TimeSlot('8:00', '9:00'))
     self.timetable.remove_slot('Thursday', Classroom('LT ', 45, 'PBOO2'),
                                TimeSlot('8:00', '9:00'))
     print(self.timetable)
     print(
         '################################# INSERT SLOT #####################################'
     )
     self.timetable.insert_slot(
         'Monday',
         TimetableSlot('Monday', Classroom('LT ', 45, 'PBOO2'),
                       TimeSlot('8:00', '10:00')))
     print(self.timetable)
Пример #27
0
def collect_repos(auth, university, course, get_repos_filepath):
    """ Clone (download) all repositories of a course """

    call_dir = os.getcwd()
    repos_filepath = os.path.join(call_dir, get_repos_filepath, "%s_all_repos" % course)
    if not os.path.isdir(repos_filepath):
        os.makedirs(repos_filepath)
    else:
        if os.listdir(repos_filepath) != []:
            print "There are already repos in this folder, please \
                    remove them before cloning new into this folder"
            sys.exit(0)

    org = "%s-%s" % (university, course)
    url_orgs = 'https://api.github.com/orgs/%s' % (org)
    url_repos = 'https://api.github.com/repositories/'
    classroom = Classroom(auth, url_orgs)
    print "Getting list of repositories..."
    repos = classroom.get_repos()
    print "Found {} repositories.".format(len(repos))

    # Create the SSH links
    SSH_links = []
    for i, repo in enumerate(repos):
        print "Getting repository links: {}%".format((100*i)/len(repos))
        if course in repo['name'].encode('utf-8'):
            r = get(url_repos + str(repo['id']), auth=auth)
            SSH_links.append(r.json()['ssh_url'])

    # Change to destination folder
    os.chdir(repos_filepath)

    # Clone into the repos
    for i, SSH_link in enumerate(SSH_links):
        print "Cloning repositories {}%".format((100*i)/len(SSH_links))
        result = os.system('git clone ' + SSH_link)
        print "done."

    # Change back to call dir
    os.chdir(call_dir)
def edit_page():
    uid = current_user.uid
    room = Classroom.from_uid(uid, db)
    classes = [
        {
            "name": c["name"],
            "id": c["id"],
            "webhook": (
                a.get_webhook_url() if (a := current_user.get_class(c["id"])) else ""
            ),
        }
        for c in room.get_courses()
    ]
Пример #29
0
    def test_first_fit(self):
        lecturer = Lecturer('Benjamin Kommey',4564541,'Mr')
        course = Course('Embedded Systems','COE 361')

        section = Section('ED CoE',25,3,'Electrical and Electronics Engineering','Computer Engineering')
        c_item = CurriculumItem(section,course,lecturer)

        lecture = Lecture(c_item,60)

        ttslot =  TimetableSlot('Mon', Classroom('LT ', 45, 'PBOO2'),TimeSlot('8:00', '9:00'))

        print('----------------First Fit-----------------------------')
        print(self.timetable.first_fit(lecture))
Пример #30
0
    def test_add_lecture(self):

        #test for the case of adding a lecture to a slot that is free with free parameter
        lecturer = Lecturer('Benjamin Kommey',4564541,'Mr')
        course = Course('Embedded Systems','COE 361')

        section = Section('ED CoE',25,3,'Electrical and Electronics Engineering','Computer Engineering')
        c_item = CurriculumItem(section,course,lecturer)

        lecture = Lecture(c_item,60)

        print(self.timetable)
        print('---------------------------After Adding Lecture-----------------')
        ttslot =  TimetableSlot('Mon', Classroom('LT ', 45, 'PBOO2'),TimeSlot('8:00', '9:00'))
        self.assertTrue(self.timetable.add_lecture(lecture,ttslot))
        print(self.timetable)

        #test for the case of adding a lecture to a slot that is not free with free parameter
        lecturer = Lecturer('Selasi Agbemenu',4564541,'Mr')
        course = Course('Linear Electronics','COE 361')

        section = Section('ED CoE',25,3,'Electrical and Electronics Engineering','Computer Engineering')
        c_item = CurriculumItem(section,course,lecturer)

        lecture = Lecture(c_item,60)
        
        print('---------------------------After Adding Lecture to Occupied---------')
        ttslot =  TimetableSlot('Mon', Classroom('LT ', 45, 'PBOO2'),TimeSlot('8:00', '9:00'))
        self.assertFalse(self.timetable.add_lecture(lecture,ttslot))
        print(self.timetable)
        


        #test for adding a lecture to slot that is not in the timetable 
        print('---------------------------After Adding Lecture to Occupied---------')
        ttslot =  TimetableSlot('Mon', Classroom('LT ', 45, 'PBOO2'),TimeSlot('6:00', '7:00'))
        self.assertFalse(self.timetable.add_lecture(lecture,ttslot))
        print(self.timetable)
Пример #31
0
def new_connection(uid, classId, webhookUrl, db):
    webhookId, webhookToken = clean_webhook_url(webhookUrl)

    regId, time = Classroom.from_uid(uid, db).register(classId)

    con = Connection(
        uid=uid,
        classId=classId,
        webhookId=webhookId,
        webhookToken=webhookToken,
        registration=regId,
        expire=parsetime(time),
    )
    db.add(con)
Пример #32
0
 def add_classroom(self):
     # For creating new Classroom variable
     username = self.authorizor.authenticator.logged_user
     if self.authorizor.check_permission('admin', username):
         classroom_name = input('Enter classroom name: ')
         while classroom_name in building.classrooms:
             classroom_name = input('Enter new classroom name: ')
         classroom_number = str(input('Enter classroom number: '))
         classroom_capacity = input('Enter classroom capacity: ')
         classroom_equipment = input(
             'Enter classroom equipment(ex: TV projector): ').split(' ')
         building.classrooms.append(
             Classroom(classroom_number, classroom_capacity,
                       classroom_equipment))
Пример #33
0
    def test_remove_all(self):
         #test for the case of adding a lecture to a slot that is free with free parameter
        lecturer = Lecturer('Benjamin Kommey',4564541,'Mr')
        course = Course('Embedded Systems','COE 361')

        section = Section('ED CoE',25,3,'Electrical and Electronics Engineering','Computer Engineering')
        c_item = CurriculumItem(section,course,lecturer)

        lecture = Lecture(c_item,60)
        
        ttslot =  TimetableSlot('Mon', Classroom('LT ', 45, 'PBOO2'),TimeSlot('8:00', '9:00'))
        ttslot1 =TimetableSlot('Mon', Classroom('LT ', 45, 'PBOO2'),TimeSlot('9:00', '10:00'))
        ttslot2 = TimetableSlot('Mon', Classroom('LT ', 45, 'PBOO2'),TimeSlot('10:00', '11:00'))
        ttslot3 = TimetableSlot('Mon', Classroom('LT ', 45, 'PBOO2'),TimeSlot('11:00', '12:00'))
        self.assertTrue(self.timetable.add_lecture(lecture,ttslot))
        self.assertTrue(self.timetable.add_lecture(lecture,ttslot1))
        self.assertTrue(self.timetable.add_lecture(lecture,ttslot2))
        self.assertTrue(self.timetable.add_lecture(lecture,ttslot3))
        print('---------------------------After Adding Lectures-----------------')
        print(self.timetable)
        self.assertTrue(self.timetable.remove_all())
        print('---------------------------After Removing Lectures-----------------')
        print(self.timetable)
Пример #34
0
    def test_occupied_slots(self):
        #if all slots are empty return an empty lists
        self.assertEqual([],self.timetable.occupied_slots())
        print(self.timetable.occupied_slots())

        lecturer = Lecturer('Benjamin Kommey',4564541,'Mr')
        course = Course('Embedded Systems','COE 361')

        section = Section('ED CoE',25,3,'Electrical and Electronics Engineering','Computer Engineering')
        c_item = CurriculumItem(section,course,lecturer)

        lecture = Lecture(c_item,60)
        
        ttslot =  TimetableSlot('Mon', Classroom('LT ', 45, 'PBOO2'),TimeSlot('8:00', '9:00'))
        ttslot1 =TimetableSlot('Mon', Classroom('LT ', 45, 'PBOO2'),TimeSlot('9:00', '10:00'))
        ttslot2 = TimetableSlot('Mon', Classroom('LT ', 45, 'PBOO2'),TimeSlot('10:00', '11:00'))
        ttslot3 = TimetableSlot('Mon', Classroom('LT ', 45, 'PBOO2'),TimeSlot('11:00', '12:00'))
        self.assertTrue(self.timetable.add_lecture(lecture,ttslot))
        self.assertTrue(self.timetable.add_lecture(lecture,ttslot1))
        self.assertTrue(self.timetable.add_lecture(lecture,ttslot2))
        self.assertTrue(self.timetable.add_lecture(lecture,ttslot3))

        self.assertEqual([ttslot,ttslot1,ttslot2,ttslot3],self.timetable.occupied_slots())
Пример #35
0
def collect_repos(auth, university, course, get_repos_filepath):

    call_dir = os.getcwd()
    repos_filepath = os.path.join(call_dir, get_repos_filepath,
                                  "%s_all_repos" % course)
    if not os.path.isdir(repos_filepath):
        os.makedirs(repos_filepath)
    else:
        if os.listdir(repos_filepath) != []:
            print "There are already repos in this folder, pleace \
                    remove them before cloning new into this folder"

            sys.exit(0)

    org = "%s-%s" % (university, course)
    url_orgs = 'https://api.github.com/orgs/%s' % (org)
    url_repos = 'https://api.github.com/repositories/'
    classroom = Classroom(auth, url_orgs)
    repos = classroom.get_repos()

    # Create the SSH links
    SSH_links = []
    for repo in repos:
        if course in repo['name'].encode('utf-8'):
            r = get(url_repos + str(repo['id']), auth=auth)
            SSH_links.append(r.json()['ssh_url'])

    # Change to destination folder
    os.chdir(repos_filepath)

    # Clone into the repos
    for SSH_link in SSH_links:
        result = os.system('git clone ' + SSH_link)
        #print(result)

    # Change back to call dir
    os.chdir(call_dir)
Пример #36
0
    parameters[key] = value[:-1]
course = parameters["course"] + "-"


# Get username and password for admin to classroom
admin = input('Username: '******'Password:'******'https://api.github.com/orgs/%s' % (org)
classroom = Classroom(auth, url_orgs)
list_teams = classroom.get_teams()
list_repos = classroom.get_repos()

# Find list of teams to delete
teams_to_delete = []
text = open(path.join(path.dirname(__file__), "Attendance", course + "students_base.txt"), 'r')
for line in text:
    line = re.split(r'\s*\/\/\s*', line)
    teams_to_delete.append(line[1])

# Delete teams
for team in list_teams:
   if team['name'].encode('utf-8') in teams_to_delete:
       print "Deleting ", team["name"]
       r = requests.delete(url + "/teams/" + str(team['id']), auth=auth)
    def __init__(self, auth, university, course, output_path):
        self.auth = auth
        self.university = university
        self.course = course
        #self.output_path = output_path

        self.org = "%s-%s" % (university, course)
        url_orgs = 'https://api.github.com/orgs/%s' % (self.org)

        # Need help functions from classroom
        self.classroom = Classroom(auth, url_orgs)

        # To look up information about students
        attendance_path = os.path.join(os.path.dirname(__file__), \
                                        'Attendance', '%s-students_base.txt' % course)
        if os.path.isfile(attendance_path):
            self.students_base_dict = self.get_students(codecs.open(attendance_path, 'r',
                                                        encoding='utf-8').readlines())
        else:
            attendance_path = input('There is no file %s, pleace provide the' % attendance_path \
                                     + 'filepath to where the student base file is located:')
            self.students_base_dict = self.get_students(open(attendance_path, 'r').readlines())

        # Header for each file
        self.header = "/"*50 + "\n// Name: %(name)s \n" + "// Email: %(email)s \n" + \
                       "// Username: %(username)s \n" + "// Repo: %(repo)s \n" + \
                        "// Editors: %(editors)s \n" + "/"*50 + "\n\n"
        self.header = self.header.encode('utf-8')

        # TODO: these should be accessible through default_parameters
        # User defined variables
        assignment_name = input('What is this assignment called: ')
        feedback_name_base = input('\nWhat are the base filename of your feedback ' \
                                    + 'files called, e.g.\nif you answer "PASSED" the ' \
                                    + 'program will look for "PASSED_YES \nand "PASSED_NO" ' \
                                    + '(case insensetive) : ').lower()

        # The files to look for
        self.file_feedback = [feedback_name_base + '_yes', feedback_name_base + '_no']
       
        # Create path
        original_dir = os.getcwd()
        if output_path == "":
            feedback_filepath = os.path.join(original_dir, "%s_all_feedbacks" % course)
        else:
            feedback_filepath = os.path.join(original_dir, output_path, \
                                              "%s_all_feedbacks" % course)

        # Path for feedback
        self.passed_path = os.path.join(feedback_filepath, assignment_name, 'PASSED')
        self.not_passed_path = os.path.join(feedback_filepath, assignment_name, 'NOT_PASSED')
        self.not_done_path = os.path.join(feedback_filepath, assignment_name)

        # Create folder structure
        try:
            os.makedirs(self.passed_path)
            os.makedirs(self.not_passed_path)
        except Exception as e:
            if os.listdir(self.passed_path) == [] and os.listdir(self.not_passed_path) == []:
                pass
            else:
                print("There are already collected feedbacks for %s." % assignment_name \
                       + " Remove these or copy them to another directory.") 
                sys.exit(1)
class Feedbacks:

    def __init__(self, auth, university, course, output_path):
        self.auth = auth
        self.university = university
        self.course = course
        #self.output_path = output_path

        self.org = "%s-%s" % (university, course)
        url_orgs = 'https://api.github.com/orgs/%s' % (self.org)

        # Need help functions from classroom
        self.classroom = Classroom(auth, url_orgs)

        # To look up information about students
        attendance_path = os.path.join(os.path.dirname(__file__), \
                                        'Attendance', '%s-students_base.txt' % course)
        if os.path.isfile(attendance_path):
            self.students_base_dict = self.get_students(codecs.open(attendance_path, 'r',
                                                        encoding='utf-8').readlines())
        else:
            attendance_path = input('There is no file %s, pleace provide the' % attendance_path \
                                     + 'filepath to where the student base file is located:')
            self.students_base_dict = self.get_students(open(attendance_path, 'r').readlines())

        # Header for each file
        self.header = "/"*50 + "\n// Name: %(name)s \n" + "// Email: %(email)s \n" + \
                       "// Username: %(username)s \n" + "// Repo: %(repo)s \n" + \
                        "// Editors: %(editors)s \n" + "/"*50 + "\n\n"
        self.header = self.header.encode('utf-8')

        # TODO: these should be accessible through default_parameters
        # User defined variables
        assignment_name = input('What is this assignment called: ')
        feedback_name_base = input('\nWhat are the base filename of your feedback ' \
                                    + 'files called, e.g.\nif you answer "PASSED" the ' \
                                    + 'program will look for "PASSED_YES \nand "PASSED_NO" ' \
                                    + '(case insensetive) : ').lower()

        # The files to look for
        self.file_feedback = [feedback_name_base + '_yes', feedback_name_base + '_no']
       
        # Create path
        original_dir = os.getcwd()
        if output_path == "":
            feedback_filepath = os.path.join(original_dir, "%s_all_feedbacks" % course)
        else:
            feedback_filepath = os.path.join(original_dir, output_path, \
                                              "%s_all_feedbacks" % course)

        # Path for feedback
        self.passed_path = os.path.join(feedback_filepath, assignment_name, 'PASSED')
        self.not_passed_path = os.path.join(feedback_filepath, assignment_name, 'NOT_PASSED')
        self.not_done_path = os.path.join(feedback_filepath, assignment_name)

        # Create folder structure
        try:
            os.makedirs(self.passed_path)
            os.makedirs(self.not_passed_path)
        except Exception as e:
            if os.listdir(self.passed_path) == [] and os.listdir(self.not_passed_path) == []:
                pass
            else:
                print("There are already collected feedbacks for %s." % assignment_name \
                       + " Remove these or copy them to another directory.") 
                sys.exit(1)

    def __call__(self):
        print("\nLooking for feedbacks, this may take some time ...\n")
        repos = self.classroom.get_repos()    
        not_done = []

        for repo in repos:
            # Assumes that no repo has the same naming convension
            if self.course + "-" in repo['name'].encode('utf-8'):

                # Get sha from the last commit
                url_commits = repo['commits_url'][:-6]
                sha = get(url_commits, auth=self.auth).json()[0]['sha']

                # Get tree
                self.url_trees = repo['trees_url'][:-6]
                r = get(self.url_trees + '/' + sha, auth=self.auth)

                # Get feedback file
                success, contents, status, path, extension = self.find_file(r.json()['tree'])

                # Get infomation about user and the file
                # Need some extra tests since multiple teams can have
                # access to the same repo.
                r = get(repo['teams_url'], auth=self.auth)
                for i in range(len(r.json())):
                    try:
                        personal_info = self.students_base_dict[r.json()[i]['name'].encode('utf-8')]
                        personal_info['repo'] = repo['name'].encode('utf-8')
                        break
                    except Exception as e:
                        if i == len(r.json()) - 1:
                            print("There are no owners (team) of this repo " \
                                  +  "matching student base. " +
                                  r.json()[i]['name'])
                            personal_info['name'] = repo['name']

                if success:
                    # Check if there is reason to belive that the user have cheated
                    personal_info['editors'] = ", ".join(self.get_correctorss(path, repo))
                    
                    #TODO: Store this feedback in a list of potential cheaters

                    # Write feedback with header to file
                    # Work around for files with different
                    # formats, could be fixed with google forms.
                    try:
                        text = self.header % personal_info
                        text += contents.decode('utf-8')
                    except UnicodeDecodeError as e:
                        if 'ascii' in e:
                            for key, value in personal_info.iteritems():
                                print value
                                personal_info[key] = value.decode('utf-8')
                            text = self.header % personal_info
                        elif 'utf-8' in e:
                            text += contents.decode('latin1')
                    except Exception as e:
                        print("Could not get the contents of %(name)s feedback file. Error:" \
                                 % personal_info)
                        print(e)

                    filename = personal_info['name'].replace(' ', '_') + '.' + extension
                    folder = self.passed_path if status == 'yes' else self.not_passed_path
                    folder = os.path.join(folder, filename)
                    feedback = codecs.open(folder, 'w', encoding='utf-8')
                    feedback.write(text)
                    feedback.close()

                # No feedback
                else:
                    not_done.append(personal_info)

        # TODO: Only write those how where pressent at group and didn't get feedback
        #       now it just writes everyone how has not gotten any feedback.
        text = "Students that didn't get any feedbacks\n"
        text += "Name   //  username    //  email\n"
        for student in not_done:
            text += "%(name)s // %(username)s // %(email)s\n" % student 
        not_done_file = codecs.open(os.path.join(self.not_done_path, 'No_feedback.txt'), 'w',
                                     encoding='utf-8')
        not_done_file.write(text)
        not_done_file.close()

        number_of_feedbacks = len(repos) - len(not_done)
        print("\nFetched feedback from %s students and %s have not gotten any feedback" % \
                (number_of_feedbacks, len(not_done)))

    def get_students(self, text):
        student_dict = {}
        for line in text[1:]:
            pressent, name, username, email, rank = re.split(r"\s*\/\/\s*", line.replace('\n', ''))
            student_dict[name.encode('utf-8')] = {'name': name, 
                                                   'username': username, 'email': email}
        return student_dict

    def find_file(self, tree):
        for file in tree:
            # Explore the subdirectories recursively
            if file['type'].encode('utf-8') == 'tree':
                r = get(file['url'], auth=self.auth)
                success, contents, status, path, extension = self.find_file(r.json()['tree'])
                if success:
                    return success, contents, status, path, extension

            # Check if the files in the folder match file_feedback
            if file['path'].split(os.path.sep)[-1].split('.')[0].lower() in self.file_feedback:
                # Get filename and extension
                if '.' in  file['path'].split(os.path.sep)[-1]:
                    file_name, extension = file['path'].split(os.path.sep)[-1].lower().split('.')
                else:
                    file_name = file['path'].split(os.path.sep)[-1].lower()
                    extension = 'txt'

                r = get(file['url'], auth=self.auth)
                return True, base64.b64decode(r.json()['content']), \
                        file_name.split('_')[-1], file['path'], extension

        # If file not found
        return False, "", "", "", ""

    def get_correctors(self, path, repo):
        url_commit = 'https://api.github.com/repos/%s/%s/commits' % (self.org, repo['name'])
        r = get(url_commit, auth=self.auth, params={'path': path})
        # TODO: Change commiter with author?
        editors = [commit['commit']['author']['name'] for commit in r.json()]
        return editors