예제 #1
0
 def create_account(self):
   # use this as a simple way to create a command instead of some gui just for now
   print 'Please create a new customer first!'
   first_name = raw_input('First Name: ')
   last_name = raw_input('Last Name: ')
   m = Message()
   m.first_name = first_name
   m.last_name = last_name
   self._bus.publish(m, Command.CREATE_CUSTOMER)
   print 'finished command'
예제 #2
0
파일: actions.py 프로젝트: AnithaT/eden
 def errorMsg(self, message):
     """
         Method used to check for error messages
         @param message: the message to be searched for in the banner
         returns:        boolean reporting success
     """
     self.startCoverage("errorMsg")
     m = Message(self)
     result = m._findMsg(message, "error")
     self.endCoverage()
     return result
예제 #3
0
    def auth(self):
	self.transport.send(Message.nick(self.name).pack())
	data = self.transport.receive()
	try:
	    msg = Message.parse(data)
	except MessageError:
	    return False
	if msg.type == 'auth' and msg.payload == 'success':
	    return True
	else:
	    return False
예제 #4
0
파일: actions.py 프로젝트: AnithaT/eden
 def findResponse(self, successMsg, errorMsg):
     """
         Method to check on the response of an action by looking at the message
         @param SuccessMsg:  the message to be searched for in the banner upon success
         @param errorMsg:    the message to be searched for in the banner upon failure
         returns:            boolean reflecting the type of message found
         side effect:        exception if neither message found
     """
     self.startCoverage("findResponse")
     m = Message(self)
     result = m.findResponse(successMsg, errorMsg)
     self.endCoverage()
     return result
def test_terminate_on_unexpected_transport_finished():
    with create_upstream_context() as ctxt:
        ctxt.send_msg(Message.ServiceDescription("AcceptanceTest", 2))
        ctxt.expect_message("ServiceDescription")

        msg = Message.TransportFinished(TransferState.COMPLETE, "some_guid")
        ctxt.send_msg(msg)
        # other end has to close connection so check if socked is dead now, optionally a Notification can be sent before closing
        try:
            ctxt._socket.recv(0)
            uc.expect_message("Notification")
            ctxt.close()
            raise ValueError("TransportFinished erroneously accepted after handshake")
        except:
            pass
예제 #6
0
 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_terminate_on_unexpected_revoke_machine_ready():
    with create_upstream_context() as ctxt:
        ctxt.send_msg(Message.ServiceDescription("AcceptanceTest", 2))
        ctxt.expect_message("ServiceDescription")

        msg = Message.RevokeMachineReady()
        ctxt.send_msg(msg)
        # other end has to close connection so check if socked is dead now, optionally a Notification can be sent before closing
        try:
            ctxt._socket.recv(0)
            uc.expect_message("Notification")
            ctxt.close()
            raise ValueError("RevokeMachineReady erroneously accepted after handshake")
        except:
            pass
예제 #8
0
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}]
예제 #9
0
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
예제 #10
0
 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')
         })
예제 #11
0
def index():
    code = request.args.get('code', '')
    if code:
        Code.objects.delete()
        Code.objects.insert(Code(code=code))
        return redirect('http://wolfware4.com')
    return render_template('index.html', messages=Message.objects())
예제 #12
0
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)
예제 #13
0
	def get(self, tab='info'):
		params = {}

		params['bigboard'] = self.request.get('bigboard')
		
		if tab == 'info':
			feed = []
			for msg in Message.query(Message.show_in_day_of == True).order(-Message.added).fetch(limit=20):
				feed.append({"date": msg.added, "type": "message", "message": msg})
			for post in Post.query(Post.feed == 'twitter/user/HackAtBrown', Post.is_reply == False).order(-Post.date).fetch(limit=20):
				feed.append({"date": post.date, "type": "tweet", "tweet": post})
			feed.sort(key=lambda x: x['date'], reverse=True)
			params['feed'] = feed[:min(len(feed), 20)]
		elif tab == 'requests':
			def request_to_dict(req):
				return {
				"name": req.requester.get().name if req.requester else None,
				"issue": req.issue,
				"tags": req.tags,
				"location": req.location,
				"time": req.created
				}
			params['requests'] = map(request_to_dict, MentorRequest.query().order(-MentorRequest.created).fetch(limit=100))

		content = template("day_of/{0}.html".format(tab), params) # TODO: security-ish stuff
		
		if self.request.get('ajax'):
			self.response.write(content)
		else:
			index_params = {
				"tab": tab,
				"tab_content": content,
				"bigboard": self.request.get('bigboard')
			}
			self.response.write(template("day_of/index.html", index_params))
예제 #14
0
def save_result_into_RS_db(message: Message):
    if isinstance(message, MsgTestSuiteReport):
        m_data = message.tc_results  # this is a list
        m_type = "final"
    elif isinstance(message, MsgTestCaseVerdict):
        m_data = message.to_dict()
        m_type = "intermediate"
    else:
        raise TypeError("Expecting Report or TC verdict message")

    m = MsgReportSaveRequest(
        type=m_type,
        data=m_data,
    )
    logger.info("Sending %s results to RS" % m_type)
    try:

        reply = amqp_request(
            connection=pika.BlockingConnection(pika.URLParameters(AMQP_URL)),
            request_message=m,
            component_id=COMPONENT_ID,
            retries=3,
            use_message_typing=True,
        )

    except AmqpSynchCallTimeoutError as tout:
        logger.warning("Request for %s timed out. Is RS up?" % type(m))
        return

    if not reply or not reply.ok:
        logger.warning("Couldn't save results, got response: %s " %
                       repr(reply))
        return

    logger.info("Successful %s results save into RS" % m_type)
예제 #15
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')
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
예제 #17
0
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))
예제 #18
0
 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)
예제 #19
0
def abbreviate_textplan(textplan):
    """
    recursive helper function that prints only the skeletton of a textplan 
    (message types and RST relations but not the actual message content)
    
    :param textplan: a text plan, a constituent set or a message
    :type textplan: ``TextPlan`` or ``ConstituentSet`` or ``Message``
    
    :return: a message (without the attribute value pairs stored in it)
    :rtype: ``Message``
    """
    if isinstance(textplan, TextPlan):
        score = textplan["title"]["book score"]
        abbreviated_textplan = abbreviate_textplan(textplan["children"])
        return TextPlan(book_score=score, children=abbreviated_textplan)
    if isinstance(textplan, ConstituentSet):
        reltype = textplan[Feature("relType")]
        nucleus = abbreviate_textplan(textplan[Feature("nucleus")])
        satellite = abbreviate_textplan(textplan[Feature("satellite")])
        return ConstituentSet(relType=reltype,
                              nucleus=nucleus,
                              satellite=satellite)
    if isinstance(textplan, Message):
        msgtype = textplan[Feature("msgType")]
        return Message(msgType=msgtype)
예제 #20
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
예제 #21
0
    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)
예제 #22
0
파일: feed.py 프로젝트: lover2668/stemsible
    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))
예제 #23
0
def _WriteSharedVar(sharedVarType, name, data):
    
    w = str(data)
    if sharedVarType == SharedVarTypes.BYTE_ARRAY:
        w = '0x' + ''.join([ "%02X" % x for x in data ])
    elif sharedVarType in [SharedVarTypes.INT, SharedVarTypes.LONG]:
        w = str(int(data))
    elif sharedVarType == SharedVarTypes.DOUBLE:
        w = str(float(data))
    elif sharedVarType in [SharedVarTypes.INT_ARRAY, SharedVarTypes.LONG_ARRAY]:
        w = ' '.join([str(int(x)) for x in data])
    elif sharedVarType == SharedVarTypes.DOUBLE_ARRAY:
        w = ' '.join([str(float(x)) for x in data])
    elif sharedVarType == SharedVarTypes.STRING:
        w = Message._SerializeString(data)
    elif sharedVarType == SharedVarTypes.MATRIX:
        w = SharedVar._SerializeMatrix(data)
    elif sharedVarType == SharedVarTypes.RECOGNIZED_SPEECH:
        w = SharedVar._SerializeRecognizedSpeech(data)
    else:
        print 'pyRobotics - ERROR: Unhandled shared var type'
        return False
    
    r = BB.SendAndWait(Command('write_var', sharedVarType + ' ' + name + ' ' + w), 2000, 2)
    
    return (r and r.successful)
예제 #24
0
 def __init__(self, group_id):
     self.group_id = group_id
     self.users = set ([])
     self.user_photos = {}
     self.survey_data_filename = "c:/users/aaron/desktop/survey_data.txt"
     self.meetup_client = meetup.Meetup(conf.api_key)
     self.message_client = Message()
def test_terminate_on_illegal_message():
    with create_upstream_context() as ctxt:
        msg_bytes = b"<Hermes Timestamp='2020-04-28T10:01:20.768'><ThisIsNotAKnownMessage /></Hermes>"
        ctxt.send_tag_and_bytes(None, msg_bytes)
        # other end has to close connection so check if socked is dead now, optionally a Notification can be sent before closing
        try:
            ctxt._socket.recv(0)
            uc.expect_message("Notification")
            ctxt.close()
            raise ValueError("illegal message erroneously accepted")
        except:
            # try the same after initial handshake
            ctxt.close()
            with create_upstream_context() as ctxt:
                ctxt.send_msg(Message.ServiceDescription("AcceptanceTest", 2))
                ctxt.expect_message("ServiceDescription")

                ctxt.send_tag_and_bytes(None, msg_bytes)
                # other end has to close connection so check if socked is dead now, optionally a Notification can be sent before closing
                try:
                    ctxt._socket.recv(0)
                    uc.expect_message("Notification")
                    ctxt.close()
                    raise ValueError("illegal message erroneously accepted after handshake")
                except:
                    pass
예제 #26
0
def _WriteSharedVar(sharedVarType, name, data):

    w = str(data)
    if sharedVarType == SharedVarTypes.BYTE_ARRAY:
        w = '0x' + ''.join(["%02X" % x for x in data])
    elif sharedVarType in [SharedVarTypes.INT, SharedVarTypes.LONG]:
        w = str(int(data))
    elif sharedVarType == SharedVarTypes.DOUBLE:
        w = str(float(data))
    elif sharedVarType in [
            SharedVarTypes.INT_ARRAY, SharedVarTypes.LONG_ARRAY
    ]:
        w = ' '.join([str(int(x)) for x in data])
    elif sharedVarType == SharedVarTypes.DOUBLE_ARRAY:
        w = ' '.join([str(float(x)) for x in data])
    elif sharedVarType == SharedVarTypes.STRING:
        w = Message._SerializeString(data)
    elif sharedVarType == SharedVarTypes.MATRIX:
        w = SharedVar._SerializeMatrix(data)
    elif sharedVarType == SharedVarTypes.RECOGNIZED_SPEECH:
        w = SharedVar._SerializeRecognizedSpeech(data)
    else:
        print 'pyRobotics - ERROR: Unhandled shared var type'
        return False

    r = BB.SendAndWait(
        Command('write_var', sharedVarType + ' ' + name + ' ' + w), 2000, 2)

    return (r and r.successful)
예제 #27
0
async def client_read(reader, writer, connection):
    """
        Utilized by the Telnet and SSH client_handlers.

        We want this coroutine to run while the client is connected, so we begin with a while loop
        We first await control back to the loop until we have received some input (or an EOF)
            Mark the connection to disconnected and break out if a disconnect (EOF)
            else we handle the input. Client input packaged into a JSON payload and put into the
            messages_to_game asyncio.Queue()
    """
    while connection.state["connected"]:
        inp = await reader.readline()
        log.info(f"Raw received data in client_read : {inp}")

        if not inp:  # This is an EOF.  Hard disconnect.
            connection.state["connected"] = False
            return

        payload = {
            "uuid": connection.uuid,
            "addr": connection.addr,
            "port": connection.port,
            "msg": inp.strip(),
        }
        msg = {
            "event": "player/input",
            "secret": WS_SECRET,
            "payload": payload,
        }

        asyncio.create_task(
            messages_to_game.put(
                Message("IO",
                        message=json.dumps(msg, sort_keys=True, indent=4))))
예제 #28
0
def sendmessage():
    input = request.get_json()
    messageobj = Message(input['username'])
    messageobj.readmessages()
    messageobj.addmessages(messageobj.username, input['messagetxt'],
                           input['channelname'])
    messageobj.writemessages()
    resp = make_response(jsonify(status='success'), 200)
    return resp
예제 #29
0
 def dataLine(self, name):
     self.__dataline_return = None  # Stores the response from the callback
     self.__pipes['COLLECTOR'].send(Message(
         'DATALINE', NAME=name))  # Send message for incomming request
     self.__event['DATALINE'].wait()
     self.__event['DATALINE'].clear()
     return self.__dataline_return[
         'LINE']  # Return the response from the callback to the caller
예제 #30
0
 def logName(self):
     self.__logname_return = None  # Stores the response from the callback
     self.__pipes['LOG'].send(
         Message('LOGNAME'))  # Send message for incomming request
     self.__event['LOGNAME'].wait()
     self.__event['LOGNAME'].clear()
     return self.__logname_return[
         'NAME']  # Return the response from the callback to the caller
예제 #31
0
 def summary(self):
     self.__summary_return = None  # Stores the response from the callback
     self.__pipes['COLLECTOR'].send(
         Message('SUMMARY'))  # Send message for incomming request
     self.__event['SUMMARY'].wait()
     self.__event['SUMMARY'].clear()
     return self.__summary_return[
         'SUMMARY']  # Return the response from the callback to the caller
예제 #32
0
def getMessage(id):
    try:
        message = Message(id)
        data = message.data
        data['user'] = message.user.data
        return jsonify(data)
    except Exception, e:
        return problem(e)
예제 #33
0
 def snapshot(self):
     self.__snapshot_return = None  # Stores the response from the callback
     self.__pipes['COLLECTOR'].send(
         Message('SNAPSHOT'))  # Send message for incomming request
     self.__event['SNAPSHOT'].wait()
     self.__event['SNAPSHOT'].clear()
     return self.__snapshot_return[
         'SNAPSHOT']  # Return the response from the callback to the caller
예제 #34
0
 def supportedCommands(self):
     self.__s_commands_return = None  # Stores the response from the callback
     self.__pipes['WORKER'].send(Message(
         'SUPPORTED_COMMANDS'))  # Send message for incomming request
     self.__event['SUPPORTED_COMMANDS'].wait()
     self.__event['SUPPORTED_COMMANDS'].clear()
     return self.__s_commands_return[
         'SUPPORTED_COMMANDS']  # Return the response from the callback to the caller
예제 #35
0
 def queues(self):
     self.__queues_return = None  # Stores the response from the callback
     self.__pipes['ECU'].send(
         Message('GETQUEUES'))  # Send message for incomming request
     self.__event['GETQUEUES'].wait()
     self.__event['GETQUEUES'].clear()
     return self.__queues_return[
         'QUEUES']  # Return the response from the callback to the caller
예제 #36
0
 def val(self, name):
     self.__val_return = None  # Stores the response from the callback
     self.__pipes['COLLECTOR'].send(Message(
         'VAL', NAME=name))  # Send message for incomming request
     self.__event['VAL'].wait()
     self.__event['VAL'].clear()
     return self.__val_return[
         'VAL']  # Return the response from the callback to the caller
예제 #37
0
    def send(self, message, payload=None):
        """Formats message and payload into packet and sends it to device.

        Args:
            command: Command to send.
            payload: Additional payload to send in packet.
        """
        cmd = Command(message, payload)
        rospy.logdebug("Sending %s: %s", Message.to_string(message), payload)
        self.conn.write(cmd.serialize())
예제 #38
0
 def post(self, message_type):
     message_dict = self._decoode_json_body()
     try:
         message = Message.from_dict(message_dict)
     except MessageParsingError as e:
         raise HTTPError(500, reason=e.message)
     if message_type != message.type:
         raise HTTPError(500, reason="Request message type {body_type} "
                                     "doesn't match URL {url_type}".format(body_type=message.type,
                                                                           url_type=message_type))
     self.manager.message_router.put_message(message)
예제 #39
0
파일: player.py 프로젝트: jhuang314/pyaudio
    def auth(self):
	recv = None
	with Timeout(Player.auth_timeout, PlayerError("Authentication timed out")):
	    try:
		msg = self.transport.receive()
	    except PlayerError as e:
		print("error on receive")
		print(e)
		return False

	try:
	    msg = Message.parse(msg)
	except MessageError:
	    print("bad message")
	    return False
	if msg.type == "nick":
	    self.name = msg.payload
	    self.transport.send(Message.auth_success().pack())
	    return True
	return False
예제 #40
0
 def __init__(self, group_id):
     """Initialize a Pair Data Science pairing system"""
     self.group_id = group_id
     self.users = set ([])
     self.user_photos = {}
     ## Survey data filename is exclusively for SurveyMonkey text
     self.survey_data_filename = "c:/users/aaron/desktop/survey_data.txt"
     ## Survey api survey id is exclusively for the SurveyMonkey API
     self.survey_api_survey_id = u"67951656"
     self.meetup_client = meetup.Meetup(conf.meetup_api_key)
     self.message_client = Message()
     self.aaron_matches = False
예제 #41
0
파일: game.py 프로젝트: jhuang314/pyaudio
    def run_p2(self):
	while True:
	    rec = self.p2.listen()
	    try:
		msg = Message.parse(rec)
	    except MessageError:
		continue
	    if msg.type == 'punch' and msg.payload == '1':
		self.p1.health -= Game.damage
		print "player 1 health: " + str(self.p1.health)
		if self.p1.health <= 0:
		    self.end.set()
예제 #42
0
    def get(self, message=None, wait=2):
        """Sends command and returns reply.

        Args:
            message: Message to expect (default: first to come in).
            wait: Seconds to wait until received if a specific message is
                required (default: 2).

        Returns:
            Reply.

        Raises:
            SonarNotInitialized: Attempt reading serial without opening port.
            TimeoutError: Process timed out while waiting for specific message.
        """
        # Verify sonar is initialized.
        if not self.initialized:
            raise exceptions.SonarNotInitialized()

        expected_name = None
        if message:
            expected_name = Message.to_string(message)
            rospy.logdebug("Waiting for %s message", expected_name)

        # Determine end time.
        end = datetime.datetime.now() + datetime.timedelta(seconds=wait)

        # Wait until received if a specific message ID is requested, otherwise
        # wait forever.
        while message is None or datetime.datetime.now() < end:
            try:
                reply = self.conn.get_reply()

                # Update state if mtAlive.
                if reply.id == Message.ALIVE:
                    self.__update_state(reply)

                # If first was asked, respond immediately.
                if message is None:
                    return reply

                # Otherwise, verify reply ID.
                if reply.id == message:
                    rospy.logdebug("Found %s message", expected_name)
                    return reply
                elif reply.id != Message.ALIVE:
                    rospy.logwarn(
                        "Received unexpected %s message",
                        reply.name
                    )
            except exceptions.PacketCorrupted, serial.SerialException:
                # Keep trying.
                continue
예제 #43
0
    def wait(self, msg_type):
	"""
	Waits for a specific message type, then returns the received message
    	"""
	while True:
	    rec = self.transport.receive()
	    try:
		msg = Message.parse(rec)
	    except MessageError:
		continue
	    if msg.type == msg_type:
		return msg
예제 #44
0
 def _SerializeRecognizedSpeech(cls, data):
     
     if not data:
         return None
     
     txt = StringIO()
     txt.write('{ ' + str(len(data)) + ' ')
     
     for t in data:
         txt.write(Message._SerializeString(t[0]) + ' ' + str(t[1]) + ' ')
     
     txt.write('}')
     return txt.getvalue()
예제 #45
0
 def post(self, message_type):
     if config.RestServer.LOG_RECEIVED_MESSAGES:
         app_log.debug("Received message from controller:\n%s" % self.request.body)
     message_dict = self._decoode_json_body()
     try:
         message = Message.from_dict(message_dict)
     except MessageParsingError as e:
         raise HTTPError(500, reason=e.message)
     if message_type != message.type:
         raise HTTPError(500, reason="Request message type {body_type} "
                                     "doesn't match URL {url_type}".format(body_type=message.type,
                                                                           url_type=message_type))
     self.manager.message_router.put_message(message)
    def _process_message(self, log_entry):
        message = Message.create_message(log_entry)
        if message:  # If a supported message is found

            if message.is_internal_message():

                # (internal messages should always be sent then received,
                # not always case at beginning and end of logfile)
                if message.is_sent_message():

                    message.data['index'] = len(self.messages)
                    self.messages.append(message)

                    index = len(self.messages) - 1
                    self.internal_messages.append({'index': index, 'message': message})

                # If an received message, try find sent message in list and merge extra info
                # If sent message not found update the message to say not found and append to list
                elif message.is_received_message():

                    for index, sent_message in enumerate(self.internal_messages):

                        # Handle the case when duplicate messages are logged
                        if Message.is_same_message(sent_message['message'], message):

                            merged_message = Message.merge(sent_message['message'], message)
                            self.messages[sent_message['index']] = merged_message
                            self.internal_messages.pop(index)
                            break

                    else:
                        # Externally received message
                        message.data['index'] = len(self.messages)
                        self.messages.append(message)

            else:
                message.data['index'] = len(self.messages)
                self.messages.append(message)
 def _extract_transaction_info(self, snapshot_id, grouped_messages):
     self.transactions = []
     for group in grouped_messages.itervalues():
         self.transactions.append({
             'snapshot_id':    str(snapshot_id),
             'transaction_id': group[0].get_transaction_id(),
             'request':        group[0].get()['method'],
             'status':         group[-1].get()['status'],
             'utc':            group[0].get()['utc'],
             'message_ids':    Message.get_message_ids(group),
             'call_id':        self._get_group_call_id(group),
             'local_tag':      self._get_group_local_tag(group),
             'remote_tag':     self._get_group_remote_tag(group)
         })
예제 #48
0
 def _DeserializeRecognizedSpeech(cls, data):
     '''Returns a list which contains tuples (2 elements each) with string and confidence.'''
     if data == '' or data == 'null':
         return None
     
     if data[0] != '{' or data[-1] != '}':
         return None
     
     data = data[1:-1].strip()
     count = 0
     
     if data.find(' ') > -1:
         count, data = data.split(None, 1)
     else:
         return None
     
     count = int(count)
     l = []
     for _ in range(count):
         if data[0] != '"':
             return None
         pos = 1
         str_len = len(data)
         while pos < str_len:
             if data[pos] == '"':
                 break
             elif data[pos] == '\\':
                 pos += 1
             pos += 1
 
         if pos == str_len:
             return None
         currentText = Message._DeserializeString(data[:pos + 1])
         data = data[pos+1:].strip()
         if data.find(' ') > -1:
             currentConfidence, data = data.split(None, 1)
         else:
             currentConfidence = data
         currentConfidence = float(currentConfidence)
         l.append((currentText, currentConfidence))
     
     return l
예제 #49
0
파일: game.py 프로젝트: jhuang314/pyaudio
    def _run(self):
	print "game is starting"
	self.p1.transport.send(Message.opponent(self.p2.name).pack())
	self.p2.transport.send(Message.opponent(self.p1.name).pack())
	
	self.p1.transport.send(Message.start_game().pack())
	self.p2.transport.send(Message.start_game().pack())
	player1 = gevent.spawn(self.run_p1)
	player2 = gevent.spawn(self.run_p2)

	self.end.wait()
	gevent.killall([player1, player2])

	if self.p1.health <= 0:
	    print("player 1 won")
	    self.p1.send(Message.win().pack())
	    self.p2.send(Message.lose().pack())
	else:
	    print("player 2 won")
	    self.p1.send(Message.lose().pack())
	    self.p2.send(Message.win().pack())
	
	self.exit()
예제 #50
0
 def _ProcessReadVar(cls, var):
 
     try:
         if not var.data:
             return None
         
         if var.svType == SharedVarTypes.STRING:
             return Message._DeserializeString(var.data)
         
         if var.svType in [SharedVarTypes.INT, SharedVarTypes.LONG]:
             return int(var.data)
         
         if var.svType == SharedVarTypes.DOUBLE:
             return float(var.data)
         
         if var.svType in [SharedVarTypes.INT_ARRAY, SharedVarTypes.LONG_ARRAY]:
             return [int(x) for x in var.data.split()]
         
         if var.svType == SharedVarTypes.DOUBLE_ARRAY:
             return [float(x) for x in var.data.split()]
         
         if var.svType == SharedVarTypes.BYTE_ARRAY:
             return SharedVar._DeserializeByteArray(var.data)
         
         if var.svType == SharedVarTypes.RECOGNIZED_SPEECH:
             return SharedVar._DeserializeRecognizedSpeech(var.data)
         
         if var.svType == SharedVarTypes.MATRIX:
             return SharedVar._DeserializeMatrix(var.data)
         
         if var.svType == SharedVarTypes.VAR:
             if var.data == 'null':
                 return None
             return var.data
     except:
         pass
     
     print 'Error parsing type: ' + var.svType
     return None
예제 #51
0
    def handle_punch(self):
	while True:
	    gevent.sleep(2)




            """ Record a few seconds of audio and save to a WAVE file. """
            from scipy.io.wavfile import read, write
            from scipy.fftpack import rfft, irfft
            from scipy import *
            from pylab import *
            import numpy as np
            import pyaudio
            import matplotlib.pyplot as plt
            import wave
            import sys
            
            
            
            last = 0.
            last2 = 0.
            cal = []
            mean = 0.
            std = 0.
            hit = 0
            
            chunk = 1024
            FORMAT = pyaudio.paInt16
            CHANNELS = 1
            RATE = 44100
            #RECORD_SECONDS = 0.1
            WAVE_FILENAME = '/tmp/ashfs/output.wav'
            
            p = pyaudio.PyAudio()
            
            stream = p.open(format = FORMAT,
                            channels = CHANNELS,
                            rate = RATE,
                            input = True,
                            output = True,
                            frames_per_buffer = chunk)
            
            
            init = True
            
            while True:
                #print "* recording"
                all = []
                #for i in range(0, RATE / chunk * RECORD_SECONDS):
                i = 0
                while i < 5: # ~120ms
                    try:
                        data = stream.read(chunk)
                        all.append(data)
                        i = i + 1
                    except:
                        pass
                    
            
                #print "* done recording"
            
                #print data[0]
                #print type(data[0])
                #print "%d" % ord(data[0])
                #audio = numpy.fromstring(data)
                #print type(audio)
            
                #audio.shape = (audio.shape[0], 1)
                #print audio.shape
            
            
                #f = scipy.fft(audio[:,0])
            
            
                # write data to WAVE file
                data = ''.join(all)
                wf = wave.open(WAVE_FILENAME, 'wb')
                wf.setnchannels(CHANNELS)
                wf.setsampwidth(p.get_sample_size(FORMAT))
                wf.setframerate(RATE)
                wf.writeframes(data)
                wf.close()
            
                rate, input = read(WAVE_FILENAME)
                input_max = max(input)
                input = input / float(input_max)
                fmax = rate / 2
                input_len = len(input)
                input_time = float(input_len) / float(rate)
                #print "%d samples @ %dHz, duration = %f seconds" % (input_len, rate, input_time)
                t = linspace(0, input_time, input_len);
            
                ft = rfft(input)
                mgft = abs(ft)
                df = fmax/float(input_len/2)
                f = linspace(0, fmax, input_len/2 + 1)
            
                if init:
                    plt.ion()
                    fig = plt.figure()
            
                    ax = fig.add_subplot(211)
                    title('Time-Domain of Signal')
                    tplot, = ax.plot(t, input)
            
                    bx = fig.add_subplot(212)
                    title('Fourier-Domain Magnitude of Signal')
                    fplot, = bx.plot(f, mgft[0:input_len/2+1])
            
                    init = False
                
                #plot(t, input)
                tplot.set_ydata(input)
                fplot.set_ydata(mgft[0:input_len/2+1])
            
                fig.canvas.draw()
            
            
                #show()
            
                sum = 0.
                # @50 22000, 25000
                # @5 2200, 2500
                # @4 1300, 1500
                #print f[1300]
                #print f[1500]
                #print f[1800]
                #print f[2200]
                #print f[2500]
                sum_d = 0.
            
                for i in range(2200, 2500):
                    sum += mgft[i]
                    if i > 2300:
                        sum_d += mgft[i]
            
                hitstr="""
#     #  ###  #######  
#     #   #      #     
#     #   #      #     
#######   #      #     
#     #   #      #     
#     #   #      #     
#     #  ###     #     
            
                """
                ratio = sum_d/sum
                #print sum
                if sum > 200:
                    #print "ratio: %f, sum: %f" % (ratio * 100 , sum)
                    last = ratio * 100
                    delta = last - last2
                    print "%f" % (delta)
                    last2 = last
                    #delta = ratio - last
                    
                    if abs(delta) > 6:
                        hit = hit + 1
                        print hitstr
                        print "Hits = %d" % (hit)
                        print "Sending punch"
                        self.transport.send(Message.punch().pack())
            
                    #if ratio > 7:
                    #print sum
                    #delta = last - sum;
                    #if len(cal) < 21:
                    #    cal.append(sum)
                    #    print "Calibrating Delta = %f..." %(delta)
                    #    if len(cal) == 21:
                    #        mean = np.average(cal)
                    #        std = np.std(cal)
                    #        print "Done calibrating! STD=%f, MEAN=%f" % (std, mean)
                    #        print cal
                    #else:
                    #    print "STD: %f" % (float(sum - mean)/std)
                    #print "Delta (%f%%) : %f" % (sum/last * 100, delta);
                    #if sum > 60000000:
            
                #last = sum
                #print sum
                #print sum2
                #print "stability: %f, delta: %f, sum: %f" % (ratio * 100, ratio_d * 100, sum)
            
            
            
            stream.close()
            p.terminate()
    





	    print "sending punch"
예제 #52
0
파일: player.py 프로젝트: jhuang314/pyaudio
    def close(self):
	self.transport.send(Message.exit().pack())
	self.transport.close()
예제 #53
0
    def handle_punch(self):
	while True:
	    gevent.sleep(7)
	    #print "sending punch"
	    self.transport.send(Message.punch().pack())
예제 #54
0
class Main:
    """Run the Pair Data Science process"""
    conf = Config()

    def __init__(self, group_id):
        """Initialize a Pair Data Science pairing system"""
        self.group_id = group_id
        self.users = set ([])
        self.user_photos = {}
        ## Survey data filename is exclusively for SurveyMonkey text
        self.survey_data_filename = "c:/users/aaron/desktop/survey_data.txt"
        ## Survey api survey id is exclusively for the SurveyMonkey API
        self.survey_api_survey_id = u"67951656"
        self.meetup_client = meetup.Meetup(conf.meetup_api_key)
        self.message_client = Message()
        self.aaron_matches = False

    def get_weekly_opt_ins(self):
        """Grab list interested in matching this week from Meetup event API"""
        arg_dict = {}
        arg_dict["group_id"] = self.group_id

        events = self.meetup_client.get_events(**arg_dict).results
        opt_ins = {}
        for x in events:
            if not "Pair Data Science" in x.name:
                print "Skipped",x.name
                continue
            else:
                print "Calculating Pairs -", x.name
            rsvps = x.get_rsvps(self.meetup_client)
            try:
                for rsvp in rsvps.results:
                    opt_ins[rsvp.member["member_id"]] = rsvp.member["name"]
                    try:
                        self.user_photos[rsvp.member["member_id"]] = rsvp.member_photo["highres_link"]
                    except:
                        self.user_photos[rsvp.member["member_id"]] = None
            except:
                print "didn't get 'em"

        return opt_ins

    def get_users_parser(self,parser_type,survey_unique_identifier):
        """Use parser to grab data from relevant source"""
        parser = parser_type(survey_unique_identifier)
        if not parser.parse():
            return None
        all_users = parser.get_users()

        ## Remember all previous matches
        ## TODO: Update analyze function to exclude previous pairs (Don't want the same person each week)
        ## TODO: Persist to a database instead of a file
        previous_pairs = set([])
        previous_pairs_filename = "c:/users/aaron/desktop/previous_pairs.txt"
        if os.path.isfile(previous_pairs_filename):
            with open (previous_pairs_filename) as prev:
                for line in prev:
                    usera, userb = line.strip().split(",")
                    previous_pairs.add((usera,userb))
                    previous_pairs.add((userb,usera))

        ## Grabs the list of people interested in being matched this week
        ## From the Meetup event API
        opt_ins = self.get_weekly_opt_ins()

        missing_surveys = set([str(u) for u in opt_ins.keys()]).difference(set([str(u.user_id) for u in all_users]))
        print "Missing Surveys", len(missing_surveys), missing_surveys

        ## Filter to just opted-in users
        print "Pre-filter # users", len(all_users)
        users = set([i for i in all_users if int(i.user_id) in opt_ins])

        ## Filter out Aaron, as desired
        if not self.aaron_matches:
            for u in set(users):
                if u.user_id in ["87429312","185839888"]:
                    users.remove(u)
                    break
        print "Post-filter # users", len(users)

        return users

    def get_users(self):
        """Read in the survey data or simulate new data"""
        self.users = self.get_users_parser(APIParser, self.survey_api_survey_id)
        print self.users
        if self.users is None:
            if os.path.isfile(self.survey_data_filename):
                self.users = self.get_users_parser(TextParser, self.survey_data_filename)
            else:
                print "Simulating data"
                ## Simulate some number of survey responses
                sim = Simulator()
                sim.simulate(200) ## By adding a seed parameter, you can have reproducible sims
                self.users = sim.get_users()

    #    ## Print some summaries
    #    for user in users:
    #        user.to_string()

        # Print some descriptive stats
        print "# Users", len(self.users), [u.name for u in self.users]


    def analyze_pairs(self):
        """Match pairs of users"""
        # Analyze pairs
        ## GeogMatcher is a very basic algorithm that only makes use of geography
        ## TODO: Update algorithm to incorporate more than geography
        analyze = GeogMatcher(self.users)
        match_results = analyze.get_best_matches()

        return match_results

    

    def send_missing_survey_messages(self,debug=True):
        """Send message to users that haven't taken survey yet"""
        msg_no_name = Text(self.group_id).take_survey

        opt_ins = self.get_weekly_opt_ins()
        user_ids = [u.user_id for u in self.users]

        for opt_in in opt_ins:
            if str(opt_in) not in user_ids:
                msg = msg_no_name % (opt_ins[opt_in])
                if debug:
                    print msg
                else:
                    print "Starting Message:",msg.split("\n")[0]
                    print self.message_client.send(msg,str(opt_in))
                    print msg

    def send_pair_assignment_messages(self,finish_date,pairs,debug=True):
        """Send message to pairs of users alerting them to their pairings"""
        msg_no_names = Text(self.group_id).assign_pair
        if raw_input('Continue Sending Messages - T or F : ') != "T":
            return
        for pair in pairs:
            msg = msg_no_names % (finish_date,pair[0].name,pair[1].name)
            if raw_input("Send Pair %s -- %s -- T or F: " % (pair[0].name,pair[1].name)) != "T":
                print "Skipping %s -- %s" % (pair[0].name,pair[1].name)
                continue
            else:
                if debug:
                    print "DEBUG ONLY - NOT ACTUALLY SENDING"
                    print msg
                else:
                    self.message_client.send2(msg,[str(p.user_id) for p in pair])
예제 #55
0
    def parse(self):
        """Parses packet into header, message ID, sequence and payload.

        This method also checks if the packet contains all relevant fields and
        has the correct size.

        Raises:
            PacketIncomplete: Packet is incomplete.
            PacketCorrupted: Packet is corrupted.
        """
        try:
            # Parse message header and check for line feed.
            self.bitstream.bytepos = 0
            if self.bitstream.endswith("0x0A"):
                header = self.bitstream.read("uint:8")
            else:
                raise PacketIncomplete("Packet does not end with line feed")

            # Verify message header is '@'.
            if header != 0x40:
                raise PacketCorrupted("Unexpected header: {}".format(header))

            # Find package Hex Length from byte 6, excluding LF
            # as it is noted in packet bytes 2-5.
            self.bitstream.bytepos = 1
            hex_list = [self.bitstream.read("hex:8") for i in range(4)]
            ascii_string = ''.join((chr(int(i, 16)) for i in hex_list))
            self.size = int(ascii_string, 16)

            # Check if the size of the packet is correct,
            # by comparing packet's real size to self.size.
            real_size = (self.bitstream.len / 8) - 6  # 6 bytes
            if real_size < self.size:
                raise PacketIncomplete(
                    "Packet is undersize: {} / {}"
                    .format(real_size, self.size)
                )
            elif real_size > self.size:
                raise PacketCorrupted(
                    "Packet is oversize: {} / {}"
                    .format(real_size, self.size)
                )

            # Check if Bin Length equals Hex Length.
            # Note we read num as little-endian unsigned int.
            self.bitstream.bytepos = 5
            bin_ln = self.bitstream.read("uintle:16")
            if bin_ln != self.size:
                raise PacketCorrupted(
                    "Binary and hex size mismatch: bin: {}, hex: {}"
                    .format(bin_ln, self.size)
                )

            # Parse Packet Source Identification Node.
            self.bitstream.bytepos = 7
            source_id = self.bitstream.read("uint:8")

            # Check Packet Destination Identification Node is 255.
            self.bitstream.bytepos = 8
            dest_id = self.bitstream.read("uint:8")
            if dest_id != 255:
                raise PacketCorrupted(
                    "Invalid Packet Destination Identification Node: {}"
                    .format(dest_id)
                )

            # Parse message ID and verify it's between 0-72.
            self.bitstream.bytepos = 10
            self.id = self.bitstream.read("uint:8")
            self.name = Message.to_string(self.id)
            if not 0 <= self.id <= 72:
                raise PacketCorrupted("Invalid message ID: {}".format(self.id))

            # Check for size following byte 10, excluding LF.
            self.bitstream.bytepos = 9
            byte_count = self.bitstream.read("uint:8")
            if self.id == Message.HEAD_DATA and byte_count == 0:
                # HEAD_DATA single-packet replies are different; always 0.
                # Could be used to confirm whether it's in single-packet mode.
                pass
            else:
                # For all other replies, verify size.
                # Byte count differs from self.size by 5 bytes.
                if byte_count != self.size - 5:
                    raise PacketCorrupted(
                        "Bytes left mismatch: recv: {}, exp: {}, id: {}"
                        .format(byte_count, self.size - 5, self.id)
                    )

            # Parse message sequence bitset.
            self.bitstream.bytepos = 11
            self.is_last = self.bitstream.read("bool")
            self.sequence = self.bitstream.read("uint:7")

            # Read bitset to determine number of packets.
            # Necessary for Multi-packet mode.
            pass

            # Verify TX Node number. Should be equal to Packet Source
            # Identification Node number.
            self.bitstream.bytepos = 12
            tx_node = self.bitstream.read("uint:8")
            if tx_node != source_id:
                raise PacketCorrupted(
                    "Node number mismatch: TX: {}, Source ID: {}"
                    .format(tx_node, source_id)
                )

            # Parse message payload (byte 14 to end, excluding LF).
            self.bitstream.bytepos = 13
            size_payload = (self.size - 8) * 8
            self.payload = self.bitstream.read(size_payload)
        except (ValueError, ReadError) as e:
            raise PacketCorrupted("Unexpected error", e)
예제 #56
0
class Main:
    conf = Config()

    def __init__(self, group_id):
        self.group_id = group_id
        self.users = set ([])
        self.user_photos = {}
        self.survey_data_filename = "c:/users/aaron/desktop/survey_data.txt"
        self.meetup_client = meetup.Meetup(conf.api_key)
        self.message_client = Message()

    def get_weekly_opt_ins(self):
        arg_dict = {}
        arg_dict["group_id"] = self.group_id

        events = self.meetup_client.get_events(**arg_dict).results
        opt_ins = {}
        for x in events:
            if not "Pair Data Science" in x.name:
                print "Skipped",x.name
                continue
            else:
                print "Calculating Pairs -", x.name
            rsvps = x.get_rsvps(self.meetup_client)
            try:
                for rsvp in rsvps.results:
                    opt_ins[rsvp.member["member_id"]] = rsvp.member["name"]
                    try:
                        self.user_photos[rsvp.member["member_id"]] = rsvp.member_photo["highres_link"]
                    except:
                        self.user_photos[rsvp.member["member_id"]] = None
            except:
                print "didn't get 'em"

        print "Missing Surveys", set(opt_ins.keys()).difference(set([str(u.user_id) for u in self.users]))
        return opt_ins

    def get_users(self):
        ## Read in the survey data or simulate new data
        if os.path.isfile(self.survey_data_filename):
            parser = Parser(self.survey_data_filename)
            all_users = parser.get_users()

            ## Remember all previous matches
            ## TODO: Update analyze function to exclude previous pairs (Don't want the same person each week)
            ## TODO: Persist to a database instead of a file
            previous_pairs = set([])
            previous_pairs_filename = "c:/users/aaron/desktop/previous_pairs.txt"
            if os.path.isfile(previous_pairs_filename):
                with open (previous_pairs_filename) as prev:
                    for line in prev:
                        usera, userb = line.strip().split(",")
                        previous_pairs.add((usera,userb))
                        previous_pairs.add((userb,usera))

            ## Grabs the list of people interested in being matched this week
            ## From the Meetup event API
            opt_ins = self.get_weekly_opt_ins()

            ## Filter to just opted-in users
            self.users = set([i for i in all_users if int(i.user_id) in opt_ins])

        else:
            print "Simulating data"
            ## Simulate some number of survey responses
            sim = Simulator()
            sim.simulate(200) ## By adding a seed parameter, you can have reproducible sims
            self.users = sim.get_users()

    #    ## Print some summaries
    #    for user in users:
    #        user.to_string()

        # Print some descriptive stats
        print "# Users", len(self.users), [u.name for u in self.users]


    def analyze_pairs(self):
        # Analyze pairs
        ## This is a very basic algorithm that only makes use of geography
        ## TODO: Update algorithm to incorporate more than geography
        analyze = Analyze(self.users)
        analyze.analyze_easy_potentials()
        match_results = analyze.get_best_matches()
        potential_pairs = analyze.get_potential_pairs()

        return match_results

    #    for user in users:
    #        if user.user_id not in potential_pairs:
    #            print "No Matches for:", user.name
    #        print user.user_id,user.name

    def send_missing_survey_messages(self,debug=True):
        msg_no_name = Text(self.group_id).take_survey

        opt_ins = self.get_weekly_opt_ins()
        user_ids = [u.user_id for u in self.users]

        for opt_in in opt_ins:
            if str(opt_in) not in user_ids:
                msg = msg_no_name % (opt_ins[opt_in])
                if debug:
                    print msg
                else:
                    print message_client.send(msg,str(opt_in))

    def send_pair_assignment_messages(self,finish_date,pairs,debug=True):
        msg_no_names = Text(self.group_id).assign_pair
        for pair in pairs:
            msg = msg_no_names % (finish_date,pair[0].name,pair[1].name)
            if debug:
                print msg
            else:
                self.message_client.send2(msg,[str(p.user_id) for p in pair])