class CacheManager: def __init__(self, fn, port): self.fn = fn self.server = None self.t = None self.port = port def _reload_cache(self): self.fn() def _loop(self): self.server = socket() self.server.bind(('localhost', self.port)) self.server.listen(1) while 1: connection, address = self.server.accept() value = connection.recv(32) if value.strip() == 'clear': self._reload_cache() connection.send('cleared') connection.close() def run(self): self.t = Thread(target=self._loop) self.t.start() def kill(self): if self.server: self.server.close() if self.t: self.t.kill()
class StreamQueue: logger = None def __init__(self, _bytes_per_read, _proc, _stream_id): self.bytes_per_read = _bytes_per_read self.sout = _proc.stdout self.queue = [] self.proc = _proc self.stream_id = _stream_id def _populate_queue(): """ Collect lines from 'stream' and put them in 'queue'. """ self.logger.debug( 'Starting Stream Buffer Process PID={} Stream ID={}'.format( self.proc.pid, self.stream_id)) while True: try: video_data = self.sout.read(self.bytes_per_read) if video_data: self.queue.append(video_data) else: self.logger.debug( 'Stream ended for this process, exiting queue thread' ) break except ValueError: # occurs on termination with buffer must not be NULL break self._t = Thread(target=_populate_queue, args=()) self._t.daemon = True self._t.start() # start collecting blocks from the stream def read(self): is_queue_changing = True queue_size = len(self.queue) while is_queue_changing: time.sleep(0.2) if len(self.queue) != queue_size: queue_size = len(self.queue) else: is_queue_changing = False if len(self.queue) > 0: clone_queue = self.queue.copy() # TBD ADD A MAX LIMIT ON A PULL del self.queue[:len(clone_queue)] return b''.join(clone_queue) return None def terminate(self): self._t.kill() self._t.join()
class Fish(QRect): def __init__(self): super().__init__() self.type_ = random.choice(FISHES) self.x = random.randint(0, 945) self.y = random.randint(0, 600) self.speed = 20 self.hunger = 100 self.img = QImage('images/' + self.type_ + '.png') self.life = Thread(target=self.live) self.life.start() def __del__(self): print("Fish died") self.life.kill() def live(self): while (self.hunger > 0): self.hunger -= 1 self.rand_move() time.sleep(TIMEHOLD) self.img = QImage('images/' + self.type_ + 'RIP.png') while (self.y > self.speed): self.y -= self.speed time.sleep(TIMEHOLD) self.moveTo(self.x, self.y) def feed(self): self.hunger = 100 def rand_move(self): x = random.randrange(3) - 1 y = random.randrange(3) - 1 self.x += x * self.speed self.y += y * self.speed if self.x > 945: self.x -= 2 * abs(x) * self.speed if self.y > 550: self.y -= 2 * abs(y) * self.speed if self.x < 0: self.x += 2 * abs(x) * self.speed if self.y < 0: self.y += 2 * abs(y) * self.speed self.moveTo(self.x, self.y)
class ThreadBackend(ConcBase): def __init__(self, function, calling_worker=None, fargs=[], fkwargs={}, daemon=True, timeout=None): super().__init__(function, calling_worker, fargs=fargs, fkwargs=fkwargs) self.t = None self.daemon = daemon self.timeout = timeout def run(self): def exec_function(): try: result = self.function(*self.fargs, **self.fkwargs) self.result = result self._status = CONC_STATUS.success except Exception as e: self.exception = e self._status = CONC_STATUS.error self.t = Thread(name=self.uid, target=exec_function, daemon=self.daemon) self._status = CONC_STATUS.running self.t.start() def kill(self): self.t.kill() def join(self): self.t.join(timeout=self.timeout) @staticmethod def sleep(period): time.sleep(period)
class ThreadedStream(SS): def __init__(self, port, chunkSize=2048, numClients=1): SS.__init__(self, port, chunkSize=chunkSize, numClients=numClients) self.center = None self.frame = None self.stopped = True self.dimg = None def start(self): self.stopped = False self.t = Thread(target=self.update) self.t.daemon = True self.t.start() return self def get(self): return self.center, self.frame, self.dimg def update(self, inverted=1): while True: try: if self.stopped: self.close() return # otherwise, read the next frame from the stream self.frame = self.receiveFrame(mode=cv2.IMREAD_GRAYSCALE) self.center, self.dimg = detect_and_locate_position(self.frame) if self.center is not None: if inverted: self.center = (self.center[0], self.frame.shape[0] - self.center[1]) except Exception as e: print(traceback.print_tb(e.__traceback__)) def stop(self): self.stopped = True def close(self): SS.close(self) self.t.kill()
class Stream: def __init__(self): self.length = 100 self.buffer = b'' self.queue = Queue() self.thread = Thread(target=self.run) self.thread.start() def read(self): if (not self.queue.empty()): return self.queue.get(block=False) return b'nothing' def run(self): while (True): r = os.read(sys.stdin.fileno(), 1024) #print(r) self.queue.put(r) def stop(self): self.thread.kill()
if initBB is not None: (success, box) = tracker.update(gray) if success: (x, y, w, h) = [int(v) for v in box] cv2.rectangle(frame, (max(x - offset, 0), max(y - offset, 0)), (x + w + offset, y + h + offset), (0, 255, 0), 2) x0, x1, y0, y1 = (max(y - offset, 0), y + h + offset, max(x - offset, 0), x + w + offset) edges = cv2.Canny(frame[x0:x1, y0:y1], 50, 50) if faces is not None: if len(faces) != 0: initBB = tuple(faces[0]) tracker = cv2.TrackerMOSSE_create() tracker.init(frame, initBB) faces = None if edges is not None: frame[x0:x1, y0:y1, 0] = edges frame[x0:x1, y0:y1, 1] = edges cv2.imshow('frame', frame) key = cv2.waitKey(1) & 0xff if key == ord('q'): break p.kill = False sem.set() p.join() cv2.destroyAllWindows()
plaza = str(row[0]) localidad = str(row[1]) connection.commit() connection.close() except (Exception, psycopg2.DatabaseError) as error: print(error) if __name__ == "__main__": #INICIALIZAMOS EL HILO DE LA INTERFAZ obtenerPlazaYLocalidad() thread1 = Thread(target=interface, args=()) thread3 = Thread(target=leerCodQR, args=()) thread4 = Thread(target=leerArchivo, args=()) try: thread1.start() thread3.start() time.sleep(.4) thread4.start() except Exception as e: pass while (thread1.is_alive()): kill = 0 kill = 1 thread3.kill() print("\nTermine")
s.sendall(random_no+" "+str(len(random_no))) a='' some='' after=time.time() print "communication delay : %f" % (after-before) s.close() #create threads for different controllers thread1 = Thread(target = conn_c1) thread2 = Thread(target = conn_c2) thread1.start() thread2.start() thread1.join() thread2.join() sleep(20) thread = Thread(target = threaded_function) thread.kill=1 thread.start() #thread.join() CLI( net ) thread.kill=0 thread.join() print "*** Stopping network" net.stop() if __name__ == '__main__': setLogLevel( 'info' ) # for CLI output multiControllerNet()
'fl':[FL], 'cgs':[CGS], 'chdg':[CHdg]})) """ """insert_table_fields('FIELDS', connect(database_name='activus'), tid=tid, dst=dst, ds=ds, src=src, cat=cat, sac=sac, sic=sic, tod=toD, tn=tn, theta=theta, rho=rho, fl=FL, cgs=CGS, chdg=CHdg) insert_table('CHDG', connect(database_name='activus'), tid=tid, dst=dst, ds=ds , y=CHdg, yhat='NULL', yhat_lower='NULL', yhat_upper='NULL') insert_table('FL', connect(database_name='activus'), tid=tid, dst=dst, ds=ds , y=FL, yhat='NULL', yhat_lower='NULL', yhat_upper='NULL') insert_table('CGS', connect(database_name='activus'), tid=tid, dst=dst, ds=ds , y=CGS, yhat='NULL', yhat_lower='NULL', yhat_upper='NULL') disconnect('activus')""" if (not (i % 1000)): print(i) #A enlever si on souhaite avoir toutes les données de la date1 à la date2 if (i == 100000): break if __name__ == '__main__': #main() """ date1=str(sys.argv[1]) date2=str(sys.argv[2]) plane_selected=str(sys.argv[3]) radar_selected=str(sys.argv[4])""" TH = Thread(target=main, args=('2019-05-04-12:00:00', '2019-05-04-16:00:00', 'JAF3ML', '01:00:5e:50:01:42')) TH.start() #TH.join() sleep(15) TH.kill()