Exemple #1
0
 def engage(self):
     self.left_initial_distance = self.left_encoder.e.GetDistance()
     self.right_initial_distance = self.right_encoder.e.GetDistance()
     self.right_thread = threading.thread(target=self.run_right_drive_macro)
     self.left_thread = threading.thread(target=self.run_left_drive_macro)
     self.right_thread.start()
     self.left_thread.start()
Exemple #2
0
 def play(self):
     next="m1"
     step=self.dice[next]
     timer=getattr(self,"time")(step)
     print(next)
     test=getattr(self,next)
     thread(target=test).start()
     thread(target=timer).start()
    def __init__(self):
        """
        this __init__ function initializes all of the variables
        we want to keep track of in our class.
        We also use threading to decrease the processing power
        requirements of our script. We thread the readings from the ADC and
        the calculations for wind direction, wind speed, and water speed.
        """
        # in the MCP3008, we connect Pin 1 to the green wire from the wind
        # sensor, which measures direction
        self.wind_direction_channel = 0
        # we connect Pin 2 to the black wire from the wind sensor, which
        # measures wind speed
        self.wind_speed_channel = 1
        # we connect Pin 3 to the green wire from the water speed sensor, which
        # measures water speed
        self.water_speed_channel = 2

        # these are really the three outputs we want from this class: the wind
        # direction in degrees, wind speed, and water speed, in knots
        self.wind_direction = None
        self.wind_speed_knots = None
        self.water_speed_knots = None

        # degines and starts all our threads, decreasing processing power
        # needed from RPi
        wd_thread = thread(target=self.Convert_Degrees_Wind_Direction)
        ws_thread = thread(target=self.SensorFrequencyWind)
        was_thread = thread(target=self.SensorFrequencyWater)

        # this makes sure that when we stop running our script, our threads
        # also stop running
        wd_thread.isDaemon()
        ws_thread.isDaemon()
        was_thread.isDaemon()

        wd_thread.start()  # starts our threads
        ws_thread.start()
        was_thread.start()

        #used for debugging purposes, uncomment these and the if statements below 
        #to see the calculated values from the instrumentation
        # self.t0 = time.time()
        # self.t1 = time.time()
        # self.t2 = time.time()

        while True:
            # this gives the RPi some time to start processing and ensures that
            # our threads stay running even after __init__ function ended
            time.sleep(30)
            pass
    def __init__(self):
        self.macAddr = ""
        self.timeLimit = 1000000
        self.receiveQueue = q.Queue()
        self.transferQueue = q.Queue()
        self.lowerLayer = physicalLayer.PhysicalLayer()

        
        self.tr = True
        self.re = True
        trTh = thread(target=self.transferTh)
        reTh = thread(target=self.receiveTh)
        trTh.start()
        reTh.start()
Exemple #5
0
    def Execute(self, threaded=False):
        """
		ファイルオペレーションを実行。threaded=True にすると、バックグラウンドで実行される。
		この関数自体は、ファイルオペレーションが開始できたかどうかを帰すだけで、結果は通知しない。
		"""
        if not self.instructions:
            self.log.error("No instructions specified.")
            return False
        #end 命令がない
        if self.started:
            self.log.error("This operation is already started.")
            return False
        #end すでに実行した
        try:
            op = self.instructions["operation"]
        except KeyError:
            self.log.error(
                "operation is not specified in the given instructions.")
            return False
        #end キーがセットされてない
        op = op.lower()
        if threaded:
            self.thread = threading.thread(self._process)
        else:
            self._process()
        #end スレッドかそうじゃないか
        return True
Exemple #6
0
 def __init__(self, **params):
     from mn_wifi.mobility import mobility
     mobility.thread_ = thread(name='vanet', target=self.start,
                               kwargs=dict(params,))
     mobility.thread_.daemon = True
     mobility.thread_._keep_alive = True
     mobility.thread_.start()
Exemple #7
0
 def __init__(self, net, nodes=None):
     self.net = net
     Mobility.thread_ = thread(name='replayingMobility', target=self.mobility,
                               args=(nodes,))
     Mobility.thread_.daemon = True
     Mobility.thread_._keep_alive = True
     Mobility.thread_.start()
 def __init__(self, Mininet_wifi, nodes=None):
     mobility.thread_ = thread(name='replayingMobility',
                                    target=self.mobility,
                                    args=(nodes,Mininet_wifi,))
     mobility.thread_.daemon = True
     mobility.thread_._keep_alive = True
     mobility.thread_.start()
    def __init__(self, Mininet_wifi, **kwargs):

        mobility.thread = thread( name='replayingNetConditions',
                                        target=self.behavior, args=(Mininet_wifi,) )
        mobility.thread.daemon = True
        mobility.thread_._keep_alive = True
        mobility.thread.start()
Exemple #10
0
 def __init__(self, **params):
     from mn_iot.mac80211.mobility import mobility
     mobility.thread_ = thread(name='vanet', target=self.start,
                               kwargs=dict(params,))
     mobility.thread_.daemon = True
     mobility.thread_._keep_alive = True
     mobility.thread_.start()
Exemple #11
0
def server_loop(local_host, local_port, remote_host, remote_port,
                receive_first):
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    try:
        server.bind((local_host, local_port))
    except:
        print "[!!] Failed to listen on %s:%d" % (local_host, local_port)
        print "[!!] Check for other listening sockets or correct permissions."
        sys.exit(0)

    print "[*] Listening on %s:%d" % (local_host, local_port)

    server.listen(5)

    while True:
        client_socket, addr = server.accept()

        # print out local connection information
        print "[==>] Received incoming connection from %s:%d" % (addr[0],
                                                                 addr[1])

        # start a thread to talk to the remote host
        proxy_thread = threading.thread(target=proxy_handler,
                                        args=(client_socket, remote_host,
                                              remote_port, receive_first))
        proxy_thread.start()
Exemple #12
0
 def __init__(self, net):
     self.net = net
     Mobility.thread_ = thread(name='replayingBandwidth',
                               target=self.throughput)
     Mobility.thread_.daemon = True
     Mobility.thread_._keep_alive = True
     Mobility.thread_.start()
Exemple #13
0
 def __init__(self, net, **kwargs):
     self.net = net
     Mobility.thread_ = thread(name='replayingNetConditions',
                               target=self.behavior)
     Mobility.thread_.daemon = True
     Mobility.thread_._keep_alive = True
     Mobility.thread_.start()
Exemple #14
0
 def __init__(self, **kwargs):
     from mn_wifi.mobility import mobility
     mobility.thread_ = thread(name='vanet', target=self.start,
                               kwargs=kwargs)
     mobility.thread_.daemon = True
     mobility.thread_._keep_alive = True
     mobility.thread_.start()
Exemple #15
0
 def __init__(self, Mininet_wifi, nodes=None):
     mobility.thread_ = thread(name='replayingMobility',
                                    target=self.mobility,
                                    args=(nodes,Mininet_wifi,))
     mobility.thread_.daemon = True
     mobility.thread_._keep_alive = True
     mobility.thread_.start()
Exemple #16
0
    def __init__(self, Mininet_wifi, **kwargs):

        mobility.thread_ = thread( name='replayingNetConditions',
                                        target=self.behavior, args=(Mininet_wifi,) )
        mobility.thread_.daemon = True
        mobility.thread_._keep_alive = True
        mobility.thread_.start()
Exemple #17
0
 def __init__(self, Mininet_wifi):
     mobility.thread_ = thread(name='replayingBandwidth',
                               target=self.throughput,
                               args=(Mininet_wifi, ))
     mobility.thread_.daemon = True
     mobility.thread_._keep_alive = True
     mobility.thread_.start()
Exemple #18
0
    def __init__(self, s1, s2, nome):
        self.s1 = s1
        self.s2 = s2

        self.nome = nome

        # prepara instancias para os leds

        # coloca os sensores como input
        GP.setup(s1, GP.IN)
        GP.setup(s2, GP.IN)

        # carrega o estado do semaforo

        semaforos.append(self)

        thread(None, self.sensores, None, (0, 0)).start()
Exemple #19
0
 def __init__(self, **kwargs):
     kwargs['nodes'] = kwargs['cars']
     Mobility.thread_ = thread(name='vanet',
                               target=self.start,
                               kwargs=kwargs)
     Mobility.thread_.daemon = True
     Mobility.thread_._keep_alive = True
     Mobility.thread_.start()
 def run(self):
     while self.running:
         (sockconn, peer) = self.s.accept()
         if self.running:
             conn = socks5connection(self, sockconn, peer)
             thread = threading.thread(none, conn.handle)
             thread.daemon = true
             thread.start()
Exemple #21
0
 def __init__(self, cars, aps, **kwargs):
     mobility.thread_ = thread(name='vanet',
                               target=self.configureApp,
                               args=(cars, aps),
                               kwargs=dict(kwargs, ))
     mobility.thread_.daemon = True
     mobility.thread_._keep_alive = True
     mobility.thread_.start()
 def enterMatchMode(self):
     self.inMatch = True
     self.matchReadyStart = True
     
     self.matchPaused = True
     joy.end = False
     self.t = threading.thread(target = joy.run(self.matchPaused, self.matchEnded))
     self.t.start()
Exemple #23
0
 def on_scheduled_start(self, source, identifier):
     """Starts a scheduled recording, replacing the mediapackage in use"""
     logger.info("Scheduled Start")
     self.conf.reload()
     self.current_mediapackage = identifier
     self.scheduled_recording = True
     a = thread(target=self.start_thread, args=(identifier, ))
     a.daemon = False
     a.start()
Exemple #24
0
 def on_scheduled_start(self, source, identifier):
     """Starts a scheduled recording, replacing the mediapackage in use"""
     logger.info("Scheduled Start")
     self.conf.reload()
     self.current_mediapackage = identifier
     self.scheduled_recording = True
     a = thread(target=self.start_thread, args=(identifier,))
     a.daemon = False
     a.start()
Exemple #25
0
def start():
	print "starting say thread"
	sayqueue = Queue()
	sayer = thread(target = sayer_thread, args = (sayqueue,))
	sayer.start()
	
	# print "got captions: %s" % captions
	for caption in captions:
		queue.put(caption)
Exemple #26
0
    def __init__(self, net, ppm='friis', n=32, **kwargs):
        self.net = net
        for key in kwargs:
            setattr(self, key, kwargs[key])

        Mobility.thread_ = thread(name='replayingRSSI', target=self.rssi,
                              args=(ppm, n))
        Mobility.thread_.daemon = True
        Mobility.thread_._keep_alive = True
        Mobility.thread_.start()
    def resume_instance_status(self,context,server_id,volume_dir,action_sign,slp_time,chk_pices):
        self.ctxt=context
        t=threading.thread(target=self._trd_func_for_resume,args=(server_id,volume_dir,action_sign,slp_time,chk_pices))
        t.setDaemon(False)
        t.start()
        
        
        

                    
Exemple #28
0
 def execute_cmd(self):
     os.system("clear")
     a = thread(target=pydl.InfoGather.file_loop_check())
     print ""
     if a == 0:
          print "Command executed correctly"
     else:
          print "Command terminated with error"
     raw_input("Press enter")
     print ""
Exemple #29
0
def main():
    if len(sys.argv < 2):
        print("[-] Pass zipfile and dictionary")
    else:
        zfile = zipfile.ZipFile(sys.argv[1], "r")
        hash_dict = open(sys.argv[2], 'r')
        for password in hash_dict:
            password = word.strip('\n')
            t = thread(target=extractFile, args=(zfile, password))        extractFile(zfile, hash_dict)
        print("[-] Incorrect password list")
Exemple #30
0
 def echoServ(self):
     dead = [
         thread(target=self.echo, args=(i, )) for i in range(self.numol)
     ]
     lastdead = [0 for i in range(len(dead))]
     for pl, i in enumerate(dead):
         i.start()
         print('live', pl)
     while 1:
         for pl, i in enumerate(dead):
             if not i.is_alive() and lastdead[pl]:
                 print('dead', pl)
                 dead[pl] = thread(target=self.echo, args=(pl, ))
                 dead[pl].start()
                 print('live', pl)
                 lastdead[pl] = False
                 time.sleep(1)
             else:
                 lastdead[pl] = True
         time.sleep(0.1)
    def __init__(self):
        self.navAGM = tc.NavioCompass()

        #starts thread
        tilt_thread = thread(target=self.navAGM.runcompass)

        #makes thread stop running when script does
        tilt_thread.isDaemon()

        #starts thread
        tilt_thread.start()
Exemple #32
0
    def __init__(self, Mininet_wifi, propagationModel='friis', n=32, **kwargs):
        """ propagationModel = Propagation Model
            n: Power Loss Coefficient """
        for key in kwargs:
            setattr(self, key, kwargs[key])

        mobility.thread_ = thread(name='replayingRSSI',
                                  target=self.rssi,
                                  args=(Mininet_wifi, propagationModel, n))
        mobility.thread_.daemon = True
        mobility.thread_._keep_alive = True
        mobility.thread_.start()
    def __init__(self, mininet, propagationModel='friis',
                 n=32, **kwargs):
        """ propagationModel = Propagation Model
            n: Power Loss Coefficient """
        for key in kwargs:
            setattr(self, key, kwargs[key])

        mobility.thread = thread(name='replayingRSSI', target=self.rssi,
                                       args=(Mininet_wifi, propagationModel, n))
        mobility.thread.daemon = True
        mobility.thread_._keep_alive = True
        mobility.thread.start()
Exemple #34
0
 def thresholdWork(self,flag):
     if len(self.thresholdJob)!=0:
         try:
             thresh = self.thresholdJob.pop(0)
             size,image_points=threshold(thres)
             self.projectionJob.append((size,image_points))
             t = threading.thread(target=self.projectionWork, args=(True,))
             t.start()
         except Exception as nfe:
             print(nfe)
             time.sleep(5)
             exit()
    def authentication(self, conn, addr):
        """
        authentication here
        :param ip: str
        :return: None
        """
        try:
            data = conn.recv(16)
            name = str(data.decode())
            if not name:
                raise Exception("No name received")

            conn.sendall("1".encode())

            player = Player(addr, name)
            self.handle_queue(player)
            threading.thread(targets=self.player_thread, args=(conn, player))

        except Exception as e:
            print("[EXCEPTION] ", e)
            conn.close()
def main(path, numthreads, download_root):
    global progress
    global all_
    global already_downloaded
    global miss
    path = os.path.normpath(path)
    path = os.path.abspath(path)
    if not os.path.isdir(path):
        print('Path is not correct!')
        return -1

    files = [fp for fp in glob.glob(os.path.join(path, '*.txt'))]

    for file in sorted(files):
        filename = os.path.basename(file)
        print('Download form', filename)
        name = filename[:filename.rfind('.')]
        with open(file) as file_urls:
            urls = [url[:-1] for url in file_urls]
        name = name.replace(' ', '_')
        dpath = os.path.join(download_root, name)
        os.makedirs(dpath, exist_ok=True)
        fn_template = os.path.join(dpath, name) + '_{0}.{1}'

        dict_urls = { url: len(urls) - i for i, url in enumerate(urls[::-1], 1) }
        urls = [key_val[::-1] for key_val in dict_urls.items()]

        open(fn_template.format('downloaded', 'txt'), 'a').close()

        downloaded = []
        with open(fn_template.format('downloaded', 'txt')) as dfile:
            for line in dfile:
                info = line[:-1].split('\t')
                downloaded.append((int(info[0]), info[1]))

        already_downloaded = open(fn_template.format('downloaded', 'txt'), 'a')

        urls = list(set(urls) - set(downloaded))
        urls.sort(key=lambda x: x[0])
        progress, miss, all_ = 0, 0, len(urls)

        step = round(len(urls) / numthreads)
        if step == 0: continue
        ranges = [(a, a + step) for a in range(0, len(urls), step)]
        threads = []
        for i, (a, b) in enumerate(ranges):
            arg = (i, urls[a:b], fn_template)
            t = thread(target=download_process, args=arg)
            threads.append(t)
            t.start()
        for t in threads: t.join()
        already_downloaded.close()
Exemple #37
0
def server_loop():
    global target
    if not len(target):
        target = "0.0.0.0"
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.bind(target, port)
    server.listen(5)

    while True:
        client_socket, addr = server.accept()
        client_thread = threading.thread(target=client_hendelr,
                                         args=(client_socket, ))
        client_thread.start()
Exemple #38
0
def main():
    while True:
        try:
            accounts = json.loads(
                Path('accounts.json').read_text(encoding='utf-8'))['ready']
            for account in accounts:
                print('start: account {}'.format(account['id']))

                proxies = {
                    'http': 'http://{}'.format(account['proxy']),
                    'https': 'https://{}'.format(account['proxy'])
                }

                thread(target=way,
                       args=(account['access_token'], proxies)).start()
                time.sleep(3)

            output(accounts)

        except:
            print('BIG ERROR')
            time.sleep(5)
Exemple #39
0
 def upload(self):
     while True:
         for file in [
                 file for file in os.listdir(settings.dir_ready) if file.endswith('.warc.gz')
                     and not os.path.isfile(os.path.join(settings.dir_ready, file+'.upload'))]:
             while not settings.upload_running:
                 time.sleep(1)
             time.sleep(1)
             if concurrent_uploads > settings.max_concurrent_uploads or not self.upload_allowed():
                 time.sleep(10)
             concurrent_uploads += 1
             open(os.path.join(settings.dir_ready, file+'.upload'), 'a').close()
             date = re.search(r'([0-9]{4}-[0-9]{2}-[0-9]{2})', file).group(1)
             if not file in self.uploads:
                 self.uploads[file] = {}
                 self.uploads[file]['date'] = date.replace('-', '')
                 self.uploads[file]['size'] = os.path.getsize(file)
                 if not self.uploads[file]['date'] in self.items:
                     self.items[self.uploads[file]['date']] = {}
                     self.items[self.uploads[file]['date']]['item_num'] = 0
                     self.items[self.uploads[file]['date']]['item_size'] = 0
                 elif self.items[self.uploads[file]['date']]['item_size'] > self.max_item_size:
                     self.items[self.uploads[file]['date']]['item_num'] += 1
                     self.items[self.uploads[file]['date']]['item_size'] = 0
                 self.items[self.uploads[file]['date']]['item_size'] += self.uploads[file]['size']
                 self.uploads[file]['item_num'] = self.items[self.uploads[file]['date']]['item_num']
                 self.uploads[file]['item_size'] = self.items[self.uploads[file]['date']]['item_size']
             name = self.uploads[file]['date']+str(self.uploads[file]['item_num']).zfill(4)
             ia_args = {'title': 'Archive Team Newsgrab: {name}'.format(name=name),
                        'mediatype': 'web',
                        'description': 'A collection of news articles grabbed from a wide variety of sources around the world automatically by Archive Team scripts.',
                        'collection': 'archiveteam_newssites',
                        'date': date}
             threading.thread(target=self.upload_single, args=(name, file, ia_args)).start()
             concurrent_uploads -= 1
             os.remove(os.path.join(settings.dir_ready, file+'.upload'))
             if os.path.isfile(os.path.join(settings.dir_ready, file)):
                 settings.irc_bot.send('PRIVMSG', '{name} uploaded unsuccessful.'.format(
                         name=file), settings.irc_channel_bot)
Exemple #40
0
 def on_rec(self,button=None): 
     """Manual Recording """
     logger.info("Recording")
     self.dispatcher.emit("starting-record")
     self.recorder.record()
     self.mediapackage.status=mediapackage.RECORDING
     self.mediapackage.setDate(datetime.datetime.utcnow().replace(microsecond = 0))
     self.timer_thread_id = 1
     self.timer_thread = thread(target=self.timer_launch_thread) 
     self.timer_thread.daemon = True
     self.timer_thread.start()
     self.change_state(GC_RECORDING)
     return True  
Exemple #41
0
def main():
    sys.meta_path = [gitimporter()]

    while true:
        if task_queue.empty():
            config = get_trojan_config()

            for task in config:
                t = threading.thread(target=module_runner, args=(task['module'],))
                t.start()
                time.sleep(random.randint(1, 10))


        time.sleep(random.randint(1000, 100000))
def dubBuffer(format1, channels1, rate1, input1):
    global wavStream
    global wavStreamOpen
    tWrBuff1 = threading.thread(target=writeBuf1, args=10)
    tWrBuff2 = threading.thread(target=writeBuf2, args=10)
    # change foo to desired function for both funs
    tMdBuff1 = threading.thread(target=foo, args=10)
    tMdBuff2 = threading.thread(target=foo, args=10)
    while wavStream.is_active():
        # writing to buffer2 and modifying and playing buffer1 at the same time
        tWrBuff2.start()
        tMdBuff1.start()
        tWrBuff2.join()
        tMdBuff1.join()

        # writing to buffer1 and modifying and playing buffer2 at the same time
        tWrBuff1.start()
        tMdBuff2.start()
        tWrBuff1.join()
        tMdBuff2.join()
    # when stream is done terminate
    wavStream.close()
    wavStreamOpen.terminate()
    def __init__(self, port, baud, verbose=True):
        self.verbose = verbose

        self.vprint("Connecting...")
        self.mav = mavutil.mavlink_connection(port, baud, autoreconnect=True)
        self.vprint("Waiting for first heartbeat")
        self.mav.wait_heartbeat()

        self.modes = self.mav.mode_mapping()
        self.lastSentHeartbeat = time.time()

        self.vprint("Starting message handler thread")
        T = threading.thread(Target=self.mavMsgHandler, args=(self.mav, ))
        T.start()
Exemple #44
0
    def sensores(self, *args):
        # sensores ficam lendo infinitamente
        while True:
            s1 = not GP.input(self.s1)
            s2 = not GP.input(self.s2)

            if s1:
                if semaforos[not self.nome].estado == fechado:
                    self.abrirCuidado()
                else:
                    fecha = thread(None, self.fechar, None, (base, 0))
                    fecha.start()

                sleep(1)
    def __init__(self):
        self.WaterSpeedMPH = 0 #Initializes variables for program
        self.WaterSpeed = 0
        self.WindSpeedMPH = 0
        self.WindSpeed = 0
        self.SerialInfo = ''
        self.SampleRate = 0.005 #The rate at which samples are being taken.  This rate appeared to be the slowest reliable rate to free up processor room and not drop samples
        self.SampleLength = .5
        self.freq = 0
        self.freqW = 0
        self.lastSig = 0
        self.lastSignal = 0

        self.WaterSensor = True #Creating the Threads which each sensor runs on
        self.WindSensor = True
        self.WindDirection = True
        WaterSensorTh = thread(target=self.frequencyToSpeedWater)
        WindSensorTh = thread(target=self.frequencyToSpeedWind)
        WindDirectionTh = thread(target=self.Wind_Direction)
        WaterSensorTh.isDaemon()
        WindSensorTh.isDaemon()
        WindDirectionTh.isDaemon()
        WaterSensorTh.start() #starting them
        WindSensorTh.start()
        WindDirectionTh.start()
        
        while True:
            sleep(1)
            WaterData = (' Word Water Speed: ' + str('%.2f' % self.WaterSpeedMPH) +' mph (' + str('%.2f' % self.WaterSpeed) + ' knots)')#sets up the data in the appropriate form
            WindData = ('Wind Speed: ' + str('%.2f' % self.WindSpeedMPH) + ' mph (' + str('%.2f' % self.WindSpeed) + ' knots)') #sets up the data in the appropriate form
            with open('/home/pi/Sailing_Team/Data/WaterData.txt', "w") as file: #opens the file and clears it
                file.write("{}\n".format(json.dumps(WaterData))) #writes the new data
            with open('/home/pi/Sailing_Team/Data/WindData.txt', 'w') as file:
                file.write("{}\n".format(json.dumps(WindData)))
            with open('/home/pi/Sailing_Team/Data/WindDirection.txt', 'w') as file:
                file.write("{}\n".format(json.dumps(self.SerialInfo)))
Exemple #46
0
 def on_rec(self, button=None):
     """Manual Recording """
     logger.info("Recording")
     self.dispatcher.emit("starting-record")
     self.record.record()
     self.mediapackage.status = mediapackage.RECORDING
     self.mediapackage.setDate(
         datetime.datetime.utcnow().replace(microsecond=0))
     self.clock = self.record.get_clock()
     self.timer_thread_id = 1
     self.timer_thread = thread(target=self.timer_launch_thread)
     self.timer_thread.daemon = True
     self.timer_thread.start()
     self.change_state(GC_RECORDING)
     return True
Exemple #47
0
def main(args):
	""" subvertle: the master operations block """
		
	init_settings(args)
	queue = Queue()

	# try:
	if True:
		# source is our media source.  
		# should contain captions and an RTSP video URL.
		#  - source.captions: list of caption events
		#  - source.rtspUrl:  string URL of RTSP stream
		print " - fetching feed information"
		source = iplayerlib.fetch(settings.url)
		translator = translate(settings.dialect,settings.dialectOptions)
		# mood = moodmeter()
		# stream = streamer()

		print " - processing captions (%d)" % len(source.captions)
		for caption in source.captions:
			# skip translation for now
			caption.translated = translator.process(caption.text)
			# caption.translated = caption.text
			# print caption.text
			# print " -> %s" % caption.translated
			# caption.mood = mood.process(caption.text)

		print " - initialising audio"
		swmixer.init(samplerate = 44100, chunksize = 1024)
		swmixer.start()

		print " - starting speech generator thread"
		settings.cachedir = settings.cachedir % source.id
		# should really handle fail here
		if not os.path.exists(settings.cachedir):
			os.mkdir(settings.cachedir)

		# generator = thread(target = generate_thread, args = (settings, source.captions, queue))
		# generator.start()

		# print " - buffering (%ds)" % settings.buffertime
		# time.sleep(settings.buffertime)

		sayqueue = Queue()
		sayer = thread(target = sayer_thread, args = (sayqueue,))
		sayer.start()
def server_loop():
    global target
    
    # if there is no target, listen on all interfaces
    if not len(target):
        target = "0.0.0.0"
        
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.bind((target,port))
    server.listen(5)
    
    while True:
        client_socket, addr = server.accept()
        
        # Start a new thread for each client
        client_thread = threading.thread(target=client_handler, args=(client_socket,))
        client_thread.start()
Exemple #49
0
    def on_rec(self,button=None, pre_filled=False): 
        """Manual Recording """
        logger.info("Recording")
        self.dispatcher.emit("starting-record")
        self.recorder.record()
        self.mediapackage.status=mediapackage.RECORDING
        now = datetime.datetime.utcnow().replace(microsecond=0)
        self.mediapackage.setDate(now)

        if self.mediapackage.manual and not pre_filled:
            self.mediapackage.setTitle(_("Recording started at {0}").format(now.isoformat()))

        self.timer_thread_id = 1
        self.timer_thread = thread(target=self.timer_launch_thread) 
        self.timer_thread.daemon = True
        self.timer_thread.start()
        self.change_state(GC_RECORDING)
        context.get_state().is_recording = True
        return True  
Exemple #50
0
    def __init__(self, address):

        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.connect((address, 1024))

        iThread = threading.thread(target=self.sendMsg, args=(sock, ))
        iThread.daemon = True
        iThread.start()

        while True:
            data = sock.recvfrom(1024)
            if not data:
                break
            if data[0:1] == b'\x11':
                self.updatePeers(data[1:])

            else:
                print(str(data, 'utf-8'))
 def chat():
     #开启子线程,获取服务端推送的信息
     pushClient_t = threading.thread(target = pushClient, args = {})
     pushClient_t.setDaemon(True)
     pushClient_t.start()
     pushClient_t.join()
     
     #登录
     if login():
         #在线用户
         getOnlineUsers           
         
         toChatUserName = raw_input("请输入你要聊天的用户名:")
         
         if toChatUserName:
             toContent = raw_input("请输入聊天内容:")
             if toContent:
                 msg = {"command": "IMByServer", "data": {"tochatusername": toChatUserName, 'tocontent': toContent}}
                 recvData = sendMessage(msg = msg, type = 'mainChat')
                 
             
     else:
         help()
Exemple #52
0
for i, active_obj in enumerate(can_objects):
    data = active_obj.status()
    data["time"] = datetime.datetime.now().isoformat()
    json.dump(data, open(can_files[i], "w"))

# mysql setup
engine = sqla.create_engine(serveraddr, pool_recycle=3600)
dbstorage.Base.metadata.create_all(engine)
session_init = sessionmaker(bind=engine)
session = session_init()

COMMIT_RATE = 60

msg_queue = queue.Queue()

threading.thread(target=mysql_worker, args=(session, msg_queue))
while 1:
    msg = bus.recv()
    for i, active_obj in enumerate(can_objects):
        if msg.arbitration_id in active_obj.can_range:
            # Get a copy of old data, update and count changes
            old_data = active_obj.status()
            active_obj.parse_can_msg(msg.arbitration_id, msg.data)
            data = active_obj.status()
            data["time"] = datetime.datetime.now().isoformat()
            changed = {}
            for key in old_data:
                # only log updated values, saves space.
                # SQLalchemy needs to be explicitly told a key is NULL
                if data[key] == old_data[key]:
                    changed[key] = None
Exemple #53
0
 def _notify(self, **kwargs):
     thread(target=balloon_tip, kwargs=kwargs).start()
Exemple #54
0
    def __init__(self, package=None): 
  
        logger.info("Creating Recording Area")
        gtk.Box.__init__(self)
	builder = gtk.Builder()
        builder.add_from_file(get_ui_path('recorder.glade'))
       
        self.repo = context.get_repository()
        self.dispatcher = context.get_dispatcher()
        self.worker = context.get_worker()
        self.recorder = None
        self.current_mediapackage = None
        self.current = None
        self.next = None
        self.restarting = False
        self.font = None
        self.scheduled_recording = False
        self.focus_is_active = False
        self.net_activity = None

        self.error_id = None
        self.error_text = None
        self.error_dialog = None
        self.ok_to_show = False
        self.swap_active = None
        self.swap = False

        # BUILD
        self.recorderui = builder.get_object("recorderbox")
        self.main_area = builder.get_object("videobox")
        self.vubox = builder.get_object("vubox")
        self.gui = builder

        # BIG STATUS
        big_status = builder.get_object("bg_status")
        self.view = self.set_status_view()
        big_status.add(self.view)

        # STATUS BAR
        self.statusbar=status_bar.StatusBarClass()
        self.dispatcher.connect("update-rec-status", self.statusbar.SetStatus)
        self.dispatcher.connect("update-video", self.statusbar.SetVideo)
        self.dispatcher.connect("galicaster-init", self.check_status_area)
        self.dispatcher.connect("galicaster-init", self.check_net)
        self.dispatcher.connect("restart-preview", self.check_status_area)
        self.dispatcher.connect("net-up", self.check_net, True)        
        self.dispatcher.connect("net-down", self.check_net, False)        
        self.statusbar.SetTimer(0)

        # VUMETER
        self.audiobar=Vumeter()

        # UI
        self.vubox.add(self.audiobar)
        self.pack_start(self.recorderui,True,True,0)

        # Event Manager       
        self.dispatcher.connect("start-record", self.on_scheduled_start)
        self.dispatcher.connect("stop-record", self.on_stop)
        self.dispatcher.connect("start-before", self.on_start_before)
        self.dispatcher.connect("restart-preview", self.on_restart_preview)
        self.dispatcher.connect("update-rec-vumeter", self.audiobar.SetVumeter)
        self.dispatcher.connect("galicaster-status", self.event_change_mode)
        self.dispatcher.connect("galicaster-notify-quit", self.close)

        nb=builder.get_object("data_panel")
        pages = nb.get_n_pages()        
        for index in range(pages):
            page=nb.get_nth_page(index)
            nb.set_tab_label_packing(page, True, True,gtk.PACK_START)

        # STATES
        self.status = GC_INIT
        self.previous = None
        self.change_state(GC_INIT)

        self.dispatcher.connect("reload-profile", self.on_recover_from_error)

        # PERMISSIONS
        self.conf = context.get_conf()
        self.allow_pause = self.conf.get_permission("pause")
        self.allow_start = self.conf.get_permission("start")
        self.allow_stop = self.conf.get_permission("stop")
        self.allow_manual = self.conf.get_permission("manual")
        self.allow_overlap = self.conf.get_permission("overlap")
     
        # OTHER
        builder.connect_signals(self)
        self.net_activity = self.conf.get_boolean('ingest', 'active')

        self.change_state(GC_READY)

        self.proportion = 1
        self.on_start()

        # SCHEDULER FEEDBACK
        self.scheduler_thread_id = 1
        self.clock_thread_id = 1
        self.start_thread_id = None

        self.scheduler_thread = thread(target=self.scheduler_launch_thread)
        self.clock_thread = thread(target=self.clock_launch_thread)
        self.scheduler_thread.daemon = True
        self.clock_thread.daemon = True
        self.scheduler_thread.start()
        self.clock_thread.start() 
        self.dispatcher.emit("galicaster-init")

        # SHOW OR HIDE SWAP BUTTON
        if self.conf.get_boolean('basic', 'swapvideos'):
            self.swap_active = True
        else:
            self.swap_active = False
Exemple #55
0
def main():
    http = threading.thread(StartHttpServer)
    https = threading.thread(StartHttpsServer)
    http.start()
    https.start()
    http.join()
Exemple #56
0
 def __init__( self, cars, aps, **kwargs ):
     mobility.thread_ = thread(name='vanet', target=self.configureApp,
                               args=(cars, aps), kwargs=dict(kwargs,))
     mobility.thread_.daemon = True
     mobility.thread_._keep_alive = True
     mobility.thread_.start()
 def start(self):
     try:
         logger.info("start location_track_system")
         
         self.serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
         #设置端口重用    修正  Address Already In Use 错误   参考http://www.2cto.com/kf/201208/150347.html
         self.serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
         self.serversocket.setblocking(False)
         self.serversocket.bind(('0.0.0.0', const.bindPort))
         self.serversocket.listen(const.listenNum)
         
         #开启子进程
         global g_subUnix
         g_subUnix = self.subUnix = subprocess.Popen('python subUnix.py', stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)
         
         #开启子线程 推送消息  tcp
         pushServer_t = threading.thread(target = push_server.PushServer.push2Client, args = {})
         pushSerer_t.setDaemon(True)
         pushServer_t.start()
         #开启子线程  p2p  chat udp
         p2pChat_t = threading.thread(target = p2p_chat.P2pChat.start, args = {})
         p2pChat_t.setDaemon(True)
         p2pChat_t.start()
         
         
         self.epoll = select.epoll()
         
         self.epoll.register(self.serversocket.fileno(), select.EPOLLIN)
         
        
         while True:
             #epoll监听事件, 1秒没有事件退出
             self.epoll_list = self.epoll.poll(1)
             
             for fd,events in self.epoll_list:
                 if fd == self.serversocket.fileno():
                     conn,addr = self.serversocket.accept()
                     logger.info("客户端请求:fileno " + str(conn.fileno()) + ", address " + addr[0] + ":" + str(addr[1]))
                     self.connections[conn.fileno()] = conn
                     self.addresses[conn.fileno()] = addr
                     self.threads[conn.fileno()] = busProcess(self, conn, addr)
                     #true 主线程关闭时,会kill子线程   false等子线程关闭时,才关闭  就算按ctrl + c 也不能关闭主线程
                     self.threads[conn.fileno()].setDaemon(True)
                     self.threads[conn.fileno()].start()
                 #长连接  读    
                 elif select.EPOLLIN & events:
                     self.threads[fd] = busProcess(self, self.connections[fd], self.addresses[fd])
                     self.threads[fd].setDaemon(True)
                     self.threads[fd].start()
                 #有中断时    
                 elif select.EPOLLHUP & events:
                     fd.unregister(fd)
                     self.connections[fd].close()
                     
                     del self.connections[fd]
                     del self.addresses[fd]
                     del self.threads[fd]
                     
                     
                     
                 
             
     except KeyboardInterrupt:
         print sys.exc_info()[:1]
     except Exception,e:
         print traceback.format_exc()
			#sys.exit()
		
		finally :
			sock.close()

		try :
			if recieved == "EMPTY" or recieved == "INVALID":
				msgbox = QMessageBox()
				msgbox.setText("Authentication Failure")
				msgbox.exec_()
				sys.exit()

			else :
				mchat = MainWindow()
				mchat.exec_()
				threading.thread(target=mchat.RecievingMessages, args=(self.uname,)).start()
				self.layout.setVisible(False)
		except Exception, f:
			msgbox = QMessageBox()
			msgbox.setText(str(f))
			msgbox.exec_()

	
		
	def Close(self):
			
		""" Code for Exit Button """

		test = QMessageBox.question(self, 'Message', "Are you sure to quit?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
		if test == QMessageBox.StandardButton.Yes:
			sys.exit()
Exemple #59
0
 def setWifiParameters(cls, mobility):
     from threading import Thread as thread
     thread = thread(name='wifiParameters', target=mobility.parameters)
     thread.start()