def __init__(self, playerNum): self.worker1 = worker.Worker() self.worker2 = worker.Worker() self.workers = [self.worker1, self.worker2] self.lastMovedWorker = -1 self.previousPositionWorker = worker.Worker() self.playerNum = playerNum
def test_init_server_local(self): try: server = worker.Worker('localhost', 6667, 'deadbeef', 1) except OSError as err: self.fail('cannot create server on local host') # giving a nonesense host name and expect an exception with self.assertRaises(OSError): worker.Worker('blah', 1234, 'deadbeaf', 1)
def test_repo(): """test""" bill = worker.Worker('Bill') john = worker.Worker('John') log_file = log.Log() fixed_task = task.Task('fixed') hourly_task = task.Task('hourly', time=2) log_file.confirm(bill, fixed_task) log_file.confirm(john, hourly_task) assert log_file.report() == """Bill\t$20
def test_report_one(): """test one: workers try to take not completed tasks""" log1 = log.Log() worker1 = worker.Worker("Dima") worker2 = worker.Worker("John") task1 = hourlytask.HourlyPaymentTask("Homework", 10, 3) task2 = task.Task("Take cup of tea", 5) worker1.take_task(task1, log1) worker2.take_task(task2, log1) assert log1.report() == 'Dima\t$30\nJohn\t$5'
def test_report(): worker1 = worker.Worker("Bill") worker2 = worker.Worker("John") mylog = log.Log() task_fixed = fixedpayment.FixedPayment("build home", 20) task_per_h = paymentperhour.PaymentPerHour("do nothing", 15, 2) worker1.take_task(task_fixed) worker2.take_task(task_per_h) worker2.confirm(task_per_h, mylog) worker1.confirm(task_fixed, mylog) assert mylog.report() == """Bill\t$20
def test_report_three(): """test three: one of workers try to take few not completed tasks""" log1 = log.Log() worker1 = worker.Worker("Dima") worker2 = worker.Worker("John") task1 = hourlytask.HourlyPaymentTask("Homework", 10, 3) task2 = task.Task("Take cup of tea", 5) task3 = task.Task("Web serfing", 25) worker1.take_task(task1, log1) worker2.take_task(task2, log1) worker1.take_task(task3, log1) assert log1.report() == 'Dima\t$55\nJohn\t$5'
def test_report_one(): info = log.Log() worker_artem = worker.Worker("Artem") worker_alex = worker.Worker("Alex") worker_masha = worker.Worker("Masha") masha_fixet_task = task.Task("Task1", 300) fixet_task = task.Task("Task2", 100) hoyrly_task = hourlytask.HourlyTask("Task3", 200, 3) worker_masha.get_task(masha_fixet_task, info) worker_artem.get_task(fixet_task, info) worker_alex.get_task(hoyrly_task, info) assert info.report() == 'Masha\t$300\nArtem\t$100\nAlex\t$600'
def test_report_four(): """test four: workers try to take not completed tasks""" log1 = log.Log() worker1 = worker.Worker("Dima") worker2 = worker.Worker("John") worker3 = worker.Worker("Bill") task1 = hourlytask.HourlyPaymentTask("Homework", 10, 3) task2 = task.Task("Take cup of tea", 5) task3 = task.Task("Web serfing", 25) worker1.take_task(task1, log1) worker2.take_task(task2, log1) worker3.take_task(task3, log1) assert log1.report() == 'Dima\t$30\nJohn\t$5\nBill\t$25'
def test_tasks_reporting(): """Check if tasks are properly logged and reported""" logg = log.Log() task_1 = tasks.Task("one", 20) task_2 = tasks.Task("two", 70) day_plan_obj = day_plan.DailyPlan() day_plan_obj.create_plan(task_1, task_2) worker_1 = worker.Worker("John") worker_2 = worker.Worker("Mary") worker_2.get_task_from_dp(day_plan_obj) worker_2.log_task(logg, worker_2.get_current_task()) worker_1.get_task_from_dp(day_plan_obj) worker_1.log_task(logg, worker_1.get_current_task(), 5) assert (logg.get_report()) == """Mary earned $70
def __init__(self): super().__init__() self.label = QLabel("0") # 1 - create Worker and Thread inside the Form self.obj = worker.Worker() # no parent! self.thread = QThread() # no parent! # 2 - Connect Worker`s Signals to Form method slots to post data. self.obj.intReady.connect(self.onIntReady) # 3 - Move the Worker object to the Thread object self.obj.moveToThread(self.thread) # 4 - Connect Worker Signals to the Thread slots self.obj.finished.connect(self.thread.quit) # 5 - Connect Thread started signal to Worker operational slot method self.thread.started.connect(self.obj.procCounter) # * - Thread finished signal will close the app if you want! #self.thread.finished.connect(app.exit) # 6 - Start the thread self.thread.start() # 7 - Start the form self.initUI()
def __init__(self, parent=None): BaseFrame.__init__(self, parent, -1, lang.getstr("measurement_report")) self.Bind(wx.EVT_CLOSE, self.OnClose) self.SetIcons(config.get_icon_bundle([256, 48, 32, 16], appname)) res = TempXmlResource(get_data_path(os.path.join("xrc", "report.xrc"))) res.InsertHandler(xh_fancytext.StaticFancyTextCtrlXmlHandler()) res.InsertHandler( xh_filebrowsebutton.FileBrowseButtonWithHistoryXmlHandler()) res.InsertHandler(xh_hstretchstatbmp.HStretchStaticBitmapXmlHandler()) res.InsertHandler(xh_bitmapctrls.BitmapButton()) res.InsertHandler(xh_bitmapctrls.StaticBitmap()) self.panel = res.LoadPanel(self, "panel") self.Sizer = wx.BoxSizer(wx.VERTICAL) self.Sizer.Add(self.panel, 1, flag=wx.EXPAND) self.set_child_ctrls_as_attrs(self) self.measurement_report_btn = wx.Button(self.panel, -1, lang.getstr("measure")) self.panel.Sizer.Insert(2, self.measurement_report_btn, flag=wx.RIGHT | wx.BOTTOM | wx.ALIGN_RIGHT, border=16) self.worker = worker.Worker(self) self.worker.set_argyll_version("xicclu") BaseFrame.setup_language(self) self.mr_setup_language() self.mr_init_controls() self.mr_update_controls() self.mr_init_frame()
def initScript(): # Get parameters and inputs lists GDict['parameters'] = mp.ModelParameters() GDict['parameters'].make_param(GObject, GSolver, GDict) GDict['parameters'].get_parameters() GDict['parameters'].get_model_inputs() GDict['script'] = GDict['parameters'].script_name GDict['script_input'] = GDict['parameters'].script_input # Create socket GDict['worker'] = wrk.Worker(GDict['parameters'].port) # Get reward object GDict['reward'] = reward.Reward(GObject, GSolver, GDict, MVec3) # Get observation params param_values = GDict['parameters'].get_parameters_values() # Send request with init worker state request = [param_values, 0, True, 'in'] GDict['worker'].send(request) # Get reply that reset successful reply = GDict['worker'].recv() #print("Finished", reply) GDict['done'] = False GDict['episodeTime'] = GDict['parameters'].episode_duration GDict['routerState'] = 'st' GDict['delay'] = GDict['parameters'].delay GDict['oldTime'] = 0 GDict['reward'].custom_start()
def generate_workers(self, workers_number): self.workers = [] self.workers_number = workers_number for i in range(self.workers_number): self.workers.append(worker.Worker(self.cl, self.rest)) for w in self.workers: w.do_work()
def exec_search(self, title, author=None): br = self.create_browser() _result_queue = [] # TODO CUSTOM LINE # query = Melonbooks.BASE_URL + '/search/search.php?mode=search&search_disp=&category_id=0&text_type=&text_type=all&' # post_data = urlencode({ 'name':title, 'is_end_of_sale':1, 'is_end_of_sale2':1 }) try: # REJECT ADULT FORM response = br.open_novisit(query + post_data, timeout=30) except Exception as e: err = 'Failed to make identify query: %s%s' % (query, post_data) print(err) print(e) return False try: raw = response.read().strip() raw = raw.decode('utf-8', errors='replace') if not raw: log.error('Failed to get raw result for query: %s%s' % (query, post_data)) return root = fromstring(raw) except Exception as e: msg = 'Failed to parse melonbooks page for query: %s%s' % ( query, post_data) print(msg) print(e) return False # TODO CUSTOM LINE # all_result = root.xpath('//*[@id="container"]//div[@class="thumb"]/a/@href') all_result = null matches = [] for rindex, ritem in enumerate(all_result): # TODO CUSTOM LINE # matches.append('%s%s'%(Melonbooks.BASE_URL, ritem.strip())) matches.append(null) if not matches: print('No matches found with query: %s%s' % (query, post_data)) return False workers = [ worker.Worker(br, url, all_result[i], i, _result_queue) for i, url in enumerate(matches) ] self.run_workers(workers) ret_records = [] for windex, w in enumerate(_result_queue): w.printMetadata() ret_records.append(w.createRecord()) return ret_records
def __init__(self): super().__init__() self.title = 'Home Meet' self.left = 10 self.top = 10 self.width = 640 self.height = 640 self.firstTxt = True # 1 - create Worker and Thread inside the Form self.obj = worker.Worker() # no parent! self.thread = QThread() # no parent! # 2 - Connect Worker`s Signals to Form method slots to post data. self.obj.txtReady.connect(self.onTxtReady) self.obj.newMsg.connect(self.updateMsg) # 3 - Move the Worker object to the Thread object self.obj.moveToThread(self.thread) # 4 - Connect Worker Signals to the Thread slots # self.obj.finished.connect(self.thread.quit) # 5 - Connect Thread started signal to Worker operational slot method self.thread.started.connect(self.obj.getText) # * - Thread finished signal will close the app if you want! #self.thread.finished.connect(app.exit) # 6 - Start the thread self.thread.start() self.initUI()
def main(): http_fetcher = fetcher.HTTPFetcher() rb = robot.Robot(http_fetcher, [ ('/.*', AHandler), ]) worker.Worker(rb).start() IOLoop.instance().start()
def __init__(self): super(main, self).__init__() self.thread = QThread() self.obj = worker.Worker() self.obj.moveToThread(self.thread) # MSMT.moveToThread(self.thread) self.thread.started.connect(self.run_seq) # self.thread.start() self.setupUi(self) self.statusBar().showMessage('hello!') ####################################################### self.fig_dict = {} self.colx_dict = {} self.coly_dict = {} self.seq_dict = {} #############Button and labels ################################################################# self.LoadSeq.clicked.connect(self.Load_Seq) self.NewSeq.clicked.connect(self.SeqGetItem) self.ClearSeq.clicked.connect(self.clear_que) self.AddSeqItem.clicked.connect(self.se_control) self.AbortSeq.clicked.connect(self.Abort_MS) self.StartSeq.clicked.connect(self.Start_MS) self.PauseSeq.clicked.connect(self.Pause_MS) self.StartSeq.clicked.connect(self.run_seq) self.QueList.addItem('Secondary_control_disabled!\n') self.statusBar().setStyleSheet( "QStatusBar{padding-left:8px;background-color:black;color:yellow;font: 75 16pt 'Arial';}" )
def main(): '''Example of A3C running on MountainCar environment''' tf.reset_default_graph() history = [] with tf.device('/{}:0'.format(DEVICE)): sess = tf.Session() global_model = ac_net.AC_Net( STATE_SIZE, ACTION_SIZE, LEARNING_RATE, 'global', n_h1=N_H1, n_h2=N_H2) workers = [] for i in xrange(NUM_WORKERS): env = gym.make(ENV_NAME) env._max_episode_steps = MAX_STEPS workers.append(worker.Worker(env, state_size=STATE_SIZE, action_size=ACTION_SIZE, worker_name='worker_{}'.format(i), global_name='global', lr=LEARNING_RATE, gamma=GAMMA, t_max=T_MAX, sess=sess, history=history, n_h1=N_H1, n_h2=N_H2, logdir=LOG_DIR)) sess.run(tf.global_variables_initializer()) for workeri in workers: worker_work = lambda: workeri.work(NUM_EPISODES) thread = threading.Thread(target=worker_work) thread.start()
def setup(self, send, log, cfg, botopts): BotMod.setup(self, send, log, cfg, botopts) def_cfg = { 'chime_start_sound': 'sounds/prompt.wav', 'chime_stop_sound': 'sounds/finish.wav', 'play_start_cmd': '', 'play_stop_cmd': '', 'chime_start_cmd': 'play %s', 'chime_stop_cmd': 'play %s', 'start_stream_cmd': 'tools/stream_ssh %s', 'stop_stream_cmd': '', 'play_chimes': True, 'start_muted': False } cfg = cfg.get_section('player', def_cfg) self.log("player_cfg:", cfg) self.worker = worker.Worker() self.worker.set_chime_sound('start', cfg['chime_start_sound']) self.worker.set_chime_sound('stop', cfg['chime_stop_sound']) self.worker.set_command('play_start', cfg['play_start_cmd']) self.worker.set_command('play_stop', cfg['play_stop_cmd']) self.worker.set_command('chime_start', cfg['chime_start_cmd']) self.worker.set_command('chime_stop', cfg['chime_stop_cmd']) self.worker.set_command('start_stream', cfg['start_stream_cmd']) self.worker.set_command('stop_stream', cfg['stop_stream_cmd']) self.worker.set_play_chimes(cfg['play_chimes']) self.worker.set_callback('state', self._state_cb) self.worker.set_callback('error', self._error_cb) self.worker.set_callback('info', self._info_cb) start_muted = cfg['start_muted'] self.control = control.Control(self, self.send_event, start_muted)
def __init__(self, conf, continuous_monitor_dir): logging.info("Saving continuous monitor logs to directory: %s", continuous_monitor_dir) self.conf = conf num_workers = self.conf.num_workers logging.debug("Creating Simulator with %s Worker(s)", num_workers) self.workers = [ worker.Worker(self, self.conf, continuous_monitor_dir) for _ in xrange(num_workers) ] # The Event queue contains elements of the form (Event time ms, Event object) and is serviced # in increasing order of Event time. self.event_queue = Queue.PriorityQueue() # A list of the Jobs that this Simulator will execute. Jobs must be executed sequentially. self.jobs = self.conf.jobs self.current_job = None self.current_stage = None # A mapping from Job to a tuple of (ideal Job completion time (in ms), actual Job completion # time (in ms)). self.job_to_jcts = {} # A log file in which to record simulation configuration info and results. self.info_file = open( path.join(continuous_monitor_dir, "simulation_info.txt"), "w") self.info_file.write("%s\n" % str(self.conf))
def test_report(): """tested""" worker1 = worker.Worker(1, "bill") worker2 = worker.Worker(2, "tom") task1 = fix_price_task.FTask(1, "task1", 34) task2 = fix_price_task.FTask(2, "task2", 10) task3 = hourly_rate_task.HTask(3, "task3", 5, 10) test_log = log.Log() worker1.approve(test_log, task2) worker2.approve(test_log, task1) worker2.approve(test_log, task3) assert test_log.report() == "task3,tom:50\n" \ "task1,tom:34\n" \ "task2,bill:10"
def exit(self): f = self.scene.factories[self.factory_index] f.set_frame(3) f.activated = True w = worker.Worker(f.gx, f.gy) self.scene.snake = [w] self.selection.kill() self.scene.animatedsprites.remove(self.selection)
def test_empty_init(self): "Test the default Worker creation" # 1. Create default Worker object myobj = worker.Worker() # 2. Make sure it has the default values self.assertEqual(myobj.id, None) self.assertEqual(myobj.step, None) self.assertEqual(myobj.when, None)
def test_tasks_assignment_from_daily_plan(): """Check if tasks are properly assigned from Daily Plan to worker and if Daily Plan is properly updated""" task_1 = tasks.Task("one", 20) task_2 = tasks.Task("two", 25) day_plan_obj = day_plan.DailyPlan() day_plan_obj.create_plan(task_1, task_2) worker_1 = worker.Worker("John") worker_1.get_task_from_dp(day_plan_obj) assert (worker_1.get_current_task()) == ('two', 25) assert (day_plan_obj.get_plan()) == [('one', 20)]
def start_workers(self, workers_count, connection_string): if self.workers: return self.workers runner = query_runner.redshift(connection_string) self.workers = [worker.Worker(self, runner) for _ in range(workers_count)] for w in self.workers: w.start() return self.workers
def load_data_from_file(self): try: f = open("database.txt", "r") for line in f: data = line.rstrip().split(",") worker = w.Worker(data[0], data[1], data[2], data[3], data[4]) self.workers.append(worker) self.print_workers() f.close() except: pass
def configure_worker(self) -> None: """Initialise a worker to run a timer in a separate thread. Attaches the timeProgress signal of worker to callback "time_progress". Attaches the finished signal of worker to callback "timer_ended" """ self.timer_worker = worker.Worker(self.time_limit) self.timer_thread = QThread() self.timer_worker.timeProgress.connect(self.time_progress) self.timer_worker.moveToThread(self.timer_thread) self.timer_worker.finished.connect(self.timer_ended) self.timer_thread.started.connect(self.timer_worker.timeCounter)
def _create_worker(self, silent=False): try: self.worker = worker.Worker( self.conf, pipeline_mode=True, data_mount_prefix=self.preferences.data_mount_prefix) except IOError: if not silent: logger.warning( "Cannot create worker instance (IOError). Data might not be mounted." ) self.worker = DummyWorker(self.conf)
def __init__(self, root, source_root, checksum_function, filter_function, max_age=None, max_entries=None, auto_scrub=False): Cache.__init__(self, root, source_root, checksum_function, filter_function, max_age, max_entries, auto_scrub) self.__wlock = Lock() self.__worker = worker.Worker(autostart=True)
def executer(args): config.setupConf(args.cfg_file) initServer("{}/{}".format(config.G_Conf.Worker.LogDir, config.G_Conf.Worker.LogFile), config.G_Conf.Common.MysqlConn) signal.signal(signal.SIGINT, sigint_handler) signal.signal(signal.SIGTERM, sigint_handler) signal.signal(signal.SIGQUIT, sigquit_handler) task_worker = worker.Worker( parallelism=config.G_Conf.Worker.Parallelism, heartbeat_interval=config.G_Conf.Worker.HearteatInterval, woker_timeout=config.G_Conf.Worker.TaskTimeOut, retry_times=config.G_Conf.Worker.Retry) task_worker.run()