コード例 #1
0
    def handleRunList(self, runList):
        self.runs = []
        run_nodes = runList[0].getElementsByTagName('run')

        for run in run_nodes:
            #converting to miles
            dist_string = self.getText(run.getElementsByTagName('distance'))
            dist = float(dist_string) / 1.609
            #converting to seconds
            dur_string = self.getText(run.getElementsByTagName('duration'))
            dur = int(dur_string) / 1000
            #get the startTime
            startTime = self.getText(run.getElementsByTagName('startTime'))
            startTime = strptime(startTime[:-6], '%Y-%m-%dT%H:%M:%S')
            #get Nike+ run info
            howFelt = self.getText(run.getElementsByTagName('howFelt'))
            if howFelt: howFelt = int(howFelt)
            weather = self.getText(run.getElementsByTagName('weather'))
            if weather: weather = int(weather)
            terrain = self.getText(run.getElementsByTagName('terrain'))
            if terrain: terrain = int(terrain)
            #make the run object
            run_obj = Run(dist, dur, startTime, howFelt, weather, terrain)
            self.runs.append(run_obj)

        self.runs = self.runs[self.startRun:]
        self.paces = [run.pace for run in self.runs]
コード例 #2
0
ファイル: game.py プロジェクト: mirrorcult/speedbot
 def get_run_id(self, category, user):
     """Retrieves a run's ID in the given
     category name by the given user."""
     try:
         cat_name = self.fuzzy_match_categorylevel(category)
         leaderboard = self.get_categorylevel_leaderboard(cat_name)
         runs = leaderboard["runs"]
         players = leaderboard["players"]["data"]
         names_by_run = {}
         for r in runs:
             idx = runs.index(r)
             run_data = Run(r["run"])  # run
             try:
                 user_name = players[idx]["names"]["international"]
             except KeyError:
                 continue
             names_by_run[run_data.get_run_id()] = user_name
         result = process.extractOne(user, names_by_run.values())
         log.info(
             f"Found run by and matched user {user} to {result[0]} with {result[1]}% confidence"
         )
         # thanks speedrun.com
         return list(names_by_run.keys())[list(names_by_run.values()).index(
             result[0])]
     except srcomapi.exceptions.APIRequestException:
         return None
コード例 #3
0
    def test_login_menu_employee(self, mocksql, inputs, role, employee):
        """ Test login menu method."""
        role.return_value = 22
        employee.return_value = True
        inputs.side_effect = ['email', 'pswd', '#']

        assert Run(mocksql).login_menu() is True
コード例 #4
0
ファイル: importer.py プロジェクト: gaudenz/bosco
    def import_data(self, store):

        for line in self.__runs:
            course_code = line[SIRunImporter.COURSE]
            cardnr = line[SIRunImporter.CARDNR]

            self._punches = []
            i = SIRunImporter.BASE
            while i < len(line):
                self.add_punch(int(line[i]), line[i + 1])
                i += 2

            run = Run(
                int(cardnr),
                course=course_code,
                punches=self._punches,
                card_start_time=self.__datetime(line[SIRunImporter.START]),
                card_finish_time=self.__datetime(line[SIRunImporter.FINISH]),
                check_time=self.__datetime(line[SIRunImporter.CHECK]),
                clear_time=self.__datetime(line[SIRunImporter.CLEAR]),
                readout_time=self.__datetime(line[SIRunImporter.READOUT]),
                store=store)
            run.complete = True
            store.add(run)
            if self._replay is True:
                print "Commiting Run %s for SI-Card %s" % (course_code, cardnr)
                store.commit()
                sleep(self._interval)
コード例 #5
0
    def test_login_menu_admin(self, mocksql, inputs, role, admin):
        """ Test login menu method."""
        role.return_value = 11
        admin.return_value = True
        inputs.side_effect = ['email', 'pswd', '#']

        assert Run(mocksql).login_menu() is True
コード例 #6
0
    def test_get_role_failure(self, mocksql):
        """ Test get role method."""
        sqlite_execute_mock = mock.Mock()
        mocksql.cursor.return_value = sqlite_execute_mock
        mocksql.execute.return_value = sqlite_execute_mock
        sqlite_execute_mock.fetchone.return_value = None

        assert Run(mocksql).get_role('email', 'pswd') == 0
コード例 #7
0
 def __init__(self, cotrans = False):
     self.run = Run()
     self.run.cotrans = cotrans
     self.__processor = None
     self._targets = None
     self._masks = None
     self._profiles = None
     self.force_mask = None
コード例 #8
0
ファイル: main.py プロジェクト: mitsuhiko-nozawa/atmacup_08
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--config")
    args = parser.parse_args()

    CONFIG = yaml.safe_load(open(args.config))

    run = Run(CONFIG)
    run()
コード例 #9
0
ファイル: worker.py プロジェクト: krivard/codalab-cli
 def _run(self, bundle, resources):
     if self.shared_file_system:
         bundle_path = bundle['location']
     else:
         bundle_path = self._dependency_manager.get_run_path(bundle['uuid'])
     run = Run(self._bundle_service, self._docker, self._image_manager,
               self, bundle, bundle_path, resources)
     if run.run():
         self._worker_state_manager.add_run(bundle['uuid'], run)
コード例 #10
0
    def create_run(self, match):
        self.run = Run()

        map_name = match.group(4)
        self.run.map_file = map_name

        self.run.give_recommendation = (match.group(5) == 'True')
        self.run.with_justification = (match.group(6) == 'True')

        self.run.start_real_time = float(match.group(2))
コード例 #11
0
ファイル: worker.py プロジェクト: Akhila-Yerukola/codalab-cli
 def _run(self, bundle, resources):
     if self.shared_file_system:
         bundle_path = bundle['location']
     else:
         bundle_path = self._dependency_manager.get_run_path(bundle['uuid'])
     run = Run(self._bundle_service, self._docker, self._image_manager,
               self, bundle, bundle_path, resources)
     if run.run():
         with self._runs_lock:
             self._runs[bundle['uuid']] = run
コード例 #12
0
    def setUp(self):
        print
        self.run = Run()

        def setUpWorkingDirectory():
            work_dir = self.get_working_directory()
            shutil.rmtree(work_dir, True)
            os.mkdir(work_dir)

        setUpWorkingDirectory()
コード例 #13
0
 def test_run_update_available(self):
     """
     Test ability to run PyUpdaterWxDemo and confirm that an update is available.
     """
     self.assertEqual(__version__, CURRENT_VERSION)
     from run import Run
     self.app = Run(argv=['RunTester', '--debug'],
                    clientConfig=self.clientConfig)
     self.assertEqual(self.app.statusBar.GetStatusText(),
                      "Update available but application is not frozen.")
     sys.stderr.write("We can only restart a frozen app!\n")
コード例 #14
0
 def __init__(self, debug=False):
     '''
     initializes the advanced class for awscm
     
     :param debug: enables debug information to be printed
     '''
     
     self.debug = debug
     self.run = Run(debug=debug)
     self.result_dir = {}
     self.final_result = ''
コード例 #15
0
    def test_run_no_updates_available(self):
        """
        Test ability to run PyUpdaterWxDemo and confirm that no updates are available.
        """
        from run import Run
        self.assertRaises(SystemExit, Run, ['RunTester', '--version'])

        self.assertEqual(__version__, CURRENT_VERSION)
        self.app = Run(argv=['RunTester', '--debug'],
                       clientConfig=self.clientConfig)
        self.assertEqual(self.app.statusBar.GetStatusText(),
                         "No available updates were found.")
コード例 #16
0
ファイル: uiset.py プロジェクト: oregu93/autofp
 def open(self, path):
     self.state = 1
     self.run = Run()  # get a new Run()
     self.showMsg(path + " open")
     self.run.reset(path)
     self.text_path.setText(unicode(path, "gbk", "ignore"))
     self.updateTable()
     self.pcr_yorn = True
     self.window_order.init(self.run.job)
     self.window_order.ui.combobox_job.currentIndex = self.run.job
     self.tabwidget_run.setEnabled(True)
     return
コード例 #17
0
ファイル: api.py プロジェクト: wangdayaya/NER-LOC
def get_result():
    if not request.args or 'input' not in request.args:
        # 没有指定imgage则返回全部
        return json.dumps({'result':'args error'})
    else:
        try:
            input = request.args['input']
            main  = Run(type = 'line')
            res = main.online(input)
            return res
        except:
            return json.dumps({'result': 'error'})
コード例 #18
0
 def policy_value_fn(self, board):
     run_game = Run()
     legal_positions = []
     for i in list(board.generate_legal_moves()):
         legal_positions.append(i.uci())
     current_state = np.ascontiguousarray(run_game.current_state().reshape(
         -1, 18, 8, 8))
     #current_state = run_game.current_state()
     #print(current_state)
     act_probs, value = self.policy_value(current_state)
     act_probs = zip(legal_positions, act_probs[0])
     #print('act_probs,value', list(act_probs), value)
     return act_probs, value
コード例 #19
0
def main():
    board = [
        Run(BLUE, [7, 8, 9, 10]),
        Group(11, [BLACK, BLUE, RED, ORANGE]),
        Run(BLACK, [7, 8, 9, 10, 11, 12]),
        Group(7, [BLACK, RED, ORANGE])
    ]
    # target_tile = Tile(9, BLUE)
    # tiles = [target_tile]

    tiles = [Tile(6, BLACK), Tile(10, BLACK)]
    for s in board:
        tiles += s.get_tiles()

    # for s in board:
    #     print(s)

    tiles_copy = copy.deepcopy(tiles)
    tiles_copy = rearrange(tiles_copy)
    print('*' * 100)
    print('*' * 100)
    print('*' * 100)
    print(tiles_copy)
コード例 #20
0
ファイル: script.py プロジェクト: mmoya26/testrail-automation
def get_runs(user):
    # Gets all the currents runs in our mainProject
    # use mainProject.id as part of the API get call
    try:
        test_runs = client.send_get(f'get_runs/{mainProject.id}')
    except:
        print(
            "Something went wrong when trying to get the tests runs, try again later."
        )

    # If there is no user then do not print the following statement
    if user != None:
        print(
            f'Getting runs for: User Name: {user["name"]} - User Email: {user["email"]} - User ID: {user["id"]}'
        )
        print(
            f"Getting runs from Suite: Suite ID: {SUITE_ID} - Suite Name: {SUITE_NAME}"
        )
    else:
        print(
            f"Getting all runs from Suite: Suite ID: {SUITE_ID} - Suite Name: {SUITE_NAME}"
        )

    print(
        "################################################################################################################"
    )

    # Loop through the runs
    for run in test_runs:
        # Create a temporary run instance
        r = Run(run["id"], run["name"], run["is_completed"], run["project_id"],
                run["suite_id"], run["created_by"], run["url"])

        if user != None:
            # If run is not completed/closed belong to the main project and it is within the suite that we are working with
            # and it mataches the user id from the provided user email then, add that run to our runs list
            if r.is_completed == False and r.project_id == mainProject.id and r.suite_id == SUITE_ID and r.created_by == int(
                    user["id"]):
                runs.append(r)
                print(
                    f'RunID {r.id}: was added to "runs" list. Current lenght of "runs" list is: {len(runs)}'
                )
        else:
            # If run is not completed/closed and belong to the main project and it is within the suite that we are working with
            # add that run to our runs list
            if r.is_completed == False and r.project_id == mainProject.id and r.suite_id == SUITE_ID:
                runs.append(r)
                print(
                    f'RunID {r.id}: was added to "runs" list. Current lenght of "runs" list is: {len(runs)}'
                )
コード例 #21
0
ファイル: autofp.py プロジェクト: oregu93/autofp
def start_autofp():
    app = QtGui.QApplication(sys.argv)
    com.com_init("ui")
    if (params.gettime() > 21160831):
        print "find a new version , please download ...  "
        p = newversion_set.Ui_version()
        p.show()
        sys.exit(app.exec_())
    r = Run()
    window = Ui()
    com.ui = window
    window.run = r
    window.show()
    sys.exit(app.exec_())
コード例 #22
0
    def declare_run(self, run_id):
        '''
        Declare a run. Use it like this::

            with self.declare_run(run_id) as run:
                # add output files and information to the run here
        '''
        # Replace whitespaces by underscores
        run_id = re.sub(r'\s', '_', run_id)
        if run_id in self._runs:
            raise UAPError("Cannot declare the same run ID twice: %s." %
                           run_id)
        run = Run(self, run_id)
        self.add_run(run)
        return run
コード例 #23
0
ファイル: io.py プロジェクト: jason790/crayimage
def load_index(index_file, root):
  """
  Loads runs defined bu the provided index file.
  Index file is a definition of runs.

  :param index_file: path to the index file.
    It can be:
      1. a path on your local filesystem,
      2. a path relative to the data root,
      3. a name of predefined index file.

    The file is searched in the described above order.
  :param root: path to the data root
  :return: list of Run objects defined by the index file.
  """
  spec = get_index_file(index_file, root)

  runs = dict()
  for run in spec:
    if type(spec[run]['path']) is list:
      paths = np.array([
        osp.normpath(item)
        for item in spec[run]['path']
      ])
    else:
      paths = get_run_paths(root, spec[run]['path'])

    timestamps = extract_from_paths(paths, spec[run]['timestamp'], long)

    sorting_index = np.argsort(timestamps)

    info = dict()
    for k in spec[run]['info']:
      info[k] = extract_from_paths(paths, spec[run]['info'][k])[sorting_index]

    runs[run] = Run(
      paths=paths[sorting_index],
      timestamps=timestamps[sorting_index],
      source=spec[run]['source'],
      image_type=spec[run]['type'],
      meta_info=info,
      run_info=spec[run].get('run_info', None),
      index_info=spec[run],
      name=run,
      data_root=root
    )

  return runs
コード例 #24
0
    def test_update_csv(self):
        m = MagicMock()
        m.val = {
            'mcc': [1, 2, 3],
            'acc': [1, 2, 3]
        }
        m.train = {
            'mcc': [1, 2, 3],
            'acc': [1, 2, 3]
        }
        m.test = {
            'mcc': [1, 2, 3],
            'acc': [1, 2, 3]
        }

        m2 = MagicMock()
        m2.val = {
            'mcc': [4, 5, 6],
            'acc': [4, 5, 6]
        }
        m2.train = {
            'mcc': [4, 5, 6],
            'acc': [4, 5, 6]
        }
        m2.test = {
            'mcc': [4, 5, 6],
            'acc': [4, 5, 6]
        }

        r = Run("unit_test", 0)
        r.target.update(1, m)
        r.naive.update(1, m)
        r.target.update(2, m2)
        r.naive.update(2, m2)
        r.target.update(3, m)
        r.naive.update(3, m)
        r.target.update(4, m2)
        r.naive.update(4, m2)

        self.assertListEqual(m.val['mcc'], list(r.target.val.mcc.df["1"].values))
        self.assertListEqual(m2.val['mcc'], list(r.target.val.mcc.df["2"].values))
        self.assertListEqual(m.val['mcc'], list(r.target.val.mcc.df["3"].values))
        self.assertListEqual(m2.val['mcc'], list(r.target.val.mcc.df["4"].values))
コード例 #25
0
    def start(self):
        runs = [
            Run("1", self.dataSet, 0, 2),
            Run("2", self.dataSet, 0, 2),
            Run("3", self.dataSet, -2, 2),
            Run("4", self.dataSet, -2, 2),
            Run("5", self.dataSet, -2, 2),
            Run("6", self.dataSet, 0, 3),
            Run("7", self.dataSet, 0, 3),
            Run("8", self.dataSet, 0, 3)
        ]

        for run in runs:
            run.start()
        # for

        for run in runs:
            run.join()
        # for

        self.scikit.calculateLinReg()
コード例 #26
0
ファイル: lit.py プロジェクト: kazarin1alex/lit
    def __init__(self, worker, client):
        super(Lit, self).__init__()

        self.worker = worker
        self.client = client

        from go import Go
        from run import Run
        #from recent import Recent
        #from iciba import Iciba
        #from f import F
        #lit = Lit([Go(), Run(), Recent(), Iciba()])
        plugins = [
            Go(worker=worker, client=client),
            Run(worker=worker, client=client)
        ]

        lay = QVBoxLayout()

        # spacing of search box
        lay.setSpacing(0)
        lay.setMargin(0)

        self.inp = Input(self.act, self)
        self.inp.textChanged.connect(self._try_query)
        self.completer = Suggest(self.inp)
        #self.inp.setCompleter(self.completer)
        self.completer.activated[QModelIndex].connect(self.select)
        lay.addWidget(self.inp)
        self.setLayout(lay)
        self._install_plugins(plugins)
        self.setWindowFlags(
            Qt.FramelessWindowHint
            | Qt.Popup
            | Qt.WindowStaysOnTopHint
        )
        self.setWindowTitle('lit')

        self.mutex = QMutex()

        self.jobs = []
コード例 #27
0
ファイル: speedbot.py プロジェクト: mirrorcult/speedbot
def create_top_run_embed(category_name, n):
    """Creates an embed containing the top n runs in the given category."""
    runs = api.get_categorylevel_leaderboard(category_name)["runs"]
    n = n if len(runs) > n else len(runs)

    embed = discord.Embed(title=f":medal: - Top {n} {category_name} runs",
                          colour=discord.Colour.blue())

    for x in range(n):
        run = Run(runs[x]["run"])  # run

        runner = api.get_user(run.get_runner_id())
        runner_name = runner.get_name()
        flag = runner.get_flag()
        time = run.get_primary_time_formatted()
        link = run.get_link()

        embed.add_field(name=f"{suf(x + 1)} | {flag} {runner_name} | {time}",
                        value=link,
                        inline=False)
    return embed
コード例 #28
0
ファイル: demo.py プロジェクト: brownmagik352/uwpmp_nlp_hw4
def demo(config):
    app = Flask(__name__)

    with tf.device("/cpu:0"):
        demo_run = Run(config)

        supervisor = tf.train.Supervisor(
            logdir=config.out_dir,
            save_model_secs=config.save_model_secs,
            summary_op=None)
        coord = tf.train.Coordinator()

    @app.route("/")
    def index():
        return render_template('index.html')

    @app.route("/_get_answer")
    def get_answer():
        context = request.args.get('context', "", type=str)
        ques = request.args.get('ques', "", type=str)
        squad = create_squad(context, ques)
        with open(config.squad_path, 'w') as fp:
            json.dump(squad, fp)
        demo_run.data.load()

        with supervisor.managed_session(config=tf.ConfigProto(
                allow_soft_placement=True)) as sess:
            demo_run.start_queue(sess, coord)
            e = demo_run.lap(supervisor, sess)
            print(e)

            # coord.request_stop()
            # demo_run.join_queue(coord)
            answer = next(iter(e.get_answers().values()))
            print(answer)
            return jsonify(answer=answer)

    app.run(port=config.port, host=config.host)
コード例 #29
0
ファイル: worker.py プロジェクト: RogerXT/codalab-cli
    def _run(self, bundle, resources):
        if self.shared_file_system:
            bundle_path = bundle['location']
        else:
            bundle_path = self._dependency_manager.get_run_path(bundle['uuid'])

        cpuset, gpuset = self._allocate_cpu_and_gpu_sets(
            resources['request_cpus'], resources['request_gpus'])

        if len(cpuset) == 0 and len(
                gpuset
        ) == 0:  # revert self._cpuset_free and self._gpuset_free in-place
            logger.debug(
                'Unsuccessful allocation of cpu and gpu sets for bundle %s',
                bundle['uuid'])
            return

        run = Run(self._bundle_service, self._docker, self._image_manager,
                  self, bundle, bundle_path, resources, cpuset, gpuset)
        if run.run():
            self._worker_state_manager.add_run(bundle['uuid'], run)
        else:  # revert self._cpuset_free and self._gpuset_free in-place
            self._deallocate_cpu_and_sets(cpuset, gpuset)
コード例 #30
0
    def __init__(self, init_model = None):
        self.board_width = 8
        self.board_height = 8
        self.readed_files_count = 0
        self.valid_files_num = 0

        self.run_game = Run()

        self.learn_rate = 1e-6
        self.lr_multiplier = 1.0
        self.temp = 1.0
        self.chess_mcts_playout = 4
        self.mcts_num = 10
        self.c_puct = 5
        self.buffer_size = 10000
        self.batch_size = 384
        self.data_buffer = deque(maxlen=self.buffer_size)
        self.play_batch_size = 1
        self.epochs = 5
        self.kl_targ = 0.02
        self.check_freq = 10
        self.game_batch_num = 15000
        self.best_win_ratio = 0.0

        self.loss_list = []
        self.entropy_list = []

        if init_model:
            self.policy_value_net = Policy_value_net(model_file=init_model)
        else:
            self.policy_value_net = Policy_value_net()

        self.mcts_player = MCTSPlayer(self.policy_value_net.policy_value_fn,
                                      c_puct=self.c_puct,
                                      n_playout=self.chess_mcts_playout,
                                      is_selfplay=1)