예제 #1
0
def performSimulation(i, first_vehicle, verbose=True):
    """
	Performs a single simulation with id 'i' starting the message spreading
	from the vehicle with index 'first_vehicle' in cars list
	"""
    # Load vehicle data
    cars = init_cars()

    # Init simulator with the vehicle connectivity graph
    s = Simulator(cars)

    # Get one random car and start the dissemination from it
    if s.no_graphics:
        cars[first_vehicle].on_receive(Msg.dummy())
    else:
        bubbles = displayCars(s.car_dict)
        firstinfected = s.getCar(firstInfection())
        firstinfected.infect(Msg.dummy())

    # Run simulation
    s.runSimulation()

    # If verbose print the result of this simulation
    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
예제 #2
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")
예제 #3
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
예제 #4
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
 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,"错误","没有此用户!"))
예제 #9
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
예제 #10
0
파일: hub.py 프로젝트: TLoebner/apbteam
 def accept (self):
     """Accept a new connection and create a client."""
     # Add client.
     a = self.socket.accept ()
     if self.log:
         self.log ('[%d] connect from %s' % (self.date, str (a[1])))
     c = Hub.Client (self, a[0], self.next_client_id)
     self.next_client_id += 1
     assert self.next_client_id < 256
     self.clients[c.id] = c
     if self.min_clients:
         self.min_clients -= 1
     # Send first date.
     date = Msg (mex.DATE)
     date.push ('L', self.date)
     c.send (date)
예제 #11
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()
예제 #12
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
예제 #13
0
파일: gui.py 프로젝트: ulrich3110/mfc
 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()
예제 #14
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 = []
예제 #15
0
파일: manager.py 프로젝트: lodevil/pyrinet
 def on_msg(self, msg):
     msg = Msg.new_msg(msg)
     if msg is not None:
         processor = self.msg_processors.get(msg.cmd, None)
         if processor is not None:
             try:
                 return processor(msg)
             except MgrShutdown:
                 raise
             except Exception, e:
                 logging.error('exception: %r', e)
                 raise
예제 #16
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 ''
예제 #17
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
예제 #18
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 = []
예제 #19
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
예제 #20
0
 def msg_handler(self, msgs):
     for m in msgs:
         if type(m) == type(""):
             variable.Offine = True
             self.logout()
             break
         msg = Msg(m.get("poll_type"), m.get("value"))
         # print("data: ", msg.getData())
         # 消息类型(群消息or个人消息)
         mtype = msg.getPollType()
         # 发送者
         fuin = msg.getFromUin()
         # print("fuin: ", fuin)
         # 群消息发送者
         suin = msg.getSendUin()
         # print("suin: ", suin)
         content = msg.getContent()
         # print("content: ", content)
         content = msg.getMsg()
         # print("content: ", content)
         # 被挤下线
         if mtype == "kick_message":
             reason = msg.getReason()
             data = {"from":variable.Email, "to":variable.Email, "title":"QQ下线", "msg":reason}
             self._http.post(variable.EmailUrl, data)
         # 私聊or临时
         elif mtype in ("message", "sess_message"):
             # qq = self.uin_to_qq(msg.getFromUin())
             # print("qq: ", qq)
             # item = (函数,发送者,None,None,消息)
             if not variable.State:
                 return    # 机器人被管理员关闭
             item = (self._task.delwith, fuin, None, None, content)
             self._event.add(item)
         # 群聊
         elif mtype == "group_message":
             if not variable.State:
                 return    # 机器人被管理员关闭
             # 群号码
             iseq = msg.getInfoSeq()
             # print("iseq: ", iseq)
             # suin = msg.getSendUin()
             # print("suin: ", suin)
             # item = (函数,发送群,发送者,群号码,消息)
             print(content)
             item = (self._task.delwith, fuin, suin, iseq, content)
             self._event.add(item)
예제 #21
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
예제 #22
0
파일: hub.py 프로젝트: TLoebner/apbteam
 def select (self):
     """Wait until the next event (connection or message) occurs and handle
     it."""
     if not self.min_clients:
         # Check idle and wanted dates.
         idle = True
         min_wait_date = None
         for c in self.clients.itervalues ():
             if not c.idle:
                 idle = False
                 break
             if c.wait_date != None and (c.wait_date < min_wait_date or
                     min_wait_date == None):
                 min_wait_date = c.wait_date
         # Abort if everyone waits forever.
         if idle and min_wait_date == None:
             self.date = None
             return
         # Send new date.
         if idle:
             self.date = min_wait_date
             if self.log:
                 self.log ('[%d] date' % self.date)
             date = Msg (mex.DATE)
             date.push ('L', self.date)
             for c in self.clients.itervalues ():
                 c.send (date)
     # Prepare fdset and select.
     infds = [ self.socket ]
     if not self.min_clients:
         infds += self.clients.values ()
     readyfds = select.select (infds, (), ()) [0]
     for i in readyfds:
         if i is self.socket:
             self.accept ()
         else:
             i.read ()
예제 #23
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)
예제 #24
0
 def receive_msg(self):
     while True:
         try:
             byte_arr = self.sock.recv(1024)
         except Exception as e:
             print("Receive Error.")
         finally:
             # unpack the bytes
             msg = Msg.decode(byte_arr)
             # handle the msg
             if msg.mode == Msg.HELLO:
                 pass
             elif msg.mode == Msg.TALK:
                 # print the msg
                 # print("[%s:%s] > %s" % (msg.ip, msg.port, msg.data))
                 # return the str(msg)
                 return ("[%s:%s] > %s" % (msg.ip, msg.port, msg.data))
             elif msg.mode == Msg.FINISH:
                 pass
예제 #25
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
예제 #26
0
 def udt_send(self, newsocket: socket.socket, msg: Msg, rate=0.95):
     randnum = random.randint(0, 100)
     if randnum < rate * 100:
         newsocket.send(Msg.encode(msg))
예제 #27
0
 def make_pkt(self, data, checksum=None, seq=None):
     m = Msg(data, checksum, seq)
     return m
예제 #28
0
 def rdt_rcv(self, newsocket: socket.socket, rcvpkt: list):
     msg = newsocket.recv(65510)
     ## not allow me to use Msg here
     newmsg = Msg.decode(msg)
     rcvpkt.append(newmsg)
예제 #29
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()
예제 #30
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')
}
예제 #31
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))
예제 #32
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))
예제 #33
0
파일: hub.py 프로젝트: TLoebner/apbteam
 def read (self):
     """Read and dispatch a message from this client."""
     # Read message.
     head = self.socket.recv (calcsize (mex.HEADER_FMT))
     if head == '':
         self.socket.close ()
         del self.hub.clients[self.id]
         return
     size, seq = unpack (mex.HEADER_FMT, head)
     data = self.socket.recv (size)
     m = Msg (data)
     if self.hub.log:
         self.hub.log ('[%d] received from %d(%d): %s' %
                 (self.hub.date, self.id, seq, str (m)))
     # Dispatch.
     if m.mtype == mex.IDLE:
         if seq == self.seq:
             self.idle = True
             if len (m):
                 self.wait_date, = m.pop ('L')
                 assert self.wait_date >= self.hub.date
             else:
                 self.wait_date = None
     elif m.mtype == mex.DATE:
         date = Msg (mex.DATE)
         date.push ('L', self.hub.date)
         self.send (date)
     elif m.mtype == mex.REQ:
         m.pop ('B')
         mr = Msg (mex.REQ)
         mr.push ('B', self.id)
         mr.push (m.pop ())
         self.hub.broadcast (mr, self)
     elif m.mtype == mex.RSP:
         to, = m.pop ('B')
         mr = Msg (mex.RSP)
         mr.push ('B', 0)
         mr.push (m.pop ())
         self.hub.clients[to].send (mr)
     elif m.mtype == mex.RES:
         mtype_str = m.pop ()
         mr = Msg (mex.RES)
         mr.push ('B', self.hub.reserve (mtype_str))
         self.send (mr)
     else:
         self.hub.broadcast (m, self)
예제 #34
0
파일: maze.py 프로젝트: change-L/pycode
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,
                )
예제 #35
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)
예제 #36
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)