def status(self): s = {} self.__s_ecu_return = None # Stores the response from the callback self.__s_data_return = None # Stores the response from the callback self.__s_worker_return = None # Stores the response from the callback self.__s_log_return = None # Stores the response from the callback self.__s_gps_return = None # Stores the response from the callback self.__pipes['WORKER'].send( Message('GETSTATUS')) # Send message for incomming request self.__event['GETSTATUS'].wait() self.__event['GETSTATUS'].clear() s['WORKER'] = self.__s_worker_return['STATUS'] self.__pipes['ECU'].send( Message('GETSTATUS')) # Send message for incomming request self.__event['GETSTATUS'].wait() self.__event['GETSTATUS'].clear() s['ECU'] = self.__s_ecu_return['STATUS'] self.__pipes['COLLECTOR'].send( Message('GETSTATUS')) # Send message for incomming request self.__event['GETSTATUS'].wait() self.__event['GETSTATUS'].clear() s['COLLECTOR'] = self.__s_data_return['STATUS'] self.__pipes['LOG'].send( Message('GETSTATUS')) # Send message for incomming request self.__event['GETSTATUS'].wait() self.__event['GETSTATUS'].clear() s['LOG'] = self.__s_log_return['STATUS'] self.__pipes['GPS'].send( Message('GETSTATUS')) # Send message for incomming request self.__event['GETSTATUS'].wait() self.__event['GETSTATUS'].clear() s['GPS'] = self.__s_gps_return['STATUS'] return s # Return the response from the callback to the caller
def with_profiles(self, data_profile, pipeline_profile): self.tests, self.warnings = [], [] if data_profile is not None: for column_profile in data_profile.profiles: # print(column_profile) for test in self.col_wise.values(): self.tests.append(test(column_profile)) for test in self.scale_wise[column_profile.scale].values(): self.tests.append(test(column_profile)) for test in self.set_wise.values(): self.tests.append(test(data_profile)) else: self.warnings.append( Warning(ErrorType.UNAVAILABLE, Severity.CRITICAL, Message().data_profile_not_available)) if pipeline_profile is not None: for step in pipeline_profile: # print(step) for test in self.pipe.values(): self.tests.append(test(pipeline_profile)) else: self.warnings.append( Warning(ErrorType.UNAVAILABLE, Severity.CRITICAL, Message().pipeline_profile_not_available)) return self
def lightning_attack(*args, **kwargs): caster = args[0] entities = kwargs.get('entities') fov_map = kwargs.get('fov_map') damage = kwargs.get('damage') max_range = kwargs.get('max_range') results = [] target = None closest_dist = max_range + 1 for entity in entities: if entity.fighter and entity != caster and libtcod.map_is_in_fov(fov_map, entity.x, entity.y): distance = caster.distance_to(entity) if distance < closest_dist: target = entity closest_dist = distance if target: results.append({'consumed': True, 'target': target, 'message': Message('A lightning bolt hits {0}! It does {1} points of damage'.format(target.name, damage))}) results.extend(target.fighter.take_damage(damage)) else: results.append({'consumed': False, 'target': None, 'message': Message('No enemy is within range'.libtcod.red)}) return results
def start(self): """This is a prove that I have no understanding of sockets. Whats a socket, whats a conn, when is it open, when closed?""" import socket self.runserver = 1 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) s.bind((self.addr, self.port)) s.listen(1) self.socket = s self.init_conn() while self.runserver: data = self.conn.recv(2048) if len(data) == 0: self.init_conn() data = self.conn.recv(2048) data = data.replace('\r', '') try: m = Message(jsontext=data) self.newMessage(m) except Exception, e: try: self.write(Message('WrongFormat', str(e))) except Exception: pass
def waitForReceipt(self, message): 'after sending we need a receipt' if message.type == 'Receipt': self.state = self.finish return Message('Goodbye') else: return Message('Please send a receipt')
def start(self, message): if message.type == 'sendMoney': if self.wallet: self.wallet.coins.extend(message.data) self.state = self.Goodbye return Message('Receipt') else: return Message('Please send me money, mama')
def run(self, data): assert self.tests is not None, Message().no_profile assert self.warnings is not None, Message().no_profile for test in self.tests: for check in test.checks: if check.assumption(data): continue self.warnings.append( Warning(check.error_type, test.severity, check.message)) return self.tests, self.warnings
def setUp(self): self.location_a = Location(5, 3) self.node_a = Node(node_id="1", location=self.location_a) self.arguments_a = {'arg_1':1, 'arg_2':2, 'arg_3':3} self.message_a = Message(sender=self.node_a, emit_location=self.location_a, \ function_to_call=self.an_example_function, arguments=self.arguments_a) self.location_b = Location(1, 2) self.message_b = Message(sender=self.node_a, emit_location=self.location_b, \ function_to_call=self.an_example_function, arguments=self.arguments_a) self.message_broker = MessageBroker()
def start(self, message): import base64 from fraction import Fraction if message.type == 'SUM_ANNOUNCE': try: encoded_transaction_id, standard_identifier, currency_identifier, encoded_amount, self.target = message.data except ValueError: return ProtocolErrorMessage('SA') if not isinstance(encoded_transaction_id, types.StringType): return ProtocolErrorMessage('SA') if not isinstance(standard_identifier, types.StringType): return ProtocolErrorMessage('SA') if not isinstance(currency_identifier, types.StringType): return ProtocolErrorMessage('SA') if not isinstance(encoded_amount, types.StringType): return ProtocolErrorMessage('SA') if not isinstance(self.target, types.StringType): return ProtocolErrorMessage('SA') # Decode the transaction_id try: self.transaction_id = base64.b64decode(encoded_transaction_id) except TypeError: return ProtocolErrorMessage('SA') # Setup sum self.sum = Fraction(encoded_amount) # And do stuff #get some feedback from interface somehow action = self.wallet.confirmReceiveCoins('the other wallet id', self.sum, self.target) if action == 'reject': self.state = self.goodbye return Message('SUM_REJECT') else: self.action = action self.state = self.handleCoins return Message('SUM_ACCEPT') elif message.type == 'PROTOCOL_ERROR': pass else: return ProtocolErrorMessage('TokenSpendRecipient')
def execute(self): env = self.state register = env.registers[self.n] try: message = Message("Error: ") + self.message.instantiate(env.args) except messages.BadInstantiation: raise BadCommand("invalid reference") old_cmd = register.cmd.command_for_raise() error = Message(old_cmd.string) cmd = self.copy(old_cmd=old_cmd) state = old_cmd.state.add_register(error, message, cmd=cmd) return None, state, cmd
def start(self, message): if message.type == 'HANDSHAKE': if message.data['protocol'] == 'opencoin 1.0': self.newState(self.dispatch) return Message('HANDSHAKE_ACCEPT') else: self.newState(self.goodbye) return Message('HANDSHAKE_REJECT', 'did not like the protocol version') else: return Message('PROTOCOL_ERROR', 'please do a handshake')
def heal(*args, **kwargs): entity = args[0] amount = kwargs.get('amount') results = [] if entity.fighter.hp == entity.fighter.max_hp: results.append({'consumed': False, 'message': Message('You are at full health already.', libtcod.yellow)}) else: entity.fighter.heal(amount) results.append({'consumed': True, 'message': Message('You drank the potion!', libtcod.green)}) return results
def unregister(self, handle, channel_id=None): if channel_id is None: for channel_id in self.boards: if handle in self.boards[channel_id]: self.message_handler.publish( Message("disconnect", self.boards[channel_id][handle]), channel_id) del self.boards[channel_id][handle] else: self.message_handler.publish( Message("disconnect", self.boards[channel_id][handle]), channel_id) del self.boards[channel_id][handle]
def run(self): logger.info('Starting GPS process on PID {}'.format(self.pid)) self.__pipes['GPS'].start() self.__running = True while self.__running: try: logger.debug('Running = {}, Paused = {}'.format( self.__running, self.__paused)) t = time() for new_data in self.__gpsd: if new_data: logger.debug('New Data') self.__stream.unpack(new_data) logger.debug('Stream values: {},{},{},{}'.format( self.__stream.lat, self.__stream.lon, self.__stream.speed, self.__stream.alt)) if not self.__paused: logger.debug('Inserting values to queue') self.__pollCount += 1 self.__resultQue.put( Message('ALTITUDE', VALUE=None if type(self.__stream.alt) is not float else self.__stream.alt)) self.__resultQue.put( Message('LATITUDE', VALUE=None if type(self.__stream.lat) is not float else self.__stream.lat)) self.__resultQue.put( Message('LONGITUDE', VALUE=None if type(self.__stream.lon) is not float else self.__stream.lon)) self.__resultQue.put( Message('HEADING', VALUE=None if type(self.__stream.track) is not float else self.__stream.track)) self.__resultQue.put( Message('GPS_SPD', VALUE=None if type(self.__stream.speed) is not float else self.__stream.speed * 3.6)) # GPS reports speed in m/s sleep(1) except (KeyboardInterrupt, SystemExit): self.__running = False self.__gpsd.close() return except: logger.critical('Unhandled exception occured in GPS process:', exc_info=True, stack_info=True) continue logger.info('GPS process stopping')
def send_keystrokes(self): pygame.event.pump() keys = pygame.key.get_pressed() impulses = [] for x in ACTIVATORS: if keys[x]: impulses.append(x) if keys[pygame.K_ESCAPE]: self.conn.send(Message(common.QUIT, "quit")) return False if impulses: msg = Message(common.IMPULSE, impulses) self.conn.send(msg)
def followup(self, followup, cmd): env = self.state followup, env = env.contextualize(followup) env = env.copy(parent_cmd=cmd) addressed_answer = Message("A: ") + self.message addressed_followup = Message("Q: ") + followup new_contents = env.registers[0].contents + (addressed_answer, addressed_followup) env = env.add_register(*new_contents, contextualize=False, cmd=self.copy(result_cmd=cmd), replace=True, n=0) return env
def run(self): self.__running = True logger.info('Starting Worker process on PID {}'.format(self.pid)) # Start watcher threads for pipes for p in self.__pipes: self.__pipes[p].start() while self.__running: try: if not self.__isConnected(): self.__paused = True self.__firstPoll = None self.__connect() else: if self.__firstPoll is None: self.__firstPoll = datetime.now() if not self.__paused and self.__running: #while self.__workQue.qsize() > 0: if self.__workQue.qsize() > self.__maxQueLength: self.__maxQueLength = self.__workQue.qsize() m = self.__workQue.get() if m is None: break if self.__isConnected(): if not self.__testing: q = self.__interface.query(obd.commands[m]) self.__pollCount += 1 if self.__firstPoll is None: self.__firstPoll = datetime.now() if self.__testing: self.__resultQue.put(Message(m, VALUE=0.0)) else: if not q.is_null(): logger.debug('{} - {}'.format(m, q.value)) self.__resultQue.put( Message(m, VALUE=q.value.magnitude)) self.__pollRate = self.__pollCount / ( datetime.now() - self.__firstPoll).total_seconds() #sleep(1.0 / self.__frequency) except (KeyboardInterrupt, SystemExit): self.__running = False self.__resultQue.put(None) continue except: logger.critical( 'Unhandled exception occured in Worker process:', exc_info=True, stack_info=True) continue logger.info('Worker process stopping')
def finish(self, result, result_cmd, sub_budget_consumed): env = self.state result, env = env.contextualize(result) question = Message("Q: ") + self.message answer = Message("A: ") + result new_contents = self.register.contents + (question, answer) cmd = self.copy(result_cmd=result_cmd, budget_consumed=sub_budget_consumed) env = env.add_register(*new_contents, cmd=cmd, contextualize=False, n=self.n, replace=True) env = env.consume_budget(cmd.budget_consumed) return None, env, cmd
def test_typos_in_data_with_random_forest(self): classifier = RandomForest() model = self.pipeline.with_estimator(classifier).fit(self.X_train, self.y_train) error_generator = Typos() num_cols = 3 # Will fail if the number of columns is less than 3 columns = np.random.choice(self.features, num_cols, replace=False) corrupted_X_test = error_generator.run(self.X_test, columns=columns) # prediction = model.predict(X_test) # print(accuracy_score(y_test, prediction)) # suite = TestSuite() pipeline_profile = SklearnPipelineProfiler().on(model) tests, warnings = (self.automated_suite .with_profiles(self.data_profile, pipeline_profile) .on(corrupted_X_test)) for column, profile in zip(columns, self.data_profile.profiles): if profile.scale != DataScale.NOMINAL: continue self.assertIn(Test(Severity.CRITICAL).is_in_range(profile), tests) self.assertIn(Warning(ErrorType.NOT_IN_RANGE, Severity.CRITICAL, Message().not_in_range % (profile.column_name, str(profile.range))), warnings)
class TopLevel: bg_filename = "nebula.png" def __init__(self, screen): self.screen = screen self.clock = pygame.time.Clock() self.shipset = pygame.sprite.RenderUpdates() self.halt = 0 self.xmit_cntdown = xmit_subfreq self.main_sprite = PX74Sprite("b.png") self.shipset.add(self.main_sprite) # (try to) load background image try: self.bg_sfc = pygame.image.load(self.bg_filename).convert() except pygame.error, message: print "Foobar: " + message # blit up the background image onto the screen surface self.screen.blit(self.bg_sfc, (0, 0)) pygame.display.update() # required after initial blit before sprites self.netw = ClientNetWrangler(('127.0.0.1', 9000), ('', 9001)) if not self.netw.startup(): print "ERROR: couldn't start; network init failed" self.halt = 1 return hellomsg = Message() hellomsg.type = ClientMessages.HELLO self.netw.enqueue_message(hellomsg) self.handle = 0
def fetchMintingKey(self, transport, denominations=None, keyids=None, time=None): denominations_str = [str(d) for d in denominations] protocol = protocols.fetchMintingKeyProtocol( denominations=denominations_str, keyids=keyids, time=time) transport.setProtocol(protocol) transport.start() protocol.newMessage(Message(None)) # Get the keys direct from the protcool. retreivedKeys = protocol.keycerts for key in retreivedKeys: try: cdd = self.cdds[key.currency_identifier] except KeyError: continue # try the other currencies if not self.keyids.has_key(key.key_identifier): if key.verify_with_CDD(cdd): self.keyids[key.key_identifier] = key else: raise Exception('Got a bad key')
def process_selected_item(item, *, player=None, game_map=None, game_state=None, player_turn_results=None): # Check which inventory screen we are on and call the appropriate method. if game_state == GameStates.SHOW_INVENTORY: if item.usable: player_turn_results.extend(item.usable.use(game_map, player)) player_turn_results.extend(item.consumable.consume()) elif game_state == GameStates.THROW_INVENTORY: if item.throwable: # Cannot throw weapons that are equipped. if item.equipable and item.equipable.equipped: message = Message(f"Cannot throw equipped weapon {item.name}") player_turn_results.append({ResultTypes.MESSAGE: message}) return player_turn_results.extend(item.throwable.throw(game_map, player)) player_turn_results.extend(item.consumable.consume()) elif game_state == GameStates.EQUIP_INVENTORY: if item.equipable and item.equipable.equipped: player_turn_results.extend(item.equipable.remove(player)) elif item.equipable: player_turn_results.extend(item.equipable.equip(player)) elif game_state == GameStates.DROP_INVENTORY: player_turn_results.extend(player.inventory.drop(item))
def __init__(self, main, explorer, editor, model): super().__init__() self.explorer = explorer self.editor = editor self.model = model self.main = main self.message = Message(main)
def process(self): # add new messages if 'new_message' in self.page.form: data = { 'user_id': self.page.session.user.id, 'text': self.page.form['new_message'].value } id = self.messages.add(data) # add like if 'like' in self.page.form: message_id = int(self.page.form['like'].value) if message_id: message = Message(message_id) MessageLikes(message).toggle(self.page.session.user.id) # add comment for field in self.page.form.keys(): if field.startswith('new_comment_'): reference_id = field.split('_')[2] if reference_id: data = { 'user_id': self.page.session.user.id, 'reference_id': reference_id, 'text': self.page.form[field].value } id = self.messages.add(data) break # remember scroll if 'scroll_pos' in self.page.form: p = self.page.form['scroll_pos'].value self.scroll_pos = int(round(float(p), 0))
def use(self, item_entity, **kwargs): results = [] item_component = item_entity.item if item_component.use_function is None: results.append({ 'message': Message('The {0} cannot be used'.format(item_entity.name), tcod.yellow) }) else: if item_component.targeting and not (kwargs.get('target_x') or kwargs.get('target_y')): results.append({'targeting': item_entity}) else: kwargs = {**item_component.function_kwargs, **kwargs} item_use_results = item_component.use_function( self.owner, **kwargs) for item_use_result in item_use_results: if item_use_result.get('consumed'): self.remove_item(item_entity) results.extend(item_use_results) return results
def main_loop(self): while True: self.took_turn = False self.timer, next_actor = heapq.heappop(self.event_queue) if isinstance(next_actor, Player): while True: self.draw_screen() try: c = self.main.getch() msg = self.keybindings[c]["function"]( **self.keybindings[c]["args"]) except KeyError: continue else: if msg: self.add_message(msg) self.add_event(next_actor) self.current_level.heatmap(self.player.x, self.player.y) break else: msg = next_actor.take_turn(self.current_level) if msg: if msg == "Game over.": self.save_game() self.msg_handler.new_message(Message(msg)) self.add_event(next_actor)
def sendTweet(userInput): startIndex = userInput.find('\"') #the starting index of the tweet message #startIndexHash = userInput.find('#') #the starting index of the hashtags if startIndex != -1: #i.e. if the first quote was found endIndex = userInput.find('\"', startIndex + 1) if startIndex != -1 and endIndex != -1: #i.e. both quotes were found tweetMessage = userInput[startIndex + 1:endIndex] if len(tweetMessage) < 1: print("message format illegal.") elif len(tweetMessage) > 150: print("message length illegal, connection refused.") else: hashPart = userInput[ endIndex:] #search for hashtag after the tweet message startIndexHash = hashPart.find( '#') #the starting index of the hashtags if startIndexHash != -1: #hashtags found hashtags = hashPart[startIndexHash + 1:] hashtagList = hashtags.split("#") for hashtag in hashtagList: if not hashtag.isalnum() or len(hashtag) < 1: print( "hashtag illegal format, connection refused.") else: #Send the tweet to the server userTweet = Message(tweetMessage, username, hashtagList) request = Request(Method.TWEET, userTweet) clientSocket.send(pickle.dumps(request)) response = clientSocket.recv(1024) response = pickle.loads(response) if response.status == Status.ERROR: print(response.body)
def hit(self, x, y, damage, name, map, entities, results): """Long range 'attack' for spells.""" target = map.get_entity(x, y, entities) if target: results.append({ 'message': Message( 'The {} hits {} for {} hitpoints.'.format( name, target.name, damage), 'crimson') }) target.take_damage(damage, results) else: results.append({ 'message': Message('Oops, {} does nothing.'.format(name), 'white') })
def use_staff(staff_usable, callback_cls, game_map, user): """Generic function for using a staff. Parameters ---------- staff_usable: Usable component. The usable component of the item entity. callback_cls: Class to use for the callback after the position to use the staff has been selected. game_map: GameMap The current game map. user: Entity The entity that used the staff. """ if staff_usable.owner.consumable.uses > 0: callback = callback_cls(staff_usable, game_map, user) return [{ ResultTypes.CURSOR_MODE: (user.x, user.y, callback, CursorTypes.RAY) }] else: message = Message( f"Cannot use {staff_usable.owner.name} with zero charges.") return [{ResultTypes.MESSAGE: message}]
def waterblast(game_map, center, *, radius=4, damage=6, user=None): """Create a blast of water centered at a position of a given radius. The waterblast both deals damage, and floods all tiles within a given radius. """ results = [] harmable_within_radius = (get_all_entities_with_component_within_radius( center, game_map, "harmable", radius)) for entity in (x for x in harmable_within_radius if x != user): text = f"The {entity.name} is caught in a waterblast!" message = Message(text, COLORS.get('white')) results.append({ ResultTypes.DAMAGE: (entity, None, damage, [Elements.WATER]), ResultTypes.MESSAGE: message }) blast_coordinates = coordinates_within_circle(center, radius) for coord in blast_coordinates: if game_map.walkable[coord]: entities = get_all_entities_of_type_within_radius( coord, game_map, EntityTypes.TERRAIN, 0) for entity in entities: results.append({ResultTypes.REMOVE_ENTITY: entity}) water = Water.make(game_map, coord[0], coord[1]) results.append({ResultTypes.ADD_ENTITY: water}) results.append( {ResultTypes.ANIMATION: (Animations.WATERBLAST, center, radius)}) return results