Example #1
0
    def inviteTender(self):
        mInv = msg.msg(self.ip)
        id = datetime.datetime.now()
        mInv.to_IFB(id)  # tender_ID为当前时间
        self.sendlist.append(mInv)

        time.sleep(1)  # 等待1秒
        tenderlist = []
        for i in range(len(self.recvlist)):
            if (self.recvlist[i].tender_ID
                    == id) and (self.recvlist[i].msg_type == "tender"):
                tenderlist.append(self.recvlist[i])
                self.recvlist.pop(i)  # 从消息接收列表中把对应本次招标的投标消息都拿走

        win = 0  # 挑选一个幸运儿
        n = len(tenderlist)
        if n != 0:
            for i in range(n):
                win = win + tenderlist[i].tender_num
            win = win % n  # 选择一个中标节点
        else:
            return 0
            # 没人投标,gg
        mWin = msg.msg(self.ip)
        mWin.to_tell_win(ip, tenderlist[win].fromIP)
        self.sendlist.append(mWin)  # 发送中标消息;mRecv接收资源消息

        time.sleep(1)  # 等待1秒
        for i in range(len(self.recvlist)):
            if (self.recvlist[i].tender_ID
                    == id) and (self.recvlist[i].msg_type == "src"):
                self.src = self.src + self.recvlist[i].src  # 拿到车位
                self.recvlist.pop(i)
                refresh()
                break
Example #2
0
    def tender(self, mInv):
        if self.src > mInv.least_src:
            id = mInv.tender_ID
            mTndr = msg.msg(self.ip)
            mTndr.to_Tender(mInv.tender_ID, mInv.fromIP)
            self.sendlist.append(mTndr)  # 发送投标消息
            time.sleep(1)  # 等待1秒

            for i in range(len(self.recvlist)):
                if (self.recvlist[i].tender_ID
                        == id) and (self.recvlist[i].msg_type == "win"):
                    srcSend = self.src / 2  # 发送一定数量的资源给招标节点 TODO 确定一个函数
                    if (self.src > srcSend) and (
                            self.src > mInv.least_src):  # 防止同时中标两次,发完一次后自己资源不足
                        mSrc = msg.msg(self.ip)
                        mSrc.to_send_src(srcSend, mInv.fromIP)
                        self.sendlist.append(mSrc)
                        self.src = self.src - srcSend
                    else:
                        mSrc = msg.msg(self.ip)
                        mSrc.to_send_src(0, mInv.fromIP)
                        self.sendlist.append(mSrc)
                        # 不足就发0
                    self.recvlist.pop(i)
                    break
                # 发现自己中标就发送资源,没中就算了
        self.recvlist.remove(mInv)
        refresh()
Example #3
0
 def test_inventory(self, preambleCommands, commandToTest, linesToLookFor):
     for command in preambleCommands:
         self.b.checkForResponse(msg(command))
     if commandToTest:
         self.b.checkForResponse(msg(commandToTest))
     for line in linesToLookFor:
         assert checkFileForResponse("tests/botChatDump", line)
Example #4
0
    def test_tlaAndBandName(self, preambleCommands, triggerToSend, lineToLookFor):

        for command in preambleCommands:
            self.b.checkForResponse(msg(command))
        self.b.checkForResponse(msg(triggerToSend))
        assert checkFileForResponse("tests/botChatDump", lineToLookFor)
        self.b.checkForResponse(msg(lineToLookFor))
        assert checkFileForResponse("tests/botChatDump", "good name for a band")
 def test_variableExpansion(self):
     self.b.checkForResponse(msg("bucket, noun+ noun"))
     self.b.checkForResponse(msg("bucket, nouns+ nouns"))
     self.b.checkForResponse(msg("bucket, verb+ verb"))
     self.b.checkForResponse(msg("bucket, verbs+ verbs"))
     self.b.checkForResponse(msg("bucket, verbed+ verbed"))
     self.b.checkForResponse(msg("bucket, verbing+ verbing"))
     self.b.checkForResponse(msg("bucket, adjective+ adjective"))
     self.b.checkForResponse(msg("bucket, place+ place"))
     self.b.checkForResponse(msg("bucket, add \"test\" \"$noun $nouns $verb $verbs $verbed $verbing $adjective $place\""))
     self.b.checkForResponse(msg("test"))
     assert checkFileForResponse("tests/botChatDump", "noun nouns verb verbs verbed verbing adjective place")
Example #6
0
 def test_forgetThat(self, preambleCommands, triggersToSend, linesToLookFor,
                     linesForgotten):
     for command in preambleCommands:
         self.b.checkForResponse(msg(command))
     for trigger in triggersToSend:
         self.b.checkForResponse(msg(trigger))
     for line in linesToLookFor:
         assert checkFileForResponse("tests/botChatDump", line)
     self.b.checkForResponse(msg("bucket, forget that"))
     os.system('echo "" > tests/botChatDump')
     for trigger in triggersToSend:
         self.b.checkForResponse(msg(trigger))
     for line in linesForgotten:
         assert not checkFileForResponse("tests/botChatDump", line)
     os.system('echo "" > tests/botChatDump')
Example #7
0
 def connectionMade(self):
     print "Connect %s" % self.transport.getPeer()
     m = msg.msg("serverok", (PROTOCOL,))
     self.envoi(m)
     app = self.factory.parent
     if not app.partie_on :
         reactor.callLater(0, app.debut_game, app.options.inter)
Example #8
0
 def fin_tour(self) :
     self.tour_on = False
     self.jo.check_tick()
     self.envoi_all(msg.msg("mot_top",(str(self.coord_mot_top), self.mot_top)))
     self.info("Top retenu : %s-%s (%d pts)" % (self.coord_mot_top, self.mot_top, self.pts_mot_top))
     if self.options.log :
         self.log.fin_tour(self.coord_mot_top, self.mot_top, self.pts_mot_top)
     print "%d/%d : %s - %s" % (len(self.jo.liste_actif()), len(self.jo), self.coord_mot_top, self.mot_top)
     self.gr.pose(self.coord_mot_top, self.mot_top)
     message = self.jo.score_fin_tour(self.pts_mot_top)
     if message != "" :
         self.info(message)
     self.envoi_all(msg.msg("score", self.jo.tableau_score()))
     if self.pa.liste :
         reactor.callLater(self.options.inter, self.debut_tour)
     else :
         reactor.callLater(self.delta_calllater, self.fin_partie)
Example #9
0
 def envoi_mot(self) :
     "Envoie le mot courant au serveur"
     g = self.frame.grille
     debut, mot = g.get_mot_temp()
     if mot is not None :
         m = msg.msg("propo", (str(debut), mot, 0))
         self.envoi(m)
     g.reinit_saisie()
Example #10
0
    def post(self):

        username = self.get_argument("uname")
        password = self.get_argument("pswd")
        message = self.get_argument("msg")
        mobileNo = self.get_argument("mob")

        self.write(dict(Status=msg(username, password, message, mobileNo)))
 def envoi_mot(self):
     "Envoie le mot courant au serveur"
     g = self.frame.grille
     debut, mot = g.get_mot_temp()
     if mot is not None:
         m = msg.msg("propo", (str(debut), mot, 0))
         self.envoi(m)
     g.reinit_saisie()
Example #12
0
 def decr_chrono(self) :
     self.envoi_all(msg.msg("chrono", self.chrono))
     self.chrono -= 1
     if self.chrono >= 0 :
         self.chrono_on = True
     else :
         self.stop_chrono()
         reactor.callLater(self.delta_calllater, self.fin_tour)
Example #13
0
def sendmsg():
    global moved_md
    #create a class of msg
    m = msg(moved_md, phone_num="13991219316")
    print("medicine list:" + ','.join(moved_md))
    print("phone number:" + m.receive_num)
    #set the GSM module
    m.write()
    #write message content in chinese
    m.write_content()
Example #14
0
 def pose(self, e) :
     p = self.props.GetSelection()
     if p < 0 :
         self.app.envoi_mot()
     else :
         coo, mot = self.props.GetClientData(p)
         m = msg.msg("propo",(coo, mot, 0))
         self.app.envoi(m)
         self.grille.reinit_saisie()
         self.home_props()
Example #15
0
 def sysJoin(self):
     mJoin = msg.msg(self.ip)
     mJoin.to_Join()
     self.sendlist.append(mJoin)  # 发送加入系统消息
     time.sleep(1)
     if len(self.IPlist) == 1:
         self.src = 60  # 如果我是第一个节点,就给我所有资源
     else:
         self.inviteTender()  # 初始src分配:招标
     refresh()
Example #16
0
 def pose(self, e) :
     p = self.props.GetSelection()
     if p < 0 : 
         self.app.envoi_mot()
     else :
         coo, mot = self.props.GetClientData(p)
         m = msg.msg("propo",(coo, mot, 0))
         self.app.envoi(m)
         self.grille.reinit_saisie()
         self.home_props()
Example #17
0
def sendWeather(customer_id, send_type=None):
    db = MySQL.Database('users')
    usr = db.usr(customer_id)
    number = usr.phone

    # send the message:
    if send_type == 'mms':
        send_mms(number, MMSimage.img(customer_id))
    else:
        send(number, msg.msg(customer_id))
    print(number)
Example #18
0
 def test_verifyEntryCreation(self, query, feedId, feedURL):
     self.b.checkForResponse(msg("bucket, rss \"{0}\" \"{1}\"".format(
                                 query, feedURL)))
     db = sqlite3.connect('tests/testResponses.db')
     c = db.cursor()
     c.execute('SELECT * FROM rss WHERE rssId = "{0}" AND feed = "{1}"'.format(
               feedId, feedURL))
     assert c.fetchone()
     c.execute('SELECT * FROM responses WHERE query = "{0}" AND rssId = "{1}"'.format(
               query, feedId))
     assert c.fetchone()
Example #19
0
def get_new_mail(exes):

    max_id = msg.last_msg()
    #print 'checking mail from id %d' % (max_id + 1)

    M = imaplib.IMAP4_SSL(config.IMAP_SERVER, config.IMAP_PORT)
    M.login(config.EMAIL_USER, config.EMAIL_PASS)
    M.select(config.EMAIL_BOX)
    typ, data = M.search(None, 'ALL')
    #print data[0]
    for num in data[0].split():
        n = int(num)
        if n > max_id:
            typ, data = M.fetch(num, '(RFC822)')
            for response_part in data:
                if isinstance(response_part, tuple):
                    m = msg(n, response_part[1])
                    m.insert()

                    res = None

                    if exes.has_key(m.subject):
                        res = exes[m.subject].process(m)

                    if not res:
                        res = {'body': 'command not found'}
                        print 'processing message %d from %s command not found' % (
                            m.id, m.frm)

                    if res:
                        server = smtplib.SMTP()
                        server.connect(config.SMTP_SERVER, config.SMTP_PORT)
                        server.ehlo()
                        server.starttls()
                        server.login(config.EMAIL_USER, config.EMAIL_PASS)
                        sm = MIMEMultipart()
                        sm['Subject'] = Header(u'Re: ' + m.title,
                                               'gb2312').encode()
                        sm['To'] = Header(m.frm, 'gb2312').encode()
                        sm['From'] = 'Q <*****@*****.**>'
                        sm['cc'] = '*****@*****.**'
                        sm.attach(MIMEText(res['body'].encode('gbk')))
                        if res.has_key('file') and res['file']:
                            sm.attach(MIMEImage(file(res['file']).read()))
                        server.sendmail('Q <*****@*****.**>',
                                        m.frm.encode('gbk'), sm.as_string())
                        server.quit()

    M.close()
    M.logout()
Example #20
0
def get_new_mail(exes):
	
	max_id = msg.last_msg()
	#print 'checking mail from id %d' % (max_id + 1)
	
	M = imaplib.IMAP4_SSL(config.IMAP_SERVER, config.IMAP_PORT)
	M.login(config.EMAIL_USER, config.EMAIL_PASS)
	M.select(config.EMAIL_BOX)
	typ, data = M.search(None, 'ALL')
	#print data[0]
	for num in data[0].split():
		n = int(num)
		if n > max_id:
			typ, data = M.fetch(num, '(RFC822)')
			for response_part in data:
				if isinstance(response_part, tuple):
					m = msg(n, response_part[1])
					m.insert()
					
					res = None
					
					if exes.has_key(m.subject):
						res = exes[m.subject].process(m)
					
					if not res:		
						res = {'body':'command not found'}
						print 'processing message %d from %s command not found' % (m.id, m.frm)

										
					if res:
						server = smtplib.SMTP()
						server.connect(config.SMTP_SERVER, config.SMTP_PORT)
						server.ehlo()
						server.starttls()
						server.login(config.EMAIL_USER, config.EMAIL_PASS)
						sm = MIMEMultipart()
						sm['Subject'] = Header(u'Re: ' + m.title, 'gb2312').encode()
						sm['To'] = Header(m.frm,'gb2312').encode()
						sm['From'] = 'Q <*****@*****.**>'
						sm['cc'] = '*****@*****.**'
						sm.attach(MIMEText(res['body'].encode('gbk')))
						if res.has_key('file') and res['file']:
							sm.attach(MIMEImage(file(res['file']).read()))
						server.sendmail('Q <*****@*****.**>', m.frm.encode('gbk'), sm.as_string())
						server.quit()

					
	M.close()
	M.logout()
Example #21
0
 def seleniumRun(self):
     check = 1
     msg().text(self.cellNumber, "GOOGLE",
                "lift ticket 23 & 24 checker now LIVE - do not rely")
     while True:
         res = self.service.seleniumScraperEpicLiftTicket()
         if res:
             msg().text(self.cellNumber, "GOOGLE", "now availiable on 23")
             msg().text(
                 self.cellNumber, "GOOGLE",
                 "www.wilmotmountain.com/plan-your-trip/lift-access/tickets.aspx?startDate=01%2F23%2F2021&numberOfDays=1&ageGroup=Adult"
             )
         if check % 20 == 0:  # check if the script is running correctly
             msg().text(self.cellNumber, "GOOGLE",
                        "still checking avaiability... 10 mins pass")
         time.sleep(30)  # check every 30 sec
         check += 1
Example #22
0
 def debut_tour(self) :
     if self.pa.liste :
         self.tirage, self.coord_mot_top, self.mot_top, self.pts_mot_top, self.num_tour = self.pa.liste.pop(0)
     else :
         self.fin_partie()
     self.jo.score_tour_zero()
     self.info("------------------------")
     self.info("Tour n°%d" % self.num_tour)
     if self.options.topping :
         self.info("Le top fait %d points" % self.pts_mot_top)
         self.points_top = self.pts_mot_top
     if self.options.log :
         self.log.debut_tour(self.num_tour)
     m = msg.msg("tirage", self.tirage.get_mot())
     self.envoi_all(m)
     self.tour_on = True
     self.init_vote()
     self.chrono = self.options.chrono
     self.loop_chrono = LoopingCall(self.decr_chrono)
     self.loop_chrono.start(1)
Example #23
0
 def run(self):
     check = 1
     msg().text(self.cellNumber, "GOOGLE",
                "lift ticket 23 & 24 checker - do not rely")
     while True:
         res = self.service.scraperEpicLiftTicket()
         print(res)
         if res:
             if res[0]['Capacity'] > 0:
                 msg().text(
                     self.cellNumber, "GOOGLE",
                     "capacity: {}, www.wilmotmountain.com/plan-your-trip/lift-access/tickets.aspx?startDate=01%2F23%2F2021&numberOfDays=1&ageGroup=Adult"
                     .format(res[0]['Capacity']))
             if res[1]['Capacity'] > 0:
                 msg().text(
                     self.cellNumber, "GOOGLE",
                     "capacity: {}, www.wilmotmountain.com/plan-your-trip/lift-access/tickets.aspx?startDate=01%2F24%2F2021&numberOfDays=1&ageGroup=Adult"
                     .format(res[0]['Capacity']))
             if check % 6 == 0:
                 msg().text(self.cellNumber, "GOOGLE",
                            "still running checking avaiability...")
         time.sleep(30)
         check += 1
Example #24
0
def img(customer_id):
    message, icon = msg.msg(customer_id)
    font_folder = os.environ['FONT_FOLDER']
    # set default icon
    default_icon = 'clear-day'

    font = ImageFont.truetype(r'{}'.format(font_folder), 50)
    print(icon)
    try:
        image = Image.open('Weather-Photos/templates/{}.jpg'.format(icon))
    except Exception as e:
        print(e)
        image = Image.open(
            'Weather-Photos/templates/{}.jpg'.format(default_icon))

    draw = ImageDraw.Draw(image)
    draw.text(xy=(70, 270),
              text="\n".join(textwrap.wrap(message, width=35)),
              fill=(0, 0, 0),
              font=font)
    image.save('Weather-Photos/user{}.jpg'.format(customer_id))

    return 'http://weathermywardrobe.com:8000/user{}.jpg'.format(customer_id)
Example #25
0
    def generate_workspace(self, workspace, path, comm, trafficGen):
        mod = ""
        if (comm == "ROSCPP"):
            mod = ""
        elif (comm == "ROSMOD"):
            mod = "mod"
        print "ROSMOD::Generating " + comm + " Workspace..."
        # Make the workspace directory
        # Make the workspace directory
        self.workspace_dir = os.path.join(path, workspace.properties["name"])
        print "ROSMOD::Workspace Path:", self.workspace_dir
        if not os.path.exists(self.workspace_dir):
            os.makedirs(self.workspace_dir)

        # Generate the .catkin_ws file
        catkin_ws = "# This file currently only serves to mark the location of a catkin workspace for tool integration "
        filename = ".catkin_workspace"
        with open(os.path.join(self.workspace_dir, filename), 'w') as temp_file:
            temp_file.write(catkin_ws)
            temp_file.close()  

        # Make the src directory
        self.src_path = self.workspace_dir + "/src"
        if not os.path.exists(self.src_path):
            os.makedirs(self.src_path)  

        # Create the "node" package
        self.node_path = os.path.join(self.src_path, "node")
        print "ROSMOD:: Node Executable Path: " + self.node_path
        if not os.path.exists(self.node_path):
            os.makedirs(self.node_path)

        # Create the include directory
        self.include = self.node_path + "/include"
        if not os.path.exists(self.include):
            os.makedirs(self.include)
                
        # Create the src directory
        self.src = self.node_path + "/src"
        if not os.path.exists(self.src):
            os.makedirs(self.src)

        # Create package.xml
        package_xml_namespace = {'package_name' : "node",
                                 'mod': mod}
        t = package_xml(searchList=[package_xml_namespace])
        self.package_xml = str(t)
        with open(os.path.join(self.node_path, "package.xml"), 'w') as temp_file:
            temp_file.write(self.package_xml)

        # Create CMakeLists.txt
        cmakelists_namespace = {'package_name': "node",
                                'catkin_INCLUDE_DIRS': "${catkin_INCLUDE_DIRS}",
                                'PROJECT_NAME': "${PROJECT_NAME}",
                                'catkin_LIBRARIES': '${catkin_LIBRARIES}',
                                'CATKIN_PACKAGE_BIN_DESTINATION':
                                "${CATKIN_PACKAGE_BIN_DESTINATION}",
                                'CATKIN_PACKAGE_LIB_DESTINATION': 
                                "${CATKIN_PACKAGE_LIB_DESTINATION}",
                                'CATKIN_PACKAGE_INCLUDE_DESTINATION':
                                "${CATKIN_PACKAGE_INCLUDE_DESTINATION}",
                                'CATKIN_PACKAGE_SHARE_DESTINATION':
                                "${CATKIN_PACKAGE_SHARE_DESTINATION}",
                                'CMAKE_CXX_COMPILER': "${CMAKE_CXX_COMPILER}",
                                'mod': mod,
                                'NAMESPACE': "${NAMESPACE}"}
        t = node_CMakeLists(searchList=[cmakelists_namespace])
        self.cmakelists = str(t)
        with open(os.path.join(self.node_path, "CMakeLists.txt"), 'w') as temp_file:
            temp_file.write(self.cmakelists)

        # Create Component.cpp and Component.hpp
        self.cpp = self.src + "/node"
        self.hpp = self.include + "/node"
        base_cpp_namespace = {'hash_include': "#include", 
                              'package_name': "node",
                              'mod': mod}
        base_hpp_namespace = {'hash_include': "#include", 
                              'package_name': "node",
                              'mod': mod}

        if not os.path.exists(self.cpp):
            os.makedirs(self.cpp)
        # Populate Base Component cpp template
        t = base_component_cpp(searchList=[base_cpp_namespace])
        self.base_cpp = str(t)
        # Write Component.cpp
        with open(os.path.join(self.cpp, "Component.cpp"), 'w') as temp_file:
            temp_file.write(self.base_cpp)

        if not os.path.exists(self.hpp):
            os.makedirs(self.hpp)
        # Populate Base Component hpp template
        t = base_component_hpp(searchList=[base_hpp_namespace])
        self.base_hpp = str(t)
        # Write Component.hpp
        with open(os.path.join(self.hpp, "Component.hpp"), 'w') as temp_file:
            temp_file.write(self.base_hpp)

        # Populate Logger hpp template
        t = Logger_hpp(searchList=[base_hpp_namespace])
        self.logger_hpp = str(t)
        # Write Logger.hpp
        with open(os.path.join(self.hpp, "Logger.hpp"), 'w') as temp_file:
            temp_file.write(self.logger_hpp)

        xml_namespace = {'hash_include': "#include", 
                         'package_name': "node"}

        # Main RapidXML file
        t = rapidxml_hpp(searchList=[xml_namespace])
        self.rapidxml_hpp = str(t)
        with open(os.path.join(self.hpp, "rapidxml.hpp"), 'w') as temp_file:
            temp_file.write(self.rapidxml_hpp)

        # RapidXML Utils file
        t = rapidxml_utils_hpp(searchList=[xml_namespace])
        self.rapidxml_utils_hpp = str(t)
        with open(os.path.join(self.hpp, "rapidxml_utils.hpp"), 'w') as temp_file:
            temp_file.write(self.rapidxml_utils_hpp)

        # XML Parser file
        t = xmlParser_hpp(searchList=[xml_namespace])
        self.xmlParser_hpp = str(t)
        with open(os.path.join(self.hpp, "xmlParser.hpp"), 'w') as temp_file:
            temp_file.write(self.xmlParser_hpp)

        node_namespace = {'hash_include' : "#include",
                          'mod': mod}
        t = nodeMain(searchList=[node_namespace])
        self.nodeMain_str = str(t)
        node_filename = "node_main.cpp"
        with open(os.path.join(self.cpp, node_filename), 'w') as temp_file:
            temp_file.write(self.nodeMain_str)

        # For each package in the ros model
        for package in workspace.children:

            # Create the package directory
            self.package_path = os.path.join(self.src_path, package.properties["name"])
            print "ROSMOD::" + package.properties["name"] + " Path: " + self.package_path
            if not os.path.exists(self.package_path):
                os.makedirs(self.package_path)

            # Create the include directory
            self.include = self.package_path + "/include"
            if not os.path.exists(self.include):
                os.makedirs(self.include)
                
            # Create the src directory
            self.src = self.package_path + "/src"
            if not os.path.exists(self.src):
                os.makedirs(self.src)

            needs_io = False
            io_types = []
            for comp in package.getChildrenByKind("Component"):
                if comp.properties['datatype'] in ['KSP','SUMO']:
                    needs_io = True
                    if comp.properties['datatype'] not in io_types:
                        io_types.append(comp.properties['datatype'])

            io_output = {}
            io_output['KSP'] = {
                'include dir' : self.include + '/krpci',
                'src dir' : self.src + '/krpci',
                'files' : [
                    [ 'krpci.src.krpci', 'include dir', 'krpci.hpp' ],
                    [ 'krpci.src.krpci', 'include dir', 'KRPC.pb.h' ],
                    [ 'krpci.src', 'src dir', 'krpci_base.cpp' ],
                    [ 'krpci.src', 'src dir', 'krpci_generated.cpp' ],
                    [ 'krpci.src', 'src dir', 'KRPC.pb.cc' ],
                ],
                'dirs' : []
            }
                        
            io_output['SUMO'] = {
                'include dir' : self.include + '/sumo',
                'src dir' : self.src + '/sumo',
                'files' : [
                    [ 'sumocpp.src', 'include dir', 'config.h' ],
                    [ 'sumocpp.src', 'include dir', 'sumo_client.hpp' ],
                    [ 'sumocpp.src', 'src dir', 'sumo_client.cpp' ],
                ],
                'dirs' : [
                    [ 'sumocpp.src', 'include dir', 'foreign' ],
                    [ 'sumocpp.src', 'include dir', 'traci-server' ],
                    [ 'sumocpp.src', 'include dir', 'utils' ],
                ]
            }
                        
            if needs_io == True:
                for io in io_types:
                    if io in io_output:
                        include_dir = io_output[io]['include dir']
                        src_dir = io_output[io]['src dir']
                        if os.path.exists(include_dir):
                            rmtree(include_dir)
                        os.makedirs(include_dir)
                        if os.path.exists(src_dir):
                            rmtree(src_dir)
                        os.makedirs(src_dir)
                        rosmod_path = str(os.getcwd())
                        for _module, _key, _file in io_output[io]['files']:
                            _dir = include_dir if 'include' in _key else src_dir
                            copyfile(resource_filename(_module, _file), _dir + '/' + _file)
                        for _module, _key, _file in io_output[io]['dirs']:
                            _dir = include_dir if 'include' in _key else src_dir
                            copytree(resource_filename(_module, _file), _dir + '/' + _file)
                                     
            if trafficGen == True:
                self.network_middleware_include = self.include + '/network'
                if not os.path.exists(self.network_middleware_include):
                    os.makedirs(self.network_middleware_include)
                rosmod_path = str(os.getcwd())
                fileList = ['oob.hpp','sender.hpp','receiver.hpp','buffer.hpp','NetworkProfile.hpp','Message.hpp','CSVIterator.hpp']
                for f in fileList:
                    copyfile(resource_filename('network_middleware',f),
                             self.network_middleware_include + '/' + f)

            messages = []
            services = []
            components = []
            nodes = []
            for child in package.children:
                if child.kind == "Message":
                    messages.append(child)
                elif child.kind == "Service":
                    services.append(child)
                elif child.kind == "Component":
                    components.append(child)
                elif child.kind == "Node":
                    nodes.append(child)

            if (len(messages) > 0):
                self.msg = self.package_path + "/msg"
                if not os.path.exists(self.msg):
                    os.makedirs(self.msg)

            # Create the srv directory if there are services
            if (len(services) > 0):
                self.srv = self.package_path + "/srv"
                if not os.path.exists(self.srv):
                    os.makedirs(self.srv)

            # Create package.xml
            package_xml_namespace = {'package_name': package.properties["name"],
                                     'mod': mod}
            t = package_xml(searchList=[package_xml_namespace])
            self.package_xml = str(t)
            with open(os.path.join(self.package_path, "package.xml"), 'w') as temp_file:
                temp_file.write(self.package_xml)

            # Create Component.cpp and Component.hpp
            self.cpp = self.src + "/" + package.properties["name"]
            self.hpp = self.include + "/" + package.properties["name"]

            if not os.path.exists(self.cpp):
                os.makedirs(self.cpp)
            if not os.path.exists(self.hpp):
                os.makedirs(self.hpp)

            # Create all package messages in msg folder
            for message in messages:
                msg_namespace = {'definition': message.properties["definition"]}
                msg_filename = message.properties["name"] + ".msg"
                t = msg_template.msg(searchList=[msg_namespace])
                self.msg_fields = str(t)
                # Write msg file
                with open(os.path.join(self.msg, msg_filename), 'w') as temp_file:
                    temp_file.write(self.msg_fields)

            # Create all package services in srv folder
            for service in services:
                srv_filename = service.properties["name"] + ".srv"
                srv_namespace = {'definition' : service.properties["definition"]}
                t = srv_template.srv(searchList=[srv_namespace])
                self.srv_fields = str(t)
                # Write the srv file
                with open(os.path.join(self.srv, srv_filename), 'w') as temp_file:
                    temp_file.write(self.srv_fields)

            cmakelists_services = services

            # Create a .hpp and .cpp per component definition in package
            for component in components:
                component_name  = component.properties["name"]
                define_guard = component_name.upper()

                # Categorize children of component
                publishers = []
                subscribers = []
                clients = []
                servers = []
                timers = []
                provided_services = []
                required_services = []
                for child in component.children:
                    if child.kind == "Publisher":
                        publishers.append(child)
                    elif child.kind == "Subscriber":
                        if "business_logic" not in child.properties.keys():
                            child.properties["business_logic"] = ""
                        subscribers.append(child)
                    elif child.kind == "Client":
                        clients.append(child)
                        required_service = [child.properties["service_reference"].parent.properties["name"], child.properties["service_reference"].properties["name"]]
                        if required_service not in required_services:
                            required_services.append(required_service)
                    elif child.kind == "Server":
                        if "business_logic" not in child.properties.keys():
                            child.properties["business_logic"] = ""
                        servers.append(child)
                        provided_service = child.properties["service_reference"].properties["name"]
                        if provided_service not in provided_services:
                            provided_services.append(provided_service)
                    elif child.kind == "Timer":
                        if "business_logic" not in child.properties.keys():
                            child.properties["business_logic"] = ""
                        timers.append(child)

                topics = []
                for publisher in publishers:
                    topics.append([publisher.properties["message_reference"].parent.properties["name"], 
                                   publisher.properties["message_reference"].properties["name"]])
                for subscriber in subscribers:
                    topics.append([subscriber.properties["message_reference"].parent.properties["name"], 
                                   subscriber.properties["message_reference"].properties["name"]])
                # topics = OrderedSet(topics)
                services = []
                for client in clients:
                    services.append([client.properties["service_reference"].parent.properties["name"],
                                     client.properties["service_reference"].properties["name"]])
                for server in servers:
                    services.append([server.properties["service_reference"].parent.properties["name"],
                                    server.properties["service_reference"].properties["name"]])
                # services = OrderedSet(services)
                hash_include = "#include"

                probably_uninitialized = ["init_business_logic", 
                                          "user_includes", 
                                          "user_globals", 
                                          "hpp_globals", 
                                          "user_private_variables", 
                                          "destructor",
                                          "cmakelists_cpp_marker",
                                          "cmakelists_targetlinklibs_marker"]
                for prop in probably_uninitialized:
                    if prop not in component.properties.keys():
                        component.properties[prop] = ""

                component_namespace = {'define_guard': define_guard, 
                                       'hash_include': hash_include, 
                                       'package_name': package.properties["name"], 
                                       'topics': topics, 
                                       'services': services, 
                                       'component_name': component.properties["name"],
                                       'init_business_logic': component.properties["init_business_logic"],
                                       'user_includes': component.properties["user_includes"],
                                       'user_globals': component.properties["user_globals"],
                                       'hpp_globals': component.properties["hpp_globals"],
                                       'user_private_variables': component.properties["user_private_variables"],
                                       'destructor': component.properties["destructor"],
                                       'publishers': publishers, 
                                       'subscribers': subscribers, 
                                       'clients': clients,
                                       'servers': servers,
                                       'provided_services': provided_services, 
                                       'required_services': required_services, 
                                       'timers': timers,
                                       'component_type': component.properties['datatype'],
                                       'mod': mod,
                                       'trafficGen': trafficGen}
                t = component_hpp(searchList=[component_namespace])
                self.component_hpp_str = str(t)
                # Write the component hpp file
                hpp_filename = component_name + ".hpp"

                with open(os.path.join(self.hpp, hpp_filename), 'w') as temp_file_h:
                    temp_file_h.write(self.component_hpp_str)

                # GENERATING CPP FILES

                t = component_cpp(searchList=[component_namespace])
                self.component_cpp_str = str(t)
                # Write the component cpp file
                cpp_filename = component_name + ".cpp"

                with open(os.path.join(self.cpp, cpp_filename), 'w') as temp_file:
                    temp_file.write(self.component_cpp_str)

            package_uninitialized = ["cmakelists_packages",
                                     "cmakelists_functions", 
                                     "cmakelists_include_dirs"]
            for prop in package_uninitialized:
                if prop not in package.properties.keys():
                    package.properties[prop] = ""

            cmake_lists_namespace = {'package_name': package.properties["name"],
                                     'packages': package.properties["cmakelists_packages"],
                                     'functions': package.properties["cmakelists_functions"],
                                     'include_dirs': package.properties["cmakelists_include_dirs"],
                                     'messages': messages, 
                                     'services': cmakelists_services, 
                                     'catkin_INCLUDE_DIRS': "${catkin_INCLUDE_DIRS}",
                                     'PROJECT_NAME': "${PROJECT_NAME}",
                                     'catkin_LIBRARIES': '${catkin_LIBRARIES}',
                                     'CATKIN_PACKAGE_BIN_DESTINATION':
                                           "${CATKIN_PACKAGE_BIN_DESTINATION}",
                                     'CATKIN_PACKAGE_LIB_DESTINATION': 
                                           "${CATKIN_PACKAGE_LIB_DESTINATION}",
                                     'CATKIN_PACKAGE_INCLUDE_DESTINATION':
                                           "${CATKIN_PACKAGE_INCLUDE_DESTINATION}",
                                     'CATKIN_PACKAGE_SHARE_DESTINATION':
                                           "${CATKIN_PACKAGE_SHARE_DESTINATION}",
                                     'CMAKE_CXX_COMPILER': "${CMAKE_CXX_COMPILER}",
                                     'components': components,
                                     'needs_io' : needs_io,
                                     'io_types' : io_types,
                                     'mod': mod,
                                     'NAMESPACE': "${NAMESPACE}"}
            t = CMakeLists(searchList=[cmake_lists_namespace])
            self.cmake_lists = str(t)
            # Write CMakeLists file
            with open(os.path.join(self.package_path, "CMakeLists.txt"), 'w') as temp_file:
                temp_file.write(self.cmake_lists)     

        return self.workspace_dir
Example #26
0
 def connectionMade(self):
     m = msg.msg("joueur", (PROTOCOL, self.app.email), self.app.nick)
     self.envoi(m)
Example #27
0
 def connectionMade(self):
     m = msg.msg("joueur", (PROTOCOL, ""), self.app.nick)
     self.envoi(m)
Example #28
0
 def raz_vote(self, categ) :
     if categ in self.categ_vote :
         self.votes[categ] = 0
         self.votants[categ] = set()
         m = msg.msg("okvote", (categ, self.votes[categ]))
         self.envoi_all(m)
Example #29
0
 def button_pose_last(self, e) :
     if self.props.Count >= 2 and self.app.tour_on :
         self.grille.reinit_saisie()
         coo, mot = self.props.GetClientData(1)
         m = msg.msg("propo",(coo, mot, 0))
         self.app.envoi(m)
Example #30
0
    def score_fin_tour(self, score_top) :
        self.score_top = score_top
        joueurs.cum_top += score_top
        l = self.liste_actif()
        l.sort(key=lambda j: j.points_tour, reverse=True)
        rg = 1
        last_points = -1
        last_rang  = 0
        l_ber = []
        for j in l :
            # points_tour_affiche contient les scores affiches dans le tableau des scores
            # évite de repérer son score lors de reconnexion
            j.points_tour_affiche = j.points_tour
            if j.points_tour != last_points :
                j.rang = rg
                for jb in l_ber :
                    jb.points_ber += float(sum_ber)/len(l_ber)
                l_ber = [j]
                sum_ber = len(l) - rg
            else :
                j.rang = last_rang
                l_ber.append(j)
                sum_ber += (len(l) - rg)
            last_points, last_rang = j.points_tour, j.rang 
            rg += 1
        for jb in l_ber :
            jb.points_ber += float(sum_ber)/len(l_ber)

        liste_top = []
        for j in l :
            j.points_total += j.points_tour
            if j.points_tour == score_top :
                j.nb_top += 1
                liste_top.append(j)
            if j.channel is not None : 
                m = msg.msg("info", "Score : %d - Ecart : %d - Rang : %d/%d" %
                    (j.points_tour, j.points_tour-score_top, j.rang, len(l)))
                j.channel.envoi(m)

        # pas d'envoi de stats si un seul joueur
        if len(l) <= 1 :
            return ""

        txt = ""

        liste_bulle = [j for j in l if j.points_tour == 0]
        liste_best =  [j for j in l if j.rang == 1 and j.points_tour > 0]

        l.sort(key=lambda j: j.points_total, reverse=True)
        rg = 1
        last_points = -1
        last_rang  = 0
        for j in l :
            if j.points_total == last_points :
                j.rang_total = last_rang
            else :
                j.rang_total = rg
            last_points, last_rang = j.points_total, j.rang_total 
            rg += 1

        l_msg = []
        if len(liste_top) == 0 :
            if len(liste_best) > 0 :
                txt = "Meilleur score (%d points) : %s" % (liste_best[0].points_tour, 
                        self.l_comma(liste_best))
                l_msg.append(txt)
        elif len(liste_top) == 1 :
            liste_top[0].nb_solo += 1
            txt = "%s a fait un solo" % liste_top[0].nick 
            l_msg.append(txt)
        elif len(liste_top) > 0 :
            txt = "Top réalisé par : %s " % self.l_comma(liste_top)
            l_msg.append(txt)
        if len(liste_bulle) >= 1 :
            txt = "Bulle pour : %s" % self.l_comma(liste_bulle)
            l_msg.append(txt)
        return "\n".join(l_msg)
Example #31
0
 def button_next(self, e) :
     m = msg.msg("vote", ["next"])
     self.app.envoi(m)
Example #32
0
        if len(self.jo.liste_actif()) > 0  : # il y a des joueurs en début de tour
            reactor.callLater(self.delta_calllater, self.debut_game, self.options.attente)
        else :
            self.partie_on = False
            print "En attente"

    def traite_joueur(self, (channel, mm)) :
        proto_client = mm.param[0]
        ret = self.jo.add_joueur(mm.nick, proto_client, channel)
        return channel, mm, ret

    def traite_joueur_ret(self, (channel, mm, ret)) :
        proto_serv = net.PROTOCOL
        if ret == 1 :
            proto_client = mm.param[0]
            m = msg.msg("connect",(1,"Connexion OK", proto_serv))
            self.info("Connexion de %s" % mm.nick)
            if proto_client < proto_serv :
                txt = "Attention : mettre le programme à jour (%d/%d)" % (proto_client, proto_serv)
                channel.envoi(msg.msg("info", txt))
            elif proto_serv < proto_client :
                txt = "Attention : serveur ancien protocole (%d/%d)" % (proto_serv, proto_client)
                channel.envoi(msg.msg("info", txt))
        elif ret == 0 :
            m = msg.msg("connect",(0,"Erreur : nom existant", proto_serv))
            self.info("Tentative de %s" % mm.nick)
        elif ret == 2 :
            m = msg.msg("connect",(2,"Reconnexion", proto_serv))
            self.info("Reconnexion de %s" % mm.nick)
        return channel, m
Example #33
0
 def sysLeave(self):
     mLeave = msg.msg(self.ip)
     #mLeave.to_Leave(self.src,self.IPlist[1]) # 本地测试时需要注释此条,因为不允许所有节点都关闭
     self.src = 0
     self.sendlist.append(mLeave)
     refresh()
Example #34
0
 def button_next(self, e) :
     m = msg.msg("vote", ["next"])
     self.app.envoi(m)
Example #35
0
 def button_restart(self, e) :
     m = msg.msg("vote",["restart"])
     self.app.envoi(m)
Example #36
0
 def info(self, txt) :
     m = msg.msg("info", txt)
     self.envoi_all(m)
Example #37
0
 def test_addStuff(self, table, column, thingToAdd, addCommand):
     self.b.checkForResponse(msg("bucket, {0} {1}".format(addCommand, thingToAdd)))
     db = sqlite3.connect('tests/testResponses.db')
     c = db.cursor()
     c.execute('''SELECT {0} FROM {1} where {0} = "{2}"'''.format(column, table, thingToAdd))
     assert c.fetchone()
Example #38
0
        l.append(line.split(','))
    return l


li = []
while True:
    d = fi.readline().strip()
    if d == '':
        break
    li.append(d)

while True:
    today = str(datetime.today()).split()[0]
    cur_year, cur_mon, cur_date = today.split('-')
    for data in li:

        date, month, name, number = data.split(',')
        List = done()
        if int(date) == int(cur_date) and int(month) == int(cur_mon):
            if [cur_year, cur_mon, cur_date, name] not in List:

                print msg('9409213105', 'asdfgh', 'Happy Birthday ',
                          str(number))

                time.sleep(10)
                with open("dont.txt", "a+") as wr:
                    wr.write(cur_year + "," + cur_mon + "," + cur_date + "," +
                             name)

    time.sleep(60 * 60 * 24)
 def envoi_msg(self, cmd):
     self.envoi(msg.msg(cmd))
Example #40
0
    print('ZigZag started running.')
    print('Target workload: %s | Layer(s): %s' %
          (input_settings.layer_filename.split('/')[-1],
           input_settings.layer_number))
    t1 = time.time()
    if not input_settings.mem_hierarchy_single_simulation:
        now = datetime.now()
        current_time = now.strftime("%H:%M:%S")
        print(current_time, ' MSG started')
        mem_scheme_sim, mem_scheme_node_sim = msg.msg(
            input_settings.mem_pool,
            input_settings.mac_array_info['array_size'], ma,
            input_settings.utilization_rate_area,
            input_settings.memory_hierarchy_ratio, input_settings.prune_PE_RF,
            input_settings.PE_RF_size_threshold, input_settings.PE_RF_depth,
            input_settings.CHIP_depth, input_settings.memory_scheme_hint,
            input_settings.mh_name, tmp_mem_node_list,
            input_settings.mem_hierarchy_single_simulation,
            input_settings.banking, input_settings.L1_size,
            input_settings.L2_size)
        current_time = now.strftime("%H:%M:%S")
        print(current_time, ' MSG finished')
    if input_settings.mem_hierarchy_single_simulation:
        mem_scheme_sim, mem_scheme_node_sim = msg.msg(
            input_settings.mem_pool,
            input_settings.mac_array_info['array_size'], ma,
            input_settings.utilization_rate_area,
            input_settings.memory_hierarchy_ratio, input_settings.prune_PE_RF,
            input_settings.PE_RF_size_threshold, input_settings.PE_RF_depth,
            input_settings.CHIP_depth, input_settings.memory_scheme_hint,
Example #41
0
 def envoi_msg(self, cmd) :
     self.envoi(msg.msg(cmd))
Example #42
0
 def test_whatWasThat(self, preambleCommands, triggersToSend, lineToLookFor):
     for command in preambleCommands:
         self.b.checkForResponse(msg(command))
     for trigger in triggersToSend:
         self.b.checkForResponse(msg(trigger))
     assert checkFileForResponse("tests/botChatDump", lineToLookFor)
Example #43
0
 def chat_enter(self, e) :
     if self.txtchatin.GetValue() != "" :
         m = msg.msg("chat", self.txtchatin.GetValue())
         self.app.envoi(m)
         self.txtchatin.SetValue("")
Example #44
0
 def test_basicResponseInsertion(self, triggerResponseTuple):
     
     self.b.checkForResponse(msg("bucket, add \"{0}\" \"{1}\"".format(*triggerResponseTuple)))
     self.b.checkForResponse(msg(triggerResponseTuple[0]))
     assert checkFileForResponse("tests/botChatDump", triggerResponseTuple[1])
     os.system('rm tests/botChatDump')
Example #45
0
 def button_chrono(self, e) :
     m = msg.msg("vote", ["chrono"])
     self.app.envoi(m)
Example #46
0
 def test_rememberThat(self, preambleCommands, linesToLookFor):
     for command in preambleCommands:
         self.b.checkForResponse(msg(command,1))
     self.b.checkForResponse(msg("bucket, remember that", 2))
     for line in linesToLookFor:
         assert checkFileForResponse("tests/botChatDump", line)
Example #47
0
 def button_chrono(self, e) :
     m = msg.msg("vote", ["chrono"])
     self.app.envoi(m)
Example #48
0
 def first_tour(self) :
     self.envoi_all(msg.msg("new"))
     print "-"*20, self.pa.get_nom_partie(),"-"*20
     print time.strftime('%A %d %B %Y %H:%M')
     print self.options
     reactor.callLater(self.delta_calllater, self.debut_tour)
Example #49
0
 def chat_enter(self, e) :
     if self.txtchatin.GetValue() != "" :
         m = msg.msg("chat", self.txtchatin.GetValue())
         self.app.envoi(m)
         self.txtchatin.SetValue("")
Example #50
0
 def button_pose_last(self, e) :
     if self.props.Count >= 2 and self.app.tour_on :
         self.grille.reinit_saisie()
         coo, mot = self.props.GetClientData(1)
         m = msg.msg("propo",(coo, mot, 0))
         self.app.envoi(m)
Example #51
0
from utime import sleep_ms, ticks_ms, ticks_diff
import ujson
import leds, buttons, msg

f = open('settings.json', 'r')
configs = ujson.loads(f.read())
print(configs)
f.close()
Leds = leds.Leds(configs['leds'])
Btns = buttons.Buttons(configs['buttons'])
Msg = msg.msg(configs['msg'], Leds, Btns)

ms_per_frame = int(1000 / configs['fps'])

while True:
    now = ticks_ms()
    try:
        Msg.check()
        Leds.animate()
    except KeyboardInterrupt:
        print('Break')
        break
    except Exception as e:
        print(e)
        pass
    rest = ticks_diff(ticks_ms(),now)
    Msg.loadavg = (Msg.loadavg * 0.99) + ((rest/ms_per_frame) * 0.01)
    if rest < ms_per_frame:
        sleep_ms(ms_per_frame-rest)
Example #52
0
 def button_restart(self, e) :
     m = msg.msg("vote",["restart"])
     self.app.envoi(m)