def update(self): """ Check keyboard events and length of the name """ if Events().right_pressed: if self.cursor < 26: self.cursor += 1 self.cursor_rect.x += 20 if Events().left_pressed: if self.cursor > 0: self.cursor -= 1 self.cursor_rect.x -= 20 if Events().fire2_pressed: if len(self.name) < 3: self.name = self.name + self.letters[self.cursor] else: self.status.high_scores.append([self.name, self.status.score]) self.status.high_scores = sorted(self.status.high_scores, key=lambda x: x[1], reverse=True) self.status.high_scores.pop(-1) self.status.score = 0 self.status.new_hs = False if Events().cancel_pressed: if len(self.name) > 0: self.name = self.name[:-1] if len(self.name) == 3: self.done = True elif self.done: self.done = False
def __init__(self): # Event handlers self.updateSummaryState = Events() self.updateSummaryState.on_change += self.on_ticker_update self.orderbook_callback = Events() self.orderbook_callback.on_change += self.on_orderbook self.orderbook_update = Events() self.orderbook_update.on_change += self.on_orderbook_update self.trades = Events() self.trades.on_change += self.on_trades # Queues self.control_queue = queue.Queue() self.order_queue = None # Other self.connections = {} self.order_books = {} self.threads = {} self.url = [ 'https://socket-stage.bittrex.com/signalr', 'https://socket.bittrex.com/signalr', 'https://socket-beta.bittrex.com/signalr' ] self.tickers = Ticker() self.max_tickers_per_conn = 20 self._start_main_thread()
def run_game(): """Init game and run game""" # init config CFG() # pre-init sound pygame.mixer.pre_init(44100, -16, 2, 2048) # init pygame and screen pygame.init() if CFG().fullscreen: screen = pygame.display.set_mode((CFG().screen_width, CFG().screen_height), pygame.FULLSCREEN) else: screen = pygame.display.set_mode((CFG().screen_width, CFG().screen_height)) pygame.display.set_caption('Space War 2027') # Internal screen int_screen = pygame.Surface((CFG().int_screen_width, CFG().int_screen_height)) show_loading(screen) # Calculate internal scaling scale = CFG().screen_width / float(CFG().int_screen_width) CFG().int_scale_width = int(CFG().int_screen_width * scale) CFG().int_scale_height = int(CFG().int_screen_height * scale) # Init sound sfx.SFX() # Init graphics gfx.GFX() # Init game clock clock = pygame.time.Clock() # Status status = GameStatus() # Init menu menu = Menu(int_screen, status) # Init game itself game = Game(int_screen, status) # Init events Events() hud = HUD(status, screen, clock) # Main loop while True: dt = clock.tick(60) # time between frames, should alter speed of everything that is not based on real time Events().get_events() if status.game_running: if game.update(dt): # If update is true level ended -> start new level game = Game(int_screen, status) game.draw() status.update() else: menu.update(game, dt) menu.draw() update_screen(screen, int_screen, hud)
def __init__(self, *args): self.d_ev = Events(('output')) self.rd_buff = Queue(1) self.output = self.d_ev.output self.event_id = 0 self.c_ev = Events(('output')) self.rc_buff = Queue(1) self.coutput = self.c_ev.output self.init(*args)
def __init__(self, pipline, name): self.events = Events() self._pipeline = pipline self._callback = None self._algorithmName = name self._nodeName = name self._input = []
def __init__(self): app = QtWidgets.QApplication(sys.argv) MainWindow = QtWidgets.QMainWindow() self.ui = Ui_MainWindow() self.ui.setupUi(MainWindow) MainWindow.show() # Стандартные характеристики зарядов self.radius = DEFAULT_RADIUS self.min_width = self.min_height = self.radius self.max_width = self.ui.graphicsView.width() - self.radius self.max_height = self.ui.graphicsView.height() - self.radius self.max_color_value = 0 # Инициализируем графическую сцену и привязываем её к graphicsView self.scene = QGraphicsScene() self.ui.graphicsView.setScene(self.scene) # Выделенные заряды на сцене self.selected_charges = [] # Создаём экземпляр класса событий self.events = Events() self.events.focus_in_event[Charge].connect(self.enable_editing) self.events.focus_out_event.connect(self.disable_editing) self.events.mouse_press_event[Charge].connect(self.delete_connections) self.events.mouse_release_event.connect(self.add_connections) # Инициализируем обработчики событий от элементов пользовательского интерейса self.ui.addCharge.clicked.connect(self.add_charge) self.ui.deleteCharge.clicked.connect(self.delete_charge) self.ui.chargeValue.editingFinished.connect(self.change_charge_value) # Запускаем бесконечный цикл обработки событий от пользовательского интерфейса sys.exit(app.exec_())
def main(argv): URL = "https://<my community GQDN>/services/4.0" UID = "my UID" GID = "my Group Id" CID = "my Category Id" print('\n[main] Acquiring auth token...\n') authorized_session = AuthToken(URL) authorized_session.setToken() print('\n[main] Returned token: ' + authorized_session.getToken() + '\n') event_handler = Events(URL, authorized_session.getToken(), UID, GID, CID) week = 0 #replace with your start date and time start = datetime.datetime(2019, 11, 20, 11, 0) while week < 52: end = start + datetime.timedelta(hours=1) print("Week: " + str(week) + " Start: " + str(start) + " End: " + str(end)) event_handler.createEvent(str(start), str(end)) print('EventId: ' + event_handler.getEventId()) start = start + datetime.timedelta(weeks=1) week += 1
def __init__( self, urls, user="", password="", only_block_id=False, on_block=None, keep_alive=25, num_retries=-1, timeout=60, *args, **kwargs ): self.num_retries = num_retries self.keepalive = None self._request_id = 0 self.ws = None self.user = user self.password = password self.keep_alive = keep_alive self.run_event = threading.Event() self.only_block_id = only_block_id self.nodes = Nodes(urls, num_retries, 5) # Instantiate Events Events.__init__(self) self.events = Events() # Store the objects we are interested in # self.subscription_accounts = accounts if on_block: self.on_block += on_block
class OpenProtocol: client = None __events__ = (('on_update')) t = Events() def __init__(self, ip, port=4545): self.ip = ip self.port = port def connect(self): Thread(target=self.update_cycle, daemon=True).start() def update_cycle(self): while True: print('updating cycle') self.t.on_update() sleep(1) def disconnect(self): ... def keep_alive(self): ... def job_subscribe(self): self.t.on_update += self.tool_update def tool_update(self): print('Tool updated')
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._width, self._height = self.term.width, self.term.height if not isinstance(self.store, Store): raise TypeError("Store is invalid") def worker(func, time): sleep(time) func() def timeout(func, *args, **kwargs): timeout = kwargs.pop('time', None) if timeout is None: raise TypeError("take two arguments func and time") thread = Thread(target=worker, args=( partial(func, *args, **kwargs), timeout)) thread.start() self.timeout = timeout self._is_active = False self._listen = True self._widgets = [] events = Events() self.on_enter = events.on_enter self.on_key_arrow = events.on_key_arrow self.on_exit = events.on_exit self.on_exit += self.close self.on_key = events.on_key
def test_len(self): # We want __events__ to be set to verify that it is not counted as # part of __len__. self.events = Events(events=("on_change", "on_get")) self.events.on_change += self.callback1 self.events.on_get += self.callback2 self.assertEqual(len(self.events), 2)
def classify_ml(event): """ Classify event according to ML model Parameters: Events : event : incoming event to be classified Returns: int : label of classified event """ return Events(classifier.predict(event.buffer.buffer))
def __init__(self): self.events = Events() # refresh UI - doesn't work -> remove keyboard.add_hotkey('r', self.refresh) # control Mobile Platform keyboard.add_hotkey('w', self.forward) keyboard.add_hotkey('s', self.backward) keyboard.add_hotkey('a', self.left) keyboard.add_hotkey('d', self.right) keyboard.add_hotkey('z', self.get_some_debug_data) # control Manipulator keyboard.add_hotkey('up+1', self.manipulator_motor_1_forward) keyboard.add_hotkey('down+1', self.manipulator_motor_1_backward) keyboard.add_hotkey('up+2', self.manipulator_motor_2_forward) keyboard.add_hotkey('down+2', self.manipulator_motor_2_backward) keyboard.add_hotkey('up+3', self.manipulator_motor_3_forward) keyboard.add_hotkey('down+3', self.manipulator_motor_3_backward) keyboard.add_hotkey('up+4', self.manipulator_motor_4_forward) keyboard.add_hotkey('down+4', self.manipulator_motor_4_backward) keyboard.add_hotkey('up+5', self.manipulator_motor_5_forward) keyboard.add_hotkey('down+5', self.manipulator_motor_5_backward) keyboard.add_hotkey('up+6', self.manipulator_motor_5_forward) keyboard.add_hotkey('down+6', self.manipulator_motor_5_backward) keyboard.add_hotkey('u', self.manipulator_status_update) keyboard.on_release(self.halt)
def __init__(self, pin, name): self.Pin = pin self.Type = GPIO.IN self.Events = Events(('onTurnedOn', 'onTurnedOff')) self.__Value = 0 self.throwEvents = True self.Name = name
def __init__( self, # accounts=[], on_block=None, only_block_id=False, steem_instance=None, keep_alive=25): # Events Events.__init__(self) self.events = Events() # Steem instance self.steem = steem_instance or shared_steem_instance() # Callbacks if on_block: self.on_block += on_block # Open the websocket self.websocket = SteemWebsocket(urls=self.steem.rpc.urls, user=self.steem.rpc.user, password=self.steem.rpc.password, only_block_id=only_block_id, on_block=self.process_block, keep_alive=keep_alive)
def parse(uri, hat_list, hat_list_flag): req = urllib.request.Request(uri, headers={'User-Agent': 'Mozilla/5.0'}) response = urllib.request.urlopen(req) content = response.read().decode('utf-8') parser = MyOddsParser() parser.feed(content) betting_companies = parser.output teams = parser.team # print(betting_companies) # print(teams) events_list = [] # print("Number of teams:", len(teams)) # print("Teams Blacklisted:", black_list) for team in teams: current_team = None if hat_list_flag == 1 and team in hat_list: current_team = team elif hat_list_flag == 0 and team not in hat_list: current_team = team else: continue # print("Team Found: ", team, end=";") odds_list = [] for i in range(len(betting_companies)): # if teams[team][i] != '0.0': odds_list.append(Odd(betting_companies[i], teams[current_team][i], current_team)) events_list.append(Event(current_team, odds_list)) # print("Number of betting companies: ", len(betting_companies)) # print("Number of events:", len(events_list)) return Events(events_list)
def __init__( self, # accounts=[], on_block=None, only_block_id=False, blockchain_instance=None, keep_alive=25, **kwargs): # Events Events.__init__(self) self.events = Events() # Steem instance if blockchain_instance is None: if kwargs.get("steem_instance"): blockchain_instance = kwargs["steem_instance"] elif kwargs.get("hive_instance"): blockchain_instance = kwargs["hive_instance"] self.blockchain = blockchain_instance or shared_blockchain_instance() # Callbacks if on_block: self.on_block += on_block # Open the websocket self.websocket = NodeWebsocket(urls=self.blockchain.rpc.nodes, user=self.blockchain.rpc.user, password=self.blockchain.rpc.password, only_block_id=only_block_id, on_block=self.process_block, keep_alive=keep_alive)
def __init__(self, options): self._url = None self._algorithm = dict() self._input = None self._events = Events() self._loadAlgorithmError = None self._bootstrap(options)
def update(self, set='start'): """ Goes trough the story list, keeps duration for showing the story and updates current image and text :param set: string start or end - which part of story to show :return: True if showing image, False if all images have been shown """ # If it's time for next story if self.story_timer < time(): self.story_image = None self.story_text = '' if set == 'start': story = self.start_story else: story = self.end_story if len(story): page = story.pop(0) # Set next story image, duration and text self.story_image = GFX().story[page['image']] self.story_timer = time() + page['time'] if 'text' in page.keys(): self.story_text = page['text'] else: return False else: # Allow skipping of story at the start of level if set == 'start': if Events().key_pressed: self.story_timer = 0 return True
def __init__( self, accounts=[], markets=[], objects=[], on_tx=None, on_object=None, on_block=None, on_account=None, on_market=None, bitshares_instance=None, ): # Events super(Notify, self).__init__() self.events = Events() # BitShares instance self.bitshares = bitshares_instance or shared_bitshares_instance() # Markets market_ids = [] for market_name in markets: market = Market(market_name, bitshares_instance=self.bitshares) market_ids.append([ market["base"]["id"], market["quote"]["id"], ]) # Accounts account_ids = [] for account_name in accounts: account = Account(account_name, bitshares_instance=self.bitshares) account_ids.append(account["id"]) # Callbacks if on_tx: self.on_tx += on_tx if on_object: self.on_object += on_object if on_block: self.on_block += on_block if on_account: self.on_account += on_account if on_market: self.on_market += on_market # Open the websocket self.websocket = BitSharesWebsocket( urls=self.bitshares.rpc.urls, user=self.bitshares.rpc.user, password=self.bitshares.rpc.password, accounts=account_ids, markets=market_ids, objects=objects, on_tx=on_tx, on_object=on_object, on_block=on_block, on_account=self.process_account, on_market=self.process_market, )
def update_dl(self, orderid, site_id): CurentDate = time.strftime("%Y-%m-%d %H:%M:%S") Date = datetime.datetime.strptime(CurentDate, "%Y-%m-%d %H:%M:%S") order_data = self.w.select( " date, urgency, payment_date ", self.table_name, " where uid = '{0}' and (id_site = '{1}') ".format( orderid, site_id))[0] create_date = order_data.get('date').date() urgency = order_data.get('urgency') payment_date = order_data.get('payment_date').date() client_dl = Date writer_dl = Date if urgency == '0.12' or urgency == '0': client_dl = Date + datetime.timedelta(hours=12) writer_dl = Date + datetime.timedelta(hours=9) else: client_dl = Date + datetime.timedelta(days=int(urgency)) writer_dl = Date + datetime.timedelta(days=(int(urgency) * 0.75)) Events().add_event(( "UPD DEADLINE - client (date: {0}, urgency: {1}, payment_date: {2})" " new client deadline: {3} " " new writer deadline: {4} ").format(str(create_date), str(urgency), str(payment_date), str(client_dl), str(writer_dl)), self.EVENT_ID_UPD_DEADLINE, orderid, self.SERVICES_ID_SESSION) return self.w.update({ "wr_deadline": writer_dl, "deadline": client_dl }, self.table_name, " where uid='{0}' and (id_site = '{1}') ".format( orderid, site_id))
def __init__(self): Thread.__init__(self) self.daemon = True self.events = Events() self.BAUD = 57600 self.TIMEOUT = 0 self.serial = None
def __init__( self, # accounts=[], on_block=None, only_block_id=False, dpay_instance=None, keep_alive=25 ): # Events Events.__init__(self) self.events = Events() # DPay instance self.dpay = dpay_instance or shared_dpay_instance() # Callbacks if on_block: self.on_block += on_block # Open the websocket self.websocket = DPayWebsocket( urls=self.dpay.rpc.nodes, user=self.dpay.rpc.user, password=self.dpay.rpc.password, only_block_id=only_block_id, on_block=self.process_block, keep_alive=keep_alive )
def test_init_world(self): events = Events([]) game = MagnumSal(events) game.add_chamber(0, 0) self.assertEqual([ChamberAdded(0, 0)], events)
def __init__(self): self.value = "" self.events = Events() self.event_dict = { 'on_reset': self.events.on_reset, 'on_change': self.events.on_change }
async def test_call_no_args(self): event_instance = Events() event_instance.my_event += self.callback_no_args await event_instance.my_event() self._callback_no_args_mock.assert_called_once()
def bentley_ottmann(segments, solution): """ computes and returns the result of the bentley ottmann algorithm for the given segments and ajuster. the intesections are given for each segments. """ # adds all the creation and destruction events for the given segments events = Events(segments) # creates the structure for the 'alive' segments: # the structure contains a list with the segment and it's key living_segments = SortedList() Segment.current_point = None while not events.isempty(): # getting the first event in the events list current_event = events.event_list.pop(0) #finishing the segments which end on the current event events.finish_segments(current_event, living_segments, solution) #updating the global current point Segment.current_point = current_event.key #beginning the segments which start from the current_event events.begin_segments(current_event, living_segments, solution)
def __init__(self, parent=None): self.internal_events = Events( ('on_perspective_change', 'on_change_slice_position')) self._ui = UiViewCanvas(parent) self._plotter = MplPlotter() # TODO probably move the voi list out to a separate file self.voi_list = ListWidget(self._ui.voi_listWidget, checkable=True) self.voi_list_dock = self._ui.parent().voiList_dockWidget self.voi_list_dock.setWidget(self._ui.voi_listWidget) self.data_sample = DataSample(self._ui.parent(), self._plotter.plotting_manager.axes) dock_widget = self._ui.parent().dataSample_dockWidget dock_widget.setWidget(self.data_sample) self._ui.vc_layout.addWidget(self._plotter) self._ui.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self._ui.updateGeometry() self._internal_events_setup() self.voi_list_set_visibility(visible=True) # "If tracking is disabled, the slider emits the valueChanged() signal only when the user releases the slider." self._ui.position_slider.setTracking(False)
def __init__(self): if self.game_is_inited is False: pygame.init() pygame.display.set_caption(Config.TITLE) self.main_window = pygame.display.set_mode( (Config.WIDTH, Config.HEIGHT)) Sounds.background_sound.play(loops=-1) # Фоновая музыка self.game_is_inited = True self.clock = pygame.time.Clock() self.background = SpriteBackGround() self.player = PlayerSpaceship() self.states = States() # Группа для всех спрайтов, их я буду обновлять и отрисовывать self.all_sprites = pygame.sprite.Group() # Группы для проверки коллизий self.lasers = pygame.sprite.Group() # Выстрелы из корабля (лазеры) self.powerups = pygame.sprite.Group() # Бафы # Создаю метеориты self.meteorites = pygame.sprite.Group() for _ in range(Config.TOTAL_METEORITES): tmp_meteorite = Meteorite() self.meteorites.add(tmp_meteorite) self.all_sprites.add(tmp_meteorite) self.events = Events(self) self.main_loop() # Запускаю main loop
def __init__(self): # ports = serial.tools.list_ports.comports() # print(list(ports)) if os.getenv("SERIAL_PORT") is not None: port = os.getenv("SERIAL_PORT") else: port = "/dev/ttyUSB0" self.ser = serial.Serial(port, baudrate=9600, timeout=1) self.periphery_events = Events() if not self.ser.is_open: self.ser.open() self.button1Pressed = False self.button2Pressed = False self.button3Pressed = False self.angleX = 0 self.angleY = 0 self.angleZ = 0 self.led_color: pygame.Color = pygame.Color(0, 0, 0) self.led_animation = None self.rotary_last_direction = 0 self.rotary_step_count = 0