コード例 #1
0
 def ScanPort(self):
     global ser
     MyLog.info("Enter ScanPort")
     MajorLog.info("Enter ScanPort")
     SharedMemory.LockList = []
     stridList.clear()
     try:
         ser = serial.Serial('/dev/ttyAMA0', 9600, timeout=0.1)
         if ser.isOpen():
             t = threading.Thread(target=InitPortList, args=(ser, self))
             t.start()
             t2 = threading.Thread(target=Normalchaxun, args=(ser, self))
             t2.start()
     except Exception as ex:
         MajorLog.error(ex)
         MyLog.error(ex)
         try:
             ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=0.1)
             if ser.isOpen():
                 t = threading.Thread(target=InitPortList, args=(ser, self))
                 t.start()
                 t2 = threading.Thread(target=Normalchaxun,
                                       args=(ser, self))
                 t2.start()
         except Exception as ex:
             MajorLog.error(ex)
             MyLog.error(ex)
コード例 #2
0
    def termTest(self):
        now = datetime.now()
        pi_id = 2017277432
        T = uniform(34, 48)  # float
        V = uniform(11, 14)  # float

        date = now.strftime("%Y-%m-%dT%H:%M:%SZ")
        location = "desert"
        print(now.timezone)
        print(now.tzinfo)

        test = {
            "id": pi_id,
            "temperature": T,
            "voltage": V,
            "date": date,
            "location": location
        }
        test_json = json.dumps(test)
        print(test_json)
        URL = ""  # Put your url
        res = requests.post(URL, data=test)

        print("Send at " + date)
        time = threading.Timer(30, self.termTest)
        time.start()
コード例 #3
0
ファイル: pay.py プロジェクト: JulioC3094/Parking-System
	def __init__(self, parent=None):
		QtGui.QMainWindow.__init__(self, parent)
		q=Queue()
		self.setupUi(self)
		self.servidor(q)
		time=threading.Timer(1,self.dato,args=q)
		time.start()
def testin():
    import threading
    import time
    import socket
    addr1 = socket.gethostbyname('ip.applause.no')
    print("started testing")
    user = mqtt_User()
    user.change_serverIp(addr1)
    user.change_userInfo('engineer', 'vykgVjYTPDcK')
    user.init_messageLogs()
    #user.add_subTopics([('#',0)]);
    t = threading.Thread(target=user.listen_until)
    print("is_alive = " + str(t.is_alive()))
    print("_initialized = " + str(t._initialized))
    t.start()
    print("is_alive = " + str(t.is_alive()))
    print("_initialized = " + str(t._initialized))
    i = 0
    while (t.isAlive()):
        if (user.check_recievedMsg()):
            print(user.get_recentMsg())
            i = 0
        else:
            print("listening ... " + str(i))
            i += 1
            time.sleep(5)
    print(user.get_recentMsg())
    print(addr1)
    print("finnished testing")
コード例 #5
0
    def train_generator(self, x_gen, epochs, batch_size, steps_per_epoch,
                        sav_dir):
        time = Time()
        time.start()
        print(
            'LSTM network training starts, with %s epochs, %s batchsize and %s batched per epoch'
            % (epochs, batch_size, steps_per_epoch))
        sav_filename = os.path.join(
            sav_dir, '%s-e%s.h5' %
            (dt.datetime.now().strftime('%d%m%Y-%H%M%S'), str(epochs)))

        callbacks = [
            ModelCheckpoint(filepath=sav_filename,
                            monitor='loss',
                            save_best_only=True)
        ]

        self.lstm_nn.fit(x_gen,
                         steps_per_epoch=steps_per_epoch,
                         epochs=epochs,
                         callbacks=callbacks,
                         workers=1)

        print('LSTM network training completed. Model saved as %s' %
              sav_filename)
        time.stop()
コード例 #6
0
    def build_nn(self, configs):
        time = Time()
        time.start()

        for layer in configs['model']['layers']:
            neurons = layer['neurons'] if 'neurons' in layer else None
            dropout_rate = layer['rate'] if 'rate' in layer else None
            activation = layer['activation'] if 'activation' in layer else None
            return_seq = layer['return_seq'] if 'return_seq' in layer else None
            input_timesteps = layers[
                'input_timesteps'] if 'input_timesteps' in layer else None
            input_dim = layers['input_dim'] if 'input_dim' in layer else None

            if layer['type'] == 'dense':
                self.lstm_nn.add(Dense(neurons, activation=activation))

            if layer['type'] == 'lstm':
                self.lstm_nn.add(
                    LSTM(neurons,
                         input_shape=(input_timesteps, input_dim),
                         return_sequences=return_seq))
            if layer['type'] == 'dropout':
                self.lstm_nn.add(Dropout(neurons, dropout_rate=dropout_rate))

        self.lstm_nn.compile(loss=configs['model']['loss'],
                             optimizer=configs['model']['optimiser'])

        print('LSTM neural network finished compiling')
        time.stop()
コード例 #7
0
ファイル: dHydra.py プロジェクト: darknessitachi/dHydra
    def start_sina(self, callback=None):
        if (self.sina is None):
            self.get_sina()

        if not (self.sina.isLogin):
            print("新浪没有登录成功,请重试")
            return False

        threads = []
        # Cut symbolList
        step = 30
        symbolListSlice = [
            self.symbolList[i:i + step]
            for i in range(0, len(self.symbolList), step)
        ]
        for symbolList in symbolListSlice:

            loop = asyncio.get_event_loop()
            if loop.is_running():
                loop = asyncio.new_event_loop()
                asyncio.set_event_loop(loop)

            t = threading.Thread(target=self.sina.start_ws,
                                 args=(symbolList, loop, callback))
            threads.append(t)
        for t in threads:
            t.setDaemon(True)
            t.start()
            print("开启线程:", t.name)
        for t in threads:
            t.join()
コード例 #8
0
ファイル: dHydra.py プロジェクト: cliff007/dHydra
	def start_sina(self, callback=None):
		if (self.sina is None):
			self.get_sina()

		if not(self.sina.isLogin):
			print("新浪没有登录成功,请重试")
			return False

		threads = []
		# Cut symbolList
		step = 30
		symbolListSlice = [self.symbolList[ i : i + step] for i in range(0, len(self.symbolList), step)]
		for symbolList in symbolListSlice:

			loop = asyncio.get_event_loop()
			if loop.is_running():
				loop = asyncio.new_event_loop()
				asyncio.set_event_loop( loop )

			t = threading.Thread(target = self.sina.start_ws,args=(symbolList,loop,callback) )
			threads.append(t)
		for t in threads:
			t.setDaemon(True)
			t.start()
			print("开启线程:",t.name)
		for t in threads:
			t.join()
コード例 #9
0
ファイル: dHydra.py プロジェクト: cliff007/dHydra
	def sina_l2_hist(self,thread_num = 15, symbolList = None):
		if (symbolList is None):
			symbolList = self.symbolList
		if (self.sina is None):
			self.get_sina()
		if not(self.sina.isLogin):
			print("新浪没有登录成功,请重试")
			return False
		threads = []
		step = int( len(symbolList)/thread_num ) if ( int( len(symbolList)/thread_num )!=0 ) else 1
		symbolListSlice = [symbolList[ i : i + step] for i in range(0, len(symbolList), step)]
		for symbolList in symbolListSlice:

			loop = asyncio.get_event_loop()
			if loop.is_running():
				loop = asyncio.new_event_loop()
				asyncio.set_event_loop( loop )

			t = threading.Thread(target = self.sina.l2_hist_list, args=(symbolList,loop,) )
			threads.append(t)

		for t in threads:
			t.setDaemon(True)
			t.start()
			print("开启线程:",t.name)
		for t in threads:
			t.join()
コード例 #10
0
ファイル: dHydra.py プロジェクト: darknessitachi/dHydra
    def sina_l2_hist(self, thread_num=15, symbolList=None):
        if (symbolList is None):
            symbolList = self.symbolList
        if (self.sina is None):
            self.get_sina()
        if not (self.sina.isLogin):
            print("新浪没有登录成功,请重试")
            return False
        threads = []
        step = int(
            len(symbolList) /
            thread_num) if (int(len(symbolList) / thread_num) != 0) else 1
        symbolListSlice = [
            symbolList[i:i + step] for i in range(0, len(symbolList), step)
        ]
        for symbolList in symbolListSlice:

            loop = asyncio.get_event_loop()
            if loop.is_running():
                loop = asyncio.new_event_loop()
                asyncio.set_event_loop(loop)

            t = threading.Thread(target=self.sina.l2_hist_list,
                                 args=(
                                     symbolList,
                                     loop,
                                 ))
            threads.append(t)

        for t in threads:
            t.setDaemon(True)
            t.start()
            print("开启线程:", t.name)
        for t in threads:
            t.join()
コード例 #11
0
ファイル: wt_Main_HV_GUI.py プロジェクト: RFQED/HV_GUI
    def __init__(self):                            # allows us to access variables, methods etc in the design.py file
        super(self.__class__, self).__init__()
        self.setupUi(self)                         # This is defined in HV_GUI.py file automatically

        self.threads = [] 
        time = TimeThread("Setting_Time")
        time.setTime.connect(self.time_set)
        self.threads.append(time)
        time.start()

        #sets the labels for date and time
     #   currentTimeOnly = time.strftime("%H:%M:%S")
     #   currentDateOnly = time.strftime("%d/%m/%Y")
     #   self.date.setText(currentDateOnly)
     #   self.time.setText(currentTimeOnly)

                                           # It sets up layout and widgets that are defined
        global height
        height = 525
        self.setFixedSize(939, height)                # Fixes windows size - 936 x 729.

        self.set_button.setEnabled(False)
        self.send_button.setEnabled(False)
        self.kill_button.setEnabled(False)
        self.exit_button.setEnabled(True)
        self.disconnect_button.setEnabled(False)

        self.connect_button.clicked.connect(self.connect)
        self.disconnect_button.clicked.connect(self.disconnect)
        self.set_button.clicked.connect(self.set)
        self.send_button.clicked.connect(self.send)
        self.kill_button.clicked.connect(self.kill)
        self.exit_button.clicked.connect(self.exit)
        self.plotly_button.clicked.connect(self.plotly)
        self.expand_button.clicked.connect(self.expand)

        self.listWidget.setReadOnly(True)

        #POWER BUTTONS
        #self.P_0.stateChanged.connect(self.power)
        #self.P_1.stateChanged.connect(self.power)
        #self.P_2.stateChanged.connect(self.power)
        #self.P_3.stateChanged.connect(self.power)
        #self.P_4.stateChanged.connect(self.power)
        #self.P_5.stateChanged.connect(self.power)
        #self.P_6.stateChanged.connect(self.power)
        #self.P_7.stateChanged.connect(self.power)
        #self.P_8.stateChanged.connect(self.power)

        for i in range(0,9):
            if i == 1:
                continue
            PowerConnect = "self.P_" + str(i) + ".stateChanged.connect(self.power)"
            eval(PowerConnect)

#Whenever a checkbox is checked or cleared it emits the signal stateChanged(). Connect to this signal if you want to trigger an action each time the checkbox changes state.

        print("GUI SET UP")
コード例 #12
0
def enthread(target, args):
    q = queue.Queue()

    def wrapper():
        q.put(target(*args))

    t = threading.Thread(target=wrapper)
    t.start()
    return q
コード例 #13
0
ファイル: optimize_J.py プロジェクト: dagopian/Island
def current_best():
    global elapsed_min
    global best_score
    global best_smiles
    global mean_score
    global min_score
    global std_score
    global all_smiles
    elapsed_min += 1
    print("${},{},{},{}".format(elapsed_min, best_score, best_smiles,
                                len(all_smiles)))
    t = threading.Timer(60, current_best, [])
    t.start()
コード例 #14
0
    def train(self, x, y, epochs, batch_size, sav_dir):
        time = Time()
        time.start()
        print('LSTM network training starts, with %s epochs and batchsize %s' % (epochs, batch_size))
        sav_filename = os.path.join(sav_dir, '%s-e%s.h5' % (dt.datetime.now().strftime('%d%m%Y-%H%M%S'), str(epochs)))

        callbacks = [
            EarlyStopping(monitor='val_loss', patience=2),
            ModelCheckpoint(filepath=sav_filename, monitor='val_loss', save_best_only=True)
        ]
        self.lstm_nn.fit(x, y, epochs=epochs, batch_size=batch_size, callbacks=callbacks)
        self.lstm_nn.save(sav_filename)
        print('LSTM network training completed. Model saved as %s' %sav_filename)
        time.stop()
コード例 #15
0
def key_press(event):
    key = event.char
    if (key == 'w'):
        Forward()
        myButtonForward.configure(state=DISABLED)
        if __name__ == '__main__':
            t = threading.Timer(0.1, timeForward)
            t.start()

    elif (key == 's'):
        Backward()
        myButtonBackward.configure(state=DISABLED)
        if __name__ == '__main__':
            t = threading.Timer(0.1, timeBackward)
            t.start()

    elif (key == 'a'):
        #  RotateLeft()
        myButtonRotateLeft.configure(state=DISABLED)
        if __name__ == '__main__':
            t = threading.Timer(0.1, timeRotateLeft)
            t.start()

    elif (key == 'd'):
        #  RotateRight()
        myButtonRotateRight.configure(state=DISABLED)
        if __name__ == '__main__':
            t = threading.Timer(0.1, timeRotateRight)
            t.start()
コード例 #16
0
    def collect_samples_multithread(self):
        #queue = Queue.Queue()
        self.lr = 1e-4
        self.weight = 10
        num_threads = 100
        seeds = [np.random.randint(0, 4294967296) for _ in range(num_threads)]

        ts = [
            mp.Process(target=self.collect_samples,
                       args=(600, ),
                       kwargs={
                           'noise': -0.5,
                           'random_seed': seed
                       }) for seed in seeds
        ]
        for t in ts:
            t.start()
            #print("started")
        self.model.set_noise(self.noise.value)
        while True:
            #if len(self.noisy_test_mean) % 100 == 1:
            #self.save_statistics("stats/MirrorJuly17Iter%d_v2.stat"%(len(self.noisy_test_mean)))
            self.save_model("torch_model/StepperSep13.pt")
            #print(self.traffic_light.val.value)
            #if len(self.test_mean) % 100 == 1 and self.test_mean[len(self.test_mean)-1] > 300:
            #   self.save_model("torch_model/multiskill/v4_cassie3dMirrorIter%d.pt"%(len(self.test_mean),))
            while len(self.memory.memory) < 60000:
                #print(len(self.memory.memory))
                if self.counter.get() == num_threads:
                    for i in range(num_threads):
                        self.memory.push(self.queue.get())
                    self.counter.increment()
                if len(self.memory.memory) < 60000 and self.counter.get(
                ) == num_threads + 1:
                    self.counter.reset()
                    self.traffic_light.switch()

            self.update_critic(128, 1280)
            self.update_actor(128, 1280, supervised=False)
            self.clear_memory()
            #self.run_test(num_test=2)
            self.run_test_with_noise(num_test=2)
            #self.validation()
            self.plot_statistics()
            if self.noise.value > -1.5:
                self.noise.value *= 1.001
                print(self.noise.value)
            self.model.set_noise(self.noise.value)
            self.traffic_light.switch()
            self.counter.reset()
コード例 #17
0
def run():
    
    threads = []
   
    func = [run_USD, run_BTC]

    print("start treading..")
    for f in func:
        t = Thread(target=f, args=())
        t.start()
        threads.append(t)
        
    
    for t in threads:
        t.join()
コード例 #18
0
def onclick(event):
    time_interval = 0.25 #0.25초 이내에 더블클릭해야 인식함 
    global time
    if event.button==3: #우클릭시
        p=ax.format_coord(event.xdata,event.ydata) 
        #matplotlib 내장함수. 클릭 위치의 좌표 string으로 추출 
        kx,ky,kz=cor(p)
        print(p)
        
        if time is None:
            time = threading.Timer(time_interval, on_singleclick, [event,kx,ky,kz,d_1,d_2,a]) #arg를 튜플형태로 넣어서 싱글클릭에 넣는듯? 
            time.start()
            
        if event.dblclick:
            time.cancel()
            ax.scatter(kx, ky, kz, color='green')
            on_dblclick(event,kx,ky,kz,s,d_1,d_2,a)
コード例 #19
0
def Hessian_matrix(Image):
	start = 0
	start = time.start()
	I = np.array(Image)
	S = np.shape(I)

	g = np.ones((1,5), np.float32)
	g_1d = np.ones((1,5), np.float32)
	g_2d = np.ones((1,5), np.float32)

	g, g_1d, g_2d = gaussian_mask(sigma)

	G = g.flatten()
	G1dx = g_1d.flatten()
	G1dy = np.transpose(G1dx)
	G2dx = g_2d.flatten()
	G2dy = np.transpose(G2dx)

	#to smoothen the image
	Igx = Igy = []
	Igx, Igy = gaussian_conv(I, G, S)

	#convoluting Image with 1st derivative of I
	Ix = Iy = []
	Ix, Iy = gaussian_1derv_conv(Igx, Igy, G1dx, G1dy)

	Ixx = Iyy= Ixy =[]
	Ixx, Iyy, Ixy = gaussian_2derv_conv(Ix, Iy, G2dx, G2dy)

	t = 87
	x=y=[]
	for i in range(S[0]):
		for j in range(S[1]):
			Hessian = ([Ixx[i][j], Ixy[i][j]], [Ixy[i][j], Iyy[i][j]])
			H = np.linalg.eigvals(Hessian)
			if(abs(H[1])>t and abs(H[0])>t):
				y.append[i]
				x.append[j]
	plt.figure()
	plt.imshow(I, cmap = cm.gray)
	plt.plot(x,y, 'ro')
	plt.show()
	return = time.start() - start
コード例 #20
0
ファイル: main.py プロジェクト: az1k-dev/MathTrainer
    def start_countdown(self):
        # Функция для обратного отсчета времени
        for i in range(self.settings['countdown_duration'], -1, -1):
            # В виджет label помещается оставшееся время в секундах
            self.countdown_label.setText(str(i))

            # Создается и запускатся объект QTime
            time = QTime()
            time.start()
            while True:
                # При достижении 1 секунды, основной цикл перезапускается
                if time.elapsed() > 1000 or self.closed:
                    break

            # При закрытии окна отсчет останавливается
            if self.closed:
                break

        # Отправляется сигнал о начале решения
        COMMUNICATE_CLASS.round_started.emit(self.stop_mode)
コード例 #21
0
    def run(self):
        data = recv_all(self.socket)
        start_time = time.time()

        if not data:
            return

        return_data = do_computation(*pickle.loads(data))
        if return_data is not None:
            self.socket.send(pickle.dumps(return_data))
            print(time.time() - time.start())
コード例 #22
0
ファイル: Client.py プロジェクト: goddess5321/P2P-Torrent
    def run(self):
        global quitflag
        while True:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

            host = "0.0.0.0"
            port = 11121
            s.bind((host, port))
            s.listen(5)

            counter = 1
            db_file = "./users1.db"
            print("control", control(db_file))
            if control(db_file) == None:
                #print("çalıştım")
                create_table(db_file)
            #create_db("./users1.db")

            while True:
                try:
                    threadQueue = Queue()
                    tQueue = queue.Queue()
                    logQueue.put("Waiting for connections.")
                    c, addr = s.accept()
                    logQueue.put("Got connection from" + str(addr))
                    # writers[addr] = threadQueue
                    time=TimeThread("Time thread-"+ str(counter),host,port)
                    time.start()
                    msg = WriteMessageThread("Msg thread-" + str(counter), host, port,tQueue)
                    msg.start()
                    logQueue.put("Starting ReaderThread - " + str(counter))
                    rThread = readerThread(c, threadQueue, addr,tQueue)
                    rThread.start()
                    logQueue.put("Starting WriterThread - " + str(counter))
                    wThread = writeThread(c, threadQueue, addr)
                    wThread.start()
                    counter += 1
                except KeyboardInterrupt:
                    s.close()
                    logQueue.put('QUIT')
                    break
コード例 #23
0
ファイル: HV_GUI.py プロジェクト: RFQED/HV_GUI
    def __init__(self):                            # allows us to access variables, methods etc in the design.py file
        super(self.__class__, self).__init__()
        self.setupUi(self)                         # This is defined in HV_GUI.py file automatically

        self.threads = [] 
        time = TimeThread("Setting_Time")
        time.setTime.connect(self.time_set)
        self.threads.append(time)
        time.start()

     # It sets up layout and widgets that are defined

        self.setFixedSize(width, height)                # Fixes windows size. Can be resized using def expand below.
        self.setWindowTitle("TRACKER - CAEN SY127 HV System")

        pixmap = QtGui.QPixmap('g-2-tracker-logo-192.ico')
        self.gm2_logo.setPixmap(pixmap)#top right logo
  
        self.set_button.setEnabled(False)
        self.send_button.setEnabled(False)
        self.kill_button.setEnabled(False)
        self.exit_button.setEnabled(True)
        self.disconnect_button.setEnabled(False)

        self.plotly_button.setEnabled(False)

        self.connect_button.clicked.connect(self.connect)
        self.connect_button.click()#click automatically

        self.disconnect_button.clicked.connect(self.disconnect)
        self.set_button.clicked.connect(self.set)
        self.send_button.clicked.connect(self.send)
        self.kill_button.clicked.connect(self.kill)
        self.exit_button.clicked.connect(self.exit)
       # self.plotly_button.clicked.connect(self.plotlyPressed) ##removed till fixed
        self.expand_button.clicked.connect(self.expand)

        self.TextBox_btm.setReadOnly(True)

        print("GUI SET UP")
コード例 #24
0
def Harris(img, th):
    start = 0
    start = time.start()
    I = np.array(img)
    S = np.shape(I)
    Gaussian = np.ones((1, 5), np.float32)
    G_1d = np.ones((1, 5), np.float32)
    Gaussian, G_1d = Gaussian_mask(sigma)
    G = Gaussian.flatten()
    G1dx = G_1d.flatten()
    G1dy = np.transpose(G1dx)

    Igx = Igy = []
    Igx, Igy = gaussian_conv(I, G, S)
    Ix2 = np.square(Igx)
    Iy2 = np.square(Igy)
    Ixy = np.ones(S)
    for i in range(S[0]):
        for j in range(S[1]):
            Ixy[i][j] = Igx[i][j] * Igy[i][j]

    Lxx = Lyy = []
    Lxx, Lyy, Lxy = gaussian_1derv_conv(Ix2, Iy2, Ixy, G1dx, G1dy, S)

    #plt.imshow(I, cmap = cm.gray)
    for i in range(S[0]):
        for j in range(S[1]):
            Harris = ([Lxx[i][j], Lxy[i][j]], [Lxy[i][j], Lyy[i][j]])
            eigenv1, eigenv2 = np.linalg.eig(Harris)[0]
            C = eigenv1 * eigenv2 - 0.04 * (eigenv1 + eigenv2)
            if (C > th):
                x.append[j]
                y.append[i]

    plt.figure()
    plt.imshow(I, cmap=cm.gray)
    plt.plot(x, y, 'ro')
    plt.axis([0, S[1]], [S[0], 0])
    plt.show()
    return (time.start() - start)
コード例 #25
0
def listen_sensors():
    # main listener task which will be running continiously. listening to sensor publishers.
    global timesRetry
    global listening
    import threading
    import time
    import socket
    try:
        addr1 = socket.gethostbyname('ip.applause.no')
    except:
        return False
    print("started testing")
    sensorListener.change_serverIp(addr1)
    sensorListener.change_userInfo('engineer', 'vykgVjYTPDcK')
    while (listening):
        t = threading.Thread(target=sensorListener.listen_until)
        print("is_alive = " + str(t.is_alive()))
        print("_initialized = " + str(t._initialized))
        t.start()
        print("is_alive = " + str(t.is_alive()))
        print("_initialized = " + str(t._initialized))
        i = 0
        messageData = ""
        while t.is_alive():
            if (sensorListener.check_recievedMsg()):
                messageData = sensorListener.get_recentMsg()
                fit_dataQueue(messageData)
                i = 0
                sensorListener.stop_listening()
            else:
                print("listening ... " + str(i))
                i += 1
                time.sleep(2)
                if (i > 40):
                    sensorListener.stop_listening()
                    time.sleep(2)
                    return False
    return True
コード例 #26
0
    def collect_samples_multithread(self):
        #queue = Queue.Queue()
        self.lr = 1e-4
        self.weight = 10
        num_threads = 10
        seeds = [
            np.random.randint(0, 4294967296) for _ in range(num_threads)
        ]

        ts = [
            mp.Process(target=self.collect_samples,args=(300,), kwargs={'noise':-2.0, 'random_seed':seed})
            for seed in seeds
        ]
        for t in ts:
            t.start()
            #print("started")
        self.model.set_noise(-2.0)
        while True:
            self.save_model("torch_model/corl_demo.pt")
            while len(self.memory.memory) < 3000:
                #print(len(self.memory.memory))
                if self.counter.get() == num_threads:
                    for i in range(num_threads):
                        self.memory.push(self.queue.get())
                    self.counter.increment()
                if len(self.memory.memory) < 3000 and self.counter.get() == num_threads + 1:
                    self.counter.reset()
                    self.traffic_light.switch()

            self.update_critic(128, self.critic_update_rate)
            self.update_actor(128, self.actor_update_rate, supervised=self.supervised)
            self.clear_memory()
            self.run_test(num_test=2)
            self.run_test_with_noise(num_test=2)
            #self.validation()
            self.plot_statistics()
            self.traffic_light.switch()
            self.counter.reset()
コード例 #27
0
def main(args):
    createDatabase(DBFILE)
    server_sock = BluetoothSocket(RFCOMM)
    server_port = PORT_ANY
    server_address = '', server_port
    server_sock.bind(server_address)
    server_sock.listen(100)

    uuid = '94f39d29-7d6d-437d-973b-fba39e49d4ee'
    advertise_service(server_sock,
                      name="CreamPi",
                      service_id=uuid,
                      service_classes=[SERIAL_PORT_CLASS],
                      profiles=[SERIAL_PORT_PROFILE])

    print('Listening for clients, on port ', server_port, '...')

    while (True):
        client_sock, addr = server_sock.accept()
        t = Thread(target=handleClient, args=(client_sock, addr))
        t.start()

    server_sock.close()
コード例 #28
0
	def __init__(self, interval = 3600, path=None):
		self.interval = interval
		self.currentFile = ""
		self.timeCur = 0
		self.timeStart = 0
		self.path = os.getcwd()
		self.f = ""
		
		p = path.split("/")
		
		fileName = ("%s_log.csv" % self.getTime())
		
		l = LogFile(fileName)
		
		for x in range(0, len(p)):
			if(os.path.exists(p[x])):
				self.path+= "/"+str(p[x])
				
			else:
				os.mkdir(self.path + "/" + str(p[x]))
				self.path+= "/"+str(p[x])
				
		if(os.path.exists(self.path + "/" + l.date)):
			self.path+= "/"+str(l.date)
			
		else:
			os.mkdir(self.path + "/" + l.date)
			self.path+= "/"+str(l.date)
		self.f = open(self.path+ "/" + fileName, "w+")
		
		try:
			t = Thread(target = self.openFile, args = ())
		except Exception:
			print("Unable to start thread")

		t.start()
コード例 #29
0
ファイル: main.py プロジェクト: prunk1al/yourlasttube
    def real_post(self):
        import time
        time_star=time.time()

        j=self.request.body
        data=json.loads(j)
        genre=data["data"]
        tracks=None
        tracks=memcache.get("%s Videos playlist"%genre)
        if tracks is None:

            playlist=Playlist()
            playlist.tipo="artist"
            playlist.param=data["data"]

            playlist.create()
            tracks=playlist.getTracks()
            memcache.set("%s Videos playlist"%genre, tracks)
        logging.error("total time of playlist= %s"%(time.time()-time.start()))
        self.response.out.write(json.dumps(tracks))
コード例 #30
0
ファイル: process (4).py プロジェクト: Jayyveee/ChatApp
class sockk:


    # gpg =
    m = menu()
    r = choices()
    r_buf = 1024
    connxn = {}
    seg = []

    def messageReceived(sock,listen,p_port,p_ip,cost,n_id):
            sock.bind(("",listen))
            host = socket.gethostbyname(socket.gethostname())
            host = str(host)
            listen = str(listen)
            r.self_id = host + ":" + listen
            neigh_ip = socket.gethostname(p_ip)
            neigh_ip = str(neigh_ip)
            neigh_id = neigh_ip + ":" + p_port
            r.routing_table[neigh_id] = {}   
            r.routing_table[neigh_id]['cost'] = cost
            r.routing_table[neigh_id]['link'] = neigh_id
            r.routing_table[neigh_id]['nickname'] = n_id
            r.adj_links[neigh_id] = cost
            r.neigh[neigh_id] = {}
            r.time_out = m.time_out()
            os.system("clear")
            start.process(sock,connxn)

            while 1:
                sock_lst = [sys.stdin,sock]
                try:
                    sread,swrite,serror = select.select(sock_lst,[],[])
                except select.error:
                    break
                except socket.error:
                    break

                for s in sread:
                    if s == sock:
                        data,address = sock.recvfrom(r_buf)
                        connxn[address] = n_id
                        if not os.path.isfile("first.asc"):
                                pgp.generate_certificates()
                                seg.append(data)
                                deseg = join(seg)
                        try:
                                decry = pgp.decrypt(deseg)
                                data = json.loads(decry)
                                seg[:]=[]
                                r.msg_handler(s_socket,data, address)      #########
                                time.sleep(0.01)
                        except:
                                pass 
                    
                    else:
                            data = sys.stdin.readline().rstrip()
                            if data=="MENU":
                                os.system("clear")      
                                strat.process(_socket,conn)
                            else:
                                r.private_msg(sock,r.destination_id,data)
                                main1()  #################
            sock.close()

    def join(data):
        joineddata = b''
        for x in data:
            joineddata +=x
        return joineddata
        
    def updatingtime(s_socket,timeout_interval):
            r.updatingneighbor(s_socket)
    def updatingroute(serverSocket,timeout_interval):
            r.n_timer(s_socket)



    if __name__ == "__main__":
            os.system("clear")
            p_ip = menu.p_ip()
            p_port= menu.p_port()
            source_port = menu.source_port()
            destination_port = menu.destination_port()
            n_id= main.node_id()
            cost = main.cost_matrix()
            time_out= main.time_out()
            s_socket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
            s_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
            messageReceived(s_socket,source_port,p_port,p_ip,cost,n_id)
            t = threading.Timer(time_out, time_update, [time_out])
            t.setDaemon(True)
            t.start()
            time = threading.Timer(time_out, updatingroute, [time_out])
            time.setDaemon(True)
            time.start()
コード例 #31
0
ファイル: Fourshot.py プロジェクト: nickkonidaris/SEDC
def fourshot(rc_control, ets = None):
    global abort_4
    
    if ets is None:
        itime = rc_control.getall()[-1]
        ets = [itime] * 4
        
    def expose(time):
        if abort_4: return
        rc_control.setexposure(time)
        
        
        print "exposing"
        while rc_control.isExposing():
            t.sleep(0.2)

        rc_control.go()
        t.sleep(5)
        
        while not rc_control.isExposureComplete():
            t.sleep(0.2)

        
    def helper():
        
        files = []
        
        cmds = GXN.Commands()
        to_move = np.array([180, 180])
        accu = -to_move[:] # accumulated move
        name = rc_control.getall()[1]
        if ets[0] != 0:
            print "move to r"
            cmds.pt(*to_move)
            accu += to_move
            t.sleep(1)
            to_move = np.array([0,0])
            rc_control.setobject("[r] %s" % name)
            files.append("[r]: %s" % rc_control.getfilename())
            expose(ets[0])
        
        to_move += np.array([-360,0])
        if ets[1] != 0:
            print "move to i"
            cmds.pt(*to_move)
            accu += to_move
            t.sleep(1)
            to_move = np.array([0,0])
            rc_control.setobject("[i] %s" % name)
            files.append("[i] %s" % rc_control.getfilename())
            expose(ets[1])
        
        to_move += np.array([0,-360])
        if ets[2] != 0:            
            print "move to g"
            cmds.pt(*to_move)
            accu += to_move
            t.sleep(1)
            to_move = np.array([0,0])
            rc_control.setobject("[g] %s" % name)
            files.append("[g] %s" % rc_control.getfilename())
            expose(ets[2])
        
        to_move += np.array([360,0])
        if ets[3] != 0:
            print "move to u"
            cmds.pt(*to_move)
            accu += to_move
            t.sleep(1)
            to_move = np.array([0,0])
            rc_control.setobject("[u] %s" % name)
            files.append("[u] %s" % rc_control.getfilename())
            expose(ets[3])
            
        rc_control.setobject("%s" % name)
        return files
    
    t= Thread(target=helper)
    t.start()
    return t.join()
コード例 #32
0
    bg2 = pg.BarGraphItem(x=x1, height=binA_plot, width=1,
                          brush='r')  # binary A
    bg3 = pg.BarGraphItem(x=x1, height=binC_plot, width=1,
                          brush='y')  # batasan steering
    bg4 = pg.BarGraphItem(x=x1, height=plot_keluaran, width=1, brush='b')
    bg5 = pg.BarGraphItem(x=x1, height=target_plot, width=1, brush='g')
    window.clear()
    # window.addItem(bg0a)
    # window.addItem(bg0)
    window.addItem(bg1)
    window.addItem(bg2)
    window.addItem(bg3)
    window.addItem(bg4)
    window.addItem(bg5)
    window.setXRange(50, 300)
    # window.setXRange(0,360)
    window.setYRange(0, 1.1)
    window.plot()

    # window.plot(x1,y1,clear=True)


time = QtCore.QTimer()
time.timeout.connect(update)
time.start(25)

if __name__ == '__main__':
    import sys
    if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
        QtGui.QApplication.instance().exec_()
コード例 #33
0
    def test_threading(self):

        t = threading.Thread(target=self.thread_function, args=None)

        t.start()
        t.join()
コード例 #34
0
ファイル: 函数练习.py プロジェクト: endlessden/gitfun
 def wrapper():
     start = time.start()
     res = func(*args, **kwargs)
     stop = stop.stop()
     print('run time is %s' % (stop - start))
     return res
コード例 #35
0
ファイル: views.py プロジェクト: tomperr/Flask-BOTSW
def manual_run():
    global actual_run
    t = Thread(target=my_function)
    t.start()
    return render_template("index.html")
コード例 #36
0
            data_mes = data_dic['Mes']
            print('收到客户端发来的数据:' + data_mes)

            if 'heart' in mes_type:
                #是心跳包数据
                # 返回心跳包数据 +1
                time_int = (int)(data_mes) + 1
                heart_str = '服务端返回心跳:%d' % (time_int)
                sendMessage('heart', heart_str)

                if time != None:
                    #如果存在time 关闭定时器触发
                    time.cancel()
                # 重新启动心跳包检测的定时器
                time = threading.Timer(20.0, socketClose)
                time.start()
            else:
                if data_mes == 'exit':
                    break
                else:
                    # 给客户端返回数据
                    mes = '服务端返回数据:' + data_mes
                    sendMessage('commamd', mes)

        except Exception as e:
            # 接收异常的情况下,断开连接。
            break

    # 主动关闭链接
    # sock.close()
    socketClose()