def test_db_add_event_point(self): db = get_db() event = Event(sx=10, sy=15, ex=10, ey=15, c_flag=10) expected = to_bytearray( [pos(10), pos(15), color(10), pos(10), pos(15), color(10)]) result = db.addEvent(event) db.close() self.assertEqual(expected, result)
def test_should_use_a_minimum_speed_for_calculation_preventing_divide_by_zero_error(self): self.listen(EventName.after) waypoint = Waypoint(Position(53.001,-2.001),5) fake_gps = FakeMovingGPS([self.current_position, waypoint.position]) fake_gps.speed = 0 expected_time = expected_time_to_steer(self.current_position,waypoint.position,0.01) navigator = self.new_navigator(fake_gps) self.exchange.publish(Event(EventName.navigate,waypoint)) self.assertEqual(self.last_event.seconds,expected_time)
def recover_password(self): db = Database(self.logger) new_event = Event("Mailer Password Reset", db, self.logger) confirmation_code = os.urandom(16).hex() user_id = db.validate_email(self.email_address) if user_id: new_event_id = new_event.log_event( user_id, { "ip_address": self.ip_address, "confirmation": confirmation_code })
def cancel_order(self, order): account = self._env.get_account(order.order_book_id) self._env.event_bus.publish_event( Event(EVENT.ORDER_PENDING_CANCEL, account=account, order=order)) order.mark_cancelled( _(u"{order_id} order has been cancelled by user.").format( order_id=order.order_id)) self._env.event_bus.publish_event( Event(EVENT.ORDER_CANCELLATION_PASS, account=account, order=order)) try: self._open_orders.remove((account, order)) except ValueError: try: self._delayed_orders.remove((account, order)) except ValueError: pass
def test_should_use_maximum_steer_time_if_its_a_long_way_to_go(self): self.listen(EventName.after) waypoint = Waypoint(Position(60.0001,10),5) fake_gps = FakeMovingGPS([self.current_position, waypoint.position]) fake_gps.speed = 1 expected_bearing = self.globe.bearing(self.current_position,waypoint.position) navigator = self.new_navigator(fake_gps) self.exchange.publish(Event(EventName.navigate,waypoint)) self.assertEqual(self.last_event.seconds,MAX_TIME_TO_STEER)
def test_from_link_list_nonterminals(self): left = Link(x=10, y=20, c_flag=5) right = Link(x=34, y=66, c_flag=5) expected = Event(sx=10, sy=20, ex=34, ey=66, c_flag=5) result = list(Event.from_links([left, right])) count = 0 for ev in result: count += 1 self.assertTrue(expected == result[0]) self.assertEqual(1, count)
def after_trading(self, event): for account, order in self._open_orders: order.mark_rejected( _(u"Order Rejected: {order_book_id} can not match. Market close." ).format(order_book_id=order.order_book_id)) self._env.event_bus.publish_event( Event(EVENT.ORDER_UNSOLICITED_UPDATE, account=account, order=order)) self._open_orders = self._delayed_orders self._delayed_orders = []
def check_blast(self, bomb, x, y): # Check if a wall has been hit if self.wall_at(x, y): return [Event(Event.BOMB_HIT_WALL, bomb.owner)] # Check monsters and characters ev = [] # Check if a monster has been hit mlist = self.monsters_at(x, y) if mlist: for m in mlist: ev.append(Event(Event.BOMB_HIT_MONSTER, bomb.owner, m)) self.monsters[self.index(x, y)].remove(m) # Check if a character has been hit clist = self.characters_at(x, y) if clist: for c in clist: ev.append(Event(Event.BOMB_HIT_CHARACTER, bomb.owner, c)) self.remove_character(c) # Return collected events return ev
def test_should_chain_a_few_events(self): ts = TestSubscriber(self.exchange) ts2 = TestSubscriber(self.exchange) self.exchange.subscribe("chain", ts.callme) self.exchange.subscribe("secondevent", ts.callme) self.exchange.subscribe("secondevent", ts2.callme) self.exchange.publish(Event("chain")) self.assertEqual(ts.event_call_count("secondevent"), 1) self.assertEqual(ts2.event_call_count("secondevent"), 1)
def _create_new_event(self): uid = uuid.uuid4() cur_time = time.time() event = Event( 'todo', 'new', uid=uid, created=cur_time, modified=cur_time, )
def test_errors_should_be_logged_and_event_processing_continues(self): ts_error = TestSubscriber(self.exchange) ts_after_error = TestSubscriber(self.exchange) event = Event("bong") self.exchange.subscribe("bong", ts_error.bad_call) self.exchange.subscribe("bong", ts_after_error.callme) self.exchange.publish(event) self.mock_logger.error.assert_has_calls( [call('Exchange, RuntimeError: oops')]) self.assertEqual(ts_after_error.event_call_count("bong"), 1)
def __init__(self, port, version, uuid): self.logger = logging.getLogger(__name__) # Store UUID based on the hostname and current time to check # if the received broadcast packet is from self self.uuid = uuid self.client_discovered = Event() self.port = port self.version = version self.__init_network_objects()
def next(self, unused_event): if self.waypoints: self._navigate_to_next_waypoint() else: self.logger.info( '**************************************************************' ) self.logger.info( 'Follower, all waypoints reached, navigation complete') self.logger.info( '**************************************************************' ) self.exchange.publish(Event(EventName.end))
def __init__(self, directory, messanger, file_name=None, block_size=4098): super().__init__() self.logger = logging.getLogger(__name__) if file_name is None: self.type = self.FROM_REMOTE else: self.type = self.TO_REMOTE self.directory = directory self.messanger = messanger self.timestamp = None self.file_name = file_name if file_name is not None: self.file_data = self.directory.get_index(self.file_name) else: self.file_data = None self.block_size = block_size self.remote_file_data = None self.remote_checksums = None self.messanger.packet_received += self.__packet_received self.messanger.disconnected += self.__disconnected self.__transfer_started = False self.__transfer_completed = False self.__transfer_cancelled = False self.__temp_file_name = None self.__temp_file_handle = None self.__file_handle = None self.transfer_started = Event() self.transfer_completed = Event() self.transfer_failed = Event() self.transfer_cancelled = Event()
def test_should_navigate_along_list_of_waypoints_with_logging(self): waypoint1 = Waypoint(Position(1, 1), 5) waypoint2 = Waypoint(Position(2, 2), 5) follower = Follower(self.exchange, [waypoint1, waypoint2], self.mock_logger) self.exchange.publish(Event(EventName.start)) self.exchange.publish(Event(EventName.arrived, waypoint1)) self.exchange.publish(Event(EventName.arrived, waypoint2)) self.mock_logger.info.assert_has_calls([ call('Follower, next waypoint +1.000000,+1.000000'), call('Follower, next waypoint +2.000000,+2.000000'), call( '**************************************************************' ), call('Follower, all waypoints reached, navigation complete'), call( '**************************************************************' ) ])
def chop_delay(stream): from quantization import delay_quantization_splits buf = [] maxdelay = 3.0 maxchopped = delay_quantization_splits[-1] for event in stream: if event.category == 'delay': value = event.value if value > maxdelay: value = maxdelay while True: if value > maxchopped: value -= maxchopped buf.append(Event('delay', maxchopped)) else: buf.append(Event('delay', value)) break else: buf.append(event) return buf
def eth_network_admin(session_token): db = database.Database(logger=current_app.logger) user_id = db.validate_session(session_token) if user_id: authorized = db.validate_permission(user_id, "ethereum-network") if authorized: peer_data = {} syncing_status = {} update_node_event_type = Event("Ethereum Node Update", db, logger=current_app.logger) epoch = datetime.datetime.today() - datetime.timedelta(hours=24) nodes = db.list_ethereum_nodes() shortest_data_set = 0 for each_node in nodes: peer_data[each_node["node_identifier"]] = [] syncing_status[each_node["node_identifier"]] = [] node_id = each_node["id"] updates = update_node_event_type.get_events_since(epoch, node_id) for each_update in updates: if each_update[2] == node_id: event_data = json.loads(each_update[0]) if event_data["synchronized"]: peer_count = event_data["peers"] peer_data[each_node["node_identifier"]].append(peer_count) syncing_status[each_node["node_identifier"]].append({"count": 0, "node_id": node_id}) else: syncing_status[each_node["node_identifier"]].append({"count": event_data['blocks_behind'], "node_id": node_id}) # truncate the peer count data window to the shortest series to # make the charts look better if len(peer_data[each_node["node_identifier"]]) > 0: if shortest_data_set == 0: shortest_data_set = len(peer_data[each_node["node_identifier"]]) else: if len(peer_data[each_node["node_identifier"]]) < shortest_data_set: shortest_data_set = len(peer_data[each_node["node_identifier"]]) peer_strings = {} for key in peer_data.keys(): if len(syncing_status[key]) > 0: syncing_status[key] = syncing_status[key][-1] peer_strings[key] = str(peer_data[key][:shortest_data_set]) return render_template("admin/admin_eth_network.jinja2", session_token=session_token, eth_nodes=nodes, peer_data=peer_strings, blocks_behind=syncing_status) abort(403)
def test_should_signal_review_after_half_way_to_way_point_based_on_speed(self): self.listen(EventName.after) waypoint = Waypoint(Position(53.0001,-1.999699),5) #23m from current position bearing = self.globe.bearing(self.current_position,waypoint.position) fake_gps = FakeMovingGPS([self.current_position, waypoint.position]) for_expected_seconds = int(0.5 * time_to_destination(self.current_position,waypoint.position,fake_gps.speed)) navigator = self.new_navigator(fake_gps) self.exchange.publish(Event(EventName.navigate,waypoint)) self.assertEqual(self.event_count(EventName.after),1,"expected 1 'after' event") self.assertEqual(self.last_event.name,EventName.after) self.assertEqual(self.last_event.seconds,for_expected_seconds) self.assertEqual(self.last_event.next_event.name,EventName.navigate_review)
def admin_tokens(session_token): if session_token: db = database.Database(logger=current_app.logger) user_id = db.validate_session(session_token) ctx = UserContext(user_id, db=db, logger=db.logger) can_launch_ico = ctx.check_acl("launch-ico") erc20_mined = Event("ERC20 Token Mined", db, logger=current_app.logger) mined_count = erc20_mined.get_event_count(user_id) mined_ids = [] if mined_count: mined_erc20_events = erc20_mined.get_latest_events(mined_count, user_id) for each in mined_erc20_events: json_data = json.loads(each[0]) token_id = json_data["token_id"] if token_id not in mined_ids: mined_ids.append(token_id) if can_launch_ico or len(ctx.acl()["management"]) > 0: owned_tokens = [] for key in ctx.acl()["management"].keys(): token_id = ctx.acl()["management"][key]["token_id"] token_info = db.get_smart_contract_info(token_id) owned_tokens.append(token_info) owned_tokens.extend(get_owned_tokens(user_id, db, current_app.logger)) if len(owned_tokens) == 0: owned_tokens = None email_address = ctx.user_info["email_address"] last_logged_in = ctx.user_info["last_logged_in"].isoformat() last_logged_in_ip = ctx.user_info["last_logged_in_ip"] credit_ctx = Credits(user_id, db, current_app.logger) credit_balance = credit_ctx.get_credit_balance() if owned_tokens: for each in owned_tokens: if each["token_id"] in mined_ids: if each["eth_address"] is None: each["pending"] = True else: each["pending"] = False return render_template("admin/admin_tokens.jinja2", session_token=session_token, owned_tokens=owned_tokens, can_launch_ico=can_launch_ico, email_address=email_address, last_logged_in=last_logged_in, last_logged_in_ip=last_logged_in_ip, credit_balance=credit_balance) abort(403)
def createEventAction(): if 'user' in session: user = Account.fromDict(session['user']) name = request.form['name'] date = request.form['date'] location = request.form['location'] event_type = request.form['event_type'] capacity = request.form['capacity'] description = request.form['description'] price = request.form['price'] tickets_remaining = request.form['tickets_remaining'] event = Event(None, name, location, event_type, date, capacity, description, price, tickets_remaining, user.email, None) user.createEvent(event) return redirect(url_for('home', events=None))
def test_should_steer_along_the_bearing_to_the_next_waypoint(self): self.listen(EventName.set_course) waypoint = Waypoint(Position(53.5,-1.5),0) expected_distance = self.globe.distance_between(self.current_position,waypoint.position) expected_bearing = self.globe.bearing(self.current_position,waypoint.position) navigator = self.new_navigator(self.mock_gps) self.exchange.publish(Event(EventName.navigate,waypoint)) self.assertEqual(self.event_count(EventName.set_course),1,"expected set course event following navigate") self.assertEqual(self.last_event.heading,expected_bearing) # self.mock_logger.info.assert_any_call('Navigator, steering to {:+f},{:+f}, bearing {:5.1f}, distance {:.1f}m, review after 600s' # .format(waypoint.latitude,waypoint.longitude,expected_bearing,expected_distance)) self.mock_logger.info.assert_has_calls([call('Navigator, steering to {:+f},{:+f}, bearing {:5.1f}, distance {:.1f}m, review after 32394s' .format(waypoint.latitude,waypoint.longitude,expected_bearing,expected_distance))])
def open(self): pos = self.region.offset x, y = pos cwidth, cheight = self.container.size self.menu.layout(BoxConstraints( max_width = cwidth - x, max_height = cheight - y )) size = self.menu.size self.menu.set_highlighted(0) add_child(self.container, self.menu, abs_pos=pos, abs_size=size) focus(self.menu) self.is_open = True self.label.set_styles([BG_BRIGHT_CYAN]) fire_event(self, Event("open", menu_button=self, menu=self.menu)) add_listener_once(get_root(), "click", lambda e: self.menu.close())
def _run_status_handlers(self, func_key): for i in [1, 0]: # originally these were in lists; the problem is you can change these lists, so make copies for unit in tuple(self.armies[i].units): for sta in tuple(unit.unit_status): ctxt = Context({"ctarget": unit}) ss = sta.stat_str func_list = status.status_info(ss, func_key) if func_list: # found a function (func_name, kwargs) # convert arguments into context event_name = func_list[0] additional_opt = {"stat_str": ss} additional_opt.update( func_list[1]) # additional arguments Event(self, event_name, ctxt.copy(additional_opt)).activate()
def _match(self, order_book_id=None): open_orders = self._open_orders if order_book_id is not None: open_orders = [(a, o) for (a, o) in self._open_orders if o.order_book_id == order_book_id] self._matcher.match(open_orders) final_orders = [(a, o) for a, o in self._open_orders if o.is_final()] self._open_orders = [(a, o) for a, o in self._open_orders if not o.is_final()] for account, order in final_orders: if order.status == ORDER_STATUS.REJECTED or order.status == ORDER_STATUS.CANCELLED: self._env.event_bus.publish_event( Event(EVENT.ORDER_UNSOLICITED_UPDATE, account=account, order=order))
def assert_course_converges(self, target_heading, rudder_effect, jitter=0): previous_deviation = self.deviation(target_heading, 0) deviation_list = [previous_deviation] while (self.deviation(target_heading,jitter) > STEERER_CONFIG['ignore deviation below'] or \ (abs(self.rudder_servo.get_position()) > 5) and self.sensors.rate_of_turn > STEERER_CONFIG['ignore rate of turn below']): self.rotate_boat(rudder_effect, jitter) self.exchange.publish(Event(EventName.check_course)) deviation_list.append( round(self.deviation(target_heading, jitter), 1)) self.assertGreater( previous_deviation + jitter, self.deviation(target_heading, jitter), "WARNING: RANDOM VALUES IN TEST. Expected deviation from course to decrease every iteration, but got list " + str(deviation_list)) previous_deviation = self.deviation(target_heading, 0)
def run(self, until=None): """Executes :meth:`step()` until the given criterion *until* is met. - If it is ``None`` (which is the default), this method will return when there are no further events to be processed. - If it is an :class:`~simpy.events.Event`, the method will continue stepping until this event has been triggered and will return its value. Raises a :exc:`RuntimeError` if there are no further events to be processed and the *until* event was not triggered. - If it is a number, the method will continue stepping until the environment's time reaches *until*. """ if until is not None: if not isinstance(until, Event): # Assume that *until* is a number if it is not None and # not an event. Create a Timeout(until) in this case. at = float(until) if at <= self.now: raise ValueError('until(=%s) should be > the current ' 'simulation time.' % at) # Schedule the event with before all regular timeouts. until = Event(self) until.ok = True until._value = None self.schedule(until, URGENT, at - self.now) elif until.callbacks is None: # Until event has already been processed. return until.value until.callbacks.append(StopSimulation.callback) try: while True: self.step() except StopSimulation as exc: return exc.args[0] # == until.value except EmptySchedule: if until is not None: assert not until.triggered raise RuntimeError('No scheduled events left but "until" ' 'event was not triggered: %s' % until)
def __init__(self, messanger, directory): self.logger = logging.getLogger(__name__) self.messanger = messanger self.directory = directory self.directory.transfer_finalized += self.__transfer_finalized self.my_index_last_updated = 0 self.remote_index = None self.address = self.messanger.address[0] self.my_uuid = self.messanger.my_uuid self.uuid = self.messanger.remote_uuid self.disconnected = Event() self.messanger.disconnected += self.__disconnected self.messanger.packet_received += self._packet_received
def on_post(self, req, resp): if req.content_length: doc = json.load(req.stream) event = Event(doc["name"]) topic_path = self.publisher.topic_path(PROJECT_ID, TOPIC_NAME) response_future = self.publisher.publish(topic_path, data=event.body) resp.body = json.dumps( { "published": "true", "result": response_future.result() }, ensure_ascii=False) resp.status = falcon.HTTP_200 else: resp.status = falcon.HTTP_400
def _send_orders_to_armies(self): orders = self.orders orderlist = [] for i in [0, 1]: order = orders[i] for u in self.armies[i].present_units(): speed = u.speed + random.uniform(-3, 3) if order == 'D': speed += 2.7 orderlist.append((speed, "order_received", Context(opt={ "ctarget": u, "order": order }))) orderlist.sort(key=lambda x: x[0]) for o in tuple(orderlist): Event(self, o[1], o[2]).defer('Q_ORDER')
def events(self, start_date, end_date, frequency): running = True self.clock_engine_thread.start() self.quotation_engine_thread.start() while running: real_dt = datetime.datetime.now() while True: try: dt, event_type = self.event_queue.get(timeout=1) break except Empty: continue system_log.debug("real_dt {}, dt {}, event {}", real_dt, dt, event_type) yield Event(event_type, calendar_dt=real_dt, trading_dt=dt)