Exemplo n.º 1
0
 def test_addDocument(self):
     message1 = Message(3, 'sdf',
                        'A project to cluster high-dimensional streams.',
                        test_time)
     message1.vector = Vector({3: 4})
     stream1 = Stream(3, message1)
     message2 = Message(4, 'sdf',
                        'A project to cluster high-dimensional streams.',
                        test_time)
     message2.vector = Vector({2: 4})
     stream2 = Stream(4, message2)
     self.assertNotEqual(test_time, self.cluster1.lastStreamAddedTime)
     self.cluster1.addDocument(stream1)
     self.assertEqual(test_time, self.cluster1.lastStreamAddedTime)
     # Test if cluster id is set.
     self.assertEqual(self.cluster1.clusterId, stream1.clusterId)
     # Test that cluster mean is updated.
     self.assertEqual({1: 2 / 2., 2: 2., 3: 2.}, self.cluster1)
     # Test that cluster aggrefate is updated.
     self.assertEqual({1: 2, 2: 4, 3: 4}, self.cluster1.aggregateVector)
     # Test that document is added to cluster documents.
     self.assertEqual(stream1,
                      self.cluster1.documentsInCluster[stream1.docId])
     self.cluster1.addDocument(stream2)
     self.assertEqual(3, self.cluster1.vectorWeights)
     self.assertEqual({1: 2 / 3., 2: 8 / 3., 3: 4 / 3.}, self.cluster1)
     self.assertEqual({1: 2, 2: 8, 3: 4}, self.cluster1.aggregateVector)
Exemplo n.º 2
0
 def setUp(self):
     self.m1 = Message(1, 'sdf',
                       'A project to cluster high-dimensional streams.',
                       test_time - timedelta(seconds=60))
     self.m1.vector = Vector({1: 1., 2: 3.})
     self.stream = Stream(1, self.m1)
     self.m2 = Message(1, 'sdf',
                       'A project to cluster high-dimensional streams.',
                       test_time)
     self.m2.vector = Vector({2: 3.})
Exemplo n.º 3
0
def congrats(surface):
    global RETRY_COUNTER
    draw_tint(GREEN, surface)
    c1 = Message(surface, (480, 220), 'You Completed ', font=pg.font.SysFont('comicsansms', 60, True),
                 bg_color=BROWN)
    c2 = Message(surface, (480, 300), 'All the Waves! ', font=pg.font.SysFont('comicsansms', 60, True),
                 bg_color=BROWN)
    c1.blit()
    c2.blit()
    RETRY_COUNTER += DT
    if RETRY_COUNTER >= 2:
        user.try_again = Message(surface, (560, 420), 'Play Again?', font=pg.font.SysFont('comicsansms', 58, True),
                                 bg_color=GREEN)
        user.try_again.blit()
Exemplo n.º 4
0
def gg(surface):
    global RETRY_COUNTER
    draw_tint(RED, surface)
    gg1 = Message(surface, (480, 223), ' You Lost All      ', font=pg.font.SysFont('comicsansms', 56, True),
                  bg_color=BROWN)
    gg2 = Message(surface, (480, 300), '      Your Lives...', font=pg.font.SysFont('comicsansms', 56, True),
                  bg_color=BROWN)
    gg1.blit()
    gg2.blit()
    RETRY_COUNTER += DT
    if RETRY_COUNTER >= 2:
        user.try_again = Message(surface, (565, 420), 'Try Again?', font=pg.font.SysFont('comicsansms', 58, True),
                                 bg_color=GREEN)
        user.try_again.blit()
Exemplo n.º 5
0
def cmd_help(args):
    if len(args) == 0:
        msg =\
"""
For additional help, run `!help <command name>` e.g. `!help !roll`

Available commands:
"""
        for cmd in commands.list:
            msg += "`{cmd}`: {desc}\n".format(cmd=cmd.name, desc=cmd.desc)
    else:
        msg = ""
        for name in args:
            if name in commands.map.keys():
                cmd = commands.map[name]
                if type(cmd.help) is str:
                    msg += cmd.help
                elif cmd.help is None:
                    msg += "Usage: `{cmd}`\n{desc}".format(cmd=cmd.name,
                                                           desc=cmd.desc)
                else:
                    msg += cmd.help(args[1:]).content
            else:
                msg += "`{name}` is not a valid command".format(name=name)
            msg += '\n'
    return Message(content=msg)
Exemplo n.º 6
0
 def setUp(self):
     self.message = Message(
         1, 'sdf', 'A project to cluster high-dimensional streams.',
         datetime.now())
     self.message.vector = Vector({1: 2., 2: 3.})
     self.s1 = Stream(1, self.message)
     self.v1 = Vector({1: 2., 3: 3.})
Exemplo n.º 7
0
def show_start_wave(user_info, surface):
    global WAVE_TIME, START_WAVE, CREATE_WAVE
    start_wave = Message(surface, (0, 10), ('Start Wave ' + str(user_info.wave + 1) + '/' + str(user_info.waves)),
                         font=pg.font.SysFont('comicsansms', 24, True), bg_color=BROWN)
    start_wave.rect.right = 48*TILE_SIZE - 10
    start_wave.blit()
    user_info.start_wave = start_wave
Exemplo n.º 8
0
    def send(self, user_id, message: Message):
        if isinstance(message, str):
            message = Message(content=message)

        assert (isinstance(message, Message))

        payload = {
            "recipient": {
                "id": user_id
            },
            "message": dict(),
            "notification_type": message.notification_type.value,
            "messaging_type": message.message_type.value
        }

        if message.content:
            payload["message"]["text"] = message.content

        if message.quick_replies:
            payload["message"]["quick_replies"] = [
                x.to_dict() for x in message.quick_replies
            ]

        if message.metadata:
            payload["message"]["metadata"] = message.metadata

        if message.tag:
            payload["tag"] = message.tag

        self.send_raw(payload)
def createMockData():
    connection = sqlite3.connect(DATABASE_URI)
    c = connection.cursor()
    c.execute("DELETE FROM users")
    c.execute("DELETE FROM messages")
    connection.commit()
    connection.close()
    user = User("*****@*****.**", hash("abcde"),"John","Smith","Decidedly male","Kansas City","Murica")
    user2 = User("*****@*****.**", hash("abcdef"),"John","Wick","Surely male","Missouri","Murica")

    message = Message(user.email, user.email, "Hello World!")
    message2 = Message(user.email, user2.email, "Hej World!")

    addUser(user)
    addUser(user2)
    addMessage(message)
    addMessage(message2)
Exemplo n.º 10
0
    def handler_custom_email(self, req: MessagingEntry):
        req.sender.send(
            Message(content="Thanks for signing up! You just got $250!"))

        self.balances[req.sender.id] = 250.0
        self.emails[req.sender.id] = req.message
        req.sender.set_state("Home")
        req.continue_processing = True
Exemplo n.º 11
0
 def send_signup(self, user):
     user.send(
         Message(content="Welcome to PayBot! What's your email?",
                 quick_replies=[
                     QuickReply("",
                                action=ExecuteFunction(self.save_email),
                                content_type=ContentType.email)
                 ]))
     user.set_state("WaitingEmail")
Exemplo n.º 12
0
def help_stats(args):
    msg =\
"""
Usage: `!stats <subcommand>`

Subcommands:
"""
    msg += commands_stats.help_commands(args)
    return Message(msg)
Exemplo n.º 13
0
 def send_home_options(self, user: User):
     user.send(
         Message(content="What do you want to do?",
                 quick_replies=[
                     QuickReply("Pay", ExecuteFunction(self.prompt_pay)),
                     QuickReply("Get balance",
                                ExecuteFunction(self.send_balance)),
                     QuickReply("Something else", SetState("Advanced"))
                 ]))
Exemplo n.º 14
0
 def test_maxClusterSize(self):
     self.assertEqual(1, self.crowd.maxClusterSize)
     message2 = Message(4, 'sdf',
                        'A project to cluster high-dimensional streams.',
                        test_time)
     message2.vector = Vector({2: 4})
     stream2 = Stream(4, message2)
     self.cluster.addDocument(stream2)
     self.assertEqual(2, self.crowd.maxClusterSize)
Exemplo n.º 15
0
def test_parse_message():
    # (message "{channel}" "{text}")
    got = lisp.parse('(message "#chan" "toxt")')
    want = Message("#chan", "toxt")
    assert got == want, f"{got} == {want}"

    assert_throw(lambda: lisp.parse('(message "chan", "toxt")'))
    assert_throw(lambda: lisp.parse('(message "#oreqizer")'))
    assert_throw(lambda: lisp.parse('(message "#oreqizer" "oreqizer" asd)'))
    print("test_parse_message OK")
Exemplo n.º 16
0
 def setUp(self):
     self.m1 = Message(1, 'sdf',
                       'A project to cluster high-dimensional streams.',
                       test_time - timedelta(seconds=60))
     self.m1.vector = Vector({1: 2, 2: 4})
     self.stream1 = Stream(1, self.m1)
     self.m2 = Message(2, 'sdf',
                       'A project to cluster high-dimensional streams.',
                       test_time)
     self.m2.vector = Vector({2: 4})
     self.stream2 = Stream(2, self.m2)
     self.m3 = Message(3, 'sdf',
                       'A project to cluster high-dimensional streams.',
                       test_time + timedelta(seconds=60))
     self.m3.vector = Vector({2: 4})
     self.stream3 = Stream(3, self.m3)
     self.cluster1 = StreamCluster(self.stream1)
     self.cluster2 = StreamCluster(self.stream2)
     self.cluster3 = StreamCluster(self.stream3)
Exemplo n.º 17
0
    def execute(self, args):
        if len(args) == 0:
            return Message(
                content="Please provide a subcommand\nSubcommands:\n{}".format(
                    self.help_commands(args)))

        subcommand = args[0]
        try:
            if len(args) > 1 and args[1] == 'help':
                help_data = self.map[subcommand].help
                if type(help_data) is str: return Message(help_data)
                elif help_data is None:
                    return Message("Usage: `{name}`".format(name=subcommand))
                else:
                    return self.map[subcommand].help(args[1:])
            else:
                return self.map[subcommand].func(args[1:])
        except KeyError:
            return Message(
                content="{name} is not a valid subcommand".format(subcommand))
Exemplo n.º 18
0
 def convertTweetJSONToMessage(tweet, **twitter_stream_settings):
     tweetTime = getDateTimeObjectFromTweetTimestamp(tweet['created_at'])
     message = Message(tweet['user']['screen_name'], tweet['id'],
                       tweet['text'], tweetTime)
     message.vector = Vector()
     for phrase in getPhrases(getWordsFromRawEnglishMessage(tweet['text']),
                              twitter_stream_settings['min_phrase_length'],
                              twitter_stream_settings['max_phrase_length']):
         if phrase not in message.vector: message.vector[phrase] = 0
         message.vector[phrase] += 1
     return message
Exemplo n.º 19
0
def cmd_about(args):
    msg = \
"""
**Great Names Bot** v{ver}

This bot assists in performing die rolls and success calculation in the
Great Names system by Adam Franti.

Bot maintainer: Brandon Nguyen
""".format(ver=VERSION_STRING)
    return Message(msg)
Exemplo n.º 20
0
 def handler_advanced(self, req: MessagingEntry):
     req.sender.send(
         Message(content="Your options are:",
                 quick_replies=[
                     QuickReply("Delete my account",
                                action=ExecuteFunction(
                                    self.delete_account)),
                     QuickReply("Send my location",
                                payload="",
                                content_type=ContentType.location),
                     QuickReply("Go back", SetState("Home"))
                 ]))
Exemplo n.º 21
0
 def getClusterFromMapFormat(clusterMap):
     dummyMessage = Message(1, '', '', datetime.now())
     dummyMessage.vector = Vector({})
     dummyStream = Stream(1, dummyMessage)
     cluster = StreamCluster(dummyStream)
     cluster.clusterId = clusterMap['clusterId']
     cluster.lastStreamAddedTime = getDateTimeObjectFromTweetTimestamp(
         clusterMap['lastStreamAddedTime'])
     cluster.mergedClustersList = clusterMap['mergedClustersList']
     cluster.documentsInCluster = clusterMap['streams']
     for k, v in clusterMap['dimensions'].iteritems():
         cluster[k] = v
     return cluster
Exemplo n.º 22
0
def cmd_stats_sim_success_histogram(args):
    if len(args) < 2:
        return Message("Expected at least 2 arguments, found {}".format(
            len(args)))

    msg_parse = ""
    try:
        sample_size = int(args[0])
    except ValueError:
        msg_parse += "`{}` is not a valid integer for sample size".format(
            args[0])

    if sample_size > MAXIMUM_SAMPLE_SIZE:
        return Message(
            "`{num}` exceeds the number of maximum sample size (`{max}`)".
            format(num=sample_size, max=MAXIMUM_SAMPLE_SIZE))
    attr = 0
    try:
        attr = int(args[1])
    except ValueError:
        msg_parse += "`{}` is not a valid integer for sample size".format(
            args[1])

    n = attr
    if len(args) > 2:
        try:
            if args[2][0] == '+': n = attr + int(args[2][1:])
            else: n = int(args[2])
        except ValueError:
            msg_parse += "`{}` is not a valid integer for sample size".format(
                args[1])

    if n <= 0:
        return Message("Number of dice to be rolled must be greater than 0")

    if len(msg_parse) > 0: return Message(msg_parse)

    path = stats.success_histogram(sample_size, attr, n)
    return Message("Simulation results", file_path=path)
Exemplo n.º 23
0
def show_user_info(surface, user_info):
    global RED_COINS, RED_COINS_TIME
    # Create Message instances to display user info
    wave = Message(surface, (5, 5), ('WAVE ' + str(user_info.wave) + '/' + str(user_info.waves)),
                   font=pg.font.SysFont('comicsansms', 24, True), bg_color=LIGHT_BLUE)
    lives = Message(surface, (5, 35), ('Lives: ' + str(user_info.lives)), bg_color=LIGHT_BLUE)
    if RED_COINS:
        RED_COINS_TIME += DT
        if RED_COINS_TIME <= 1:
            color = RED
        else:
            color = LIGHT_BLUE
            RED_COINS = False
            RED_COINS_TIME = 0
    else:
        color = LIGHT_BLUE

    coins = Message(surface, (5, 60), ('Coins: ' + str(user_info.coins)), bg_color=color)
    # Blit the info
    wave.blit()
    lives.blit()
    coins.blit()
Exemplo n.º 24
0
def getMessage():
    error = False
    id = request.json['id']
    new = Message()
    try:
        new.get(id)
    except (Exception) as err:
        error = True
        return handleError(err)
    finally:
        if not (error):
            result = new.json()
            return jsonify({'result': 'success', 'data': result})
Exemplo n.º 25
0
def send_message():

    data = request.args

    if not (('sender' in data) and ('receiver' in data) and ('text' in data)):
        return 'Message not correct. Try again.'

    now = datetime.now()
    dt_string = now.strftime("%d-%m-%Y %H:%M:%S")

    message = Message(data['sender'], data['receiver'], data['text'],
                      dt_string)
    response = db_i.send_message(message)

    return jsonify(response)
Exemplo n.º 26
0
def addMessage():
    error = False
    msg = request.json['msg']
    id_user = request.json['id_user']
    id_chat = request.json['id_chat']
    read = request.json['read']
    new = Message(msg, None, id_user, id_chat, read)
    try:
        new.add()
    except (Exception) as err:
        error = True
        return handleError(err)
    finally:
        if not (error):
            return jsonify({'result': 'success'})
Exemplo n.º 27
0
def parse(command):
    tokens = command.split()
    cmd = tokens[0]
    args = tokens[1:]

    # run the command
    try:
        func = commands.map[cmd].func
        log('Running command \'{cmd}\' with args {args}'.format(cmd=cmd,
                                                                args=args))
        return func(args)
    except KeyError:
        # nothing to do if command not found
        pass
    except Exception as e:
        log('Ran into exception!')
        log(str(e))
        return Message("I ran into an error on my end, sorry :cry:")

    return None
Exemplo n.º 28
0
def parse_message(root):
    # (message "{channel}" "{text}")
    if len(root) != 3:
        raise Exception(
            f"invalid number of argumetns. want 3, got {len(root)}")

    channel = root[1]
    if type(channel) is not String:
        raise Exception(
            f"invalid argument #1. want {String}, got {type(channel)}")

    channel_value = repr(channel)
    if not is_channel(channel_value):
        raise Exception(
            f"invalid channel format. want #<alphanum>, got {channel_value}")

    text = root[2]
    if type(text) is not String:
        raise Exception(
            f"invalid argument #2. want {String}, got {type(text)}")

    return Message(channel_value, text.value)
Exemplo n.º 29
0
def new_message(data):
    u_name = data["nickname"]
    u_channel = int(data["channel"])
    u_name = u_name.encode("raw_unicode_escape").decode("utf-8")
    user = User(u_name, u_channel)
    print(u_name, u_channel)
    if user in users:
        join_room(u_channel)
        text = data["message"]
        text = text.encode("raw_unicode_escape").decode("utf-8")
        msg = Message(user, text)
        channels[u_channel].add_message(msg)
        print("收到消息:", text, "from", u_name)
        emit("write_message", {
            "nickname": u_name,
            "message": text
        },
             room=u_channel)

        nickname_array = json.dumps(channels[session["channel"]].users)
        emit("current_client_list", {"users": nickname_array},
             room=session["channel"])
    else:
        print('未登录!')
Exemplo n.º 30
0
def cmd_red(args):
    black = np.random.randint(1, high=11)
    red = np.random.randint(1, high=11)
    msg = "Black: {black}\nRed: {red}".format(black=black, red=red)
    return Message(msg)