Beispiel #1
0
def print_time(no,interval):
    cnt = 0
    while cnt<10:
        print("Thread:(%d) Time :%s\n"%(no,time.ctime()))
        time.sleep(interval)
        cnt+=1
    _thread.exit()
Beispiel #2
0
 def insert_info(self,info):
     self.txtInfo.insert(END,info)
     self.txtInfo.see(END)
     if self.thread_exit_flag == True:
         self.txtInfo.insert(END,'停止小爬爬成功!!!\n')
         self.txtInfo.see(END)
         _thread.exit()
Beispiel #3
0
def child():
	global exitstat
	exitstat += 1
	threadid = _thread.get_ident()
	print('Hello from child', threadid, exitstat)
	_thread.exit()
	print('never reached')
def child():
    global exitstat                               # process global names
    exitstat += 1                                 # shared by all threads
    threadid = thread.get_ident()
    print('Hello from child', threadid, exitstat)
    thread.exit()
    print('never reached')
Beispiel #5
0
def Read(s):
  while Flag:
    try:
      rdata = s.recv(1024)
      print("Recd: %s" %rdata.strip().decode('utf'))
    except Exception:
      _thread.exit()
Beispiel #6
0
def print_time(threadName,delay,counter):
        while counter:
            if exitFlag:
                _thread.exit()
            time.sleep(delay)
            print ("%s,%s" % threadName,time.ctime(time.time()))
            counter -= 1
Beispiel #7
0
def get_parser(url):
    for key in PARSERS.keys():
        if key in url:
            parser = importlib.import_module("parsers.{}".format(PARSERS[key]))
            return parser.parse, parser.parse_ch1
    progress_queue.put((None, "No parser found for {}".format(repr(url))))
    _thread.exit()
Beispiel #8
0
def stop_all_threads():
    ''' NOT WORKING

        Stop all threads.

        Avoid "Exception ... (most likely raised during interpreter shutdown)".

        When the python interpreter exits, it clears globals before it stops
        threads. That causes running threads die very messily. This is a
        security risk. Call stop_all_threads() at the end of your program,
        and before any call to sys.exit() or os._exit().

        Calling thread.exit() is usually a bad idea, but it's ok in this case
        because the threads are about to die anyway.

        WARNING: This function should only be called when the python
        interpreter is about to exit.

        NOT WORKING >>> stop_all_threads()
    '''

    for thread in threading.enumerate():
        try:
            if IS_PY2:
                if not thread.daemon:
                    thread.exit()
            else:
                if not _thread.daemon:
                    _thread.exit()
        except:
            # this thread would die anyway as we exit the program, so be quiet
            pass
    assert not threading.enumerate(), 'Not all threads stopped'
    def _tcp_thread(self):
        while True:
            if self.end:
                _thread.exit()

            try:
                # Send request
                self.tcp_sock.send(b'?SHGPS.LOCATION;\r\n')
                # Get response
                rx_data = self.tcp_sock.recv(4096)

                # Release the lock in case of previous TCP error
                #self.lock.release()

                # Save last gps received to buffer
                with self.lock:
                    self.gps_buffer = json.loads(rx_data.decode('ascii'))
                    if not self.log_time:
                       self.log_time = self.gps_buffer['time']

            except socket.timeout:
                self.lock.locked()
            except OSError as e:
                if e.errno == errno.EAGAIN:
                    pass
                else:
                    self.lock.locked()
                    print("Error: Android 'ShareGPS' connection status should be 'Listening'")
                    print('Change mode and soft reboot Pycom device')
            except Exception:
                self.lock.locked()
                print("TCP recv Exception")
            time.sleep(0.5)
Beispiel #10
0
 def run_background(self):
     """Run as a background process."""
     loops = randint(10, 160)
     for i in range(loops):
         self.main_process_body()
     self.dispatcher.proc_finished(self)  # tell dispatcher that process is finished
     _thread.exit()
def manager_connection(_socket, conn, addr, buffer_size):
    print ("THREAD")

    data = conn.recv(buffer_size)
    #data = "asd"

    print ("Informação Recebida(", addr[0],"):", data.decode())
    print ("TRATAR INFORMAÇÃO....")
    
    process = ProcessInformation()
    status = process.process_information(data.decode())


    if (status == process.SUCESSO):
        message = '1'
    elif(status == process.FALHA_HORARIO_INVALIDO):
        message = '2'
    elif(status == process.FALHA_CRACHA_NAO_CADASTRADO):
        message = '3'
    elif(status == process.FALHA_NO_PROCESSO):
        message = '0'
    print ("MESSAGE: ", message )
    if(conn.send(message.encode())):
        print ("Mensagem de confirmação enviada")
    else:
        print ("ERRO: Mensagem de confirmação não pode ser enviada!")
    conn.close()    
    _thread.exit()
Beispiel #12
0
 def run(self):
     while True:
         try:
             def _error_handler(exc, interval):
                 logger.error("Cannot connect to %s: %s. Trying again in %s" %
                              (conn.as_uri(), exc, str(interval)))
             with self.celery_connection as conn:
                 conn.ensure_connection(_error_handler)
                 recv = celery.events.EventReceiver(conn,
                                                    handlers={"task-sent": CeleryManager.on_event,
                                                              "task-received": CeleryManager.on_event,
                                                              "task-started": CeleryManager.on_event,
                                                              "task-failed": CeleryManager.on_event,
                                                              "task-retried": CeleryManager.on_event,
                                                              "task-succeeded": CeleryManager.on_event,
                                                              "task-revoked": CeleryManager.on_event,
                                                              })
                 recv.capture(limit=None, timeout=None)
         except (KeyboardInterrupt, SystemExit):
             try:
                 import _thread as thread
             except ImportError:
                 import thread
             thread.exit()
         except Exception, e:
             logger.error("Failed to capture events: '%s'." % str(e))
             logger.info(e, exc_info=True)
Beispiel #13
0
 def ask_user(self):
     """Ask the user for number of loops."""
     self.iosys.write(self, "How many loops? ")
     input = self.iosys.read(self)
     if self.state == State.killed:
         _thread.exit()
     return int(input)
def Writer_tfidf():

    with  open( 'output_ranking.txt', 'r') as f:
        i = 60
        for line in f:
            can3.create_text(20, i, text=line, anchor=NW, font=("Arial", 12))
            i += 25
    thread.exit()
    root.mainloop()
Beispiel #15
0
 def main_process_body(self):
     # Something like the following but you will have to think about
     # pausing and resuming the process.
     self.event.wait()
     # check to see if supposed to terminate
     if self.state == State.killed:
         _thread.exit()
     self.iosys.write(self, "*")
     sleep(0.1)
Beispiel #16
0
def forward_stream(proc, stream_in, stream_out):
    try:
        for line in iter(stream_in.readline, b''):
            if proc.poll() is None:
                stream_out.write(line.decode(encoding='UTF-8'))
            else:
                _thread.exit()
    except Exception as e:
        _thread.exit()
Beispiel #17
0
 def stop(self):
     Session.remove()
     self.ssh_socket.close()
     if self.chan:
         self.chan.close()
     try:
         _thread.exit()
     except SystemExit:
         pass
Beispiel #18
0
 def run(self):
   begin = time.time()
   with open(self.log_file, 'w') as log:
     task = subprocess.Popen(self.test_command, stdout=log, stderr=log)
     try:
       self.exit_code = sigint_handler.wait(task)
     except sigint_handler.ProcessWasInterrupted:
       thread.exit()
   self.runtime_ms = int(1000 * (time.time() - begin))
   self.last_execution_time = None if self.exit_code else self.runtime_ms
    def stdin_feed_thread(self):
        for line in sys.stdin:
            GObject.idle_add(self.handle_line, line)
            self.cancel_lock.acquire()
            cancelled = self.cancelled
            self.cancel_lock.release()
            if cancelled:
                break

        _thread.exit()
Beispiel #20
0
	def controller(self, handler):
		while 1:
			try:
				data, route = handler.sock.recv()
				handler.handle(data, route)
			except Exception as e:
				if not is_socket_related_error(e):
					self.print_trace(handler.sock)
				self.attempt_graceful_close(handler, handler.sock)
				_thread.exit()
def child():
    with statlock:
        global exitstat
        exitstat += 1
        stat = exitstat
    with stdoutlock:
        threadid = _thread.get_ident()
        print('Hello from child', threadid, stat)
        _thread.exit()
        print('never reached')
def Writer_impsent():
    with  open('summary_output.txt', 'r') as f:
        i = 60
        for line in f:
            l = len(line)
            l /= 20
            print l
            can4.create_text(20, i, text=line, anchor=NW, width=300, font=("Arial", 12))
            i += l * 10 + 30
    thread.exit()
    root.mainloop()
Beispiel #23
0
def TCP(conn,addr):
 global FLAG
 while 1:
  try:
   DATA = conn.recv(1024).strip().decode('utf')
   if DATA.strip() != "quit": 
    FLAG = 1
    print("Recd: %s" %DATA)
    _thread.start_new_thread(S_TCP,(conn,addr))
   else:
    FLAG = 0
    print(addr[0], "connection closed")
    break
  except Exception:
    _thread.exit()
def fetch3(entries):
    #global Textpath
    can4.delete("all")
    global thread_impsent
    #thread_impsent = thread.start_new_thread(NewThreadedProcess_important_sentences,(Textpath,))
    childprocess = subprocess.Popen(['Python', 'text_analysis7.py', command])
    childprocess.wait()
    childprocess.terminate()
    with  open('summary_output.txt', 'r') as f:
        i = 60
        for line in f:
            l = len(line)
            l /= 20
            print l
            can4.create_text(20, i, text=line, anchor=NW, width=300, font=("Arial", 12))
            i += l * 10 + 30
    thread.exit()
Beispiel #25
0
	def run(self):
		print('Opening connection {}'.format(self.fileno))
		while True:
			try:
				data = self.client.recv(self.size)
				self.data += data
				end_of_request = re.search(b'\r\n\r\n', data)
				if end_of_request:
					self.process_request()
					break
				elif len(self.data) >= self.MAX_SIZE or len(data) == 0:
					break
			except socket.timeout:
				print('Connection {} timed out'.format(self.fileno))
				break
		self.client.close()
		print('Closed connection {}'.format(self.fileno))
		_thread.exit()
    def ask_user(self):

        # this method is used inthe run_interactive method above. It
        # asks the user for a number to run the loop
        # if the input is -1 then the process is quit. If above -1 then it runs and
        # asks the user again for an input

        """Ask the user for number of loops."""
        self.iosys.write(self, "How many loops? ")

        input = None

        while input is None:
            self.event.wait()
            input = self.iosys.read(self)

        if self.state == State.killed:
            _thread.exit()
        return int(input)
Beispiel #27
0
    def main(self):

        self.gui.createMainUI(self.handle_gui_event)

        while True:
            if self.gui.events() == 1:
                break

            self.gui.fillScreen()
            self.gui.updateCards()
            self.gui.drawNames(self.players, self.points)
            self.gui.drawUIElements()
            self.gui.updateSurface()

            time.sleep(0.05)

        if self.connection:
            self.connection.close()
        _thread.exit()
        sys.exit()
Beispiel #28
0
def conectado(con, cliente):
    """Controle de threads conectadas ao servidor """
    global start
    global palavraDoJogo
    global tentativas
    print('Novo jogador:', cliente)

    while True:
        msg = con.recv(1024)
        if msg and con == lider['socket']:
            msg = msg.decode()
            if len(participantes) >= 3 and not start:
                if tentativas == 0:
                    tentativas = int(msg)
                    lider['socket'].send(str.encode("OK"))
                    print("Número de Tentativas: {}".format(tentativas))
                elif palavraDoJogo == "":
                    palavraDoJogo = msg
                    sendToAll("Configurações realizadas. Iniciando o jogo.")
                    print("Palavra definida: {}".format(palavraDoJogo))
                    gerarPalavraSecreta()
                    start = True
                    lider['socket'].send(str.encode("Aguarde até que a partida seja finalizada." \
                                         " Você será notificado das ações ocorrentes no jogo!"))
        elif start == True and jogadorAtual['socket'] == jogadores[0]['socket']:
            msg = msg.decode()
            l = list(msg)
            jogada(l[0])
            threadLock.release()
        elif start == True and con == jogadorAtual['socket'] == jogadores[1][
                'socket']:
            msg = msg.decode()
            l = list(msg)
            jogada(l[0])
            threadLock.release()

    print('Sessão com jogador: {}, finalizada!'.format(cliente))
    con.close()
    _thread.exit()
def enviar(IP_ACESSADO, PORT):

    # Cria o Socket (Transmissor)
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # Configurações (quem deve ser acessado?)
    server_address = (IP_ACESSADO, PORT)
    print(
        'Thread Enviar: Acessando o IP: {} Porta: {}'.format(*server_address))

    try:
        # Enviando mensagem
        sock.connect(server_address)

        message = b'heartbeat'
        #print('Remetente: Enviando para {!r}'.format(message))
        sock.sendall(message)

    finally:
        #print('Remetente: Fechando conexão')
        sock.close()
        thread.exit()
    def get_executor(self, max_processes_cnt=1):
        """
        Get an executor.

        This method may be called by different business from different threads.
        So it needs to be tread-safe.
        """
        with self._lock:
            if self._exiting:
                self._logger.info(
                    "System is exiting, will terminate the thread.")
                _thread.exit()

            executor = Executor(max_processes_cnt=max_processes_cnt,
                                exit_callback=functools.partial(
                                    self._remove_executor,
                                    executor_id=self._executor_id_counter),
                                exit_check_fn=self._check_exit)

            self._executors[self._executor_id_counter] = executor
            self._executor_id_counter += 1
            return executor
Beispiel #31
0
def daemon():
    """ Measure the temperature at fixed intervals and adjust fan speed. """
    global temp0, temp1, dutycycle

    ds = DS18X20(OneWire(Pin("P21")))

    if len(ds.roms) == 0:
        print("no temperature sensors found")
        _thread.exit()

    t = 0

    while True:
        # measure +- every 30 seconds
        time.sleep(27)
        for i in range(len(ds.roms)):
            time.sleep_ms(750)
            ds.start_conversion(ds.roms[i])
            time.sleep_ms(750)
            t = int(ds.read_temp_async(ds.roms[i]))
            with lock:
                if i == 0:
                    temp0 = t
                else:
                    temp1 = t

        temp = max(temp0, temp1)  # inlet temperature is highest

        if temp < (temp_fan_on - hysteresis):
            dutycycle = 0
            set_dutycycle(dutycycle)

        if temp > temp_fan_on:
            dutycycle_range = max_dutycycle - min_dutycycle
            temp_range= temp_fan_max - temp_fan_on
            temp_clipped = min(max(temp - temp_fan_on, 0), temp_range)
            dutycycle_raw = int(temp_clipped * (dutycycle_range / temp_range))
            dutycycle = 0 if dutycycle_raw <= 0 else min_dutycycle + dutycycle_raw
            set_dutycycle(dutycycle)
Beispiel #32
0
def threaded_client(conn, ipaddr, port):
    ip_plus_port = str(ipaddr) + str(port)
    last_sent = {}
    with active_connections_lock:
        active_connections.append(ip_plus_port)

    while True:
        try:
            data_encoded = conn.recv(2048)
            data = pickle.loads(data_encoded)
            if not data_encoded == b'':
                #print(data)
                with master_blob_map_lock:
                    master_blob_map[ip_plus_port] = data
        except:
            pass  ##SHHH, ... I know this is bad
        try:
            if (master_blob_map !=
                    last_sent):  ##Make sure they are getting new info
                with master_blob_map_lock:
                    logging.debug("Sending {} to {}".format(
                        master_blob_map, ip_plus_port))
                    encoded_map = pickle.dumps(master_blob_map)
                    conn.sendall(encoded_map)
                    last_sent = copy.copy(master_blob_map)
                with print_lock:
                    logging.debug('Sent map to {}'.format(conn))
        except Exception as e:
            if str(e) == 'Error sending: [Errno 32] Broken pipe':
                ##User has disconnected, proceeding is clean up code to remove them from game
                logging.info("User {} has disconnected".format(ip_plus_port))
                with active_connections_lock:
                    active_connections.remove(ip_plus_port)
                with master_blob_map_lock:
                    del master_blob_map[ip_plus_port]
                _thread.exit()
            else:
                logging.error("Error '{}' sending to {}".format(str(e)),
                              ip_plus_port)
def fetch3(entries):
    #global Textpath
    can4.delete("all")
    global thread_impsent
    #thread_impsent = thread.start_new_thread(NewThreadedProcess_important_sentences,(Textpath,))
    childprocess = subprocess.Popen(['Python', 'text_analysis7.py', command])
    childprocess.wait()
    childprocess.terminate()
    with open('summary_output.txt', 'r') as f:
        i = 60
        for line in f:
            l = len(line)
            l /= 20
            print l
            can4.create_text(20,
                             i,
                             text=line,
                             anchor=NW,
                             width=300,
                             font=("Arial", 12))
            i += l * 10 + 30
    thread.exit()
def camera_procedure():
    print("Thread Starting for Camera")
    print("Camera Starting")

    # Rotate Camera Imaging 180 Degrees
    camera_sys.rotation = 180

    # Pre-formate of Video File
    file_capture = "Entranceway Recording at " + time.strftime("%Y-%m-%d---%H-%M-%S") + ".h264"

    # Recording Entryway as a 7 Second Video
    camera_sys.start_recording(file_capture)
    time.sleep(7)
    camera_sys.stop_recording()

    print("Video Recorded")
    time.sleep(2)

    print("Notifying User of Front Door Movement and Camera Recording")
    requests.post("https://maker.ifttt.com/trigger/ARGON_AC_TEST_DETECTED_MOVEMENT/with/key/eU_JJJKmZOp_tczeQ56DCVRWKFmnvYPiAZ1fMz0oI6U")

    print("Thread Exiting for Camera")
    _thread.exit()
Beispiel #35
0
def conexao(con, cliente, senha):
    print("Conectado:", cliente)
    dados = dadosServico(senha)
    con.send(dados.encode('utf-8'))
    while True:
        resposta = con.recv(1024)
        re = resposta.split(';')
        if re[0] == 'Servico Completo':
            dados = dadosServico(senha)
            con.send(dados.encode('utf-8'))
        elif re[0] == 'Achou':
            print('Sua senha é: ', re[1])
            break
        elif re[0] == 'Em Andamento':
            print('Cliente em Atividade:', cliente)
        elif not resposta:
            servico = emAndamento.get
            filaDeServico.put(servico)
            break
        print(msg, cliente)
    print("Finalizado conexao:", cliente)
    con.close()
    _thread.exit()
Beispiel #36
0
    def fetch_meta(self, video):
        try:
            site = download_npo.match_site(video['url'])
            videourl, player_id, ext = site.find_video(video['url'])
            meta = site.meta(player_id)
            text = download_npo.make_filename(video['outdir'],
                                              video['filename'], 'mp4', meta,
                                              True, True, True)

            extra_text = [
                '{} kwaliteit'.format(['hoge', 'middel',
                                       'lage'][video['quality']])
            ]
            if video['subtitles']:
                extra_text.append('ondertitels')
            if video['overwrite']:
                extra_text.append('overschrijven')
            text += ' ({})'.format(', '.join(extra_text))
        except Exception as exc:
            video['status'] = 3
            text = '{} - Fout'.format(video['url'], sys.exc_info()[1])
        self.make_progress_frame_entry(text, video)
        thread.exit()
    def _loop(self, _):
        """ read data from the file and feed it into the fifo """
        while True:
            for values in self.value_lines:
                # write values to the fifo
                for value in values:
                    # write the value
                    self.fifo_write(value)

                    # wait for 1/75 seconds - some compensation for runtime
                    time.sleep((990 / 75) / 1000)

                # check for self.stopped after every batch of values
                if self.stopped == True:
                    _thread.exit()

            # check if the file (-> the values) should be looped
            if self.loop != True:
                break

            self.loop_count += 1

        _thread.exit()
def conectado(connect, cliente, interval, dicionario_sensor, lista_servidor):
    while True:
        msg = my_recv(connect)
        if (not msg):
            break
        id_sensor, tipo_sensor, valor_sensor = msg
        if (cliente != None):

            print("Mensagem de sensor recebida!")
            if (tipo_sensor == 1):
                sensor_presenca(interval, dicionario_sensor, id_sensor,
                                tipo_sensor, valor_sensor, lista_servidor)
            elif (tipo_sensor == 2):
                sensor_luminosidade(dicionario_sensor, id_sensor, tipo_sensor,
                                    valor_sensor, lista_servidor)
            elif (tipo_sensor == 3):
                sensor_temperatura(dicionario_sensor, id_sensor, tipo_sensor,
                                   valor_sensor, lista_servidor)
            else:
                print("Tipo de sensor não identificado.")
        print(" ")
    connect.close()
    _thread.exit()
def argon_notification_procedure():
    print("Thread Starting for Argon_AC_3 Notification")
    timer_x = 0
    while timer_x < 10:
        # Secondary Client to communicate from RPi to Argon_AC_3
        secondary_client = mqtt.Client("Reception_2_mqtt")
        secondary_client.connect("test.mosquitto.org", 1883)
        secondary_client.subscribe("argon_Log_AC_3")
        secondary_client.publish("RPi_AC", "Active")
        print("Sending data to ARGON; Active; time:" + str(timer_x))
        time.sleep(1)
        timer_x += 1

    secondary_client = mqtt.Client("Reception_2_mqtt")
    secondary_client.connect("test.mosquitto.org", 1883)
    secondary_client.subscribe("argon_Log_AC_3")
    secondary_client.publish("RPi_AC", "Non_Active")
    print("Sending data to ARGON; Non_ACTIVE")

    secondary_client.unsubscribe("argon_Log_AC_3")

    print("Thread Exiting for Argon_AC_3 Notification")
    _thread.exit()
Beispiel #40
0
 def getSubmitCode(self):
     # 从self.codeList中获取到需要提交的内容
     self.submitCode = []
     for key in self.codeList:
         matchCode = []
         count = 0
         for x in self.list:
             for value in self.codeList[key]:
                 if (x in value["teacher"]):
                     count += 1
                     self.transform(value, matchCode)
         if (count == 0):
             import random
             n = random.randint(0, len(self.codeList[key]) - 1)
             self.transform(self.codeList[key][n], matchCode)
             print("随机选择{}".format(self.codeList[key][n]["teacher"]))
         if (len(matchCode) == 0):
             print("匹配出错, 课程名称{}".format(self.course))
             import _thread
             _thread.exit()
         self.submitCode.append(matchCode[0])
     for x in self.submitCode:
         print("匹配结果:{}|{}".format(x["subject"], x["teacher"]))
Beispiel #41
0
def ProvisionServerThreaded(connection, address):
    while True:
        data = connection.recv(1024)  # receive data when connected
        arcLog.create(
            "Provision Thread: Server Received Data: {}".format(address))
        if arcConfig.GetKey()[0] in str(data):
            arcLog.create(
                "Provision Thread: Key Valid from: {}".format(address))
            replyKey = "{}".format(
                arcConfig.GetKey())  # friendNode will verify key
            finalReplyKey = str.encode(replyKey)
            connection.send(finalReplyKey)  # send ack with key
            arcLog.create(
                "Provision Thread: Sending Reciprocative Key to: {}".format(
                    address))
            LanAddClients(address)  # add client to local db
            arcLog.create(
                "Provision Thread: Completed Provision with {}".format(
                    address))
            break
    arcLog.create("Provision Thread: Closing for: {}".format(address))
    connection.close()  # close connection
    thread.exit()  # exit thread
Beispiel #42
0
def peer_processing(node):

    global sha_msg

    conn = node['socket']
    addr = (node['IP'], node['PORT'])
    while True:
        print("waiting to receive !!!!")
        data = conn.recv(1024).decode('utf-8')
        if data:
            print("broad casted Info received", addr)

            lock.acquire()

            data = data
            #print("\n???????????????\n", data, "\n?????????????????\n")
            data_len = int(data.split("#")[0])
            data = data.split("#")[1]
            #print(data_len, "----------", len(data))
            while data_len > len(data):
                data = data + conn.recv(1024).decode('utf-8')
            data_hash = hashlib.sha224(data.encode('utf-8')).hexdigest()
            if data_hash not in sha_msg:
                sha_msg.add(data_hash)
                data_to_file = "RECEIVED FROM " + addr[0] + " " + str(
                    addr[1]) + "::" + data
                node_file.write(data_to_file)
                node_file.flush()
                #print("Passing to toher nodes----------\n")
                pass_to_other_nodes(data)

            lock.release()
        else:
            connected_nodes.remove(node)
            print(addr[0], ":", addr[1], "Existed System!!!")
            _thread.exit()
            break
Beispiel #43
0
def connect(con, client):
    __write_mode__ = 'a'

    DB = 'database.HUE'

    if not Path(DB).exists():
        __write_mode__ = 'w'

    print(f'Connected with {client}')

    resp = b'OK'

    while True:
        msg = con.recv(2048)

        if not msg:
            break

        p = pickle.loads(msg)

        if not p.name or not p.age or not p.sex:
            resp = b'Err'
        else:
            with open('database.HUE', __write_mode__) as _file:
                new_line = f'{p.name} | {p.age} | {p.sex} \n'
                _file.write(new_line)
                if __write_mode__ == 'w':
                    __write_mode__ = 'a'

        con.send(resp)

        print(client, p)
    print(f'Close connection...')

    con.close()
    _thread.exit()
Beispiel #44
0
def empty_database ():
	confirm = askquestion ("Clear Local Database", "This operation effectively removes all the images and their corresponding profiles from the database. Would you like to proceed?", icon = "warning");
	
	if (confirm == "yes"):
		try:
			os.chdir ("image_db");
			files = os.listdir ();
		except FileNotFoundError:
			display_alert ("Error", "The directory 'image_db' was not found.");
		except Exception as e:
			pass;
		else:
			for f in files:
				if (f == "crops"):
					cropped_files = os.listdir ("crops");
					for g in cropped_files:
						os.remove ("crops/" + g);
					continue;

				os.remove (f);
			print ("Database has successfully been cleared");
		os.chdir ("..");

		try:
			os.chdir ("profiles");
			files = os.listdir ();
		except FileNotFoundError:
			display_alert ("Error", "The directory 'image_db' was not found.");
		except Exception as e:
			pass;
		else:
			for f in files:
				os.remove (f);
		
		display_alert ('Update', 'Database was successfully cleared');
		thread.exit ();
Beispiel #45
0
	def forward_outside(self, source, destination, connect):
		string = ' '
		try:
			while string:
				string = source.recv(1024)
				if connect.socket_SSH[source] == True:
					if "b''" in str(string):
						try:
							source.close()
						except:
							print("no source socket to close")
							pass
						try:
							destination.close()
						except:
							print("no destination socket to close")
							pass
						finally:
							break
				connect.buffer_SSH[source].append(string)
				try:
					destination.sendall(string)
				except:
					pass


				
		except Exception as e:
			print(e)
			print("closing the connection ....")
			print("exception 4")
			source.shutdown(socket.SHUT_RDWR) 
			source.close()
			destination.shutdown(socket.SHUT_RDWR) 
			destination.close()
			thread.exit()
Beispiel #46
0
 def sampling(self):
     while True:
         if self.enabled is True:
             time.sleep(self.samplingFrequency-0.751)
             self.lock.acquire()
             self.powerPin(1)
             time.sleep(0.001)
             self.temp.start_convertion()
             time.sleep(0.75)
             self.lastTemperature = self.temp.read_temp_async()
             count = 0
             while((self.lastTemperature < (-55.0) or self.lastTemperature > 125.0) and count < self.erCounter):
                 self.lastTemperature = self.temp.read_temp_async()
                 count += 1
             if (self.lastTemperature < (-55.0) or self.lastTemperature > 125.0):
                 self.errorLogService.regError(self.serviceID, -11) #Incorrect Value Error code
             else:
                 self.sumTemperature += self.lastTemperature
                 self.sampleCounter += 1
             collectMemory()
             self.powerPin(0)
             self.lock.release()
         else:
             _thread.exit()
Beispiel #47
0
def f1():
    oval = c.create_oval(
        30, 30, 80, 80,
        fill="orange")  #создание эллипса с координатами и цветом
    time.sleep(1)  #приостановить таймер на 1с
    cnt = 450
    while cnt > 0:
        if (cnt <= 450) and (cnt > 300):
            k = 1
        else:
            if (cnt >= 200) and (cnt < 300):
                k = -1
                c.itemconfig(oval, fill='yellow')
            else:
                if (cnt >= 100) and (cnt < 200):
                    k = 1
                    c.itemconfig(oval, fill='white')
                else:
                    k = -1
                    c.itemconfig(oval, fill='red')
        c.move(oval, k, 1)  #перемещение эллипса
        time.sleep(0.01)  #приостановить таймер на 0.01с
        cnt -= 1
    _thread.exit()  #закрытие потока
Beispiel #48
0
    def set_block_thread(self, data):
        block = data

        if block:
            self.debug("set_block_thread blocking")
            self.blockproc = subprocess.Popen(RFKILL_BLOCK, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        else:
            self.debug("set_block_thread unblocking")
            self.blockproc = subprocess.Popen(RFKILL_UNBLOCK, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

        # Check for errors and continue
        _,err = self.blockproc.communicate()
        if err:
            error = err.decode("utf-8")
            self.debug(error)
            self.rfkill_err = error
            # Force UI update
            self.update_ui()
        else:
            self.rfkill_err = None

        self.blockproc = None
        self.debug("set_block_thread finished")
        thread.exit()
def socket_to_file(file, socketobject):
    while True:
        time.sleep(0.2)
        try:
            content = socketobject.recv(509600)
            #print('Content Recv')
            print('Content Recv')
        except:
            _thread.exit()
        if content != b'':
            with open(file, 'wb') as f:
                f.write(content)
                #print(content)
                #    print('Content Written')
                print('Content Written, Length', len(content))
        else:
            #print('Blank Content. Connection Reset?')
            #print('Close Connection...(S2F)')
            try:
                socketobject.close()
            except:
                #print('Failed to close connection.(S2F)')
                print(2)
            _thread.exit()
Beispiel #50
0
    def _check(self, dead_vid):
        self.logger.info('Monitor dead volumn server %s ...' % dead_vid)

        t = 60

        while t > 0:
            time.sleep(1)
            if dead_vid in self.act_vol_serv.keys():
                self.logger.info('Volumn %s becomes live. Stop recover' % dead_vid)
                _thread.exit()
            t -= 1

        for vid, vvids in self.db.items():
            if dead_vid in vvids:
                for recov_vid in vvids:
                    if recov_vid != dead_vid and recov_vid in self.act_vol_serv.keys():
                        from_vid = recov_vid
                        avl_vids = list(set(self.act_vol_serv.keys()) - set(vvids))
                        if avl_vids:
                            to_vid = random.choice(avl_vids)
                            _thread.start_new_thread(self._recover, (vid, dead_vid, from_vid, to_vid))
                        else:
                            self.logger.warn('No available volumns to migrate')
                        break
    def start(self, trialparams={}, loopstate={}):
        try:
            self.update(trialparams, loopstate)
            for item in self.items:
                if hasattr(item, "setAutoDraw"):
                    item.setAutoDraw(True)

        except Exception as e:
            import threading
            from psychopy import core

            logging.error(traceback.format_exc())
            mainthread = None
            current_thread = threading.currentThread()
            for th in threading.enumerate():
                #logging.error('threads:'+' '.join([x for x in threading.enumerate()]))
                if th.name == 'MainThread':
                    mainthread = th
                elif th.name != current_thread.name:
                    #logging.error('stopping stimulus with name='+str(self.name))
                    th.cancel()

            _thread.interrupt_main()
            _thread.exit()
Beispiel #52
0
def upload_image ():
	Tk ().withdraw ();
	global win_width;
	global win_height;
	
	try:
		file_path = askopenfilename ();
		if (file_path == ""):
			thread.exit ();
	except Exception as fnf:
		#print ("File was not uploaded");
		#print ("Verbose: " + str (fnf));
		thread.exit ();
	else:	
		file_name = file_path.split ("/") [-1];
		print (file_name);
		test = Image.open (file_path);
		
		width, height = test.size;
		max_width = int ( (80.7446 / 100) * win_width );
		max_height = int ( (98.6651 / 100) * win_height );

		if (width > max_width or height > max_height):
			final = test.resize ( (max_width, max_height) );
			final.save ("image_db/" + file_name);
			test.close ();
			final.close ();
			
			print ("Verbose: " + file_path + " has been added to the local DataBase");
			successfully_uploaded ();
			thread.exit ();
			
		try:
			copyfile (file_path, "image_db/" + file_name);
		except Exception as e:
			print ("The application has encountered an un-expected error. Please contact the application developer at [email protected]");
			print ("Verbose: \n" + str (e));
		else:
			print ("Verbose: " + file_path + " has been added to the local DataBase");
			successfully_uploaded ();
Beispiel #53
0
def animation():
    collect()
    global np
    global n_neopixels
    global play
    global playfile
    global framelength
    try:
        play_config = open("/sd/" + playfile + "/cfg.dat", 'r')
        play_config.close()
    except:
        play = 3
        print("/sd/" + playfile + "/cfg.dat" + " failed to open")
        _thread.exit()
    try:
        f = open("/sd/" + playfile + "/dat.dat", 'r')
        f.close()
    except:
        play = 3
        print("/sd/" + playfile + "/dat.dat" + " failed to open")
        _thread.exit()
    collect()
    while play:
        i = 0
        with open("/sd/" + playfile + "/dat.dat", "rb") as f:
            pixel = [ord(b) for b in f.read(3)]
            red = pixel[0]
            green = pixel[1]
            blue = pixel[2]
            if i >= framelength:
                i = 0
                np.write()
            else:
                i += 1
            np[i] = (red, green, blue)

    play = 3
    _thread.exit()
Beispiel #54
0
import _thread as thread

from hermite_bezier import main_hermite
from ui import start

try:
    thread.start_new_thread(main_hermite, ())
    start()
except KeyboardInterrupt:
    thread.exit()
Beispiel #55
0
 def save(event):
     widget = event.widget
     f = open(widget.get() + '.json', 'w')
     json.dump(list, f)
     _thread.exit()
Beispiel #56
0
    sleep(1)
    return values


start_search = objects.query('https://t.me/UsefullCWLinks/' + str(start_link), 'd: (.*) :d')
used_array = google('moscow-growing', 'col_values', 1)
Auth = objects.AuthCentre(os.environ['TOKEN'])
bot = Auth.start_main_bot('non-sync')
executive = Auth.thread_exec
if start_search:
    last_date = stamper(start_search.group(1)) - 3 * 60 * 60
    Auth.start_message(stamp1)
else:
    last_date = '\nОшибка с нахождением номера поста. ' + bold('Бот выключен')
    Auth.start_message(stamp1, last_date)
    _thread.exit()
# ====================================================================================


def hour():
    return int(datetime.utcfromtimestamp(objects.time_now() + 3 * 60 * 60).strftime('%H'))


def post_keys(em):
    posts_row = types.InlineKeyboardMarkup(row_width=1)
    button = [types.InlineKeyboardButton(text=em, callback_data='post')]
    posts_row.add(*button)
    return posts_row


def numeric_replace(number):
Beispiel #57
0
def manager_connection(_socket, conn, addr, buffer_size):
    #print ("THREAD")

    data = conn.recv(buffer_size)
    #data = "asd"
    string_recebida = data.decode()
    print ("Informação Recebida(", addr[0],"):", string_recebida)
    print ("TRATAR INFORMAÇÃO....")
    sub_strings = string_recebida.split("-")
    #print (sub_strings)
    
    modo_operacao = sub_strings[0]
    sala =  sub_strings[1]
    rfid_code =  sub_strings[2]

    if(sub_strings[0] == "INICIALIZACAO"):
        print ("Conexao de inicializacao")
        modo_operacao = sub_strings[1]
        process = ProcessInformation()
        sala = process.start_arduino(sub_strings[2])
        print ("SALA: ", sala)
        rfid_code =  sub_strings[3]
        message = str(sala)
        print ("MESSAGE: ", message )
        if(conn.send(message.encode())):
            print ("Mensagem de confirmação enviada inicializacao")
        else:
            print ("ERRO: Mensagem de confirmação não pode ser enviada!")


    if(modo_operacao == "INSERCAO"):
        print ("MODO INSERCAO!")
        process = ProcessInformation()
        status = process.insert(rfid_code)
        if not (status):
            print ("FALHA NO PROCESSO")
            message = '0'
        elif(status == process.SUCESSO): 
            print ("INSERCAO SUCESSO")
            message = '1'
        elif(status == process.FALHA_CRACHA_JA_CADASTRADO):
            print ("CRACHA JAH CADASTRADO")
            message = '5'
    else:
        print ("MODO NORMAL")
        process = ProcessInformation()
        status = process.process_information(rfid_code, sala)

        if (status == process.SUCESSO):
            message = '1'
        elif(status == process.FALHA_HORARIO_INVALIDO):
            message = '2'
        elif(status == process.FALHA_CRACHA_NAO_CADASTRADO):
            message = '3'
        elif(status == process.FALHA_NO_PROCESSO):
            message = '0'


    print ("MESSAGE: ", message )
    if(conn.send(message.encode())):
        print ("Mensagem de confirmação enviada")
    else:
        print ("ERRO: Mensagem de confirmação não pode ser enviada!")
    
    conn.close()    
    _thread.exit()
Beispiel #58
0
 def closeEvent(self, e):
     self.logout()
     _thread.exit()
     self.socket.close()
Beispiel #59
0
 def clientTearDown(self):
     self.done.set()
     thread.exit()
Beispiel #60
0
def keyboardInterruptHandler():
    print('[#] Port ' + device + ' closed.')
    ser.close()
    _thread.exit()