def test_constructs_single_query_no_deps(self):
     code = SqlCode("select company_name, company_id from companies", "companies")
     repo = Repository()
     repo.add_queries(code.queries)
     qg = QueryGenerator(repo)
     output = qg.generate_query("companies")
     self.assertEqual(output.lower(), "select company_name, company_id from companies")
Exemple #2
0
class Controller():
    def __init__(self, n, population, nrOfIterations, pM):
        self.__Repository = Repository(n, population, nrOfIterations, pM)

    def reinitializeController(self, n, population, nrOfIterations, pM):
        self.__Repository = Repository(n, population, nrOfIterations, pM)

    def NextIteration(self):
        self.__Repository.NextIteration()

    def getNumberOfIterations(self):
        return self.__Repository.getNumberOfIterations()

    def getMinFitness(self):
        return self.__Repository.getFitnessMinimForEachState()

    def getLastFitness(self):
        allFitnesses = self.__Repository.getFitnessMinimForEachState()
        if allFitnesses[len(allFitnesses) -
                        1] >= allFitnesses[len(allFitnesses) - 2]:
            return allFitnesses[len(allFitnesses) - 2]
        return allFitnesses[len(allFitnesses) - 1]

    def NextClimb(self):
        return self.__Repository.NextClimb()
class UI:
    def loop(self):
        self.repo = Repository('balance-scale.data')
        self.ctrl = Controller(self.repo)
        root = self.ctrl.generate(self.repo.getTrain(), [1, 2, 3, 4])
        total=0
        sum=0
        for i in self.repo.getTest():
            if(self.ctrl.test(i,root)==i[0]):
                sum+=1
            total+=1
        return sum/total


    def run(self):
        best=0
        ind=0
        iter=0
        while iter<30000:
            ind = self.loop()
            if ind > best:
                best=ind
                if best>0.5:
                    print(best)
            iter+=1
        print("Best accuracy",best)
Exemple #4
0
    def test4(self):

        self.repository = Repository()
        self.controller = Controller(self.repository)

        self.repository.store(Square(1, 1), "X")
        self.repository.store(Square(2, 2), "X")
        self.repository.store(Square(3, 3), "X")
        self.repository.store(Square(4, 4), "X")
        self.repository.store(Square(5, 5), "X")
        self.repository.store(Square(6, 6), "O")

        assert self.repository.isWon(Square(3, 3)) == True

        self.repository.store(Square(2, 6), "O")
        self.repository.store(Square(3, 5), "O")
        self.repository.store(Square(4, 4), "O")
        self.repository.store(Square(5, 3), "O")
        self.repository.store(Square(6, 2), "O")

        assert self.repository.isWon(Square(2, 6)) == True

        self.repository = Repository()
        self.controller = Controller(self.repository)

        self.repository.store(Square(4, 1), "X")
        self.repository.store(Square(4, 3), "X")
        self.repository.store(Square(4, 5), "X")

        self.controller.round(4, 4, "X")

        assert self.repository._data[4][2] == self.repository._code["O"]
    def run(self):
        repo = Repository("data.txt")
        ctrl = Controller()
        points = repo.getPoints()

        learning_rate = 0.001
        initial_b0 = 0
        initial_b1 = 0
        initial_b2 = 0
        initial_b3 = 0
        initial_b4 = 0
        initial_b5 = 0

        num_iterations = 2000
        print(
            "Error at start",
            ctrl.computeError(initial_b0, initial_b1, initial_b2, initial_b3,
                              initial_b4, initial_b5, points))
        [b0, b1, b2, b3, b4,
         b5] = ctrl.gradientDescent(points, initial_b0, initial_b1, initial_b2,
                                    initial_b3, initial_b4, initial_b5,
                                    learning_rate, num_iterations)
        print("After", num_iterations, "iterations,the error is: ",
              ctrl.computeError(b0, b1, b2, b3, b4, b5, points))
        print("The obtained function is:", b0, "+", b1, "*x1 +", b2, "*x2 +",
              b3, "*x3 +", b4, "*x4 +", b5, "*x5")
def main():
    crtDir = os.getcwd()
    filePath = os.path.join(crtDir, 'data', 'hardE.txt')
    Repo = Repository(filePath)
    Repo.read_tsp_format()
    Serv=Service(Repo)
    Cons=Console(Serv)
    Cons.print_info(100,100)
Exemple #7
0
 def test_repo_retrieves_dependencies_in_order(self):
     testQuery = SqlCode("with companies as (select company_name, company_id) select company_name from companies", "test_query")
     repo = Repository()
     repo.add_queries(testQuery.queries)
     queries = repo.retrieve_query_with_dependencies("test_query")
     self.assertEqual(len(queries), 2)
     self.assertTrue(testQuery.queries[0] == queries[0])
     self.assertTrue(testQuery.queries[1] == queries[1])
Exemple #8
0
 def test_dfanalyze(self):
     """ verify dfanalyzer works fine """
     repo = Repository()
     repo.load(CONST_FILEDIR)
     test = [
         u"+-------+-------------+---------------------------------------------+\n|  CWID |     Name    |              Complited Cources              |\n+-------+-------------+---------------------------------------------+\n| 10183 |  Chapman, O |                 ['SSW 689']                 |\n| 11111 |  HALAHA, P  |                 ['SSW 540']                 |\n| 10172 |  Forbes, I  |            ['SSW 555', 'SSW 567']           |\n| 10175 | Erickson, D |      ['SSW 564', 'SSW 567', 'SSW 687']      |\n| 11399 |  Cordova, I |                 ['SSW 540']                 |\n| 22222 |  LILILI, H  |                 ['SYS 645']                 |\n| 11658 |   Kelly, P  |                 ['SSW 540']                 |\n| 11461 |  Wright, U  |      ['SYS 611', 'SYS 750', 'SYS 800']      |\n| 11714 |  Morton, A  |            ['SYS 611', 'SYS 645']           |\n| 10115 |   Wyatt, X  | ['CS 545', 'SSW 564', 'SSW 567', 'SSW 687'] |\n| 11788 |  Fuller, E  |                 ['SSW 540']                 |\n| 10103 |  Baldwin, C | ['CS 501', 'SSW 564', 'SSW 567', 'SSW 687'] |\n+-------+-------------+---------------------------------------------+",
         u'+-------+-------------+------+---------+----------+\n|  CWID |     Name    | Dept |  Cource | Students |\n+-------+-------------+------+---------+----------+\n| 98760 |  Darwin, C  | SYEN | SYS 750 |    1     |\n| 98760 |  Darwin, C  | SYEN | SYS 645 |    2     |\n| 98760 |  Darwin, C  | SYEN | SYS 800 |    1     |\n| 98760 |  Darwin, C  | SYEN | SYS 611 |    2     |\n| 98763 |  Newton, I  | SFEN | SSW 555 |    1     |\n| 98763 |  Newton, I  | SFEN | SSW 689 |    1     |\n| 98765 | Einstein, A | SFEN | SSW 567 |    4     |\n| 98765 | Einstein, A | SFEN | SSW 540 |    4     |\n| 98764 |  Feynman, R | SFEN |  CS 501 |    1     |\n| 98764 |  Feynman, R | SFEN |  CS 545 |    1     |\n| 98764 |  Feynman, R | SFEN | SSW 564 |    3     |\n| 98764 |  Feynman, R | SFEN | SSW 687 |    3     |\n+-------+-------------+------+---------+----------+'
     ]
     self.assertEqual(repo.print_table(), test)
Exemple #9
0
 def test_dfanalyze(self):
     """ verify dfanalyzer works fine """
     repo = Repository()
     repo.load(CONST_FILEDIR)
     test = [
         "+-------+-------------+---------------------------------------------+------------------------------------------------------------------------------------------+-----------------------------------+\n|  CWID |     Name    |              Complited Cources              |                                    Remaining Required                                    |         Remaining Elective        |\n+-------+-------------+---------------------------------------------+------------------------------------------------------------------------------------------+-----------------------------------+\n| 10103 |  Baldwin, C | ['CS 501', 'SSW 564', 'SSW 567', 'SSW 687'] |            ['SSW 533', 'SSW 540', 'SSW 555', 'SSW 565', 'SSW 690', 'SSW 695']            |                 []                |\n| 10115 |   Wyatt, X  | ['CS 545', 'SSW 564', 'SSW 567', 'SSW 687'] |            ['SSW 533', 'SSW 540', 'SSW 555', 'SSW 565', 'SSW 690', 'SSW 695']            |                 []                |\n| 10172 |  Forbes, I  |            ['SSW 555', 'SSW 567']           |            ['SSW 533', 'SSW 540', 'SSW 564', 'SSW 565', 'SSW 690', 'SSW 695']            |   ['CS 501', 'CS 513', 'CS 545']  |\n| 10175 | Erickson, D |      ['SSW 564', 'SSW 567', 'SSW 687']      |            ['SSW 533', 'SSW 540', 'SSW 555', 'SSW 565', 'SSW 690', 'SSW 695']            |   ['CS 501', 'CS 513', 'CS 545']  |\n| 10183 |  Chapman, O |                 ['SSW 689']                 | ['SSW 533', 'SSW 540', 'SSW 555', 'SSW 564', 'SSW 565', 'SSW 567', 'SSW 690', 'SSW 695'] |   ['CS 501', 'CS 513', 'CS 545']  |\n| 11399 |  Cordova, I |                 ['SSW 540']                 |            ['SYS 612', 'SYS 671', 'SYS 672', 'SYS 673', 'SYS 674', 'SYS 800']            |                 []                |\n| 11461 |  Wright, U  |      ['SYS 611', 'SYS 750', 'SYS 800']      |                 ['SYS 612', 'SYS 671', 'SYS 672', 'SYS 673', 'SYS 674']                  | ['SSW 540', 'SSW 565', 'SSW 810'] |\n| 11658 |   Kelly, P  |                      []                     |            ['SYS 612', 'SYS 671', 'SYS 672', 'SYS 673', 'SYS 674', 'SYS 800']            | ['SSW 540', 'SSW 565', 'SSW 810'] |\n| 11714 |  Morton, A  |            ['SYS 611', 'SYS 645']           |            ['SYS 612', 'SYS 671', 'SYS 672', 'SYS 673', 'SYS 674', 'SYS 800']            | ['SSW 540', 'SSW 565', 'SSW 810'] |\n| 11788 |  Fuller, E  |                 ['SSW 540']                 |            ['SYS 612', 'SYS 671', 'SYS 672', 'SYS 673', 'SYS 674', 'SYS 800']            |                 []                |\n+-------+-------------+---------------------------------------------+------------------------------------------------------------------------------------------+-----------------------------------+",
         "+------+------------------------------------------------------------------------------------------+-----------------------------------+\n| Dept |                                         Required                                         |              Elective             |\n+------+------------------------------------------------------------------------------------------+-----------------------------------+\n| SFEN | ['SSW 533', 'SSW 540', 'SSW 555', 'SSW 564', 'SSW 565', 'SSW 567', 'SSW 690', 'SSW 695'] |   ['CS 501', 'CS 513', 'CS 545']  |\n| SYEN |            ['SYS 612', 'SYS 671', 'SYS 672', 'SYS 673', 'SYS 674', 'SYS 800']            | ['SSW 540', 'SSW 565', 'SSW 810'] |\n+------+------------------------------------------------------------------------------------------+-----------------------------------+"
     ]
     self.assertEqual(repo.print_table(), test)
Exemple #10
0
class Test(unittest.TestCase):


    def tearDown(self):
        del self


    def test2(self):
        
        self.repository = Repository()
        self.controller = Controller(self.repository)
        
        block = self.repository._getPattern("block")
        assert len(block) == 7
        assert block[0] == "block"
        assert block[1] == block[2] == "2"
        assert block[6] == "11"
        
        no = self.repository._getPattern("name")
        assert no == None
        
        self.repository.storePattern("block", 1, 1)
        assert self.repository._data[1][1] == self.repository._data[1][2] == self.repository._data[2][1] \
                == self.repository._data[2][2] == "X"
                
        self.assertRaises(RepoError, self.repository.storePattern, "blinker", 7, 6)
        
        self.assertRaises(RepoError, self.repository.storePattern, "blinker", 2, 2)
        
        self.assertRaises(ValueError, self.controller.addPattern, "name", 0, -1)
        
    
    def test3(self):
        
        self.repository = Repository()
        self.controller = Controller(self.repository)
        
        self.repository.storePattern("spaceship", 0, 0)
        
        assert 1 == self.repository._getNumberOfNeighbors(2, 0)
        assert 2 == self.repository._getNumberOfNeighbors(2, 2)
        assert 3 == self.repository._getNumberOfNeighbors(1, 0)
        assert 5 == self.repository._getNumberOfNeighbors(1, 1)
        
        self.repository.nextState()
                
        assert self.repository._data[1][0] == "X"
        assert self.repository._data[1][2] == "X"
        assert self.repository._data[2][1] == "X"
        assert self.repository._data[2][2] == "X"
        assert self.repository._data[3][1] == "X"
        
        assert self.repository._data[0][1] == " "
        assert self.repository._data[2][0] == " "
        
        self.assertRaises(ValueError, self.controller.tick, -1)
Exemple #11
0
 def test_repo_retrieves_dependencies_in_order(self):
     testQuery = SqlCode(
         "with companies as (select company_name, company_id) select company_name from companies",
         "test_query")
     repo = Repository()
     repo.add_queries(testQuery.queries)
     queries = repo.retrieve_query_with_dependencies("test_query")
     self.assertEqual(len(queries), 2)
     self.assertTrue(testQuery.queries[0] == queries[0])
     self.assertTrue(testQuery.queries[1] == queries[1])
 def loop(self):
     self.repo = Repository('balance-scale.data')
     self.ctrl = Controller(self.repo)
     root = self.ctrl.generate(self.repo.getTrain(), [1, 2, 3, 4])
     total=0
     sum=0
     for i in self.repo.getTest():
         if(self.ctrl.test(i,root)==i[0]):
             sum+=1
         total+=1
     return sum/total
class TestRepository(TestCase):
    def setUp(self):
        self.repository = Repository(author='ilyashusterman',
                                     name='WordCount',
                                     load_data=False)

    def test_load_repository_data(self):
        self.repository.load()
        self.assertEqual(self.repository.contributors, 1)
        self.assertEqual(self.repository.commits, 46)
        self.assertEqual(self.repository.issues, 0)
Exemple #14
0
class Student( object ):
    '''
    classdocs
    '''


    def __init__( self, data_dict ):
        '''
        Constructor
        '''
        self._1_no = data_dict[ AgGlobals.STUDENT_DB_FIED_NO ]
        self._2_uoid = data_dict[ AgGlobals.STUDENT_DB_FIED_UOID ]
        self._3_duckid = data_dict[ AgGlobals.STUDENT_DB_FIED_DUCKID ]
        self._4_last_name = data_dict[ AgGlobals.STUDENT_DB_FIED_LNAME ]
        self._5_first_name = data_dict[ AgGlobals.STUDENT_DB_FIED_FNAME ]
        self._6_email = data_dict[ AgGlobals.STUDENT_DB_FIED_EMAIL ]
        self._7_dirname = data_dict[ AgGlobals.STUDENT_DB_FIED_DIR_NAME ]
        self._8_repo = Repository( data_dict[ AgGlobals.STUDENT_DB_FIED_REPO ] )

    def __str__( self ):
        return AgGlobals.string_of( self, 3 )

    def get_dir( self, index_len ):
        # If index_len = 3, this creates a string of the form:
        # {:3}_{}
        # ret = '{}{}{}_{}'.format( '{:0>', index_len, '}', '{}' )

        # Use the format string created above to format the student
        # directory name appropriately
        # return ret.format( self._1_no, self._7_dirname )

        return AgGlobals.get_student_dir_name( index_len, self._1_no, self._7_dirname )

    def get_index( self ):
        return '{}'.format( self._1_no )

    def get_name( self ):
        return '{} {}'.format( self._5_first_name, self._4_last_name )

    def clone_student_repo( self, destination, grading_log_file, student_log_file ):
        return self._8_repo.clone( destination, grading_log_file, student_log_file )

    def pull_student_repo( self, local_path, grading_log_file, student_log_file ):
        self._8_repo.pull( local_path, grading_log_file, student_log_file )

    def copy_student_repo( self, source, destination, index_len ):
        self._8_repo.copy( source, destination, self.get_dir( index_len ) )

    def get_stud_log_file_name( self, index_len, assignment_sub_dir_name ):
        return AgGlobals.get_stud_log_file_name( self.get_dir( index_len ), assignment_sub_dir_name )

    def get_stud_grades_file_name( self, index_len, assignment_sub_dir_name ):
        return AgGlobals.get_stud_grades_file_name( self.get_dir( index_len ), assignment_sub_dir_name )
Exemple #15
0
 def __init__( self, data_dict ):
     '''
     Constructor
     '''
     self._1_no = data_dict[ AgGlobals.STUDENT_DB_FIED_NO ]
     self._2_uoid = data_dict[ AgGlobals.STUDENT_DB_FIED_UOID ]
     self._3_duckid = data_dict[ AgGlobals.STUDENT_DB_FIED_DUCKID ]
     self._4_last_name = data_dict[ AgGlobals.STUDENT_DB_FIED_LNAME ]
     self._5_first_name = data_dict[ AgGlobals.STUDENT_DB_FIED_FNAME ]
     self._6_email = data_dict[ AgGlobals.STUDENT_DB_FIED_EMAIL ]
     self._7_dirname = data_dict[ AgGlobals.STUDENT_DB_FIED_DIR_NAME ]
     self._8_repo = Repository( data_dict[ AgGlobals.STUDENT_DB_FIED_REPO ] )
Exemple #16
0
 def __init__(self):
     logging.basicConfig(filename='master.log', level=logging.INFO)
     logging.info("Master initialize...")
     self.cf = configparser.ConfigParser()
     self.cf.read('config.ini')
     self.is_stop = False
     logging.info("Load database...")
     self.repo = Repository(self.cf['database']['url'],
                            self.cf['database']['user'],
                            self.cf['database']['password'],
                            self.cf['database']['dbname'])
     self.repo.connect()
     ms = self.repo.find_master()
     self.ip = ms.ip
     self.port = ms.port
Exemple #17
0
 def __init__(self):
     self.cf = configparser.ConfigParser()
     self.cf.read('config.ini')
     self.repo = Repository(self.cf['database']['url'],
                            self.cf['database']['user'],
                            self.cf['database']['password'],
                            self.cf['database']['dbname'])
     self.repo.connect()
     self.is_terminate = False
     self.is_found = False
     self.runnable = None
     self.is_run_ga = False
     self.ip = None
     self.port = None
     '''self.slave = Thread(target=self.service, args=())
Exemple #18
0
    def buildRepoList(self):
        """
        Get a list of Repository objects corresponding to top-level git
        repositories in the path.
        """
        repoList = self.rejectIgnoredRepos(self.getReposInPath())
        self.log('Discovered {} repositories'.format(len(repoList)))
        # If we were invoked with -v,--verbose; then warn about un-versioned
        # directories in SYSGIT_PATH
        if self.argVerbose:
            self.findUnversionedDirectories(repoList)

        # Construct RepositoryFlags object
        repoFlags = RepositoryFlags(submodules=self.argSubmodules,
                                    bugs=self.argBugs,
                                    colors=not self.argNoColor,
                                    stash=self.argShowStash,
                                    remotes=self.argRemotes,
                                    verbose=self.argVerbose)

        # Construct repository objects
        repoInstances = list()
        for repo in repoList:
            repoInstances.append(Repository(repo, repoFlags=repoFlags))
        return repoInstances
Exemple #19
0
    def testWrap(self):

        self.repository = Repository()
        self.controller = Controller(self.repository)

        self.repository._data = []
        for row in range(9):
            self.repository._data.append([0] * 9)

        self.repository._data[5][5] = self.repository._code["E"]
        self.repository._endeavour = Square("E", 5)

        self.repository._data[3][3] = self.repository._code["*"]

        self.repository._data[5][1] = self.repository._code["B"]

        self.assertRaises(ValueError, self.controller.warp,
                          Square("C", 1))  # not the same line

        self.assertRaises(ValueError, self.controller.warp, Square("C",
                                                                   3))  # star

        self.assertRaises(GameOver, self.controller.warp,
                          Square("E", 1))  # computer wins

        self.controller.warp, Square("C", 7)

        self.controller.warp, Square("G", 7)

        self.controller.warp, Square("E", 5)
def redrawMappings(repo):
    # call DiffLinesFunction.sh
    # output file names into JSON object
    repo = Repository.get_by_path(repo)

    if not repo:
        print(
            "No repository has been added to the database. Please specify a database before moving forward."
        )
        exit(1)

    fileList = dict()
    subprocess.call(['./getCodeChanges.sh redrawmappings' + ' ' + repo.path],
                    shell=True)

    # print(testList)

    with open('changedCode.txt', 'r') as fp:
        files = set()
        for line in fp.readlines():
            lines = line.split()
            files.add(lines[0])
            #print(lines[0])
        fileList['filesToMap'] = files
        fp.close()

    # print(fileList) # *** call test-to-source from here ***
    for f in fileList['filesToMap']:
        print(f)
def list_comments(self, query, *args):
    with Repository(db_file, table_name) as repository:
        comments_tuple = repository.find_all()
        comments = [
            Comment(item[0], item[1], item[2]) for item in comments_tuple
        ]
    return Template.render('comments.tpl', {"comments": comments})
Exemple #22
0
def run():

        params = {"evaporation": 0.1, "distancePriority": 2, "pheromoneImportance": 0.1, "randomFactor": 0.3, "steps": 100, "antFactor": 0.9}
        repository = Repository("resources/eil51.txt")
        aco = ACO(params, repository.params)
        ui = UI(aco)

        ui.run()
Exemple #23
0
def parse_args():
    """
    docstring
    """
    proj_name = None
    proj_description = ""
    proj_license = config("LICENSE") if config("LICENSE") != 'None' else None
    proj_git_ignore = config(
        "GITIGNORE") if config("GITIGNORE") != 'None' else None
    proj_is_private = False
    proj_with_readme = True

    args = enumerate(sys.argv[1:])
    for i, arg in args:
        if arg == "-h" or arg == "--help":
            f = open(f'{SCRIPT_ROOT_DIR_PATH}/man.txt',
                     "rt",
                     encoding='unicode_escape')
            print(f.read())
            f.close()
            sys.exit(0)

        elif arg == "-c" or arg == "--config":
            configure()
            sys.exit(0)

        elif arg == "--config-defaults":
            configure_defaults()
            sys.exit(0)

        elif arg == "-d" or arg == "--description":
            proj_description = next(args)[1]

        elif arg == "-nr" or arg == "--no-readme":
            proj_with_readme = False

        elif arg == "-l" or arg == "--license":
            proj_license = next(args)[1]

        elif arg == "-gi" or arg == "--gitignore":
            proj_git_ignore = next(args)[1]

        elif arg == "-p" or arg == "--private":
            proj_is_private = True

        else:
            proj_name = arg

    if proj_name is None:
        print(f'{c.red}ERROR:{c.rst} you must supply a repository name! ')
        print(
            f'Run {c.green}create_project --help{c.rst} to get more information.\n'
        )
        sys.exit(1)

    return Repository(proj_name, proj_description, proj_with_readme,
                      proj_license, proj_git_ignore, proj_is_private)
def main():
    #seed(1)
    repository = Repository(
        "E:\\ANUL II\\SEMESTRUL II\\INTELIGENTA ARTIFICIALA\\LABORATOR4\\resources\\easy_01_tsp.txt"
    )
    params = {'popSize': 5, 'noGen': 100}
    ga = GA(params, repository.params)
    ui = UI(ga)
    ui.run()
Exemple #25
0
def sync_missed_records(api_client: ApiClient, repository: Repository):
    try:
        older_than = datetime.utcnow() - timedelta(minutes=ONLY_SYNC_MISSED_RECORDS_OLDER_THAN_NUMBER_OF_MINUTES)
        missed_readings = repository.get_unsynced_readings(MAX_NUMBER_OF_RECORDS_TO_SYNC_AT_ONCE, older_than)
        if len(missed_readings) == 0:
            print(f"Re-sync: Everything is already synced. Exiting.")
            return

        print(f"Re-sync: Syncing {len(missed_readings)} missed records.")
        result_code = api_client.post_db_temperature_readings(missed_readings)
        if result_code in (200, 201):
            repository.mark_readings_synced(list(map(lambda x: x.id, missed_readings)))
            print(f"Re-sync: Successfully synced {len(missed_readings)} records.")
            return

        print(f"Re-sync: Failed. Status code: {result_code}")
    except Exception as e:
        print("Re-sync: Failed.", e)
def storeFilesAndFunctions(src, mapping):
    rCode = src + "/R"

    repo = Repository.get_by_path(src)
    repo = Repository.create(src) if not repo else repo

    # Add files to files table
    for f in mapping.keys():
        filePath = os.path.join(rCode, f)

        if len(f) > 0:
            file = SourceFile.get_by_file_path(filePath)

            if file is None:
                file = SourceFile.create(filePath, 1, repo.path)

            for func in mapping[f]:
                function = Function.get_by_name_and_file_id(func, file.fileID)
                if not function:
                    Function.create(func, file.fileID)
 def startHC(self):
     # start button fct
     
     n = int(self.lineEditN.text())
     nrGens = int(self.lineEditGenerations.text())
     
     repo = Repository(1, n)
     self.ctrl = Controller(repo, 0)
     
     worker = Worker(self.ctrl.HC, self.threadPrintHC, nrGens)
     self.threadpool.start(worker)
Exemple #28
0
def getListEmails():
    global listEmails
    global topList
    pathOutput = os.getcwd() + "/json/"
    r = Repository()
    r.checkRepositoryExist(pathOutput)
    jsonFiles = r.getListOfFiles(pathOutput)

    for i in range(len(jsonFiles)):
        d = {}
        s = SerialiseData(d)
        data = s.readFromFile(pathOutput + jsonFiles[i])
        emails = data['data']['email']

        for e in range(len(emails)):
            listEmails.append(emails[e])
            if topList.get(str(emails[e])):
                topList[str(emails[e])] = topList.get(str(emails[e])) + 1
            else:
                topList.update({str(emails[e]): 1})
    def startPOS(self):
        # start button fct

        n = int(self.lineEditN.text())
        popSize = int(self.lineEditPopSize.text())
        nrGens = int(self.lineEditGenerations.text())

        repo = Repository(popSize, n)
        self.ctrl = Controller(repo, 0)

        worker = Worker(self.ctrl.POS, self.threadPrintPOS, nrGens)
        self.threadpool.start(worker)
Exemple #30
0
def main(argv):
    url, key, location_name, sensor_name = process_inputs(argv)
    repository = Repository()
    repository.setup_sqlite_database()

    sensor = TSYS01.TSYS01(0x76)

    api_client = ApiClient(url, key)
    location_id = api_client.get_location_id(location_name)
    sensor_id = api_client.get_sensor_id(sensor_name)

    clean_up_db_looping_call = task.LoopingCall(clean_up_db, repository)
    clean_up_db_looping_call.start(CLEAN_UP_DB_EVERY_NUMBER_OF_HOURS * 3600)

    sync_missed_records_looping_call = task.LoopingCall(sync_missed_records, api_client, repository)
    sync_missed_records_looping_call.start(SYNC_MISSED_RECORDS_EVERY_NUMBER_OF_MINUTES * 60)

    take_reading_looping_call = task.LoopingCall(take_reading, sensor, repository, api_client, location_id, sensor_id)
    take_reading_looping_call.start(TAKE_READING_EVERY_NUMBER_OF_SECONDS)

    reactor.run()
Exemple #31
0
 def test_repo_keeps_dependencies(self):
     testQuery = SqlCode(
         "with companies as (select company_name, company_id) select company_name from companies",
         "test_query")
     repo = Repository()
     repo.add_queries(testQuery.queries)
     self.assertEqual(len(repo.retrieve_all_queries()), 2)
     self.assertEqual(
         repo.retrieve_query("companies").name,
         repo.retrieve_query("test_query").dependencies[0])
Exemple #32
0
def rezolvare():
    repo = Repository()
    populatie = Populatie(repo)
    for i in range(10000):
        p1, p2 = populatie.selectie_reproducere()
        c1 = p1.crossover(p2)
        c1.mutation()
        dist = 0
        nodPrecedent = c1.repres[0]
        for nod in c1.repres[1:]:
            dist += repo.get_graf()[nodPrecedent - 1][nod - 1]
            nodPrecedent = nod
        dist += repo.get_graf()[nodPrecedent - 1][c1.repres[0] - 1]
        c1.fitness = dist
        if p1.fitness > c1.fitness and c1.repres[0] == 1:
            for k in range(len(populatie.populatie)):
                if populatie.populatie[k] == p1:
                    populatie.populatie[k] = c1
        if p2.fitness > c1.fitness and c1.repres[0] == 1:
            for k in range(len(populatie.populatie)):
                if populatie.populatie[k] == p2:
                    populatie.populatie[k] = c1
        populatie.populatie.sort(key=fct)
        print(populatie.populatie[0])
    populatie.populatie.sort(key=fct)
    repo.write_to_file(
        [populatie.populatie[0].repres, populatie.populatie[0].fitness])
Exemple #33
0
 def test_repo_keeps_dependencies(self):
     testQuery = SqlCode("with companies as (select company_name, company_id) select company_name from companies", "test_query")
     repo = Repository()
     repo.add_queries(testQuery.queries)
     self.assertEqual(len(repo.retrieve_all_queries()), 2)
     self.assertEqual(repo.retrieve_query("companies").name, repo.retrieve_query("test_query").dependencies[0])
__author__ = 'Andrew'
import csv
from Repository import Repository
from Repository import DistrInfo
from FakePatients import working_path
import scipy.stats as stats
import matplotlib.pyplot as plt
import math
import numpy as np


# print get_patients_freq()

repo = Repository()

repo.add_age_distr('050', lambda count: [18 if x < 18 else 103 if x > 103 else int(round(x))
                                     for x in stats.norm.rvs(loc=70.0, scale=16, size=count)])

# Cardiology <35
repo.add_patients_count_distr((2, 2, '050'), DistrInfo(lambda x: stats.poisson.rvs(mu=1.1, size=x), 0.7))
repo.add_rlos_distr((2, 2, '050'),
                    lambda size: [int(math.floor(x)) for x in stats.expon.rvs(scale=2.0, size=size)],
                    lambda x: x >= 1)

# Cardiology 35-50
repo.add_patients_count_distr((2, 3, '050'), DistrInfo(lambda x: stats.poisson.rvs(mu=1.17, size=x), 0.14))
repo.add_rlos_distr((2, 3, '050'),
                    lambda size: [int(math.floor(x)) for x in stats.expon.rvs(scale=2.0, size=size)],
                    lambda x: x >= 1)

# Cardiology 50-70
Exemple #35
0
    try:
      if not msg.show():
        print "Could not display message: (%s) %s"%(title, message)
    except:
      print "Error communicating with notification daemon"

  if growlNotifier is not None:
    growlNotifier.notify('Repo modified',title,message)
                        

if __name__ == "__main__":
  repos = []
  for project_folder in _CONFIG["project_folders"]:
    if os.path.exists(os.path.expanduser(project_folder)):
      print project_folder
      raw_repos = find_repo(project_folder, maxdepth=_CONFIG["MAXDEPTH"])
      for raw_repo in raw_repos:
        repo = Repository(raw_repo,GIT_PATH=_CONFIG["GIT_PATH"])
        repos.append(repo)
        for ref in repo.lockedremote:
          show_message("Warning", "%s: remote '%s' is not updatable.  Check that a passwordless SSH key exists for this remote"%(repo.name, ref))

  while True:
    for repo in repos:
      if repo.check_updates():
        show_gui_updates(repo.updates)
        for key, update in repo.get_new_updates():
          show_message("Update to %s"%update["repo"], "[%s]\n%s"%(update["ref"],update["desc"]),{key:update})
    sleep(_CONFIG["check_freq"])
    repo.update_repo()
__author__ = 'Andrew'
from Repository import Repository
from Repository import DistrInfo
from FakePatients import get_patients_freq
import scipy.stats as stats
import matplotlib.pyplot as plt
import math


repo = Repository()
# Cardiology 35-50
repo.add_patients_count_distr((2, 3, '050'), DistrInfo(lambda x: stats.poisson.rvs(mu=1.17, size=x), 0.14))
repo.add_rlos_distr((2, 3, '050'), lambda count: [int(math.floor(x)) for x in stats.expon.rvs(scale=2.0, size=count)])
# Cardiology 50-70
repo.add_patients_count_distr((2, 4, '050'), DistrInfo(lambda x: stats.poisson.rvs(mu=1.46, size=x), 0.45))
# Cardiology 50-70
repo.add_patients_count_distr((3, 4, '050'), DistrInfo(lambda x: stats.poisson.rvs(mu=1.3, size=x), 0.336))
# Urological Surgery 50-70
repo.add_patients_count_distr((2, 4, '387'), DistrInfo(lambda x: stats.poisson.rvs(mu=1.44, size=x), 0.267))
# Urological Surgery 50-70
repo.add_patients_count_distr((3, 4, '387'), DistrInfo(lambda x: stats.poisson.rvs(mu=1.17, size=x), 0.08))
repo.add_rlos_distr((3, 4, '387'), lambda count: [int(math.floor(x)) for x in stats.expon.rvs(scale=2.4, size=count)])


# put selection here
selection = (2, 3, '050')

# build chart generated data versus historical data
predicted = repo.predict(selection, 30)
historical, sd, ed = repo.history(selection, 30)
title_common = " [%4d-%02d-%02d %4d-%02d-%02d]" \
Exemple #37
0
from Repository import Repository

FILE_NAME = "logs.csv"

logs = LogFile(FILE_NAME)
slack_presenter = Slack("", "logtest")
presentation_node = PresentationNode(logs, slack_presenter)

parser = argparse.ArgumentParser(description='Parse creation inputs')
parser.add_argument("--node_file", dest = "node_file")
parser.add_argument("--node_type", dest = "node_type")
parser.add_argument("--create", dest = "create")

args = parser.parse_args()

node = None
if args.create == "true":
    node = Repository().load_node(args.node_file)
else:
    logs = LogFile(FILE_NAME)
    if args.node_type == "slack":
        slack_presenter = Slack("", "logtest")
        node = PresentationNode(logs, slack_presenter)
    else:
        node = LogNode(logs)

try:
    node.start()
except KeyboardInterrupt:
    Repository().store_node(node, args.node_file)
Exemple #38
0
 def test_repo_stores_query(self):
     testQuery = Query("Test", "SELECT 1", [])
     repo = Repository()
     repo.add_query(testQuery)
     self.assertTrue(len(repo.queries.keys()) == 1)
     self.assertTrue(repo.retrieve_query("Test") is testQuery)
Exemple #39
0
 def test_repo_keeps_dependencies(self):
     testQuery = Query("Test", "SELECT 1", ["TestDEP"])
     repo = Repository()
     repo.add_query(testQuery)
     self.assertTrue(len(repo.queries.keys()) == 1)
     self.assertTrue(repo.retrieve_query("Test").dependencies[0] == "TestDEP")
Exemple #40
0
 def test_repo_stores_query(self):
     testQuery = Query("test_query", "select company from companies")
     repo = Repository()
     repo.add_query(testQuery)
     self.assertTrue(len(repo.retrieve_all_queries()) == 1)
     self.assertTrue(repo.retrieve_query("test_query") is testQuery)