Пример #1
0
 def __loadFromFile(self):
     try:
         f = open(self.__f_name, "r")
         line = f.readline().strip()
         while line != "":
             attrs = line.split(',')
             attrs[3].strip(' ')
             attrs[3] = attrs[3].split('-')
             attrs[4].strip(' ')
             attrs[4] = attrs[4].split('-')
             attrs[5].strip(' ')
             if not attrs[5] == " False":
                 attrs[5] = attrs[5].split('-')
                 b = Rental(int(attrs[0]), int(attrs[1]), int(attrs[2]),
                            date(int(attrs[3][0]), int(attrs[3][1]), int(attrs[3][2])),
                            date(int(attrs[4][0]), int(attrs[4][1]), int(attrs[4][2])),
                            date(int(attrs[5][0]), int(attrs[5][1]), int(attrs[5][2])))
             else:
                 b = Rental(int(attrs[0]), int(attrs[1]), int(attrs[2]),
                            date(int(attrs[3][0]), int(attrs[3][1]), int(attrs[3][2])),
                            date(int(attrs[4][0]), int(attrs[4][1]), int(attrs[4][2])),
                            False)
             Repository.add(self, b)
             line = f.readline().strip()
     except IOError:
         raise RepositoryException("Can't load data from file " + self.__f_name + "!")
     f.close()
Пример #2
0
 def __init__(self, fileName):
     self.__repository = Repository(fileName)
     network, [parameters, sizePopulation] = self.__repository.getData()
     self.__ga = GA(sizePopulation, parameters, network)
     self.__ga.initialisation()
     self.__ga.evaluation()
     self.__network = network
    def __init__(
            self, storageType: str,
            studentRepositoryLocation: str,
            gradeRepositoryLocation: str,
            assignmentRepositoryLocation: str
    ):
        if storageType == 'memory':
            self.__studentRepository = Repository(Student)
            self.__gradeRepository = Repository(Grade)
            self.__assignmentRepository = Repository(Assignment)
        elif storageType == 'text':
            self.__studentRepository = TextFileRepository(Student, studentRepositoryLocation)
            self.__gradeRepository = TextFileRepository(Grade, gradeRepositoryLocation)
            self.__assignmentRepository = TextFileRepository(Assignment, assignmentRepositoryLocation)
        elif storageType == 'binary':
            self.__studentRepository = BinaryRepository(Student, studentRepositoryLocation)
            self.__gradeRepository = BinaryRepository(Grade, gradeRepositoryLocation)
            self.__assignmentRepository = BinaryRepository(Assignment, assignmentRepositoryLocation)
        elif storageType == 'json':
            self.__studentRepository = JsonRepository(Student, studentRepositoryLocation)
            self.__gradeRepository = JsonRepository(Grade, gradeRepositoryLocation)
            self.__assignmentRepository = JsonRepository(Assignment, assignmentRepositoryLocation)
        elif storageType == 'sql':
            connection = MySQLConnector().getConnection()

            self.__studentRepository = MySQLRepository(Student, studentRepositoryLocation, connection)
            self.__gradeRepository = MySQLRepository(Grade, gradeRepositoryLocation, connection)
            self.__assignmentRepository = MySQLRepository(Assignment, assignmentRepositoryLocation, connection)

        self.__repositories = {
            Student: self.__studentRepository,
            Grade: self.__gradeRepository,
            Assignment: self.__assignmentRepository
        }
Пример #4
0
    def solve(self, noChrom, noIter, cross, mutation):
        for i in range(0, noChrom):
            self.repo.add(Chromosome(self.problParam))

        self.repo.sort()
        p = Repository()
        #print(self.repo.get(0))
        for i in range(0, noIter):
            repo1 = Repository()
            #repo1.add(self.repo.get(0))
            for j in range(0, noChrom):
                if random.uniform(0, 1) <= cross:
                    parents = self.selectParents(noChrom)
                    c = parents[0].crossover(parents[1])
                    if random.uniform(0, 1) <= mutation:
                        c.mutation()
                else:
                    c = self.repo.get(j).clone()
                    if random.uniform(0, 1) <= mutation:
                        c.mutation()
                repo1.add(c)
            repo1.sort()
            self.repo = repo1
            p.add(self.repo.get(0))
        return p
 def _loadFile(self):
     f = open(self._fileName, "r")
     line = f.readline().strip()
     while len(line) > 2:
         tok = line.split(";")
         client = Client(int(tok[0]), tok[1])
         Repository.store(self, client)
         line = f.readline().strip()
Пример #6
0
 def setUp(self):
     TestCase.setUp(self)
     self.controller = ControllerGrade(Repository(), Repository(),
                                       Repository(), ValidatorGrade(),
                                       UndoController())
     # put here test logic
     self.controller.add_grade(1, 1, 1, 9)
     self.controller.add_grade(2, 1, 2, 4)
     self.controller.add_grade(3, 1, 3, 3)
 def _loadFile(self):
     try:
         f = open(self._fileName, "rb")
         res = pickle.load(f)
         for c in res:
             Repository.add(self, c)
     except EOFError:
         return []
     except IOError as e:
         raise RepositoryError(str(e))
Пример #8
0
 def reading(self):
     file = open("/Users/ecaterinacarazan/PycharmProjects/files/student.txt", "r")
     lines = file.read().splitlines()
     for line in lines:
         list = line.split(", ")
         stud = Student(int(list[0]), list[1], int(list[2]))
         for s in Repository.get_all(self):
             if s.get_id() == int(list[0]):
                 raise ControllerException("Can not add student with same id")
         Repository.add_item(self, stud)
     file.close()
Пример #9
0
 def reading(self):
     file = open("/Users/AndiD//Documents/Eclipse/lab57/student.txt", "r")
     lines = file.read().splitlines()
     for line in lines:
         list = line.split(", ")
         stud = Student(int(list[0]), list[1], int(list[2]))
         for s in Repository.get_all(self):
             if s.get_id() == int(list[0]):
                 raise ControllerException("Can not add student with same id")
         Repository.add_item(self, stud)
     file.close()
Пример #10
0
 def __init__(self, fileName, objectType):
     Repository.__init__(self)  # initialising the repository with its list
     self._fileName = fileName  # the filename of the table that will be created
     self._objectType = objectType  # The object type e.g : Student, Discipline etc..
     self._conn = sqlite3.connect(
         "DATABASE.db")  # Creating the connection to the database
     self._c = self._conn.cursor(
     )  # Getting the cursor for the database ( like a real cursor )
     self._createTable()  # Creating the table if not created
     self._readFromDB(
     )  # Reading from the table ( if there's any input data to be read )
Пример #11
0
 def reading(self):
     file = open("/Users/AndiD//Documents/Eclipse/lab57/assignment.txt", "r")
     lines = file.read().splitlines()
     for line in lines:
         list = line.split(", ")
         assign = Assignment(int(list[0]), list[1], list[2])
         for asgn in Repository.get_all(self):
             if asgn.get_id() == int(list[0]):
                 raise ControllerException("Can not add assignment with same id")
         Repository.add_item(self, assign)
     file.close()
Пример #12
0
 def reading(self):
     file = open("/Users/ecaterinacarazan/PycharmProjects/files/assignment.txt", "r")
     lines = file.read().splitlines()
     for line in lines:
         list = line.split(", ")
         assign = Assignment(int(list[0]), list[1], list[2])
         for asgn in Repository.get_all(self):
             if asgn.get_id() == int(list[0]):
                 raise ControllerException("Can not add assignment with same id")
         Repository.add_item(self, assign)
     file.close()
Пример #13
0
 def setUp(self):
     # setUp method will be executed before every test
     TestCase.setUp(self)
     self.repository = Repository()
     # add mock students to repo
     stud1 = Student(1, "A", 1)
     stud2 = Student(2, "B", 2)
     stud3 = Student(3, "C", 3)
     self.repository.add_item(stud1)
     self.repository.add_item(stud2)
     self.repository.add_item(stud3)
Пример #14
0
 def __loadFromFile(self):
     try:
         f = open(self.__f_name, "r")
         line = f.readline().strip()
         while line != "":
             attrs = line.split(',')
             c = Client(int(attrs[0]), attrs[1])
             Repository.add(self, c)
             line = f.readline().strip()
     except IOError:
         raise RepositoryException("Can't load data from file " + self.__f_name + "!")
     f.close()
Пример #15
0
 def _loadFile(self):
     try:
         f = open(self._fileName, "rb")
         res = pickle.load(f)
         while res != "":
             r = Rental(int(res.id), int(res.movie), int(res.client), res.rentedDate, res.dueDate, res.returnedDate)
             Repository.store(self, r)
             res = pickle.load(f)
     except EOFError:
         return []
     except IOError as e:
         raise RepositoryError(str(e))
Пример #16
0
 def reading(self):
     file = open("/Users/AndiD//Documents/Eclipse/lab57/student.txt", "r")
     lines = file.read().splitlines()
     for line in lines:
         list = line.split(", ")
         stud = Student(int(list[0]), list[1], int(list[2]))
         for s in Repository.get_all(self):
             if s.get_id() == int(list[0]):
                 raise ControllerException(
                     "Can not add student with same id")
         Repository.add_item(self, stud)
     file.close()
Пример #17
0
 def _loadFromFile(self):
     try:
         f = open(self._fName, "r")
     except IOError:
         return
     line = f.readline().strip()
     while line != "":
         t = line.split(";")
         c = Client(int(t[0]), t[1], t[2])
         Repository.store(self, c)
         line = f.readline().strip()
     f.close()
Пример #18
0
 def _loadFile(self):
     try:
         f = open(self._fileName, "rb")
         res = pickle.load(f)
         while res != "":
             m = Movie(int(res.id), res.title, res.description, res.genre)
             Repository.store(self, m)
             res = pickle.load(f)
     except EOFError:
         return []
     except IOError as e:
         raise RepositoryError(str(e))
 def _loadFile(self):
     f = open(self._fileName, "r")
     line = f.readline().strip()
     while len(line) > 2:
         tok = line.split(";")
         d1 = tok[3].split("-")
         d2 = tok[4].split("-")
         d3 = tok[5].split("-")
         rental = Rental(int(tok[0]), int(tok[1]), int(tok[2]), date(int(d1[0]), int(d1[1]), int(d1[2])),
                         date(int(d2[0]), int(d2[1]), int(d2[2])), date(int(d3[0]), int(d3[1]), int(d3[2])))
         Repository.store(self, rental)
         line = f.readline().strip()
Пример #20
0
def undoExampleMedium():
    undoController = UndoController()
    clientRepo = Repository()
    carRepo = Repository()

    '''
    Start rental Controller
    '''
    rentRepo = Repository()
    rentValidator = RentalValidator()
    rentController = RentalController(undoController, rentValidator, rentRepo, carRepo, clientRepo)
    
    '''
    Start client Controller
    '''
    clientValidator = ClientValidator()
    clientController = ClientController(undoController, rentController, clientValidator, clientRepo)
    
    '''
    Start car Controller
    '''
    carValidator = CarValidator()
    carController = CarController(undoController, rentController, carValidator, carRepo)

    '''
    We add 3 clients
    '''
    clientSophia = clientController.create(103, "2990511035588", "Sophia")
    clientCarol = clientController.create(104, "2670511035588", "Carol")
    clientBob = clientController.create(105, "2590411035588", "Bob")    
    printReposWithMessage("We added 3 clients", clientRepo, None, None)

    '''
    We delete 2 of the clients
    '''
    clientController.delete(103)
    clientController.delete(105)
    printReposWithMessage("Deleted Sophia and Bob", clientRepo, None, None)

    '''
    We undo twice
    '''
    undoController.undo()
    printReposWithMessage("1 undo, so Bob is back", clientRepo, None, None)
    undoController.undo()
    printReposWithMessage("Another undo, so Sophia is back too", clientRepo, None, None)
    
    '''
    We redo once
    '''
    undoController.redo()
    printReposWithMessage("1 redo, so Sophia is again deleted", clientRepo, None, None)
Пример #21
0
 def reading(self):
     file = open("/Users/ecaterinacarazan/PycharmProjects/files/grade.txt", "r")
     lines = file.read().splitlines()
     for line in lines:
         list = line.split(", ")
         student = self.repo_stud.get_by_id(int(list[1]))
         assign = self.repo_assign.get_by_id(int(list[2]))
         grade = Grade(int(list[0]), student, assign, int(list[3]))
         for g in Repository.get_all(self):
             if grade.get_id() == g.get_id():
                 raise ControllerException("Can not add grade with same id")
             Repository.add_item(self, grade)
     file.close()
Пример #22
0
 def __loadFromFile(self):
     try:
         f = open(self.__fName, "r")
         line = f.readline().strip()
         while line != "":
             params = line.split(",")
             stud = Student(params[0], params[1], params[2])
             Repository.store(self, stud)
             line = f.readline().strip()
     except IOError:
         pass
     finally:
         f.close()
Пример #23
0
def testRepository():
	repository = Repository()
	holiday1 = Holiday(0, "Madrid", "seaside", 342)
	holiday2 = Holiday(1, "Quebec", "city-break", 342)	

	assert repository.addElement(holiday1) == True
	assert repository.addElement(holiday1) == False
	assert repository.addElement(holiday2) == True

	assert len(repository.getElements()) > 0
	assert len(repository.getElements()) == 2

	return True
Пример #24
0
 def reading(self):
     file = open("/Users/AndiD//Documents/Eclipse/lab57/grade.txt", "r")
     lines = file.read().splitlines()
     for line in lines:
         list = line.split(", ")
         student = self.repo_stud.get_by_id(int(list[1]))
         assign = self.repo_assign.get_by_id(int(list[2]))
         grade = Grade(int(list[0]), student, assign, int(list[3]))
         for g in Repository.get_all(self):
             if grade.get_id() == g.get_id():
                 raise ControllerException("Can not add grade with same id")
             Repository.add_item(self, grade)
     file.close()
Пример #25
0
 def _loadFile(self):
     try:
         f = open(self._fileName, "r")
         line = f.readline().strip()
         while len(line) > 2:
             tok = line.split(";")
             movie = Movie(int(tok[0]), tok[1], tok[2], tok[3])
             Repository.store(self, movie)
             line = f.readline().strip()
     except IOError as e:
         raise RepositoryError(str(e))
     finally:
         f.close()
Пример #26
0
 def reading(self):
     file = open(
         "/Users/ecaterinacarazan/PycharmProjects/files/assignment.txt",
         "r")
     lines = file.read().splitlines()
     for line in lines:
         list = line.split(", ")
         assign = Assignment(int(list[0]), list[1], list[2])
         for asgn in Repository.get_all(self):
             if asgn.get_id() == int(list[0]):
                 raise ControllerException(
                     "Can not add assignment with same id")
         Repository.add_item(self, assign)
     file.close()
Пример #27
0
    def testRepo(self):
        repo = Repository()
        assert repo.add(Student('1', 'Mihai Ionut', 10, 10)) == False
        assert repo.add(Student('2', 'Mihai Ionut', 10, 10)) == False
        assert repo.add(Student('3', 'Mihai Ionut', 10, 10)) == False

        repo.addBonus(Student('1', 'Mihai', 13, 9), 1)
        repo.addBonus(Student('2', 'Ionut', 5, 8), 1)
        for i in repo.getAll():
            if i.getID() == 1:
                assert i.getGrade() == 10
            if i.getID() == 2:
                assert i.getGrade() == 9

        assert len(repo.getAll()) == 10
Пример #28
0
 def testUpdateMovieParameters_ValidInput_UpdateParameter(self):
     repo = Repository()
     service = MovieService(repo)
     service.add_movie(1, 'Title', 'Descr', 'Gen')
     service.update_movie_parameters(1, 'title', 'New Title')
     movie = repo.get_elements_list[1]
     self.assertEqual(movie.title, 'New Title')
Пример #29
0
 def testUpdateClientParameter_ValidInput_UpdateParameter(self):
     repo = Repository()
     service = ClientService(repo)
     service.add_client(1, 'New Client')
     service.update_client_parameters(1, 'name', 'New Name')
     client = repo.get_elements_list[1]
     self.assertEqual(client.name, 'New Name')
Пример #30
0
 def writing(self):
     file = open("/Users/AndiD//Documents/Eclipse/lab57/student.txt", "w")
     list = Repository.get_all(self)
     for stud in list:
         string = str(stud.get_id()) + ", " + str(stud.get_name()) + ", " + str(stud.get_group())
         file.write(string + "\n")
     file.close()
Пример #31
0
 def _storeToFile(self):
     f = open(self._fName, "w")
     rentals = Repository.getAll(self)
     for r in rentals:
         rl = str(r.getId()) + ";" + str(r.getClient().getId()) + ";" + str(r.getCar().getId()) + ";" + r.getStart().strftime("%Y-%m-%d") + ";" + r.getEnd().strftime("%Y-%m-%d") + "\n"
         f.write(rl)
     f.close()
Пример #32
0
 def writing(self):
     file = open("/Users/ecaterinacarazan/PycharmProjects/files/assignment.txt", "w")
     list = Repository.get_all(self)
     for assign in list:
         string = str(assign.get_id()) + ", " + str(assign.get_deadline()) + ", " + str(assign.get_description())
         file.write(string + "\n")
     file.close()
Пример #33
0
 def _loadFromFile(self):
     try:
         f = open(self._fName, "r")
     except IOError:
         return
     line = f.readline().strip()
     while line != "":
         t = line.split(";")
         
         car = self._carRepo.find(int(t[1]))
         client = self._clientRepo.find(int(t[2]))
         
         c = Rental(t[0], datetime.strptime(t[3], "%Y-%m-%d"), datetime.strptime(t[4], "%Y-%m-%d"), client, car)
         Repository.store(self, c)
         line = f.readline().strip()
     f.close()
Пример #34
0
class Service:
    def __init__(self, fileName):
        self.__repository = Repository(fileName)
        network, [parameters, sizePopulation] = self.__repository.getData()
        self.__ga = GA(sizePopulation, parameters, network)
        self.__ga.initialisation()
        self.__ga.evaluation()
        self.__network = network

    def create_solution(self, generations):
        for gen in range(generations):
            self.__ga.one_generation_elitism()
            best = self.__ga.best_chromosome()
            print(
                str(gen + 1) + " cu cel mai bun cromozom:\n" +
                str(best.representation) + "\nCu fitness: " +
                str(best.fitness) + " si " + str(best.communities) +
                " comunitati.")

        best = self.__ga.best_chromosome()
        rez = [
            best.fitness, best.communities, best.representation,
            self.__network["mat"]
        ]
        return rez
Пример #35
0
 def _storeToFile(self):
     f = open(self._fName, "w")
     cars = Repository.getAll(self)
     for c in cars:
         cf = str(c.getId()) + ";" + c.getCNP() + ";" + c.getName() + "\n"
         f.write(cf)
     f.close()
Пример #36
0
 def writing(self):
     file = open("/Users/ecaterinacarazan/PycharmProjects/files/student.txt", "w")
     list = Repository.get_all(self)
     for stud in list:
         string = str(stud.get_id()) + ", " + str(stud.get_name()) + ", " + str(stud.get_group())
         file.write(string + "\n")
     file.close()
Пример #37
0
class ClientTestCase(unittest.TestCase):
    def setUp(self):
        self.v = ClientValidator()
        self.c = Client("1", "aaa")
        self.client = Repository()

    def testClient(self):
        self.assertTrue(self.v.validate, self.c)
        self.c.name = "bbb"
        self.assertTrue(self.v.validate, self.c.name == "bbb")
        self.c.name = ""
        self.assertRaises(ValidatorException, self.v.validate, self.c)
        z = Client("1", "Anna")
        self.client.add(z)
        self.client.remove(z)
        self.assertEqual(len(self.client.getAll()), 0)
Пример #38
0
 def writing(self):
     file = open("/Users/AndiD//Documents/Eclipse/lab57/assignment.txt", "w")
     list = Repository.get_all(self)
     for assign in list:
         string = str(assign.get_id()) + ", " + str(assign.get_deadline()) + ", " + str(assign.get_description())
         file.write(string + "\n")
     file.close()
Пример #39
0
 def _storeToFile(self):
     f = open(self._fName, "w")
     cars = Repository.getAll(self)
     for c in cars:
         cf = str(c.getId()) + ";" + c.getLicenseNumber() + ";" + c.getMake() + ";" + c.getModel() + "\n"
         f.write(cf)
     f.close()
Пример #40
0
class RepositoryTest(unittest.TestCase):
    '''
    Unit test case example for Repository
    '''
    def setUp(self):
        self._repo = Repository()
    
    def testRepo(self):
        self.assertEqual(len(self._repo), 0)
        c = Client("1", "1840101223366", "Anna")
        self._repo.store(c)
        self.assertEqual(len(self._repo), 1)
        self.assertRaises(RepositoryException , self._repo.store, c)
        
        c = Client("2", "1840101223366", "Anna")
        self._repo.store(c)
        self.assertEqual(len(self._repo), 2)
        '''
Пример #41
0
 def writing(self):
     file = open("/Users/ecaterinacarazan/PycharmProjects/files/grade.txt", "w")
     list = Repository.get_all(self)
     for grade in list:
         stud_id = grade.get_student().get_id()
         assign_id = grade.get_assignment().get_id()
         string = str(grade.get_id()) + ", " + str(stud_id) + ", " + str(assign_id) + ", " + str(grade.get_grade())
         file.write(string + "\n")
     file.close()
Пример #42
0
def testController():
	repository = Repository()	
	holiday1 = Holiday(0, "Madrid", "seaside", 342)
	holiday2 = Holiday(1, "Quebec", "city-break", 342)
	holiday3 = Holiday(2, "Quebec", "seaside", 333)	
	controller = HolidayController(repository)

	assert repository.addElement(holiday1) == True
	assert repository.addElement(holiday2) == True
	assert repository.addElement(holiday3) == True

	assert len(controller.getHolidays())	== 3
	assert len(controller.getAllResorts()) 	== 2
	assert len(controller.getAllTypes())	== 2

	assert len(controller.searchByResort("Quebec")) == 2
	assert len(controller.searchByResort("Madrid")) == 1

	assert len(controller.searchByType("seaside"))	   == 2
	assert len(controller.searchByType("city-break"))  == 1

	assert controller.loadFromFile("database.txt") == True

	return True
Пример #43
0
 def __init__(self):
     Repository.__init__(self)
     self._loadFromFile()
Пример #44
0
 def delete(self, objectId):
     client = Repository.delete(self, objectId)
     self._storeToFile()
     return client
Пример #45
0
 def update(self, e):
     Repository.update(self, e)
     self._storeToFile()
Пример #46
0
 def store(self, e):
     Repository.store(self, e)
     self._storeToFile()
Пример #47
0
class TestRepository(unittest.TestCase):
    def setUp(self):
        # setUp method will be executed before every test
        TestCase.setUp(self)
        self.repository = Repository()
        # add mock students to repo
        stud1 = Student(1, "A", 1)
        stud2 = Student(2, "B", 2)
        stud3 = Student(3, "C", 3)
        self.repository.add_item(stud1)
        self.repository.add_item(stud2)
        self.repository.add_item(stud3)

    def test_add(self):
        self.repository.add_item(Student(4, "D", 4))
        self.assertEqual(len(self.repository.get_all()), 4)

    def test_remove(self):
        self.repository.remove_item(1)
        self.assertEqual(len(self.repository.get_all()), 2)
        # check for exception call
        try:
            self.repository.remove_item(4)
        except CustomException as e:
            self.assertEqual(e.get_msg(), "No such item")

    def test_update_student(self):
        self.repository.update_item(Student(1, "D", 2))
        updated_student = self.repository.get_by_id(1)
        self.assertEqual(updated_student.get_name(), "D")
        # check exception case
        try:
            self.repository.update_item(Student(4, "D", 4))
        except CustomException as e:
            self.assertEqual(e.get_msg(), "No item for update found")

    def test_get_by_id(self):
        stud1 = self.repository.get_by_id(1)
        self.assertEqual(stud1.get_name(), "A")
        stud2 = self.repository.get_by_id(4)
        self.assertIsNone(stud2)
Пример #48
0
 def delete(self, objectId):
     Repository.delete(self, objectId)
     self._storeToFile()
Пример #49
0
 def __init__(self):
     Repository.__init__(self)
Пример #50
0
 def __init__(self, clientRepo, carRepo):
     Repository.__init__(self)
     self._carRepo = carRepo
     self._clientRepo = clientRepo
     self._loadFromFile()
Пример #51
0
def undoExample():
    """
    An example for doing multiple undo operations. 
    This is a bit more difficult than in Lab2-4 due to the fact that there are now several controllers, 
    and each of them can perform operations that require undo support.
     
    Follow the code below and figure out how it works!
    """
    
    undoController = UndoController()
    
    '''
    Start client Controller
    '''
    clientRepo = Repository()
    clientValidator = ClientValidator()
    clientController = ClientController(undoController, clientValidator, clientRepo)
    
    '''
    Start car Controller
    '''
    carRepo = Repository()
    carValidator = CarValidator()
    carController = CarController(undoController, carValidator, carRepo)
    
    '''
    Start rental Controller
    '''
    rentRepo = Repository()
    rentValidator = RentalValidator()
    rentController = RentalController(undoController, rentValidator, rentRepo, carRepo, clientRepo)
    
    print("---> Initial state of repositories")
    print(clientRepo)
    print(carRepo)
    print(rentRepo)
    
    '''
    We add a client, a new car as well as a rental
    '''
    clientController.create(103, "1900102035588", "Dale")
    carController.create(201, "CJ 02 ZZZ", "Dacia", "Sandero")
    
    rentStart = datetime.strptime("2015-11-26", "%Y-%m-%d")
    rentEnd = datetime.strptime("2015-11-30", "%Y-%m-%d")
    rentController.createRental(301, clientRepo.find(103), carRepo.find(201), rentStart, rentEnd)
    
    print("---> We added a client, a new car and a rental")
    print(clientRepo)
    print(carRepo)
    print(rentRepo)
    
    '''
    Now undo the performed operations, one by one
    '''
    undoController.undo()
    print("---> After 1 undo")
    print(clientRepo)
    print(carRepo)
    print(rentRepo)
    
    
    undoController.undo()
    print("---> After 2 undos")
    print(clientRepo)
    print(carRepo)
    print(rentRepo)
    
    undoController.undo()
    print("---> After 3 undos")
    print(clientRepo)
    print(carRepo)
    print(rentRepo)
Пример #52
0
def statisticsExample():
    """
    An example for the creation of statistics.
    Several cars, clients and rentals are created and then a statistics is calculated over them.
    
    Follow the code below and figure out how it works!
    """
    undoController = UndoController()
    
    '''
    Start client Controller
    '''
    clientRepo = Repository()
    clientValidator = ClientValidator()
    clientController = ClientController(undoController, clientValidator, clientRepo)
    
    clientController.create(100, "1820203556699", "Aaron")
    clientController.create(101, "2750102885566", "Bob")
    clientController.create(102, "1820604536579", "Carol")

    # We name the instances so it's easier to create some test values later
    aaron = clientRepo.find(100)
    bob = clientRepo.find(101)
    carol = clientRepo.find(102)

    '''
    Start car Controller
    '''
    carRepo = Repository()
    carValidator = CarValidator()
    carController = CarController(undoController, carValidator, carRepo)

    carController.create(200, "CJ 01 AAA", "Audi", "A3")
    carController.create(201, "CJ 01 BBB", "Audi", "A4")
    carController.create(202, "CJ 01 CCC", "Audi", "A5")
    carController.create(203, "CJ 01 DDD", "Audi", "A6")

    audiA3 = carRepo.find(200)
    audiA4 = carRepo.find(201)
    audiA5 = carRepo.find(202)
    audiA6 = carRepo.find(203)

    '''
    Start rental Controller
    '''
    rentRepo = Repository()
    rentValidator = RentalValidator()
    rentController = RentalController(undoController, rentValidator, rentRepo, carRepo, clientRepo)

    rentController.createRental(300, aaron, audiA3, datetime.strptime("2015-11-20", "%Y-%m-%d"), datetime.strptime("2015-11-22", "%Y-%m-%d"))
    rentController.createRental(301, carol, audiA5, datetime.strptime("2015-11-24", "%Y-%m-%d"), datetime.strptime("2015-11-25", "%Y-%m-%d"))
    rentController.createRental(302, carol, audiA6, datetime.strptime("2015-12-10", "%Y-%m-%d"), datetime.strptime("2015-12-12", "%Y-%m-%d"))
    rentController.createRental(303, aaron, audiA4, datetime.strptime("2015-11-21", "%Y-%m-%d"), datetime.strptime("2015-11-25", "%Y-%m-%d"))
    rentController.createRental(304, aaron, audiA3, datetime.strptime("2015-11-24", "%Y-%m-%d"), datetime.strptime("2015-11-27", "%Y-%m-%d"))
    rentController.createRental(305, bob, audiA5, datetime.strptime("2015-11-26", "%Y-%m-%d"), datetime.strptime("2015-11-27", "%Y-%m-%d"))
    rentController.createRental(306, carol, audiA6, datetime.strptime("2015-12-15", "%Y-%m-%d"), datetime.strptime("2015-12-20", "%Y-%m-%d"))
    rentController.createRental(307, bob, audiA4, datetime.strptime("2015-12-01", "%Y-%m-%d"), datetime.strptime("2015-12-10", "%Y-%m-%d"))
    rentController.createRental(308, carol, audiA4, datetime.strptime("2015-12-11", "%Y-%m-%d"), datetime.strptime("2015-12-15", "%Y-%m-%d"))
    rentController.createRental(309, aaron, audiA5, datetime.strptime("2015-11-28", "%Y-%m-%d"), datetime.strptime("2015-12-02", "%Y-%m-%d"))

    for cr in rentController.mostRentedCars(): 
        print (cr)
Пример #53
0
 def update(self, item):
     self._history.append(deepcopy(self._items))
     Repository.update_item(self, item)
     self._history = self._history[0:self._index + 2]
     self._index = len(self._history) - 1
     self._history.pop()