コード例 #1
0
    def setUp(self):
        self.person_repository = Repository(PersonValidator)
        self.person_controller = PersonController(self.person_repository)

        self.activity_repository = Repository(ActivityValidator)
        self.activity_controller = ActivityController(self.activity_repository)

        self.repository = Repository(ParticipationValidator)
        self.controller = ParticipationController(self.repository,
                                                  self.person_controller,
                                                  self.activity_controller)

        # add test data
        self.person_controller.add(1, "John", "1234567890", "street 1")
        self.person_controller.add(2, "John", "1234567890", "street 1")
        self.person_controller.add(3, "John", "1234567890", "street 1")

        self.activity_controller.add(1, Common.convert_to_date("15.11.2016"),
                                     Common.convert_to_time("06:03"),
                                     "description")
        self.activity_controller.add(2, Common.convert_to_date("16.11.2016"),
                                     Common.convert_to_time("06:03"),
                                     "description")
        #self.activity_controller.add(3,Common.convert_to_date("16.11.2016"),Common.convert_to_time("06:04"),"description")
        #self.activity_controller.add(4,Common.convert_to_date("16.11.2016"),Common.convert_to_time("06:06"),"description")

        return super().setUp()
コード例 #2
0
    def testRentBook(self):
        client1 = Client(1, "Name1")
        client2 = Client(2, "Name2")

        book1 = Book(1, "Title", "Description", "Author")
        book2 = Book(2, "Title1", "Description1", "Author1")

        clientRepo = Repository()
        bookRepo = Repository()
        functions = ClientController(clientRepo, Statistics(clientRepo))
        functiom = BookController(bookRepo, Statistics(bookRepo))

        functions.addClient(client2.getId(), client2.getName())
        functions.addClient(client1.getId(), client1.getName())

        functiom.addBook(book1.getId(), book1.getTitle(), book1.getDescription(), book1.getAuthor())
        functiom.addBook(book2.getId(), book2.getTitle(), book2.getDescription(), book2.getAuthor())
        rentalRepo = Repository()
        functionsr = RentalController(bookRepo, clientRepo, rentalRepo, Statistics(rentalRepo))

        msg1 = functionsr.rentBook(book1.getId(), client1.getId(), createDateFromString("23.11.2017"), "30.11.2017")

        self.assertTrue(len(msg1) == 0)
        self.assertTrue(functionsr.getRentals()[0].getBookId() == book1.getId())
        self.assertTrue(functionsr.getRentals()[0].getClientId() == client1.getId())

        msg2 = functionsr.rentBook(book2.getId, client2.getId(), createDateFromString("20.11.2017"), "19.11.2017")
        self.assertTrue(msg2 == "Inconsistent dates")
コード例 #3
0
    def __init__(self, **kwargs):
        self.host = kwargs.get('host')
        self.database = kwargs.get('database')

        self.db = Repository(self.host, self.database)
        self.recipes = self.db.get_collection(kwargs.get('recipes'))
        self.combinations = self.db.get_collection(kwargs.get('combinations'))
コード例 #4
0
 def __init__(self, **kwargs):
     self.db = Repository(kwargs.get('host'), kwargs.get('database'))
     self.recipes = self.db.get_collection(kwargs.get('recipes'))
     self.combinations = self.db.get_collection(kwargs.get('combinations'))
     self.skip = kwargs.get('skip')
     self.r_min = kwargs.get('r_min')
     self.r_max = kwargs.get('r_max')
コード例 #5
0
    def setUp(self):
        self.repo = Repository()
        self.brepo = Repository()
        self.crepo = Repository()
        self.Ucontroller = UndoController()
        self.book = Book(21, 'titlu', 'descriere', 'author')
        self.book2 = Book(22, 'titlu2', 'descriere2', 'author')
        self.brepo.add(self.book)
        self.brepo.add(self.book2)
        self.client = Client(23, 'alex')
        self.client2 = Client(24, 'ana')
        self.client3 = Client(29, 'ana')

        self.crepo.add(self.client)
        self.crepo.add(self.client2)
        self.rental = Rental(21236, 21, 24, date(2017, 11, 5),
                             date(2017, 12, 6), date(2017, 12, 5))
        self.rental2 = Rental(21238, 22, 24, date(2017, 11, 5),
                              date(2017, 12, 6), date(2017, 12, 5))
        self.rental3 = Rental(21238, 23, 24, date(2017, 11, 5),
                              date(2017, 12, 6), date(2017, 12, 5))
        self.rental4 = Rental(21238, 21, 29, date(2017, 11, 5),
                              date(2017, 12, 6), date(2017, 12, 5))
        self.rental5 = Rental(21231, 21, 23, date(2017, 11, 5),
                              date(2017, 10, 6), None)

        self.controller = RentalController(self.repo, self.brepo, self.crepo,
                                           self.Ucontroller)
        self.ceva = LateRentalCount(12, 32)
        self.altceva = BookRentalCount(12, 23)
        self.nu = AuthorRentalCount('da', 23)
        self.da = ClientRentalCount(32, 12)
コード例 #6
0
ファイル: controller.py プロジェクト: Cronologium/lab5-7
 def addGrade(self, cmd, debug = None):
     '''
     Checks if using some parameteres a grade can be added in the repository
     
     Parameters:
     cmd - contains the parts which compose a grade
     debug - used only for testing
     '''
     parameters = Utility.splitParameters(cmd)
     if parameters == None:
         raise ValueError
     if len(parameters) == 4 and len(parameters[0]) > 0 and len(parameters[1]) == 1 and len(parameters[2]) == 1 and len(parameters[3]) > 0:
         disc = parameters[0][0]
         for i in range(1, len(parameters[0])):
             disc = disc + ' ' + parameters[0][i]
             
         name = parameters[3][0]
         for i in range(1, len(parameters[3])):
             name = name + ' ' + parameters[0][i]
             
         if Controller.isDuplicate(self, disc, "discipline") != -1 and Utility.isConvertableToInt(parameters[1][0]) and Controller.isDuplicate(self, int(parameters[1][0]), "studentID") != -1 and parameters[2][0]:
             Repository.push(self._repository, Grade(disc, parameters[1][0], name, parameters[2][0]))
             return
         elif Controller.isDuplicate(self, disc, "discipline") == -1:
             raise DuplicateDisciplineError
         elif Controller.isDuplicate(self, int(parameters[1][0]), "studentID") == -1:
             raise DuplicateIDError
     raise ValueError
コード例 #7
0
 def __init__(self):
     pass
     repository = Repository()
     pulls = Pulls()
     repos_url = response['pull_request']['head']['repo']['url']
     pulls_url = response['pull_request']['url']
     files_url = pulls_url + '/files'
     #user = response["pull_request"]["user"]["login"]
     #contributor_url =repos_url + TestData.contributor_parameter
     repo_name = response['pull_request']['head']['repo']['name']
     owner_name = response['pull_request']['head']['repo']['owner']['login']
     last_page = Utils().pagination(owner_name, repo_name)
     feature_dict.update(Repository().open_pr_count(repos_url, last_page))
     #print(pulls.changed_lines_in_file(files_url))
     feature_dict['forks_count'] = response['pull_request']['head']['repo']['forks_count']
     feature_dict['commits'] = response['pull_request']['commits']
     feature_dict['changed_files'] = response['pull_request']['changed_files']
     feature_dict.update(repository.pushed_time(response['pull_request']['head']['repo']['pushed_at']))
     feature_dict['watchers_count'] = response['pull_request']['head']['repo']['watchers_count']
     feature_dict['open_issue_count'] = response['pull_request']['head']['repo']['open_issues_count']
     feature_dict.update(Pulls().pull_request_size(response["pull_request"]))
     parameter_dict = {}
     parameter_dict['feature_dict'] = feature_dict
     parameter_dict['comment_url'] = comment_url
     return parameter_dict
コード例 #8
0
ファイル: sort_service.py プロジェクト: nigel-smk/mrspice-cli
    def __init__(self, **kwargs):
        self.host = kwargs.get('host')
        self.database = kwargs.get('database')
        self.r_min = int(kwargs["r_min"])
        self.r_max = int(kwargs["r_max"])

        self.db = Repository(self.host, self.database)
        self.combinations = self.db.get_collection(kwargs.get('combinations'))
コード例 #9
0
    def __init__(self, **kwargs):
        self.host = kwargs.get('host')
        self.database = kwargs.get('database')

        self.db = Repository(self.host, self.database)
        self.collection = self.db.get_collection(kwargs.get('collection'))

        self.skip = kwargs.get("skip")
コード例 #10
0
    def testUtils(self):
        bList = []
        self.assertTrue(len(bList) == 0)
        bookRepo = Repository()
        bc = BookController(bookRepo, Statistics(bookRepo))
        bc.populateBookRepository()

        self.assertTrue(0 < len(bookRepo.getAll()) < 100)
コード例 #11
0
 def setUp(self):
     self.repo = Repository()
     self.rentalRepo = Repository()
     self.Ucontroller = UndoController()
     self.client = Client(11, 'alex')
     self.client2 = Client(12, 'ana')
     self.controller = ClientController(self.repo, self.Ucontroller,
                                        self.rentalRepo)
コード例 #12
0
 def setUp(self):
     self.repo = Repository()
     self.rentalRepo = Repository()
     self.Ucontroller = UndoController()
     self.book = Book(21, 'titlu', 'descriere', 'author')
     self.book2 = Book(22, 'titlu2', 'descriere2', 'author2')
     self.controller = BookController(self.repo, self.Ucontroller,
                                      self.rentalRepo)
コード例 #13
0
    def __init__(self, **kwargs):
        self.host = kwargs.get('host')
        self.neoHost = kwargs.get('neoHost')
        self.database = kwargs.get('database')
        self.resume = kwargs.get('resume')

        self.db = Repository(self.host, self.database)
        self.recipes = self.db.get_collection(kwargs.get('recipes'))
コード例 #14
0
class MyTestCase(unittest.TestCase):
    def setUp(self):
        self.repo = Repository('test_repo.txt', Question.read_line, Question.write_line)
        self.q1 = Question(1, 'text', 3, 4, 3, 4, 'easy')

    def test_something(self):
        self.assertEqual(self.repo.size(), 1)
        self.assertRaises(RepositoryException, self.repo.store_question, self.q1)
        self.assertEqual(len(self.repo.get_all()), 1)
コード例 #15
0
def sample_collection(**kwargs):
    """exceptions:
        fewer records than sample size
        sample size not an integer
        source does not exist
        destination already exists
        database connection exceptions
    """
    db = Repository(kwargs['host'], kwargs['database'])
    source = db.get_collection(kwargs['source'])
    destination = db.get_collection(kwargs['destination'])
    # TODO pass filter in from json file
    doc_filter = {
        'attributes': {
            '$gt': {}
        },
        'attributes.course': {
            '$nin': ['Desserts', 'Cocktails', 'Beverages']
        },
        'rating': {
            '$gte': 4,
            '$lte': 5
        }
    }

    if doc_filter:
        record_count = source.count(doc_filter)
    else:
        record_count = source.count()
    seed = kwargs['seed']
    sample_size = parse_number(kwargs['size'])

    random.seed(seed)
    to_sample = random.sample(range(0, record_count), sample_size)
    to_sample.sort()

    progress = ProgressBar(sample_size)
    progress.start()

    if doc_filter:
        cursor = source.find(doc_filter)
    else:
        cursor = source.find()

    sample_count = 0
    position = 0
    for index in to_sample:
        while position <= index:
            record = cursor.next()
            position += 1
        # TODO batch insert?
        destination.insert_one(record)
        sample_count += 1
        progress.update(sample_count)

    progress.end()
コード例 #16
0
    def testUpdateBook(self):
        bookRepo = Repository()
        bc = BookController(bookRepo, Statistics(bookRepo))
        bc.populateBookRepository()
        bc.addBook(101, "Title", "Description", "Author")
        bc.updateBook(101, "title", "description", "author")

        self.assertTrue(bookRepo.getById(101).getTitle() == "title")
        self.assertTrue(bookRepo.getById(101).getAuthor() == "author")
        self.assertTrue(bookRepo.getById(101).getDescription() == "description")
コード例 #17
0
ファイル: test_repository.py プロジェクト: alexresiga/courses
 def setUp(self):
     self.repo = Repository()
     self.c = Client(12, 'alex')
     self.c1 = Client(121, 'ana')
     self.repo2 = FileRepository('testclient.txt',
                                 Client.readClientFromLine,
                                 Client.writeClientToLine)
     self.repo3 = FileRepository('testclient4.txt',
                                 Client.readClientFromLine,
                                 Client.writeClientToLine)
コード例 #18
0
ファイル: test_repository.py プロジェクト: alexresiga/courses
class TestRepository(unittest.TestCase):
    def setUp(self):
        self.repo = Repository()
        self.c = Client(12, 'alex')
        self.c1 = Client(121, 'ana')
        self.repo2 = FileRepository('testclient.txt',
                                    Client.readClientFromLine,
                                    Client.writeClientToLine)
        self.repo3 = FileRepository('testclient4.txt',
                                    Client.readClientFromLine,
                                    Client.writeClientToLine)

    def test_repo(self):
        self.assertEqual(len(self.repo), 0)
        self.repo.add(self.c)
        self.assertEqual(str(self.repo), '012. alex\n\n')
        self.assertEqual(len(self.repo), 1)
        self.assertRaises(RepositoryException, self.repo.add, self.c)
        self.assertEqual(len(self.repo.getAll()), 1)
        self.assertEqual(self.repo.findByID(12), 12)
        self.assertEqual(self.repo.findByID(13), -1)
        self.assertEqual(self.repo.get(12), self.c)
        self.assertRaises(RepositoryException, self.repo.get, 13)
        self.assertRaises(RepositoryException, self.repo.remove, 13)
        self.assertRaises(RepositoryException, self.repo.update, 13)
        self.repo.update(self.c)
        self.repo.remove(12)
        self.assertEqual(len(self.repo), 0)
        self.repo2.add(self.c)
        self.repo2.upd(self.c)
        self.repo2.rem(self.c.getID())
        self.assertEqual(len(self.repo2), 1)
コード例 #19
0
 def __init__(self, file_name, readEntity, writeEntity, validator_class):
     '''
     Constructor
     
     '''
     Repository.__init__(self, validator_class)
     self.__file_name = file_name
     self.__validator_class = validator_class
     self.__read_entity = readEntity
     self.__write_entity = writeEntity
     self.__readFromFile()
コード例 #20
0
ファイル: pyunit_tests.py プロジェクト: DrSchiop/text-library
    def testClientRepository(self):
        
        repo = Repository()
        c1 = Client(1, "Alice", 6548987854215)
        c2 = Client(2, "Vlad", 1944444444444)

        self.assertEqual( len(repo) ,  0 )

        repo.addElement(c1)
        self.assertEqual( len(repo) ,  1 )
        repo.addElement(c2)
        self.assertEqual( len(repo) ,  2 )
コード例 #21
0
 def setUp(self):
     super().setUp()
     self.__student_repository = Repository(StudentValidator)
     self.__student_controller = StudentController(
         self.__student_repository)
     self.__discipline_repository = Repository(DisciplineValidator)
     self.__discipline_controller = DisciplineController(
         self.__discipline_repository)
     self.__grade_repository = Repository(GradeValidator)
     self.__grade_controller = GradeController(self.__grade_repository,
                                               self.__student_repository,
                                               self.__discipline_repository)
コード例 #22
0
 def __init__(self, filename):
     """
     Initializing the controller
     :param filename:
     """
     self.__repo = Repository(
         filename)  # initialize the repository with the filename
     self.__validator = Validator(
     )  # initialize the validator for checking if the input is ok
     self.__scramble = self.__repo.get_scramble(
     )  # getting the randomly picked sentence from repo
     self.__undo = None
コード例 #23
0
class IndexService:
    def __init__(self, **kwargs):
        self.host = kwargs.get('host')
        self.database = kwargs.get('database')

        self.db = Repository(self.host, self.database)
        self.recipes = self.db.get_collection(kwargs.get('recipes'))
        self.combinations = self.db.get_collection(kwargs.get('combinations'))

    def index(self):

        self.recipes.create_index('ingredients')
        self.combinations.create_index('r')
コード例 #24
0
ファイル: tests.py プロジェクト: DrSchiop/text-library
def testClientRepository():

    repo = Repository()
    c1 = Client(1, "Alice", 6548987854215)
    c2 = Client(2, "Vlad", 1944444444444)

    assert len(repo) == 0

    repo.addElement(c1)
    assert len(repo) == 1
    repo.addElement(c2)
    assert len(repo) == 2

    print("ClientRepository tests ran successfully!")
コード例 #25
0
ファイル: test.py プロジェクト: Cronologium/lab5-7
 def _test_controller_isDuplicate(self):
     '''
     Tests if finding a duplicate in the repository works
     '''
     repository = Repository()
     controller = Controller(repository)
     Repository.push(repository, Student("john", 1))
     Repository.push(repository, "Test QA")
     
     assert Controller.isDuplicate(controller, 1, "studentID") == 0
     assert Controller.isDuplicate(controller, 2, "studentID") == -1
     assert Controller.isDuplicate(controller, "Test QA", "discipline") == 1
     assert Controller.isDuplicate(controller, "Tester QA", "discipline") == -1
     assert Controller.isDuplicate(controller, 1, "???") == -1
     assert Controller.isDuplicate(controller, "78", "studentID") == -1
コード例 #26
0
    def testBookController(self):
        repo = Repository()
        controller = BookController(repo)
        undoController = Undo()
        controller.addUndoController(undoController)

        self.assertEqual(controller.addBook(Book(1, "ala", "mala", "dala")),
                         True)
        self.assertNotEqual(controller.searchById(1), False)

        found = controller.searchById(1)
        self.assertEqual(found, Book(1, "ala", "mala", "dala"))
        self.assertEqual(controller.searchByTitle("ala"),
                         Book(1, "ala", "mala", "dala"))

        self.assertNotEqual(
            controller.modifyBookAuthor(Book(1, "ala", "mala", "dala"),
                                        "Mercan"), False)

        self.assertEqual(
            controller.modifyBookTitle(Book(1, "ala", "mala", "Mercan"),
                                       "Newt"), True)
        self.assertEqual(controller.findExistingId(1), True)

        self.assertEqual(
            controller.removeElement(Book(1, "Newt", "mala", "Mercan")), True)
        self.assertEqual(controller.searchById(1), False)
        self.assertEqual(controller.checkIdExists(1), False)
コード例 #27
0
    def testRemoveBook(self):
        book1 = Book(1, "Title", "Description", "Author")
        book2 = Book(2, "Title1", "Description1", "Author1")
        book3 = Book(3, "Title2", "Description2", "Author2")
        repo = Repository()
        functions = BookController(repo, Statistics(repo))

        functions.addBook(book1.getId(), book1.getTitle(), book1.getDescription(), book1.getAuthor())
        functions.addBook(book2.getId(), book2.getTitle(), book2.getDescription(), book2.getAuthor())
        functions.addBook(book3.getId(), book3.getTitle(), book3.getDescription(), book3.getAuthor())

        msg1 = functions.removeBook(1)

        self.assertTrue(len(msg1) == 0)
        self.assertTrue(functions.getBooks()[0].getId() == book2.getId())
        self.assertTrue(functions.getBooks()[0].getTitle() == book2.getTitle())
        self.assertTrue(functions.getBooks()[0].getDescription() == book2.getDescription())
        self.assertTrue(functions.getBooks()[0].getAuthor() == book2.getAuthor())

        msg2 = functions.removeBook(1)

        self.assertTrue(msg2 == "The provided ID does not exist")
        self.assertTrue(functions.getBooks()[0].getId() == book2.getId())
        self.assertTrue(functions.getBooks()[0].getTitle() == book2.getTitle())
        self.assertTrue(functions.getBooks()[0].getDescription() == book2.getDescription())
        self.assertTrue(functions.getBooks()[0].getAuthor() == book2.getAuthor())
コード例 #28
0
ファイル: repository_test.py プロジェクト: iamthebj/TestGit
    def test_get_repo_probability(self, mock_get, mock_response):
        '''Test for Repository class inside repository package'''
        mock_reponses = []
        mock_res = RepositoryTest.MockResponse([{'state':'closed',
                                                 "merged_at":'2018-08-29T20:05:38Z'}], 200)
        type(mock_response).return_value = mock.PropertyMock(
            return_value=mock_res)
        type(mock_get).return_value = mock.PropertyMock(
            return_value=type(mock_response).return_value)
        mock_reponses.append(type(mock_get).return_value)

        mock_res = RepositoryTest.MockResponse([{'state':'closed', "merged_at":None}], 200)
        type(mock_response).return_value = mock.PropertyMock(return_value=mock_res)
        type(mock_get).return_value = mock.PropertyMock(
            return_value=type(mock_response).return_value)
        mock_reponses.append(type(mock_get).return_value)
        mock_get.side_effect = mock_reponses
        mock_res = RepositoryTest.MockResponse([{'state':'closed',
                                                 "merged_at":'2018-08-29T20:05:38Z'}], 200)
        type(mock_response).return_value = mock.PropertyMock(return_value=mock_res)
        type(mock_get).return_value = mock.PropertyMock(
            return_value=type(mock_response).return_value)
        mock_reponses.append(type(mock_get).return_value)
        mock_get.side_effect = mock_reponses
        response_push = Repository().get_repo_probability('3', RepositoryTest.repos_url)
        self.assertEqual(response_push, {'pull_request_acceptance_rate': 66.66666666666666})
コード例 #29
0
def runTest1():
    repo = Repository("test1.txt")
    service = Service(repo)
    c = service.simulate(20, 10, 30)
    assert (c.get_genes() == [0, 1, 2, 3, 0])
    assert (c.get_distance() == 4)
    assert (c.fitness() == 1 / c.get_distance())
コード例 #30
0
class YummlyIngredientsService:

    URL = "http://api.yummly.com/v1/api/metadata/ingredient"
    APP_ID = "2a6406ac"
    APP_KEY = "c0aac363d1a1c8b1925e5f8898c69a48"

    def __init__(self, **kwargs):
        self.host = kwargs.get('host')
        self.database = kwargs.get('database')

        self.db = Repository(self.host, self.database)
        self.collection = self.db.get_collection(kwargs.get('collection'))

        self.skip = kwargs.get("skip")

    def get_ingredients(self):

        headers = {
            'X-Yummly-App-ID': YummlyIngredientsService.APP_ID,
            'X-Yummly-App-Key': YummlyIngredientsService.APP_KEY
        }

        r = requests.get(YummlyIngredientsService.URL, headers=headers)
        response_body = r.text
        # trim jsonp  callback
        response_body = response_body.partition(',')[2][:-2]
        response_json = json.loads(response_body)

        self.collection.insert_many(response_json)
コード例 #31
0
def runTest2():
    repo = Repository("test2.txt")
    service = Service(repo)
    c = service.simulate(50, 10, 100)
    assert (c.get_genes() == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0])
    assert (c.get_distance() == 10)
    assert (c.fitness() == 1 / c.get_distance())
コード例 #32
0
def runApplicationWithUndo():
    settings = Settings()
    undoController = UndoController()

    if str(settings.mode_repository) == "inmemory":
        student_repository = Repository(StudentValidator)
        discipline_repository = Repository(DisciplineValidator)
        grade_repository = Repository(GradeValidator)

    elif settings.mode_repository == "textfiles":
        student_repository = FileRepository(StudentValidator, settings.students, Student)
        discipline_repository = FileRepository(DisciplineValidator, settings.disciplines, Discipline)
        grade_repository = FileRepository(GradeValidator, settings.grades, Grade)

    elif settings.mode_repository == "binaryfiles":
        student_repository = BinaryRepository(StudentValidator, settings.students, Student)
        discipline_repository = BinaryRepository(DisciplineValidator, settings.disciplines, Discipline)
        grade_repository = BinaryRepository(GradeValidator, settings.grades, Grade)


    elif settings.mode_repository == "sqlfiles":
        student_repository = SQLRepository(StudentValidator, settings.students, Student, "Students", 1)
        discipline_repository = SQLRepository(DisciplineValidator, settings.disciplines, Discipline, "Disciplines", 1)
        grade_repository = SQLRepository(GradeValidator, settings.grades, Grade, "Grades", 2)



    elif settings.mode_repository == "jsonfiles":
        student_repository = JSONRepository(StudentValidator, settings.students, Student)
        discipline_repository = JSONRepository(DisciplineValidator, settings.disciplines, Discipline)
        grade_repository = JSONRepository(GradeValidator, settings.grades, Grade)

    else:
        print("You have to insert a valid repository mode!!!")

    student_controller = StudentController(student_repository, undoController)
    discipline_controller = DisciplineController(discipline_repository, undoController)
    grade_controller = GradeController(grade_repository, student_repository, discipline_repository, undoController)

    if settings.interface_mode == "gui":
        ui_gui = GUI(student_controller, discipline_controller, grade_controller, undoController)
        ui_gui.run_app()
    elif settings.interface_mode == "console":
        console = Console(student_controller, discipline_controller, grade_controller, undoController)
        console.runApp()
    else:
        print("You have to insert a valid interface!!!")
コード例 #33
0
    def __init_flash_text_corpus(self):
        """ Init flash text corpus. """
        # build slang word corpus
        slang_words_raw = Repository.get_slang_word()
        for word in slang_words_raw.values:
            self.keyword_processor_slang_word.add_keyword(word[0], word[1])

        # build emoticon corpus
        emoticon_raw = constant.EMOTICON_LIST
        for key, values in emoticon_raw:
            for value in values:
                self.keyword_processor_emoticon.add_keyword(value, key)

        # build meaning word corpus
        meaning_words_raw = Repository.get_meaning_text()
        for word in meaning_words_raw.values:
            self.keyword_processor_meaning_text.add_keyword(word[0], word[1])
コード例 #34
0
def main():
    vk_token = get_vk_token()
    vk_session = vk_api.VkApi(token=vk_token)
    # vk = vk_session.get_api()
    response = vk_session.method(
        'users.search', {
            'q': 'Ковтун Максим',
            'sex': 2,
            'age_from': 1,
            'age_to': 45,
            'hometown': 'Москва'
        })
    print(response)
    return

    repository = Repository()
    print(repository.get_repository_user())
コード例 #35
0
ファイル: controller.py プロジェクト: Cronologium/lab5-7
 def addStudent(self, cmd):
     '''
     Checks if using some parameters a student can be added in the repository
     
     Parameters:
     cmd - contains the parts which compose a student
     debug - used only for testing
     '''
     parameters = Utility.splitParameters(cmd)
     if parameters == None:
         raise ValueError
     if len(parameters) == 1 and len(parameters[0]) > 0:
         name = parameters[0][0]
         for i in range(1, len(parameters[0])):
             name = name + ' ' + parameters[0][i]
         Repository.push(self._repository, Student(name, Controller.getID(self)))
         return
     raise ValueError
コード例 #36
0
ファイル: controller.py プロジェクト: Cronologium/lab5-7
 def addDiscipline(self, cmd, debug = None):
     '''
     Checks if using some parameters a discipline can be added in the repository
     
     Parameters:
     cmd - contains the parts which compose a discipline
     debug - used only for testing
     '''
     parameters = Utility.splitParameters(cmd)
     if parameters == None:
         raise ValueError
     if len(parameters) == 1 and len(parameters[0]) > 0:
         disc = parameters[0][0]
         for i in range(1, len(parameters[0])):
             disc = disc + ' ' + parameters[0][i]
         if Controller.isDuplicate(self, disc, "discipline") == -1:
             Repository.push(self._repository, disc)
             return
         else:
             raise DuplicateDisciplineError
     raise ValueError
コード例 #37
0
ファイル: controller.py プロジェクト: Cronologium/lab5-7
 def searchID(self, criteria, debug):
     '''
     Searches a student in the list based on their ID
     
     Parameters:
     criteria - the id of the student
     debug - used for debugging to check if command is detected
     '''
     pos = Controller.isDuplicate(self, criteria, "studentID")
     if pos == -1:
         raise DuplicateIDError
     else:
         print (Repository.getList(self._repository)[pos])
コード例 #38
0
ファイル: tester.py プロジェクト: Sthephen/courses
 def test(self):
     x = Route(1,"24b",93,3)
     assert(x.getId() == 1)
     x.setId(2)
     assert(x.getId() == 2)
     assert(x.getRouteCode() == "24b")
     x.setRouteCode("24")
     assert(x.getRouteCode() == "24")
     assert(x.getUsage() == 93)
     x.setUsage(95)
     assert(x.getUsage() == 95)
     assert(x.getBuses() == 3)
     x.setBuses(x.getBuses() + 1)
     assert(x.getBuses() == 4)
     x = Route(1,"24b",93,3)
     repo = Repository()
     repo.add(x)
     assert(repo.getRoutes() == [Route(1,"24b",93,3)])
     y = Route(13,"25",93,7)
     repo.add(y)
     assert(repo.getRoutes() == [Route(1,"24b",93,3), Route(13,"25",93,7)])
     repo.add(y)
     assert(repo.getRoutes() == [Route(1,"24b",93,3), Route(13,"25",93,7), Route(13,"25",93,7)])
コード例 #39
0
ファイル: pyunit_tests.py プロジェクト: DrSchiop/text-library
    def testRental(self):
        repo = Repository()
        book1 = Book(1, "ala", "mala", "dala")
        
        rentList = Repository()
        rentList.addElement(Rental(2, book1, 0))

        lis1 = rentList.getElementList()
        self.assertEqual( len(lis1) ,  1 )

        rentList.addElement(Rental(2, book1, 1))
        lis1 = rentList.getElementList()
        self.assertEqual( len(lis1) ,  2 )
        self.assertEqual( lis1[0].getRenterId() ,  2 )
        self.assertEqual( lis1[0].getRentedBook() ,  book1 )
        self.assertEqual( lis1[0].getId() ,  0 )
コード例 #40
0
ファイル: controller.py プロジェクト: Cronologium/lab5-7
 def printElements(self, elem_type, debug = None):
     '''
     Prints the elements in the list
     
     Parameters:
     elem_type - what type of elements should be printed
     debug - used only for testing
     '''
     print ("List of " + elem_type + ': ')
     lst = Repository.getList(self._repository)
     for i in range(len(lst)):
         if elem_type == "students" and isinstance(lst[i], Student) == True:
             print (str(lst[i]))
         elif elem_type == "grades" and isinstance(lst[i], Grade) == True:
             print (str(lst[i]))
         elif elem_type == "disciplines" and isinstance(lst[i], str) == True:
             print (' * ' + str(lst[i]))
     print ("---------------------")  
コード例 #41
0
ファイル: tests.py プロジェクト: DrSchiop/text-library
def testRental():
    repo = Repository()
    book1 = Book(1, "ala", "mala", "dala")

    rentList = Repository()
    rentList.addElement(Rental(2, book1, 0))

    lis1 = rentList.getElementList()
    assert len(lis1) == 1

    rentList.addElement(Rental(2, book1, 1))
    lis1 = rentList.getElementList()
    assert len(lis1) == 2
    assert lis1[0].getRenterId() == 2
    assert lis1[0].getRentedBook() == book1
    assert lis1[0].getId() == 0

    print("Rental tests ran successfully!")
コード例 #42
0
ファイル: pyunit_tests.py プロジェクト: DrSchiop/text-library
 def testBookRepository(self):
     repo = Repository()
     book1 = Book(1, "ala", "mala", "dala")
     
     repo.addElement(book1)
     self.assertEqual( len(repo) ,  1 )
     
     try:
         if repo.addElement(book1) != False:
             self.assertEqual( False )
     except BookException:
         pass
     
     book2 = Book(2, "ala", "mala", "dala")
     repo.addElement(book2)
     
     self.assertEqual( len(repo) ,  2 )
コード例 #43
0
ファイル: controller.py プロジェクト: Cronologium/lab5-7
 def isDuplicate(self, criteria, check_type):
     '''
     Check if there is a student with id = criteria
     
     Parameters:
     criteria - what to search in the list
     check_type - what type of elements need to be compared
     '''
     lst = Repository.getList(self._repository)
     if check_type == "studentID" and isinstance(criteria, int):
         for i in range(len(lst)):
             if isinstance(lst[i], Student) and lst[i].getID() == criteria:
                 return i
     
     '''
     Checks whether criteria is a discipline found in the list
     '''
     
     if check_type == "discipline" and isinstance(criteria, str):
         for i in range(len(lst)):
             if isinstance(lst[i], str) and lst[i] == criteria:
                 return i
                     
     return -1
コード例 #44
0
ファイル: tests.py プロジェクト: DrSchiop/text-library
def testBookRepository():
    repo = Repository()
    book1 = Book(1, "ala", "mala", "dala")

    repo.addElement(book1)
    assert len(repo) == 1

    try:
        if repo.addElement(book1) != False:
            assert False
    except BookException:
        pass

    book2 = Book(2, "ala", "mala", "dala")
    repo.addElement(book2)

    assert len(repo) == 2

    print("BookRepository tests ran successfully!")
コード例 #45
0
ファイル: tests.py プロジェクト: DrSchiop/text-library
def testRentalRepository():
    rentalRepo = Repository()
    book1 = Book(0, "The Q", "Albert", "Heinrich")
    book2 = Book(1, "The D", "Elbert", "Reinsich")
    client1 = Client(0, "Mihai", 1854987548795)
    client2 = Client(1, "Alex", 1987548759658)

    rentalRepo.addElement(Rental(1, book1, 0))
    rentalRepo.addElement(Rental(0, book2, 1))

    # _find(_id) returns the Rental from the repository
    # that has the client Id equal to _id

    assert rentalRepo._find(0).getRentedBook() == book1
    assert rentalRepo._find(1).getId() == 1

    assert rentalRepo._find(1).getRentedBook() == book2
    assert rentalRepo._find(0).getId() == 0

    # findId() function for Repository class
    assert rentalRepo.findId(12) == False
    assert rentalRepo.findId(0) == True

    # elementFromId()
    assert rentalRepo.elementFromId(0).getRentedBook() == book1

    rentalRepo.addElement(Rental(1, book2, 2))

    print("Rental repository tests ran successfully!")
コード例 #46
0
ファイル: StartApp.py プロジェクト: DrSchiop/text-library
def main():
    '''
        This is the main() function and is the first thing that is ran by the program. It contains all the objects 
        necessary for execution and everything related to the UI.
    '''

    # repositories must be initialized with a string containing the type of the repository in order to use files
    clientRepository = Repository("Client")
    bookRepository = Repository("Book")
    rentalRepository = Repository("Rental")

    clientController = ClientController(clientRepository)
    bookController = BookController(bookRepository)
    rentalController = RentalController(rentalRepository, clientController, bookController)

    keepAlive = True
    while keepAlive:    
        userInput = input("Please choose the mode (memory/file). Insert 'x' to quit: ")
        if userInput == 'x':
            return
        elif userInput == 'memory':
            clientRepository.addElement(Client(0, 'Mircea', 1962353535353))
            clientRepository.addElement(Client(1, 'Dorin', 1962353535354))
            clientRepository.addElement(Client(3, 'Marius', 1962353335353))
            clientRepository.addElement(Client(6, 'Dacia', 1962353444353))
            bookRepository.addElement(Book(0, "Dorin Mateiu", "Viata pe un Stalp", "Mihaila"))
            bookRepository.addElement(Book(1, "Salutare", "Lume", "Viata"))
            bookRepository.addElement(Book(2, "Inca", "O Carte", "Buna"))

            ui_object = UserInterface(clientController, bookController, rentalController)
            ui_object.launchMainMenu()

            keepAlive = False
        elif userInput == 'file':
            print ("Available files: ")

            files = listdir('resources')
            for i in files:
                if i[-4:] == '.txt':
                    print (i)
            print()

            print ("Please choose the file you want to load.", "If that file does not exist it will be created.")
            print ("Insert 'x' at any time to quit.")
            chosenFile = input("Please insert file name: ")

            if chosenFile == 'x':
                continue

            alreadyExists = False
            existingFile = None
            for i in files:
                if i[:-4] == chosenFile:
                    alreadyExists = True
                    existingFile = i

            if alreadyExists == True:
                print ("File found! Type again to load: ")
                confirmInput = input()
                if confirmInput == 'x':
                    continue
                if confirmInput == chosenFile:
                    # file was found and will be loaded
                    if '.txt' in chosenFile:
                        chosenFile = chosenFile[:-4]
                    filePath = 'resources/' + chosenFile + '.txt'
                    
                    ui_object = UserInterface(clientController, bookController, rentalController, filePath)
                    ui_object.launchMainMenu()
                else:
                    print ("Returning...")
                    continue
            else:
                print ("Create file? Type again to confirm: ")
                confirmInput = input()
                if confirmInput == 'x':
                    continue
                if confirmInput == chosenFile:
                    filePath = 'resources/' + chosenFile + '.txt'
                    
                    ui_object = UserInterface(clientController, bookController, rentalController, None)
                    ui_object.launchMainMenu(filePath)
                else:
                    print ("Returning...")
                    continue
                
            keepAlive = False
        else:
            print ("Error! Please insert 'file' or 'memory' ")
コード例 #47
0
ファイル: test.py プロジェクト: Cronologium/lab5-7
 def _test_repository_pushremove(self):
     '''
     Tests if the functions push and remove from the repository work
     '''
     repository = Repository()
     Repository.push(repository, "5", 0)
     Repository.push(repository, 2)        
     Repository.push(repository, True, 3)
     Repository.push(repository, 7.5)
     
     assert Repository.getList(repository) == ["5", 2, 7.5]
     
     Repository.remove(repository, 3)
     Repository.remove(repository, 1)
     
     assert Repository.getList(repository) == ["5", 7.5]
     
     Repository.remove(repository, 0)
     
     assert Repository.getList(repository) == [7.5]
     
     Repository.remove(repository, 0)
     Repository.remove(repository, 0)
     
     assert Repository.getList(repository) == []
コード例 #48
0
ファイル: pyunit_tests.py プロジェクト: DrSchiop/text-library
    def testRentalRepository(self):
        rentalRepo = Repository()
        book1 = Book(0, "The Q", "Albert", "Heinrich")
        book2 = Book(1, "The D", "Elbert", "Reinsich")
        client1 = Client(0, "Mihai", 1854987548795)
        client2 = Client(1, "Alex", 1987548759658)

        rentalRepo.addElement(Rental(1, book1, 0))
        rentalRepo.addElement(Rental(0, book2, 1))

        # _find(_id) returns the Rental from the repository
        # that has the client Id equal to _id

        self.assertEqual( rentalRepo._find(0).getRentedBook() ,  book1 ) 
        self.assertEqual( rentalRepo._find(1).getId() ,  1 )

        self.assertEqual( rentalRepo._find(1).getRentedBook() ,  book2 )
        self.assertEqual( rentalRepo._find(0).getId() ,  0 )

        # findId() function for Repository class
        self.assertEqual( rentalRepo.findId(12) ,  False )
        self.assertEqual( rentalRepo.findId(0) ,  True )

        # elementFromId()
        self.assertEqual( rentalRepo.elementFromId(0).getRentedBook() ,  book1 )

        rentalRepo.addElement(Rental(1, book2, 2))