def __init__(self, id, config, clientId, clientConfig): self.id = id self.state = "follower" self.peers = [] self.voters = [] self.numVotes = 0 self.nodePorts = {} self.clientId = clientId self.clientConfig = clientConfig self.load_config(config) self.currentTerm = 0 self.VoteFor = -1 self.log = {} self.lastLogIndex = 0 self.lastLogTerm = 0 self.timeOut = random.uniform(1, 3) # socket self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock.bind(("", self.port)) # initial threads self.follower_state = kthread.KThread(target=self.follower, args=()) self.rpc_load = kthread.KThread(target=self.rpc_socket, args=(RPC_process, ))
def __init__(self, src, dest): self.src = src # 10000 self.dest = dest # 10001 self.index = 0 self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock.bind(("", self.src)) self.send_thread = kthread.KThread(target=self.send, args=()) self.recv_thread = kthread.KThread(target=self.recv, args=())
def leader(self): self.state = "leader" print("\n<Term Update>: Term {}'s Leader[{}]. / {} /\n".format( self.currentTerm, self.id, time.asctime())) self.save_state() self.heartbeat_call = kthread.KThread(target=self.send_heartbeat, args=()) self.heartbeat_call.start() self.entry_call = kthread.KThread(target=self.request_entry, args=()) self.entry_call.start()
def __init__(self, src, dest, foll): self.src = src # 10001 self.dest = dest # 10000 self.foll = foll # 10002 self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock.bind(("",self.src)) self.send_thread = kthread.KThread(target=self.send, args= ()) self.recv_thread = kthread.KThread(target=self.recv, args= ()) self.heartbeat_call = kthread.KThread(target=self.send_heartbeat, args= ()) self.lastLogIndex = 0
def __init__(self, id): self.id = id self.role = "follower" self.leaderID = 0 address = json.load(open("config.json")) port_list = address["port"] running = address["running"] self.serverlist = {} for running_id in running: self.serverlist[running_id] = port_list[running_id - 1] initial_running = [1, 2, 3, 4, 5] self.cur_term = 0 self.VoteFor = -1 self.log = [] self.peers = [i for i in initial_running if i != self.id] self.majority = 3 self.request_votes = self.peers.copy() self.port = self.serverlist[self.id] self.lastLogIndex = 0 self.lastLogTerm = 0 self.listener = kthread.KThread(target=self.listen, args=(acceptor, )) self.listener.start()
def loadSess(self): outdir = os.path.expanduser('~') log_dir = outdir + '/logs' pp = os.path.join(log_dir, "sess.json") with open(pp) as json_file: data = json.load(json_file) empty = False empty2 = False if data != None: y2 = json.loads(data) for i in y2: print(y2[i]) if y2[i] == None: empty = True else: empty2 = True if empty2 == True: QMessageBox.information(None, "Stop", "Make sure everything is ready first") if empty == True: QMessageBox.information(None, "Stop", "Make sure everything is ready first") if empty == False: self.x = gan.xx(y2['a'], y2['b'], y2['r'], y2['d'], y2['e'], y2['f'], y2['g'], y2['h'], y2['i'], y2['j'], y2['k'], y2['l'], y2['m'], y2['n'], y2['o'], y2['p'], y2['q'], y2['c'], y2['s'], y2['t'], y2['u'], y2['v'], y2['w'], y2['x'], y2['y'], y2['z'], y2['aa'], y2['bb'], y2['cc'], y2['dd'], y2['ee'], y2['ff'], y2['gg']) self.y = kthread.KThread(target=self.loop, args=()) self.y.start()
def play_chunks(self, queue: Queue): print("in play chunks: the main func of the child process") try: os.setsid() except: pass self.mode = "play_loop" self.c = Chunks() self.c.load() self.queue = queue self.is_draw_wave = False self.t_cmd_solver = threading.Thread(target=self.cmd_solver) self.t_cmd_solver.setDaemon(False) self.t_cmd_solver.start() print("cmd solver thread started") while True: self.t_play = kthread.KThread(target=self.play_thread) print("create a new thread") self.t_play.setDaemon(False) self.t_play.start() if self.is_draw_wave: self.draw_wave(self.c) self.is_draw_wave = False self.t_play.join() print('subprocess end')
def xx(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, aa, bb, cc, dd, ee, ff, gg): x = kthread.KThread(target=action, args=(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, aa, bb, cc, dd, ee, ff, gg)) x.start() return x
def step_down(self): if self.role == "candidate": self.election.kill() self.last_update = time.time() self.role = "follower" elif self.role == "leader": self.leader_state.kill() self.follower_state = kthread.KThread(target=self.follow, args=()) self.follower_state.start()
def candidate(self): self.state = "candidate" print("Node[{}]: Candidate. / {} /".format(self.id, time.asctime())) if len(self.peers) >= 0: self.currentTerm += 1 self.votefor = self.id self.numVotes = 1 self.vote_call = kthread.KThread(target=self.request_vote, args=()) self.vote_call.start()
def selectDirectory(self): dirName = QFileDialog.getExistingDirectory( None, 'Select Directory', os.path.expanduser('~') + '/Desktop') if dirName != "": self.content.edit.setText(dirName) check_folder(os.path.join(dirName, "samples")) x2 = kthread.KThread(target=self.loop, args=()) x2.start()
def listen(self, accept): srv = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) srv.bind(("", self.port)) print("start Listening") while True: data, addr = srv.recvfrom(1024) new_thread = kthread.KThread(target=accept, args=(self, data, addr)) new_thread.start() srv.close()
def start_election(self): self.role = "cadidate" print("The current state is a candidate" + " Time Stamp: " + time.asctime()) self.election = kthread.KThread(target=self.thread_election, args=()) if len(self.peers) != 0: self.cur_term += 1 self.votefor = self.id # self.log() self.numVotes = 1 self.election.start()
def __init__(self, id, port): self.id = id # 111 self.port = port # 10000 self.dest = None self.lastLogIndex = 0 self.lastLogTerm = 0 self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock.bind(("", self.port)) self.rpc_call = kthread.KThread(target=self.rpc_process, args=())
def toFollower(self, term): self.currentTerm = term if self.state == "candidate": self.term_thread(self.vote_call) self.term_thread(self.candidate_state) self.follower_state = kthread.KThread(target=self.follower, args=()) self.follower_state.start() elif self.state == "leader": self.term_thread(self.heartbeat_call) self.term_thread(self.entry_call) self.term_thread(self.leader_state) self.follower_state = kthread.KThread(target=self.follower, args=()) self.follower_state.start()
def rpc_socket(self, process): while True: try: data, addr = self.recv_socket() rpc_msg = pickle.loads(data) rpc_thread = kthread.KThread(target=process, args=(self, rpc_msg)) rpc_thread.start() except Exception as e: print(e) self.sock.close()
def follower(self): print("Node[{}]: Follower. / {} /".format(self.id, time.asctime())) self.state = "follower" self.last_update = time.time() time_out = self.timeOut while time.time() - self.last_update < time_out: pass self.candidate_state = kthread.KThread(target=self.candidate, args=()) self.candidate_state.start() #self.candidate() while True: try: self.last_update = time.time() while time.time() - self.last_update < self.timeOut: pass self.candidate_state = kthread.KThread(target=self.candidate, args=()) self.candidate_state.start() #self.candidate() except Exception as e: print(e)
def __init__(self, blocking_generator, timeout, logger, stop_if_timeout=False): self.logger = logger self.timeout = timeout self.logger.info("Nonblocking_iterator timeout %s", timeout) self.stop_if_timeout = stop_if_timeout self.msg_queue = queue.Queue() self.blocking_generator = blocking_generator self._thread = kthread.KThread( target=self._put_messages_from_blocking_generator_to_queue) self._thread.start()
def toggle(lcbbuttonvar, mcbbuttonvar, rcbbuttonvar, keyboardentry, cpsvalue, loadedjsonsettings): save(loadedjsonsettings) try: toggle.currentStatus except: toggle.currentStatus = bool() if toggle.currentStatus == False: root.focus_set() if not len(process_list) >= 1: process_list.append(str(random.randint(0, 999))) p = kthread.KThread(target=running, args=(lcbbuttonvar, mcbbuttonvar, rcbbuttonvar, keyboardentry, cpsvalue, loadedjsonsettings), name=process_list[len(process_list) - 1]) p.daemon = True process_list[len(process_list) - 1] = p print(p) p.start() win32api.Sleep(100) print('START') newPhoto = PhotoImage(file='./icons/general/stop.png') toggleButton.config(image=newPhoto) toggleButton.image = newPhoto toggle.currentStatus = True elif toggle.currentStatus == True: root.focus_set() if bool(process_list) == True: p = process_list[len(process_list) - 1] p.terminate() p.join() del (process_list[len(process_list) - 1]) print('STOP') initVars(loadedjsonsettings) newPhoto = PhotoImage(file='./icons/general/play.png') toggleButton.config(image=newPhoto) toggleButton.image = newPhoto toggle.currentStatus = False else: toggle.currentStatus = False win32api.Sleep(1000)
def runBitch(self): bb= os.path.basename(self.args[6]) patho = os.path.join(self.args[18] , bb) check_folder(self.args[18]) file1 = open(os.path.join(self.args[18] ,"log"), "w+") file1.write("0") file1.close() if self.si == True: x = gan.xx(self.args[0], self.args[1], self.args[17], self.args[3], self.args[4], self.args[5], self.args[6], self.args[7], self.args[8], self.args[9], self.args[10], self.args[11], self.args[12], self.args[13], self.args[14], self.args[15], self.args[16], self.args[2], self.args[18], self.args[19], self.args[20], self.args[21], self.args[22], self.args[23], self.args[24], self.args[25], self.args[26], self.args[27], self.args[28], self.args[29], self.args[30], self.args[31], self.args[32]) x2 = kthread.KThread(target=self.loop, args=()) x2.start() if self.si == False: QMessageBox.information(None, "Stop", "Prepare everything first") return
def start_action(): stop_action() kthread.KThread(target=autopilot, name="EDAutopilot").start()
def download_file(self, save_path, overwrite_check=False, automatic_filename=False, new_download_method=True, convert_to_mp4=False): """ This function is used for downloading the requested file from the internet and save it into a specific folder. :param save_path: Folder where the file will be saved :param overwrite_check: (Optional, default=False) If it's true the program will check if there's already a file with the same name in the "save_path" folder otherwise it will do any type of check. :param automatic_filename: (Optional, default=False) If it's true the program will generate a unique filename to the downloaded video (current datetime in yyyMMdd-hhmmss format) otherwise the video will have the one chosen before saved in the DownloadRequest object attribute. :param new_download_method: (Optional, default=True) If it's true the program will use the new download method (Youtube-DL embedded) which supports +800 websites and multiple videos streams (es: segmented videos, normal videos, ...) otherwise it will use the plain HTTP Get request do try to download the video from the web page (WARNING: it supports only the normal videos) :param convert_to_mp4: (Optional, default=False) If it's true the program will convert all the downloaded videos to mp4 format, otherwise the video file will not be converted after the download. This option is supported only using the new download method and it requires ffmpeg installed on the system. (WARNING: This video conversion can comport bad video quality and/or video/audio dystrosions) :return: True if the download process finished successful otherwise a string object containing the error message. """ try: if not new_download_method: self.notifier.notify_warning( "You are using the old download method, this method does\ support only few sites and less options.\ You rather switch to the new one by changing the config file!" ) if convert_to_mp4: self.notifier.notify_warning( "The file conversion is supported only using the new download method." ) if not automatic_filename: ''' Create the urllib object for downloading files on the internet ''' filename = self.download_req.filename else: ''' It will save the file with a unique filename based on the computer time (date and hour) ''' current_time = datetime.datetime.now() filename = current_time.strftime("%m%d%Y-%H%M%S") ''' Normalize the name (only numbers and letters) ''' filename = self._normalize_filename( filename) + self._get_file_extension(self.download_req.url) ''' Build path ''' full_path = os.path.join(save_path, filename) ''' Check for overwrite if it's enabled ''' if overwrite_check: print("[!] Starting overwrite check") if not self.overwrite_check(save_path, filename): return "[Overwrite] Error, with this filename you will overwrite a file" # Connects to the site and download the media urllib.request.urlretrieve(self.download_req.url, full_path, self.download_progress) # Uploads the video on OpenLoad self._handle_download_finished(full_path, self.TOT_DOWNLOADED) self.DOWNLOAD_FINISHED = True print("[Downloader] File named {} saved correctly".format( full_path)) self.notifier.notify_success( "File downloaded and uploaded correctly!.") else: self.notifier.notify_information("Starting download") self.notifier.notify_information("\ You are using the new download system witch supports a lot of websites,\ <a href='https://ytdl-org.github.io/youtube-dl/supportedsites.html'>view the full list </a>." ) print("[DownloadManager] Starting download in another thread") download_process = kthread.KThread(target=self._download, args=( save_path, self.download_req, automatic_filename, convert_to_mp4, )) # download_process.daemon = True download_process.start() print( "[DownloadManager] Download started in another thread: {}". format(download_process)) # Add process to the list of processes TelegramBot.DOWNLOAD_PROCESSES[TelegramBot.get_user_id( self.notifier.get_session())] = download_process # self._download(save_path, self.download_req, automatic_filename, convert_to_mp4=convert_to_mp4) # self.wait_download_to_finish() return True except FileNotFoundException as f: # If the directory where is going to save the file doesn't exists print( "[Downloader] Error of type {} while downloading file:".format( type(f).__name__), str(f)) self.notifier.notify_error( "Detected an error while downloading the resource: " + str(f))
def acceptor(server, data, addr): Msg = pickle.loads(data) type = Msg.type sender = Msg.sender term = Msg.term if type == 1: # RequestVote print("Receive Request Vote Message from {}".format(sender)+ " Time Stamp: " + time.asctime()) if sender not in server.peers: return msg = Msg.data msg = msg.split(" ") if term < server.cur_term: print("Reject vote due to old term"+ " Time Stamp: " + time.asctime()) voteGranted = 0 elif term == server.cur_term: if server.VoteFor == -1 or server.VoteFor == sender: voteGranted = 1 else: voteGranted = 0 else: server.cur_term = term server.step_down() voteGranted = 1 server.VoteFor = sender if voteGranted == 1: print("Granted") else: print("Not Granted") reply = str(voteGranted) reply_msg = VoteResponseMsg(server.id, sender, server.cur_term, reply) sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.sendto(pickle.dumps(reply_msg),("", server.serverlist[sender])) elif type == 2: #VoteResponseMsg print("Receive Vote Response Msg from server {}".format(sender)+ " Time Stamp: " + time.asctime()) msg = Msg.data voteGranted = int(msg) if voteGranted: if server.role == "candidate": server.request_votes.remove(sender) server.numVotes += 1 if server.numVotes == server.majority: print("Get majority Vote, become the leader at term {}".format(server.cur_term)+ " Time Stamp: " + time.asctime()) if server.election.is_alive(): server.election.kill() server.role = "leader" server.follower_state.kill() server.leader_state = kthread.KThread(target = server.leader, args = ()) server.leader_state.start() else: if term > server.cur_term: server.cur_term = term if server.role == "candidate": server.step_down() elif type == 0: print("Receive heartbeat from {}".format(sender)+ " Time Stamp: " + time.asctime()) if term >= server.cur_term: server.cur_term = term server.step_down() if server.role == "follower": server.last_update = time.time() success = "True" server.leaderID = sender else: success = "False" reply_msg = AppendEntryResponseMsg(server.id, sender, server.cur_term, success) s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.sendto(pickle.dumps(reply_msg), ("", server.serverlist[sender])) elif type == 3: success = Msg.success if success == "False": if term > server.cur_term: server.step_down() else: print("Receive heartbeat response from {}".format(sender)+ " Time Stamp: " + time.asctime())
def run(filename, mode): beatdetection.runBeatDetection(filename, mode) cam = cv2.VideoCapture(0) width = 1300 height = 750 totalScore = 0 increment = 10 hit = 0 startTime = time.time() shown = '' kept = 0 numTimes = 0 ################code modified from https://pastebin.com/WVhfmphS################# # construct the argument parse and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-v", "--video", help="path to the (optional) video file") ap.add_argument("-b", "--buffer", type=int, default=64, help="max buffer size") args = vars(ap.parse_args()) # define the lower and upper boundaries of the colors in the HSV color space lower = {'red': (166, 84, 141), 'blue': (97, 100, 117)} upper = {'red': (186, 255, 255), 'blue': (117, 255, 255)} # define standard colors for circle around the object colors = {'red': (0, 0, 255), 'blue': (255, 0, 0)} ############################################################################# #maybe try to add sound effects everytime they get a note/miss def scoreboard(score, hit, shown, increment, kept): font = cv2.FONT_HERSHEY_SIMPLEX if shown == 'NICE': cv2.putText(img, shown, (int(width / 2 - 125), int(height / 2 + 150)), font, 2.5, (138, 247, 165), 4, cv2.LINE_AA) else: cv2.putText(img, shown, (int(width / 2 - 125), int(height / 2 + 150)), font, 2.5, (0, 0, 0), 4, cv2.LINE_AA) if time.time() - kept == 1.5: shown = '' if hit >= 3: cv2.putText(img, "Streak: " + str(hit), (int(width / 2 - 225), int(height / 2 + 70)), font, 2.5, (255, 102, 153), 4, cv2.LINE_AA) cv2.putText(img, str(score), (int(width / 2 - 85), int(height / 2 + 297)), font, 2.5, (255, 255, 255), 4, cv2.LINE_AA) cv2.putText(img, str(score), (int(width / 2 - 82), int(height / 2 + 300)), font, 2.5, (255, 215, 144), 4, cv2.LINE_AA) cv2.putText(img, 'Press "e" to end the game', (int(width - 470), int(height - 35)), font, 1, (255, 215, 144), 2, cv2.LINE_AA) class Circle(): def __init__(self, x, y, color, thickness, radius=63, mark=False): self.x = x self.y = y self.color = color self.thickness = thickness self.radius = radius self.mark = mark def move(self): self.y -= 10 def draw(self): cv2.circle(img, (self.x, self.y), self.radius, self.color, self.thickness) def collision(self, base, ballx, bally): if self.mark == False: if (base.x - self.x)**2 + ( base.y - self.y)**2 <= self.radius**2 and ( ballx - self.x)**2 + (bally - self.y)**2 <= self.radius**2: self.mark = True return True return False beatColors = { 0: (0, 0, 255), 1: (255, 0, 255), 2: (0, 255, 255), 3: (255, 255, 0) } horiz = { 0: int(width / 5), 1: int(2 * width / 5), 2: int(3 * width / 5), 3: int(4 * width / 5) } base = [] base.append(Circle(int(width / 5), 70, (0, 0, 255), 5)) base.append(Circle(int(2 * width / 5), 70, (255, 0, 255), 5)) base.append(Circle(int(3 * width / 5), 70, (0, 255, 255), 5)) base.append(Circle(int(4 * width / 5), 70, (255, 255, 0), 5)) beats = [] print(filename) w = kthread.KThread(target=backaudio.playAudio, args=(filename, )) w.start() while (1): _, img = cam.read() img = cv2.flip(img, 1) img = cv2.resize(img, (width, height)) ################code modified from https://pastebin.com/WVhfmphS##################### # blur it, and convert it to the HSV # color space blurred = cv2.GaussianBlur(img, (11, 11), 0) hsv = cv2.cvtColor(blurred, cv2.COLOR_BGR2HSV) #for each color in dictionary check object in img for key, value in upper.items(): # construct a mask for the color from dictionary`1, then perform # a series of dilations and erosions to remove any small # blobs left in the mask kernel = np.ones((9, 9), np.uint8) mask = cv2.inRange(hsv, lower[key], upper[key]) mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel) mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel) # find contours in the mask and initialize the current # (x, y) center of the ball cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2] center = None # only proceed if at least one contour was found if len(cnts) > 0: # find the largest contour in the mask, then use # it to compute the minimum enclosing circle and # centroid c = max(cnts, key=cv2.contourArea) ((ballx, bally), radius) = cv2.minEnclosingCircle(c) M = cv2.moments(c) center = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"])) # only proceed if the radius meets a minimum size. Correct this value for your obect's size if radius > 0.5: # draw the circle and centroid on the img, # then update the list of tracked points cv2.circle(img, (int(ballx), int(bally)), int(radius), colors[key], 2) ################################################################################# for beat in beats: for circle in base: if beat.collision(circle, ballx, bally): shown = 'NICE' totalScore += increment hit += 1 for circle in base: circle.draw() for beat in beats: beat.draw() beat.move() if beat.y <= 70: if not beat.mark: hit = 0 increment = 10 shown = 'MISS' beats.remove(beat) songTime = float('%.2f' % (time.time() - startTime)) # print(songTime) for btime in beatdetection.beatTime: if songTime - 0.03 <= btime <= songTime + 0.03: ind = randint(0, 3) newCirc = Circle(horiz[ind], height - 63, beatColors[ind], -1) beats.insert(0, newCirc) if songTime > beatdetection.beatTime[len(beatdetection.beatTime) - 1] + 3: endPage.drawEnd(totalScore, img) if hit % 10 == 0 and hit > 0 and numTimes == 0: increment *= 1.3 increment = int(increment) numTimes += 1 elif hit % 10 != 0: numTimes = 0 scoreboard(totalScore, hit, shown, increment, kept) cv2.imshow('img', img) key = cv2.waitKey(1) & 0xFF # if the 'q' key is pressed, stop the loop if key == ord("q"): cam.release() cv2.destroyAllWindows() if key == ord("e"): w.kill() beatdetection.beatTime = [] if len(leaderboard.highScores ) < 5 or totalScore > leaderboard.highScores[4]: font = cv2.FONT_HERSHEY_SIMPLEX print("HIGHSCORE") cv2.rectangle(img, (100, 100), (width - 100, height - 100), (145, 159, 242), -1) cv2.putText(img, 'HIGHSCORE!!!', (150, 250), font, 3, (0, 0, 0), 2, cv2.LINE_AA) cv2.putText(img, 'Enter your name:', (150, 450), font, 1.5, (0, 0, 0), 2, cv2.LINE_AA) cv2.imshow('img', img) time.sleep(1) name = input('Your Name: ') endPage.drawEnd(totalScore, img, name)
#play stream while data: stream.write(data) data = f.readframes(chunk) #stop stream stream.stop_stream() stream.close() #close PyAudio p.terminate() #################################################################### sa = kthread.KThread(target=startScreenAudio, args=()) sa.start() while (1): _, img = cam.read() img = cv2.flip(img, 1) img = cv2.resize(img, (width, height)) font = cv2.FONT_HERSHEY_SIMPLEX cv2.putText(img, 'HANDS HANDS', (int(width / 2 - 429), int(height / 2 - 84)), font, 4, (0, 0, 0), 4, cv2.LINE_AA) cv2.putText(img, 'HANDS HANDS', (int(width / 2 - 425), int(height / 2 - 80)), font, 4, (255, 255, 255), 4, cv2.LINE_AA) cv2.putText(img, 'HANDS HANDS',
def RPC_process(server, msg): type = msg.type term = msg.term sender = msg.src receiver = msg.dest if type == 'RequestVote': print("<Vote Request>: Candidate: Node[{}] ———> followers. / {} /".format(sender, time.asctime())) if sender not in server.peers: return if term < server.currentTerm: voteGranted = 0 elif term > server.currentTerm: server.toFollower(term) voteGranted = 1 server.VoteFor = sender else: if server.VoteFor == -1 or sender: voteGranted = 1 else: voteGranted = 0 #replyPorts = server.nodePorts[sender] #replyMsg = VoteResponseRPC(server.id, sender, server.currentTerm, voteGranted) #server.send_socket(replyMsg, replyPorts) return(voteGranted) elif type == 'VoteResponse': print("<Vote Response>: follower[{}] ———> Candidate[{}]. / {} /".format(sender, receiver, time.asctime())) voteGranted = msg.data if voteGranted == 1: if server.state == "candidate": server.voters.remove(sender) server.numVotes += 1 if server.numVotes >= math.ceil(len(server.peers) / 2): server.vote_call.kill() server.state = "leader" server.follower_state.kill() server.leader_state = kthread.KThread(target = server.leader, args = ()) server.leader_state.start() else: if term > server.currentTerm and server.state == "candidate": server.toFollower(term) return(server.numVotes) elif type == 'AppendEntry': print("<Heartbeat> Leader[{}] ———> follower[{}]. / {} /".format(sender, receiver, time.asctime())) if term >= server.currentTerm: server.toFollower(term) if server.state == "follower": server.last_update = time.time() success = "True" else: success = "False" server.lastLogIndex = msg.lastLogIndex #replyPorts = server.nodePorts[sender] #replyMsg = EntryResponseRPC(server.id, sender, server.currentTerm, success) #server.send_socket(replyMsg, replyPorts) return(server.lastLogIndex) elif type == 'EntryResponse': if msg.success == "True": print("<Heartbeat Response> follower[{}] ———> Leader[{}]. / {} /".format(sender, receiver, time.asctime())) else: if term > server.currentTerm: server.toFollower(term) return(msg.success) elif type == 'ClientEntryResponse': print("\n<Client Append Entry> Client[{}] ———> Leader[{}], Log Entry[{}]. / {} /\n".format(sender, receiver, msg.lastLogIndex, time.asctime())) server.lastLogIndex = msg.lastLogIndex log = {} log["Client"] = sender log["Leader"] = receiver log["Index"] = msg.lastLogIndex server.log = log return(log)
for d in diameter: time.sleep(1.75) print(Fore.MAGENTA +' Circumference: ', d * 3.14, '\r') # print('\r') def circle2(radius): print(Fore.CYAN + ' Thread through calculating the Area of a Circle ', '\r') print('\r') for r in radius: time.sleep(1.75) print(Fore.CYAN + ' Area: ', r * r * 3.14,'\r') # print('\r') arr = [10,11,12,13,14,15] t = time.time() t1 = kthread.KThread(target=circle1, args =(arr, )) t2 = kthread.KThread(target=circle2, args =(arr, )) t1.start() t2.start() t1.join() t2.join() print('\r') print(Fore.YELLOW + 'KThreading terminated in: ', time.time()) print('\r')
def main(search): image_queue = Queue(maxsize=1) detections_queue = Queue(maxsize=1) embedding_queue = Queue(maxsize=1) info_video = InformationVideo() info_model = InformationModel() if not search: print("Enter your name: ") while True: name = input() if name: print('name', name) if os.path.exists(json_file): with open(json_file) as file: data_person = json.load(file) person_id = int(list(data_person.keys())[-1]) + 1 data_person.update({str(person_id): str(name)}) print(data_person) else: person_id = 0 data_person = {str(person_id): str(name)} # Save json with open(json_file, 'w+') as fp: json.dump(data_person, fp) break else: print("Please enter your name. Enter your name: ") else: person_id = None t1 = kthread.KThread(target=video_capture, args=(image_queue, info_video)) t2 = kthread.KThread(target=detect_face, args=(image_queue, detections_queue, info_model, info_video)) t3 = kthread.KThread(target=extract_embedding, args=(detections_queue, embedding_queue, info_model, info_video, person_id, search)) t1.daemon = True t1.start() t2.daemon = True t2.start() t3.daemon = True t3.start() num_thread = [] num_thread.append(t1) num_thread.append(t2) num_thread.append(t3) stop_all = False while True: if info_video.cap.isOpened(): encoding_vector, image_rgb, index_frame, num_vector = embedding_queue.get() if num_vector == 1000 and not search: break if index_frame == -1: while True: image_rgb = cv2.cvtColor(image_rgb, cv2.COLOR_RGB2BGR) image_rgb = cv2.resize(image_rgb, (416, 416)) cv2.imshow('output_main', image_rgb) if cv2.waitKey(10) & 0xFF == ord("c"): break if cv2.waitKey(10) & 0xFF == ord("s"): stop_all = True break if stop_all: break image_rgb = cv2.cvtColor(image_rgb, cv2.COLOR_RGB2BGR) image_rgb = cv2.resize(image_rgb, (416, 416)) cv2.imshow('output_main', image_rgb) if cv2.waitKey(10) & 0xFF == ord("q"): break else: break for t in num_thread: if t.isAlive() is True: t.terminate() cv2.destroyAllWindows()
def run(self): time.sleep(1) self.follower_state = kthread.KThread(target=self.follow, args=()) self.follower_state.start()