def registerSlot(self,acountInfo):
     self.cursor.execute("select * from acount where username='******'" % acountInfo.split(' ')[0])
     result = self.cursor.fetchone()
     #判定注册的用户账号是否已经存在
     if result:
         self.msgSignal.emit(Msg(RegisterGui,"警告","该用户已存在!"))
     else:
         #往表中插入相关用户数据
         self.cursor.execute("insert into acount values('%s','%s')" % (acountInfo.split(' ')[0],acountInfo.split(' ')[1]))
         self.connection.commit() #提交数据库更改
         self.msgSignal.emit(Msg(RegisterGui,"成功","注册成功!"))
 def enterSlot(self,stuInfo):
     stuInfoList = stuInfo.split(' ')
     #首先查询一波,看看这个学生的信息是否已经被导入
     self.cursor.execute("select * from stuinfo where name='%s' and age='%s' and num='%s' and profession='%s'" % (stuInfoList[0],stuInfoList[1],stuInfoList[2],stuInfoList[3]))
     result = list(self.cursor.fetchall())
     if len(result) > 0:
         self.msgSignal.emit(Msg(EnterGui,"错误","该学生信息已经导入!"))
     else:
         #否则就导入
         self.cursor.execute("insert into stuinfo values('%s','%s','%s','%s')" % (stuInfoList[0],stuInfoList[1],stuInfoList[2],stuInfoList[3]))
         self.connection.commit() #提交数据库更改
         self.msgSignal.emit(Msg(EnterGui,"成功","导入学生信息成功!"))
 def delSlot(self,stuInfo):
     stuInfoList = stuInfo.split(' ')
     #查询是否有这个学生的信息
     self.cursor.execute("select * from stuinfo where name='%s' and age='%s' and num='%s' and profession='%s'" % (stuInfoList[0],stuInfoList[1],stuInfoList[2],stuInfoList[3]))
     result = list(self.cursor.fetchall())
     #如果有的话则删除
     if len(result) > 0:
         self.cursor.execute("delete from stuinfo where name='%s' and age='%s' and num='%s' and profession='%s'" % (stuInfoList[0],stuInfoList[1],stuInfoList[2],stuInfoList[3]))
         self.connection.commit()
         self.msgSignal.emit(Msg(DelGui,"成功","删除学生信息成功!"))
     else:
         self.msgSignal.emit(Msg(DelGui,"错误","没有该学生信息!"))
 def loginSlot(self,acountInfo):
     self.cursor.execute("select * from acount where username='******'" % acountInfo.split(' ')[0])
     result = self.cursor.fetchone()
     #如果能够查询到这个用户的话
     if result:
         #如果密码对的话,则登陆
         if result["password"] == acountInfo.split(' ')[1]:
             self.loginSignal.emit()
         else:
             self.msgSignal.emit(Msg(LoginGui,"错误","密码错误!"))
     #否则则说明没有这个用户
     else:
         self.msgSignal.emit(Msg(LoginGui,"错误","没有此用户!"))
Пример #5
0
    def start_server(self):
        while True:
            try:
                sock, addr = self.sock.accept()
            except Exception as e:
                # some one want to connect, but fail
                print("some one want to connect, but fail")
            finally:
                # some one success connect
                print("[%s:%s] connect successfully." % (addr[0], addr[1]))
                # save in the conns
                conns.append(User(
                    sock=sock,
                    ip=addr[0],
                    port=addr[1],
                ))
                print("now has %s client." % (len(conns)))
                # tell to others and me
                msg = Msg(data="Hello, [%s:%s] login." % (addr[0], addr[1]),
                          mode=Msg.TALK,
                          ip=addr[0],
                          port=addr[1])

                for user in conns:
                    self.send_msg(user, msg)
                server_thread = threading.Thread(target=self.handle_sock,
                                                 args=(sock, addr))
                server_thread.start()
Пример #6
0
    def processOrder(self, msg):
        '''
        处理指令
        '''
        replyMsg = Msg()

        humidifier = Humidifier.Humidifier()
        content = msg.content
        replyMsg.content = content

        if ('温度' in content):
            replyMsg.content = Data().getT()

        if ('湿度' in content):
            replyMsg.content = Data().getH()

        if ('开' in content):
            humidifier.open()
            replyMsg.content = '加湿器已打开'

        if ('关' in content):
            humidifier.close()
            replyMsg.content = '加湿器已关闭'

        replyMsg.fromUserName = msg.toUserName
        replyMsg.toUserName = msg.fromUserName

        return replyMsg
Пример #7
0
    def Notify(self, app_name, notification_id, app_icon, summary, body,
               actions, hints, expire_timeout):
        msg = Msg()
        # find id.
        self._id += 1
        msg.application = str(app_name)
        msg.notid = notification_id
        msg.mid = self._id
        msg.summary = str(summary)
        msg.body = str(body)
        if int(expire_timeout) > 0:
            msg.deadline = time.time() + int(expire_timeout) / 1000.0
        if 'urgency' in hints:
            msg.urgency = int(hints['urgency'])
        self._rofication.add_notification(msg)

        os.system('awesome-client \'naughty=require("naughty"); ' +
                  'naughty.notify({title="%s",text="%s (%s)"})\'' %
                  (msg.summary, msg.body, msg.application))

        cmd = ''
        cmd += 'local naughty = require("naughty");'
        cmd += 'naughty.notify({'
        cmd + + '  title = "%s (%s)",' % (msg.summary, msg.application)
        cmd += '  text  = "%s",' % (msg.body)
        cmd += '})'

        os.system('awesome-client \'%s\'' % cmd)
        return notification_id
Пример #8
0
 def send_msg(self, text):
     try:
         msg = Msg(
             mode=Msg.TALK,
             data=text,
         )
         self.sock.send(Msg.encode(msg))
     except Exception as e:
         print("send error happens")
Пример #9
0
    def fb_feeds_webhook():
        """webhook api"""
        logging.debug('Handling webhook request!!')
        content = request.get_json()
        if content['entry'][0]['changes'][0]['value']['item'] == 'like':
            Server.MQTTC.publish(
                Config.MQTT_FB_WEBHOOK_TOPIC_NAME, Msg(
                    int(content['entry'][0]['time']),'LIKE',
                    content['entry'][0]['changes'][0]['value']['user_id']))

        logging.info('Handled webhook request ' + str(content))
        return ''
Пример #10
0
 def GBN_rcv(self, new_socket):
     seq = 0
     rcvpkt = []
     while True:
         self.rdt_rcv(new_socket,rcvpkt)
         pkt = rcvpkt[0]
         print(pkt.data)
         if not self.corrupt(pkt) and int(pkt.seqnum) == int(seq):
             self.deliver_data(pkt.data,'data.txt')
             self.udt_send(new_socket, Msg('ACK' + str(seq),True,seq), 1)
             seq = seq + 1
         rcvpkt = []
Пример #11
0
 def start_talking(self):
     while True:
         try:
             text = input("> ")
             msg = Msg(
                 mode=Msg.TALK,
                 data=text,
             )
             self.sock.send(Msg.encode(msg))
         except Exception as e:
             print("some error happens")
         finally:
             pass
Пример #12
0
 def SR_rcv(self, new_socket):
     seq = 0
     rcvpkt_wrapper = []
     rcvpkts = {}
     while True:
         self.rdt_rcv(new_socket,rcvpkt_wrapper)
         pkt = rcvpkt_wrapper[0]
         if not self.corrupt(pkt):
             seq = int(pkt.seqnum)
             if not seq in rcvpkts.keys():
                 rcvpkts[seq] = (pkt.data,False)
             self.sr_deliver_data(rcvpkts,'data.txt')
             self.udt_send(new_socket,Msg('ACK'+str(seq),True,seq),1)
         rcvpkt_wrapper = []
Пример #13
0
    def handle_result(self, wip, result):
        log(DEBUG, "started", wip=wip, result_id=result._id)
        self.wip_q.put(wip)

        result.num_server_fair_share = len(self.fc_server.cid_q_m)
        result.serv_time = time.time() - result.epoch_arrived_server
        result.epoch_departed_server = time.time()
        self.commer.send_msg(result.cid,
                             msg=Msg(_id=result._id, payload=result))

        log(DEBUG,
            "done",
            wip=wip,
            result_id=result._id,
            serv_time=result.serv_time)
Пример #14
0
 def Notify(self, app_name, notification_id, app_icon, summary, body,
            actions, hints, expire_timeout):
     msg = Msg()
     # find id.
     self._id += 1
     msg.application = str(app_name)
     msg.notid = notification_id
     msg.mid = self._id
     msg.summary = str(summary)
     msg.body = str(body)
     if int(expire_timeout) > 0:
         msg.deadline = time.time() + int(expire_timeout) / 1000.0
     if 'urgency' in hints:
         msg.urgency = int(hints['urgency'])
     self._rofication.add_notification(msg)
     return notification_id
Пример #15
0
 def show_dialog(self):
     '''Show the text notification dialogue.'''
     text = self.__msgtext.GetValue()
     if text:
         # Text is set, show dialog.
         title = self.__data.get_sys('msg_title')
         size = self.__data.get_user('msg_size')
         icon = os.path.join(self.__dir, self.__data.get_sys('icon_close'))
         font = self.__data.get_sys('msg_font')
         dlg = Msg(parent=self,
                   title=title,
                   size=size,
                   icon=icon,
                   text=text,
                   font=font)
         dlg.ShowModal()
         # Set dialog size
         size = dlg.GetSize()
         self.__data.set_user('msg_size', (size[0], size[1]))
         # Destroy dialogue.
         dlg.Destroy()
Пример #16
0
 def handle_sock(self, sock, addr):
     # receive the msg and handle it
     while True:
         try:
             byte_arr = sock.recv(1024)
             # decode the socket bytes
             msg = Msg.decode(byte_arr)
             # (1.mode), (2,ip), (3,port), (4,data)
             # update the (2, ip) and (3, port)
             msg.set_ip(addr[0])
             msg.set_port(addr[1])
             # handle the msg
             if msg.mode == Msg.HELLO:
                 pass
             elif msg.mode == Msg.TALK:
                 # send the msg to everyone
                 # for user in conns:
                 #     self.send_msg(user, msg)
                 # just print in the server
                 print("[%s:%s] > %s" % (msg.ip, msg.port, msg.data))
             elif msg.mode == Msg.FINISH:
                 pass
         except Exception as e:
             # client logout
             # del the conns who logout
             for i in range(len(conns)):
                 if conns[i].ip == addr[0] and conns[i].port == addr[1]:
                     del conns[i]
             print('now has %s client.' % (len(conns)))
             # send the link out msg for everyone
             msg = Msg(
                 data='[%s:%s] logout' % (addr[0], addr[1]),
                 mode=Msg.TALK,
                 ip=addr[0],
                 port=addr[1],
             )
             for user in conns:
                 self.send_msg(user, msg)
             return
Пример #17
0
    def parseUserOrder(self, xmlStr):
        '''
        解析用户消息
        '''
        xml = etree.fromstring(xmlStr)

        msg = Msg()

        msg.msgType = xml.find("MsgType").text
        msg.fromUserName = xml.find("FromUserName").text
        msg.toUserName = xml.find("ToUserName").text
        msg.createTime = xml.find("CreateTime").text

        if (msg.msgType == 'text'):
            msg.content = xml.find("Content").text

        if (msg.msgType == 'voice'):
            msg.content = xml.find("Recognition").text

        logger.info(msg.content)

        return msg
Пример #18
0
def performSimulation(i, verbose=True):
    cars = init_cars()

    def print_graph_stats():
        grade = 0
        for car in cars:
            for a in car.adj:
                grade += a
        print('number of cars', len(cars))
        print('number of edges', grade / 2)
        print('density', grade / (2 * len(cars)))

    #print_graph_stats()

    s = Simulator(cars)

    if s.no_graphics:
        random.sample(cars, 1)[0].infect(Msg.dummy())
    else:
        bubbles = displayCars(s.car_dict)
        firstinfected = s.getCar(firstInfection())
        firstinfected.infect(
            Msg(firstinfected.plate, 'ciao',
                (firstinfected.pos[0], firstinfected.pos[1]),
                (firstinfected.pos[0], firstinfected.pos[1]), 0, 100))

    s.runSimulation()

    if verbose:
        tmp = str([c.state for c in cars])
        print("Simulation", i, "ended")
        print("Vulnerable: ", tmp.count("State.VULNERABLE"))
        print("Infected: ", tmp.count("State.INFECTED"))
        print("Recovered: ", tmp.count("State.RECOVERED"))
        print()

    return s
Пример #19
0
 record_flag = False
 screen_flag = False
 test = False
 virtual_background = False
 virtual_background_name = ""
 user_id = 0
 frames = {}
 msgs = []
 img = cv2.imread('no_image.png')
 user_manage = User_manage()
 app.secret_key = 'super secret key'
 udp_send = SendVideo("127.0.0.1", "127.0.0.1", 12345, 9999)
 screen_send = SendVideo("127.0.0.1", "127.0.0.1", 12348, 9997)
 video = Video()
 audio = Audio()
 msg = Msg()
 record = Record()
 video.set_capture(30, 320, 240)
 virtualbackground = VirtualBackground()
 send_camera_th = threading.Thread(target=capture_video)
 send_audio_th = threading.Thread(target=capture_audio)
 get_audio_th = threading.Thread(target=audio.get_audio)
 udp_listen_th = threading.Thread(target=udp_send.get_frame,
                                  args=(frames, ))
 screen_listen_th = threading.Thread(target=screen_send.get_frame,
                                     args=(frames, ))
 screen_listen_th.start()
 send_camera_th.start()
 udp_listen_th.start()
 send_audio_th.start()
 get_audio_th.start()
Пример #20
0
from datetime import datetime
from msg import Msg

users_hash_dict={
    '8614': 'dominik',
    '0261': 'maciek',
    '3164': 'swistak',
    '7770': 'gross',
    '4426': 'bartus',
    '2567': 'sebus',
    '6249': 'karol',
    '2010': 'ryba'
}

messages_dict={
    'pogoda':Msg('messages/pogoda_mess.txt'),
    'hania':Msg('messages/hania_mess.txt'),
    'default':Msg('messages/default_mess.txt'),
    'amelka':Msg('messages/amelka_mess.txt'),
    'papiez':Msg('messages/papiez_mess.txt'),
    'hour':Msg('messages/hour_mess.txt'),
    'ryba':Msg('messages/ryba_mess.txt'),
    'swistak':Msg('messages/swistak_mess.txt'),
    'grosik':Msg('messages/grosik_mess.txt'),
    'dominik':Msg('messages/dominik_mess.txt'),
    'karol':Msg('messages/karol_mess.txt'),
    'gra':Msg('messages/gra_mess.txt'),
    'bartus':Msg('messages/bartus_mess.txt'),
    'sebus':Msg('messages/sebus_mess.txt'),
    'maciek':Msg('messages/maciek_mess.txt')
}
Пример #21
0
    # This is the endless loop of goodness
    while True:
        # Handling autoscaling sns messages for the salt master group
        try:
            master_queue_length = sqs_master.get_queue_length()
            if master_queue_length > 0:
                for i in range(master_queue_length):
                    message = sqs_master.get_a_message() 
                    if not message:
                        continue
                    #print "MASTER: type of message is: %s" % type(message)
                    message_body = message.get_body() # using boto sqs message method here
                    #print "MASTER: message body:"
                    #print message_body
                    msg = Msg(message_body)
                    instance_id = msg.get_instance_id()
                    #print "MASTER: instance_id: %s" % instance_id
                    status = msg.get_instance_action() # LAUNCH or TERMINATE or None
                    #print "MASTER: status: %s" % status
                    if not status or not instance_id:
                        #print "status: %s" % status
                        #print "instance_id: %s" % instance_id
                        continue
                    else:
                        master_mgr = MasterManager(region)
                        master_mgr.create_or_update_master(instanceid=instance_id, modified=None, ipaddr=None, status=unicode(status))
                        minion_mgr = MinionManager(region)
                        minion_mgr.create_or_update_minion(instanceid=instance_id, modified=None, highstate_runner=None,
                                                           highstate_ran=None, status=unicode(status))
                    sqs_master.delete_a_message(message)
Пример #22
0
 def multicast_blockchain(self):
     """Multicast transaction"""
     for port in self.node.peers.keys():
         url_to = host + ':{}/gossip/blockchain/'.format(port)
         msg = jsonpickle.encode(Msg(self.node.blockchain, self.node.port))
         requests.post(url_to, json=json.dumps(msg))
Пример #23
0
def run_game(x, y):
    pygame.init()
    settings = Settings()
    statue = Statue()
    screen = pygame.display.set_mode(
        (settings.screen_width, settings.screen_height))
    map = Map(x, y, settings, screen)
    fog_map = Fog_map(x, y, settings, screen)
    gamer1 = Gamer(settings, x, y, screen)
    gamer2 = Gamer(settings, x, y, screen)
    monster1 = Monster(settings, x, y, screen, map)
    monster2 = Monster(settings, x, y, screen, map)
    gamer1.monsters = [monster1, monster2]
    msg = Msg(screen, '红色:起点  蓝色:终点或正确路径  黄色:玩家', 22, 300, 75)
    msg_title = Msg(screen, '迷宫游戏', 34, 300, 100)
    button_map = Button(screen, 32, '刷新地图', 137.5, 25, 275, 50)
    button_solve = Button(screen, 32, '自动寻路', 412.5, 25, 275, 50)
    button_return = Button(screen, 22, '返回', 575, 25, 50, 50)
    button_normal = Button(screen, 32, '普通模式', 300, 200, 300, 75)
    button_fog = Button(screen, 32, '迷雾模式 ', 300, 300, 300, 75)
    button_pair = Button(screen, 32, '怪兽模式 ', 300, 400, 300, 75)
    button_pair_fog = Button(screen, 32, '迷雾怪兽模式 ', 300, 500, 300, 75)
    button_solve.draw_button()
    while True:
        if statue.game_statue == 0:
            gf.check_event_menu(statue, button_normal, button_fog, button_pair,
                                button_pair_fog)
            gf.show_menu(screen, settings, button_normal, button_fog,
                         button_pair, msg_title, button_pair_fog)
        elif statue.game_statue == 1:
            if map.gen == 0:
                gf.gen_map(map, gamer1)
                gf.update_screen(map, gamer1, screen, settings, button_map,
                                 button_solve, button_return, msg)
            if statue.solve_statue == True:
                gf.check_events(map, gamer1, button_map, button_solve,
                                button_return, statue)
                gf.solve(map, screen, settings, statue, button_return, gamer1)
                gf.update_screen(map, gamer1, screen, settings, button_map,
                                 button_solve, button_return, msg)
            else:
                gf.check_events(map, gamer1, button_map, button_solve,
                                button_return, statue)
                gf.update_screen(map, gamer1, screen, settings, button_map,
                                 button_solve, button_return, msg)
        elif statue.game_statue == 2:
            if fog_map.gen == 0:
                gf.gen_map(fog_map, gamer1)
                gf.update_screen(fog_map, gamer1, screen, settings, button_map,
                                 button_solve, button_return, msg)
            if statue.solve_statue == True:
                gf.check_events(fog_map, gamer1, button_map, button_solve,
                                button_return, statue)
                gf.solve(fog_map, screen, settings, statue, button_return,
                         gamer1)
                gf.update_screen(fog_map, gamer1, screen, settings, button_map,
                                 button_solve, button_return, msg)
            else:
                gf.check_events(fog_map, gamer1, button_map, button_solve,
                                button_return, statue)
                gf.update_screen(fog_map, gamer1, screen, settings, button_map,
                                 button_solve, button_return, msg)
        elif statue.game_statue == 3:
            if map.gen == 0:
                gf.gen_map(map, gamer1)
                gf.update_screen_monster(map, gamer1, screen, settings,
                                         button_map, button_solve,
                                         button_return, msg)
                for monster in gamer1.monsters:
                    monster.init_monster()
            if statue.solve_statue == True:
                gf.check_events(map, gamer1, button_map, button_solve,
                                button_return, statue)
                gf.solve(map, screen, settings, statue, button_return, gamer1)
                gf.update_screen_monster(
                    map,
                    gamer1,
                    screen,
                    settings,
                    button_map,
                    button_solve,
                    button_return,
                    msg,
                )
            else:
                gf.check_events(map, gamer1, button_map, button_solve,
                                button_return, statue)
                gf.update_screen_monster(
                    map,
                    gamer1,
                    screen,
                    settings,
                    button_map,
                    button_solve,
                    button_return,
                    msg,
                )
Пример #24
0
        """
        获取群组禁言列表
        :param tid:
        :param owner:
        :return:
        """
        url = "https://api.netease.im/nimserver/team/listTeamMute.action"
        data = {'tid': tid, 'owner': owner}
        resp = requests.post(url=url, headers=self.get_header(), data=data)
        return resp.json()


if __name__ == '__main__':
    APPKEY = "APPKEY"
    APP_SECRET = "APP_SECRET"
    msg = Msg(APPKEY, APP_SECRET)
    team = Team(APPKEY, APP_SECRET)
    print("-" * 30)
    print('create:')
    response = team.create('test_team', 'test3', json.dumps(['test2',
                                                             'test1']),
                           'please join us ', 0, 1)
    print(response)
    tid = response['tid']

    print("-" * 30)
    print('query:')
    response = team.query(json.dumps([
        tid,
    ]), 1)
    print(response)
Пример #25
0
 def make_pkt(self, data, checksum=None, seq=None):
     m = Msg(data, checksum, seq)
     return m
Пример #26
0
 def multicast_trx(self, trx):
     """Multicast transaction"""
     for port in self.node.peers.keys():
         url_to = host + ':{}/gossip/trx/'.format(port)
         msg = jsonpickle.encode(Msg(trx, self.node.port))
         requests.post(url_to, json=json.dumps(msg))