Exemple #1
0
def thr_callback(name,age):
    global thisexit
    print 'name is ', name, ' age is ', age
    
    thisexit = True
    thread.exit_thread()
    return
Exemple #2
0
def generate_thread(id, t):
	"""
	TODO:FIXME: porting real generate interface
		call generate(app_name, app_logo, enables) instead
	"""
	# time.sleep(t)
	o = order.objects.get(id=id)
	if o is None:
		raise Exceptions('order %s be not found' % (id))
	else:
		if o.order_is_rebuild == True:
			o.order_status = 3
		else:
			o.order_status = 2
		# generator script
		web_path = '/static/output_path/' + str(id) + '.apk'
		abs_path = os.path.abspath('Phimpme' + web_path)
		from gen_script import generate

		print o.order_features
		generate(order_id=id, output_path=abs_path, app_name=o.order_appname, app_logo=None, enables=eval(o.order_features))

		o.order_output_file = web_path
		o.save()
	thread.exit_thread()
Exemple #3
0
def simpleThdreadFun(interval):
    global g_nProcessed
    global g_nTotal
    while g_nTotal > g_nProcessed:
        time.sleep(interval)
        g_nProcessed += 1
    thread.exit_thread()
Exemple #4
0
def mysay(messages):
    '''
		控制机器人说messages
		默认messages是str类型
	'''
    # 1. 判断语言
    umesg = messages.decode('utf-8')  # 得到unicode格式的消息,判断语言
    # 从unicode中的第一个元素判断语言, 2. 切换语言
    if is_chinese(umesg[0]) == True:
        if tts.getLanguage() != u'Chinese':
            tts.setLanguage("Chinese")  # 耗时2s
        lang = 'ch'  # 语言记录
    else:
        if tts.getLanguage() != u'English':
            tts.setLanguage("English")  # 耗时0.8s
        lang = 'en'
    # 3. 说话


#	tts.say(messages)
    tts.say(chatrobot.chat(messages, lang))  # Chat Robot Talk
    # 4. 切换会英语语言包,默认英语
    tts.setLanguage("English")
    # 5. 退出线程
    thread.exit_thread()
def DetectThread(args):
    urll = args[0]
    callbackFunc = args[1]
    urlstream = urllib.urlopen(urll)
    udata = urlstream.read()
    callbackFunc(udata)
    thread.exit_thread()
Exemple #6
0
def sendMessageToAll(clientsock,client,name): #群聊监听用户发来信息
    global cancelSignal
    global judge
    global messageAll
    m = Message()
    while True:
        eve.clear()   # 若已设置标志则清除
        eve.wait()    # 调用wait方法
        if cancelSignal != "":
            if name == cancelSignal:
                # print "name" , name
                time.sleep(0.01)
                mutex.acquire()
                cancelSignal = ""
                mutex.release()
                eve.clear()
                clientsock.send(m.updateOnlineUsersMsg(name,judge[name]))#judge为判断上下线
                if judge[name] == 0:
                    clientsock.close()
                    thread.exit_thread()
                    pass
                pass
            pass
        #if judge[client2[0]] == 1:
        else:
            print messageAll
            clientsock.send(messageAll)
            pass
        time.sleep(0.05)
        pass
Exemple #7
0
def timer(no, interval):
    counter = 0
    while counter < 10:
        print "Thread :(%d), time:%s" % (no, time.ctime())
        time.sleep(interval)
        counter += 1
    thread.exit_thread()
Exemple #8
0
    def _downLoad_lyric_thread(self, fromUser, toUser, text_content,
                               wc_client):

        lyric = None
        song = ''

        if isinstance(text_content, tuple):
            song, artist_name = text_content
            lyrics = self.getLyricsBySongnameFromHttp(song, artist_name)
            if (len(lyrics) >= 1):
                lyric = lyrics[0]
        elif isinstance(text_content, Lyric):
            lyric = text_content
            song = lyric.song
        elif isinstance(text_content, unicode) or isinstance(
                text_content, str):
            reply_content = Custon_send_text_data_template % {
                'touser': fromUser,
                'content': text_content
            }
            wc_client.message.custom.send.post(body=reply_content)
            thread.exit_thread()
            return

        if isinstance(song, unicode):
            song = song.encode('utf-8')

        if lyric:
            try:

                text_content = self._downLoad_lyricFromHttp(lyric)
            except Exception, e:
                text_content = '找不到歌曲:%s %s'%(song,artist_name) if artist_name \
                    else '找不到歌曲:%s'%song
Exemple #9
0
 def __block__execute__(self,sql):
     with self.connection.cursor(pymysql.cursors.DictCursor) as cursor:
         cursor.execute(sql)
         try:
             self.connection.commit()
         finally:
             thread.exit_thread()
Exemple #10
0
 def recvLogin(self, clientsock, lines):
     print 'LOGIN DEAL'
     #print "lines:", lines
     client_host, client_port = clientsock.getpeername()
     requestline = lines[0].split(' ')
     username = requestline[2]
     port = int((lines[1].split(' '))[1])
     #print username, port
     name_exsit = False
     status = '1'
     reason = 'success'
     #print self.userinfos
     if username in self.users:
         name_exsit = True
     else:
         #print 'Process users infos'
         self.lock.acquire()
         self.users.add(username)
         self.userinfos[(client_host, port)] = username
         self.lock.release()
         print 'Processed'
     
     if name_exsit == True:
         status = '0'
         reason = 'username already exist'
     print status, reason
     print 'Status'
     self.sendMessageToAClient(clientsock, "loginJudge", [status, reason])
     thread.exit_thread()
def cal_nonce(start,end):
    value = 2**16
    for i in range(start,end):
        for nonce in range(0, 2** 16):
            nonce = nonce + value * i
#            print(nonce)
            header_hex ="000000208e930321ddc9e81115c2bca446f98fd216f10abb95554b5fc0c5bc20ddbbc851eed8022fd1b482072b353334031c26f212eefd61d1575426452d7f3d04b3d1f0dc1aa25bdeed011a" + \
                str(hex(nonce))[2:].zfill(8)
        #    print header_hex 
            header_bin = header_hex.decode('hex')
        
            #hash = hashlib.sha256(hashlib.sha256(header_bin).digest()).digest()
            #hash.encode('hex_codec')
            #print "hash:"
            #print(hash[::-1].encode('hex_codec'))    # convert from big-endian to little-endian
        
            scrypt = ltc_scrypt.getPoWHash(header_bin)
            scrypt.encode('hex_codec')
        #    print "scrypt:"
        #    ts = str((scrypt[::-1].encode('hex_codec')))[0:5]    # convert from big-endian to little-endian
            ts = (scrypt[::-1].encode('hex_codec'))[0:5]    # convert from big-endian to little-endian
            if ts=='00000':
                print header_hex 
                print(scrypt[::-1].encode('hex_codec'))
        #    print(scrypt[::-1].encode('hex_codec'))    # convert from big-endian to little-endian
    thread.exit_thread()
Exemple #12
0
def worker(bot, uid, text, interval):
    cnt = 0
    while cnt<1:
        print 'Thread:(%d) Time:%s\n'%(uid, time.ctime())
        time.sleep(interval)
        cnt+=1
    # res, qus, aut, con = queryTomcat(uid, text)
    res, qus, answers = queryTomcat(uid, text)
    #print 'before process:'+con
    # con = con.replace('<p>','')
    # con = con.replace('</p>','\n')
    # print 'after process:'+con
    #bot.sendMessage(chat_id=uid,text=res)
    #bot.sendMessage(chat_id=uid,text=qus)
    ## bot.sendMessage(chat_id=uid,text=qus.encode('utf-8'))#same result like upper one
    #bot.sendMessage(chat_id=uid,text=aut,parse_mode=ParseMode.HTML)
    #bot.sendMessage(chat_id=uid,text=con,parse_mode=ParseMode.HTML)
    ## bot.sendMessage(chat_id=uid,text=aut.decode('ISO-8859-1'))#bad using
    ## bot.sendMessage(chat_id=uid,text=aut.encode('utf-8'))#bad using
    ## bot.sendMessage(chat_id=uid,text='<b>'+aut+'</b>',parse_mode=ParseMode.HTML)#bad using
    if len(answers)>0:
        print 'get answers:'
        bot.sendMessage(chat_id=uid, text='已找到答案,请稍后...')
        for ans in answers:
            print ans
            finContent = '问题:'+ans['qus'].encode('utf-8')+'\n----------------------\n答案:'+ans['ans'].encode('utf-8')+'\n\n\n相似性:'+str(ans['sco'])
            print finContent
            bot.sendMessage(chat_id=uid, text=finContent)
    else:
        print 'no answers'
        bot.sendMessage(chat_id=uid, text='没找到答案,换个问题吧~')

    thread.exit_thread()
Exemple #13
0
def runner(arg):
    for i in range(6):
        print str(i)+':'+arg

        time.sleep(1)
    #......
    thread.exit_thread()  #...thread.exit()
Exemple #14
0
def get_content(j, ulr, interval):
    with open(str(j) + '.jpg', "wb") as f:
        each = requests.get(url)
        f.write(each.content)
        print str(j) + '.jpg 下载完成'
        time.sleep(interval)
    thread.exit_thread()
Exemple #15
0
 def glib_loop_thread(self):
     """
     runs the GLib main loop to get notified about player status changes
     """
     self.mloop.run()
     log("GLib loop exited", min_verbosity=2)
     thread.exit_thread()
Exemple #16
0
        def dl(threadName, delay, res):

            # 取文件扩展名称
            def getFileExp(file):
                return '.' + file[-3:]

            # 当前所有线程总下载数
            self.allThreadNum += 1
            # 下载文件 至分类目录 并重新命名
            reg = re.compile(r'[\\/:*?"<>|\r\n]+')
            baseName = res['name'] + getFileExp(res['res'])
            validName = reg.findall(baseName)
            if validName:
                for nv in validName:
                    baseName = baseName.replace(nv, "_")
            fileName = categoryName + '/' + baseName

            if not os.path.isfile(fileName):
                try:
                    urllib.urlretrieve(res['res'], fileName)
                    # 已下载的总文件数量
                    self._fileNum += 1
                    print threadName + res['name'] + ' file ' + res[
                        'res'] + ' is download.'
                except Exception:
                    print "Network Error: " + res['res']
            else:
                print threadName + res['name'] + ' file ' + res[
                    'res'] + ' is exist.'
            # 释放线程占用
            del self._threadsStatus[threadName]
            thread.exit_thread()
            time.sleep(2)
Exemple #17
0
 def updataCj(self):
     try:
         t=urllib2.urlopen('http://trade.taobao.com/trade/itemlist/list_bought_items.htm')
     except:
         pass
     t.close()
     thread.exit_thread()
Exemple #18
0
def repaint_repeat(ex, interval):
    while(True):
        ex.update()

        time.sleep(interval)

    thread.exit_thread()
Exemple #19
0
def ser_recv(connfd, cliaddr):
	while True:
		buf = connfd.recv(4096)
		print buf


	thread.exit_thread() 
Exemple #20
0
def funt(no,a):
    print no
    while True:
        a = a + 1
        print "Thread  no %d = %d \n" %(no, a)
        time.sleep(1)
    thread.exit_thread()                                                                                  
Exemple #21
0
def handle_unzip(filename, path, obj):
    cmd_str = "unzip -d " + path + " " + filename;
    print(cmd_str);
    ss = os.popen(cmd_str).read();
    obj.end_unzip(ss);
    thread.exit_thread();
    return;
Exemple #22
0
def handle_download(url, zip_name, obj):
    cmd_str = "wget -O " + zip_name + " " + url;
    print(cmd_str);
    ss = os.popen(cmd_str).read();
    obj.end_download(ss);
    thread.exit_thread();
    return;
Exemple #23
0
 def __block__execute__(self, sql):
     with self.connection.cursor(pymysql.cursors.DictCursor) as cursor:
         cursor.execute(sql)
         try:
             self.connection.commit()
         finally:
             thread.exit_thread()
Exemple #24
0
def do(id):
    global alive
    global finished,succeed

    aliveLock.acquire()
    alive += 1
    aliveLock.release()


    conn = httplib.HTTPConnection('tw.heuet.edu.cn:82')
    conn.request('HEAD', '/View.asp?id=%i' % id)
    res = conn.getresponse()

    fLock.acquire()
    if res.status == 200:
        succeed += 1
    else:
        lockP.acquire()
        print res.status
        print res.getheaders()
        lockP.release()
    finished += 1
    alive -= 1
    fLock.release()
    thread.exit_thread()
Exemple #25
0
def check_bypass(dump_file):
    """
    Get the file flags of domain core dump file and check it.
    """

    cmd1 = "lsof -w %s >/dev/null 2>&1" % dump_file
    while True:
        if os.path.exists(dump_file):
            if not os.system(cmd1):
                cmd2 = ("cat /proc/$(%s |awk '/libvirt_i/{print $2}')/fdinfo/1"
                        "|grep flags|awk '{print $NF}'" % cmd1)
                (status, output) = commands.getstatusoutput(cmd2)
                if status == 0:
                    if len(output):
                        logging.debug("The flags of dumped file: %s ", output)
                        file_flag = output[-5]
                        if check_flag(file_flag):
                            logging.info("Bypass file system cache "
                                         "successfully when dumping")
                        else:
                            raise error.TestFail("Bypass file system cache "
                                                 "fail when dumping")
                        break
                else:
                    logging.error("Fail to get the flags of dumped file")
                    return 1

    thread.exit_thread()
Exemple #26
0
def timer(no, interval):
    cnt = 0
    while cnt < 10:
        print 'Thread(%d) Time:%s/n' % (no, time.ctime())
        time.sleep(interval)
        cnt += 1
    thread.exit_thread()
Exemple #27
0
def simpleThdreadFun(interval):
    global g_nProcessed
    global g_nTotal
    while g_nTotal > g_nProcessed:
        time.sleep(interval)
        g_nProcessed += 1
    thread.exit_thread()
Exemple #28
0
        def dl(threadName, delay, res):

            # 取文件扩展名称
            def getFileExp(file):
                return '.' + file[-3:]

            # 当前所有线程总下载数
            self.allThreadNum += 1
            # 下载文件 至分类目录 并重新命名
            fileName = categoryName + '/' + res['name'] + getFileExp(
                res['res'])

            if not os.path.isfile(fileName):
                urllib.urlretrieve(res['res'], fileName)
                # 已下载的总文件数量
                self._fileNum += 1
                print threadName + res['name'] + ' file ' + res[
                    'res'] + ' is download.'
            else:
                print threadName + res['name'] + ' file ' + res[
                    'res'] + ' is exist.'
            # 释放线程占用
            del self._threadsStatus[threadName]
            thread.exit_thread()
            time.sleep(2)
Exemple #29
0
def update_dropbox_sharing_schedule(interval):
    '''
        a time task running in KMS server.
        as long as detect the expiration value has been reached, delete this file sharing record.
    '''
    Dropbox_time_format = '%a, %d %b %Y %H:%M:%S'
    url_to_delete = []
    db_handler = lite.connect("./SecureDropboxDB.db")
    db = db_handler.cursor()
    while True:
        print 'update sharing record'
        sql = "select url,expires from sharing_pool"
        res = db.execute(sql)
        for row in res:

            # convert time format and get the time stamp value.
            expire_time = time.mktime(time.strptime(row[1][:-6], Dropbox_time_format))
            current_time = time.time()
            if current_time >= expire_time:
                url_to_delete.append(row[0])

        #delete sharing record.
        for url in url_to_delete:
            sql = "delete from sharing_pool where url = '%s'" % url
            db.execute(sql)
        
        db_handler.commit()

        # time task, executed every 600 seconds.
        time.sleep(interval)
        
    thread.exit_thread()  
Exemple #30
0
def timer(threadNo,interval):
    cnt = 0
    while cnt<10:
        print 'Thread:%d Time: %s\n'%(threadNo, time.ctime())
        time.sleep(interval)
        cnt+=1
    thread.exit_thread()
Exemple #31
0
def DetectThread(args):
    urll = args[0]
    callbackFunc = args[1]
    urlstream = urllib.urlopen(urll)
    udata = urlstream.read()
    callbackFunc(udata)
    thread.exit_thread()
Exemple #32
0
def rsync():
    global isSyncing
    # global start
    # end=time.time()
    # if isSyncing or end-start<3:
    if isSyncing:
        thread.exit_thread()
        return
    isSyncing = True
    # start=end
    st = time.time()
    # out=os.popen(sys.path[0]+'/cwrsync.bat').readlines()
    # for line in out:
    #     print line
    p = Popen(sys.path[0] + '/cwrsync.bat ' + sys.argv[1],
              stdout=PIPE,
              stderr=subprocess.STDOUT)
    while True:
        line = p.stdout.readline()
        if not line:
            break
        print line.strip()
    isSyncing = False
    print '''=====================
    rsync finished in %s seconds!''' % int(time.time() - st)
    thread.exit_thread()
Exemple #33
0
    def _downLoad_lyric_thread(self, fromUser, toUser, text_content, wc_client):

        lyric = None
        song = ''

        if isinstance(text_content, tuple):
            song, artist_name = text_content
            lyrics = self.getLyricsBySongnameFromHttp(song, artist_name)
            if (len(lyrics) >= 1):
                lyric = lyrics[0]
        elif isinstance(text_content, Lyric):
            lyric = text_content
            song = lyric.song
        elif isinstance(text_content, unicode) or isinstance(text_content, str):
            reply_content = Custon_send_text_data_template % {'touser':fromUser, 'content':text_content}
            wc_client.message.custom.send.post(body=reply_content)
            thread.exit_thread()
            return

        if isinstance(song, unicode):
            song = song.encode('utf-8')

        if lyric:
            try:

                text_content = self._downLoad_lyricFromHttp(lyric)
            except Exception, e:
                text_content = '找不到歌曲:%s %s'%(song,artist_name) if artist_name \
                    else '找不到歌曲:%s'%song
def generate_thread(id, t):
    """
	TODO:FIXME: porting real generate interface
		call generate(app_name, app_logo, enables) instead
	"""
    # time.sleep(t)
    o = order.objects.get(id=id)
    if o is None:
        raise Exceptions('order %s be not found' % (id))
    else:
        if o.order_is_rebuild == True:
            o.order_status = 3
        else:
            o.order_status = 2
        # generator script
        web_path = '/static/output_path/' + str(id) + '.apk'
        abs_path = os.path.abspath('Phimpme' + web_path)
        from gen_script import generate

        print o.order_features
        generate(order_id=id,
                 output_path=abs_path,
                 app_name=o.order_appname,
                 app_logo=None,
                 enables=eval(o.order_features))

        o.order_output_file = web_path
        o.save()
    thread.exit_thread()
Exemple #35
0
def timer(no,interval):
    cnt = 0
    while cnt<10:
        print "thread:(%d) time %s\n"%(no,time.ctime())
        time.sleep(interval)
        cnt += 1
    thread.exit_thread()
Exemple #36
0
    def runJMeterJob(self, job_file):
        global flag_running
        flag_running = True
        jmeter_launcher = self.jmeterhome + "JMeterLauncher.bat"
        #[12/04/2015-Yanhong]need switch working directory to self.jmeterhome
        #otherwise exception in JMeterLauncher
        os.chdir(self.jmeterhome)
        cmd = 'call ' + jmeter_launcher + ' JOB "' + job_file +'"'
        self.runnerlogger.info(cmd)
        time.sleep(12)

        javahome = os.getenv("JAVA_HOME")
        java='\"'+javahome+"\\bin\\java.exe"+'\"'
        print java
        os.putenv("JM_LAUNCH", java)
        try:
            os.system(cmd)
        except:
            self.runnerlogger("Exception in run job: "+job_file)
            
        flag_running = False
        try:
            thread.exit_thread()
        except Exception, e:
            #self.runnerlogger("Exception in exit_thread. The thread may be already killed.")
            print "Exception in exit_thread: " + str(e)
Exemple #37
0
def timer01(no,interval):
	cnt  = 0
	while cnt<5:
		print('Thread:(%d) Time:%s\n' %(cnt,time.ctime()))
		time.sleep(interval)
		cnt += 1
	thread.exit_thread()
Exemple #38
0
def timer(no, interval):
    cnt = 0
    while cnt < 3:
        print 'Thread:(%d) Time:%s\n' % (no, time.ctime())
        time.sleep(interval)
        cnt += 1
    thread.exit_thread()
def DataHandle(mainframe, frame):
    from Command import DataHandleCmd

    _cmd = DataHandleCmd.DataHandleCmd(mainframe, *mainframe.getSamplingParams())
    _cmd.Excute()
    frame.Destroy()
    thread.exit_thread()
Exemple #40
0
def timer1s():
	gameinit()
	while True:
		roundinit()
		round()
		if data.gameover ==1:
			break
	thread.exit_thread() 
Exemple #41
0
def myTimer(name,num):
    global count
    while num>0:
        count+=1
        print "Thread:(%s)--(%d) Time:%s\n" %(name,count, time.ctime()) 
        num-=1
        time.sleep(1)
    thread.exit_thread()
Exemple #42
0
 def run(self):
     while self.flag:
         Watcher(file_dir=self.log_path,
                 time_skip=30,
                 sleep_time=10,
                 function=self.process).watch_dir()
         time.sleep(10)
     thread.exit_thread()
def timer(no, interval):
    while True:
        time.sleep(interval)
        print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
        for element in MyFactory.clients:
            print(element)  #在这里可以给每个客户端发送消息
            element.transport.getHandle().sendall('dddddddddddd')
    thread.exit_thread()
def Sampling(path,frame):  
    from VideoSampling import ExecuteFfmpeg 
    _efm = ExecuteFfmpeg.ExecuteFfmpeg(path)
    _efm.Run()
    _efm.WaitForProcess()
    frame.frame.getFrameNum()
    frame.Destroy()
    thread.exit_thread()  
Exemple #45
0
def timerTest(no, interval):
    print "timer thread start"
    while True:
        time.sleep(interval)
        print "runing"
        testFunc()

    thread.exit_thread()
Exemple #46
0
def sleeper(name, seconds, sss):
    memoryMonster[1] = 1000
    for i in range(100):
        print("PID: " + str(os.getpid()) + " " + str(i))
        time.sleep(seconds)
        
    print "Done sleeping"
    thread.exit_thread()
Exemple #47
0
 def timer(no, interval):
     cnt = 0
     while cnt<10:
         print 'Thread:(%d) Time:%s\n'%(no, time.ctime())
         #time.sleep(interval)
         cnt += 1
     # 线程的结束可以等待线程自然结束,也可以在线程函数中调用 thread.exit() 或 thread.exit_thread() 方法。
     thread.exit_thread()
Exemple #48
0
 def updataCj(self):
     try:
         t = urllib2.urlopen(
             'http://trade.taobao.com/trade/itemlist/list_bought_items.htm')
     except:
         pass
     t.close()
     thread.exit_thread()
Exemple #49
0
 def runAnimation(self):
     while not self.stopped:
         self.tb.planetMove()
         sleep(self.tb.tb.t)
         # in order to debug, i made the time faster
         # sleep(self.tb.tb.t)
     self.V()
     thread.exit_thread()
Exemple #50
0
 def recvGetlist(self, clientsock):
     userinfos = {}
     userinfos = {}
     for ips in self.userinfos.keys():
         user = self.userinfos[ips]
         userinfos[user] = ips
     self.sendMessageToAClient(clientsock, "onlineUserList",userinfos) 
     thread.exit_thread()
Exemple #51
0
def thread1_read_device():
    global fname1
    global fflg
    global fstmp
    ff1 = open(fname1, "r")
    while fflg:
      fstmp = ff1.readline()
    ff1.close()
    thread.exit_thread()
Exemple #52
0
 def timer(self, process, timeout):
     num = 0
     while process.poll() == None and num < timeout * 10:
         num += 1
         time.sleep(0.1)
     if process.poll() == None:
         #os.system("taskkill /T /F /PID %d"%process.pid)
         print "%d process timeout ,be killed!" % process.pid
     thread.exit_thread()