def __make_client(self): "Make this node a client" notice("Making client, getting server connection", self.color) self.mode = "c" addr = utils.get_existing_server_addr() sock = utils.get_client_sock(addr) self.__s = sock with self.__client_list_lock: self.clients = deque() self.threads = deque()
def breadth_first_search(g, v): '''Return a dictionary whose keys are all nodes reachable from v. The dictionary is the search tree obtained through a breadth-first search, so the paths are shortest paths. Assumption: g.is_vertex(v) -> True Running time: O(m) where m = num edges ''' reached = {v:v} todo = deque([v]) # O(min(n,m)) iterations # Each iteration processes one node in the todo list, # but can only process nodes that are reachable from v. while todo: curr = todo.popleft() # Number of iterations over the ENTIRE algorithm # is at most m: each node has its neighbours # expanded at most once. for succ in g.neighbours(curr): if succ not in reached: reached[succ] = curr todo.append(succ) return reached
def bfs(draw, grid, start, end): nodes = deque() nodes.appendleft(start) visited = set() visited.add(start) start.parent = None while nodes: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() current_node = nodes.popleft() if current_node is end: BFS.draw_path(end, start, draw) end.make_end() start.make_start() return True for neighbor in current_node.neighbors: if neighbor not in visited: visited.add(neighbor) neighbor.parent = current_node neighbor.make_open() nodes.append(neighbor) draw() if current_node != start: current_node.make_closed() draw() return False
def decide_nest_positions(self, nest): self.helpers['adjacent_walls'] = HelperArray('adjacent_walls', self.start_world) hypothetical_nests = [[0] * self.start_world.get_width() for _ in range(self.start_world.get_height())] hypothetical_nests[nest[1]][nest[0]] = 1 num_nests = 1 visited = {} visited[nest] = True q = Q.deque() q.append((nest, 0)) while q: location, distance = q.popleft() if distance > int( min(self.start_world.get_width(), self.start_world.get_height()) / 2.5): continue for coor in self.start_world.get_neighbours( (location[0], location[1])).values(): if coor not in visited: q.append((coor, distance + 1)) visited[coor] = True # If it has an adjacent one with a better nest, forget about it. nest_func = self.can_be_nest if not self.has_better_adjacent_nest(location) and nest_func( location, hypothetical_nests): hypothetical_nests[location[1]][location[0]] = 1 num_nests += 1 print_array(hypothetical_nests) return hypothetical_nests
def isBalanced(self, root: TreeNode) -> bool: def not_balanced(s): if len(s) > 2: return True elif len(s) == 2: (a, b) = s if abs(a - b) > 1: return True return False q = queue.deque() if not root: return True level_set = set() q.append((root, 0)) while q: (node, level) = q.popleft() if not node.left and not node.right: # print(level) level_set.add(level) if not_balanced(level_set): return False if node.left: q.append((node.left, level + 1)) if node.right: q.append((node.right, level + 1)) return True
def main(): str = input() k = int(input()) char_map = defaultdict(lambda: 0) for c in str: char_map[c] += 1 q = deque() for k in char_map.keys(): q.append(k) length = len(str) ans = "" while len(q) > 0: cnt = min(k, length) temp = [] for i in range(cnt): ch = q.popleft() ans += ch char_map[ch] -= 1 if char_map[ch] > 0: temp.append(ch) for c in temp: q.append(c)
def tokenizer(x): from queue import deque x = str(x) left = deque([]) tokens = [] count = 0 while count < len(x)+1: temp = '' if count < len(x) and x[count].isdigit(): left.append(x[count]) else: while True: try: temp += left.popleft() except: IndexError break try: int(temp) tokens.append(int(temp)) except: ValueError pass count += 1 return tokens
def solve(s): # Here the variable 'q' is used as an analogy to our concept QUEUE that is used here # The value of 'q' will be used to store the nodes until their neighbours are visited q = deque() q.append(s) visited = [False for i in range(n)] visited[s] = True prev = [None for i in range(n)] while len(q): # print(prev) # Get the next node to visit node = q.popleft() neighbours = g[node] #Visit each neighbour mark them visited and set their previous node with prev[next] = node for next in neighbours: if not visited[next]: q.append(next) visited[next] = True # print("Prev[{}] = {}".format(next,node)) prev[next] = node print("Prev:", prev) return prev
def DLS(self, start, goal, limit=-1): found, fringe, visited, came_from = False, deque([(0, start) ]), set([start]), { start: None } while not found and len(fringe): depth, current = fringe.pop() if current == goal: found = True break if limit == -1 or depth < limit: for node in current.edges.values(): if node not in visited: visited.add(node) fringe.append((depth + 1, node)) came_from[node] = current if found: print("IDDFS total time run ", datetime.now() - self.startT, " total expanded cells:", len(visited) + 1, " optimum path lenght: ", self.maze.optimum) return came_from, visited else: return None, visited
def bfsIterative(self): queue = deque([self]) while len(queue): node = queue.popleft() print(node.value, end='') for child in node.children: queue.append(child)
def compute(self, iterations): list_1 = list(self.data_to_compute_1.queue) list_2 = list(self.data_to_compute_2.queue) list_3 = complex_mult(list_1, list_2) # fft_result = DFT(list_3) # fft_result = FFT(list_3) fft_result = rFFT(list_3) # fft_result = FFT_vectorized(list_3) # fft_result = fft(list_3) # print(f'Compare DFT with built-in FFT at PE {iterations}:', np.allclose(DFT(list_3), fft(list_3))) # print(f'Compare FFT with built-in FFT at PE {iterations}:', np.allclose(FFT(list_3), fft(list_3))) # print(f'Compare rFFT with built-in FFT at PE {iterations}:', np.allclose(rFFT(list_3), fft(list_3))) # print(f'Compare FFT with built-in FFT at PE {iterations}:', np.allclose(FFT_vectorized(list_3), fft(list_3))) fft_shift_results = fftshift(fft_result)[self.cell_size // 2 - 8:self.cell_size // 2 + 8] # take middle 16-bit fft_abs = np.abs(fft_shift_results) self.cell_output.queue = deque(fft_abs) """To be continued (Alpha profile)""" ''' for j in range(len(fft_shift_results)): alpha_partial = np.absolute(fft_shift_results[j]) alpha_final = np.absolute(self.cell_partial_result) if alpha_partial > alpha_final: self.cell_partial_result = alpha_partial ''' for _ in range(self.cell_size): self.single_out = self.data_to_compute_1.get() self.cell_shift.put(self.single_out)
def _kd_tree_build(self, X): m, n = X.shape tree_depth = self._node_depth(m - 1) # 节点由两个索引组成,[0]实例索引,[1]切分特征索引 M = 2 ** tree_depth - 1 tree = np.zeros((M, 2), dtype = int) tree[:, 0] = -1 # 使用队列桉树的层级和顺序创建KD-Tree indices = np.arange(m) queue = deque([[0, 0, indices]]) while queue: # 队列弹出的一项 树节点的索引,切分特征的索引,当前区域所有实例索引 i, l, indices = queue.popleft() # 以实例第1个特征中位数作为切分点进行切分 k = indices.size // 2 indices = indices[np.argpartition(X[indices, l], k)] # 保存切分点实例到当前节点 tree[i, 0] = indices[k] tree[i, 1] = l # 循环使用下一特征作为切分特征, l = (l + 1) % n # 将切分点左右区域的节点划分到左右子树:将实例索引入队,创建左右子树 li, ri = 2*i+1, 2*i+2 if indices.size > 1: queue.append([li, l, indices[:k]]) if indices.size > 2: queue.append([ri, l, indices[k+1:]]) return tree, tree_depth
def connect(self, root): """ :type root: Node :rtype: Node """ q = queue.deque() d_r = Node(None,None,None,root) l = dict() q.append((root, 0)) while len(q) > 0: cur,level = q.popleft() if cur: if level in l: l[level].append(cur) else: l[level] = [cur] if cur.left: q.append((cur.left,level+1)) if cur.right: q.append((cur.right,level+1)) for level in l.values(): for i in range(len(level)-1): level[i].next = level[i+1] a = 1 return d_r.next
def __init__(self, window_size): self.empty = True self.window_size = window_size if window_size == 'inf': self.value = 0 else: self.window = deque(maxlen=window_size)
def zigzagLevelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ if not root: return [] from queue import deque q = deque() result = [] reverse = False q.append(root) q.append(-1) temp = [] while True: cur = q.popleft() if cur == -1: reverse = not reverse result.append(temp) temp = [] if not q: return result q.append(-1) else: if reverse: temp.insert(0, cur.val) else: temp.append(cur.val) if cur.left: q.append(cur.left) if cur.right: q.append(cur.right)
def isValidSerialization(self, preorder: str) -> bool: if not preorder: return False preorder = deque(preorder.split(",")) queue = deque([preorder.popleft()]) while queue: char = queue.popleft() if char == "#": continue if not preorder: return False queue.append(preorder.popleft()) if not preorder: return False queue.append(preorder.popleft()) return False if preorder else True
def __init__(self, **keywords): #load the image for the base class. self._base_image = Transport.sprite #load the base class super().__init__(**keywords) #sounds self.move_sound = "TankMove" self.hit_sound = "TankFire" #set unit specific things. self.type = "Transport" self.speed = 8 self.max_atk_range = 0 self.damage = 6 self.defense = 4 self.hit_effect = effects.Explosion self.health = 20 self.max_health = self.health self.capacity = 100 self.carrying = deque() #the unit cannot attack, so set the attack state to false self.turn_state = [False, True] self._update_image()
def statistic(self): now = time.time() if now > self.last_statistic_time + 60: rtt = 0 sent = 0 received = 0 for stat in self.second_stats: rtt = max(rtt, stat["rtt"]) sent += stat["sent"] received += stat["received"] self.minute_stat = {"rtt": rtt, "sent": sent, "received": received} self.second_stats = queue.deque() self.last_statistic_time = now if len(self.rtts): rtt = max(self.rtts) else: rtt = 0 self.second_stat = { "rtt": rtt, "sent": self.total_sent - self.last_sent, "received": self.total_received - self.last_received } self.rtts = [] self.last_sent = self.total_sent self.last_received = self.total_received self.second_stats.append(self.second_stat)
def sumEvenGrandparent(self, root: TreeNode) -> int: visited = set() if not root: return 0 ans = 0 q = deque() q.append(root) while q: node = q.popleft() l,r = node.left, node.right if l: q.append(l) if r: q.append(r) if node.val%2 == 0: if l: if l.left and l.left not in visited: ans += l.left.val visited.add(l.left) if l.right and l.right not in visited: ans += l.right.val visited.add(l.right) if r: if r.left and r.left not in visited: ans += r.left.val visited.add(r.left) if r.right and r.right not in visited: ans += r.right.val visited.add(r.right) return ans
def get_dependents(self, node): visited = set() queue = deque() path = {} # First, add all side effect nodes to queue for id, i in self.nodes.items(): if i.func_type.has_sideeffect: queue.append(id) # Then, do a DFS over queue, adding all reachable nodes to visited # Store children in map, creating a "path" while queue: id = queue.pop() if id in visited: continue if id == node.id: break for input in self.nodes[id].inputLinks.values(): link = input if link is None: continue queue.append(link.node.id) path[link.node] = self.nodes[id] pathTemp = node skip_nodes = [] while pathTemp is not None: # Don't skip supplied node, since that would be applied next run # if pathTemp is not node: skip_nodes.append(pathTemp) pathTemp = path.get(pathTemp) return skip_nodes
def alg_BFS(draw, grid, start, end): q = deque() q.append(start) visited = {node: False for row in grid for node in row} visited[start] = True prev = {node: None for row in grid for node in row} while len(q) != 0: node = q.pop() neighbors = node.neighbors for neighbor in neighbors: if not visited[neighbor]: q.appendleft(neighbor) visited[neighbor] = True prev[neighbor] = node if neighbor == end: neighbor.color = PURPLE else: neighbor.color = GREEN draw() create_BFS_path(start, end, prev, draw) start.color = ORANGE end.color = PURPLE
def maxAreaOfIsland(self, grid: List[List[int]]) -> int: # left = 0 m = 0 s = set() for i in range(len(grid)): for j in range(len(grid[i])): if grid[i][j] == 1: s.add((i, j)) while s: q = deque() q.append(s.pop()) square = 1 while q: cur = q.popleft() for d in [(0, 1), (0, -1), (-1, 0), (1, 0)]: x = cur[0] + d[0] y = cur[1] + d[1] if 0 <= x < len(grid) and 0 <= y < len( grid[0]) and (x, y) in s: q.append((x, y)) s.remove((x, y)) square += 1 # print(left) # print(s) m = max(square, m) if m >= len(s): return m return 0
def __init__(self, a=101): self.h = 0 if not is_prime(a): raise ValueError('a must be prime') self.a = a self.history = queue.deque() self.size = 0
def __init__(self): self.client = airsim.CarClient("10.8.105.156") self.client.confirmConnection() self.client.enableApiControl(True) self.car_controls = airsim.CarControls() self.action_space = spaces.Discrete(7) self.time_step = 0 self.x_pos_goal = 0.6 #0.545647 self.y_pos_goal = -2.5 #-1.419126 self.z_pos_goal = 0.2 #0.176768 self.counter_no_state = 0 self.w_rot_goal = 1.0 # 0.999967 self.x_rot_goal = 0.0 # self.y_rot_goal = 0.0 # -0.000095 self.z_rot_goal = 0.02 # 0.019440 self.max_step = 10 # steps to check if blocked self.last_states = queue.deque(maxlen=self.max_step) self.height = 84 self.width = 84 # old 320 # self.observation_space = spaces.Box(low=-high, high=high, dtype=np.float32) self.observation_space = spaces.Box(low=0, high=255, shape=(self.height, self.width, 2)) self.debug_mode = False self.goal_counter = 0 self.count = 0
def __init__(self, *paths, distinct_levels=0, total_levels=None, num_workers=1, max_queue=10, seed=None): self.file_data = _load_files(paths) self.level_cache = [] if total_levels is None: if len(self.file_data) == 1 and self.file_data[0][1] == "procgen": total_levels = -1 elif distinct_levels == 0: total_levels = len(self.file_data) else: total_levels = distinct_levels self.total_levels = total_levels self.distinct_levels = distinct_levels self.num_workers = num_workers if num_workers > 0: self.max_queue = max_queue self.pool = Pool(processes=num_workers) else: self.max_queue = 1 self.pool = None self.results = queue.deque(maxlen=self.max_queue) self.idx = 0 self.seed(seed)
def BFS(arr, i, j, max_size): global N visit = [[0 for _ in range(N)] for _ in range(N)] dx = [-1, 0, 1, 0] dy = [0, 1, 0, -1] queue = deque([[i, j, 0]]) near = [] while (queue): cur = queue.popleft() # print(cur) step = cur[2] for di in range(4): nx = cur[0] + dx[di] ny = cur[1] + dy[di] if inner_check(nx, ny) and visit[nx][ny] == 0: visit[nx][ny] = 1 # 0 이거나 크기가 같은 경우, step을 증가하고 queue 에 넣어 줌 if arr[nx][ny] == 0 or arr[nx][ny] == max_size: queue.append([nx, ny, step + 1]) # print(queue) # 물고기인 경우, 크기를 체크하여 보관 else: if size_check(nx, ny, max_size) and (len(near) == 0 or near[0][2] >= step + 1): near.append([nx, ny, step + 1]) return near
def __init__(self, **kwargs): self.board_gen_params = {} for key, val in kwargs.items(): if (not key.startswith('_') and hasattr(self, key) and not callable(getattr(self, key))): setattr(self, key, val) else: raise ValueError("Unrecognized parameter: '%s'" % (key, )) self.action_space = spaces.Discrete(len(self.action_names)) if self.output_channels is None: self.observation_space = spaces.Box( low=0, high=2**15, shape=self.view_shape, dtype=np.uint16, ) else: self.observation_space = spaces.Box( low=0, high=1, shape=self.view_shape + (len(self.output_channels), ), dtype=np.uint16, ) self.seed() self._board_queue = queue.deque()
def _create_newly_allowed_descendants(self, other_node: RcTreeNode): # Children only, not the subdag root descendants = queue.deque(other_node.children.values()) while descendants: descendant = descendants.popleft() self._create_children(descendant) descendants.extend(descendant.children.values())
def __init__(self, docker_client=None): if docker_client: self.docker_client = docker_client else: # Set to system docker if one is not provided self._check_heart_beat() self.docker_client = docker.from_env() # unique session id for each run of scheduler # uses UTC time. this is appended to replica dir names # see classmethods for implementation self.schedule_id = datetime.utcnow().strftime('%y%m%d-%H%M%S') self.runningContainerDict = {} self._jobQ = queue.deque() self._image_tag = 'aaraney/nwm-djs:2.0' # Max jobs is the max number of jobs # running at any given time # TODO: Find information from system to inform this self._MAX_JOBS = 2 # Max cps is the max number of cpus # running at any given time # see docker python api for help with syntax # https://docker-py.readthedocs.io/en/stable/containers.html self._MAX_CPUS = '0-1' # MPI np is the number of mpi processes # that each container will be allotted self._MPI_NP = 2
def get_source_rows(self, browser): ''' Fetches all sources (names) and returns a string queue (with all the names) ''' rows = [] no_of_rows = self.get_number_of_rows( browser) # number of rows of current page i = 1 while i <= no_of_rows: td = WebDriverWait(browser, init.DELAY_TIME).until( EC.presence_of_element_located( (By.XPATH, '//*[@id="resultDataRow' + str(i - 1) + '"]/td[4]'))) try: row = td.find_element(By.CLASS_NAME, self.doc_source_class_name) rows.append({'name': row.text, 'clickable': True}) i += 1 except: rows.append({ 'name': td.text.splitlines()[0], 'clickable': False }) i += 1 return deque(rows)
def isCousins(self, root: TreeNode, x: int, y: int) -> bool: parentLevel = [] queue = deque([(root, None, 0)]) while queue: node, parent, depth = queue.popleft() if parentLevel and parentLevel[1] != depth: return False if node.val in [x, y]: if parentLevel: return parent != parentLevel[ 0] # and depth == parentLevel[1] else: parentLevel = [parent, depth] # no need to append else: if node.left: queue.append((node.left, node, depth + 1)) if node.right: queue.append((node.right, node, depth + 1)) return False
def profile(func): name = func.__name__ samples = queue.deque(maxlen=5) @functools.wraps(func) def wrapper(self, *args, **kwargs): if not self.debug_enabled: return func(self, *args, **kwargs) start = clock() ret = func(self, *args, **kwargs) n = tfloat(clock() - start) if len(samples) < 2: m = 0 d = 0 n.color = 36 else: m = mean(samples) if stdev: d = tfloat(stdev(samples)) else: d = 0 if n <= m + d: n.color = 32 elif n > m + d * 2: n.color = 31 else: n.color = 33 samples.append(n) self.info('\x1b[34m%s\x1b[m t = %s, \u00b5 = %s, \u03c3 = %s)', name, n, m, d) return ret return wrapper
def breadth_first_explore(root): """Generator of the nodes in the subdag starting from the passed node, including it, in breadth-first order. Modifications of the subdag between yields of this generator may be done by the user of the generator. Args: root (HsDagNode): first node to be returned and starting point of the subdag search. Returns: Generator[HsDagNode, None, None]: nodes in the subdag in breadth-first order. """ if not root: return visited = set() descendants = queue.deque() descendants.append(root) visited.add(root) while descendants: descendant = descendants.popleft() for child in descendant.children.values(): if child not in visited: descendants.append(child) visited.add(child) yield descendant
def __init__(self, server): self.__server = server self.__requests = queue.deque() self.__poller = select.poll() self.__connections = {} self.__sessions = {} self.__alive = False
def __make_server(self): "Make this node a server" notice('Making server, getting listening socket') self.mode = 's' sock = utils.get_server_sock() self.__s = sock with self.__client_list_lock: self.clients = deque() self.threads = deque() notice('Making beacon') b = Thread(target=self.__beacon_thread, name='beacon') b.start() self.threads.append(b) l = Thread(target=self.__listen_thread, name='listen') notice('Starting listen thread') l.start() self.threads.append(l)
def __make_server(self): "Make this node a server" notice("Making server, getting listening socket", self.color) self.mode = "s" sock = utils.get_server_sock() self.__s = sock with self.__client_list_lock: self.clients = deque() self.threads = deque() notice("Making beacon", self.color) b = Thread(target=self.__beacon_thread, name="beacon") b.start() self.threads.append(b) l = Thread(target=self.__listen_thread, name="listen") notice("Starting listen thread", self.color) l.start() self.threads.append(l)
def __init__(self,function,job): myout.log('启动线程池') self.lock=threading.RLock() workers=range(100) self.do_jobing=queue.deque() for worker in workers: worker_man=threading.Thread(target=self.handle_job,args=(worker,function,job)) worker_man.start()
def bfs(G,s): P, Q = set(), deque(s) while Q: u = Q.popleft() for v in G[u]: if v in P: continue Q.append(v) P.add(v) return P
def __cacheGetJoints(self): from queue import deque result = [] queue = deque([self.rootJoint]) while len(queue) > 0: joint = queue.popleft() result.append(joint) queue.extend(joint.children) self.jointslist = result
def __init__(self, id, port, brand, type): self.id = id self.port = port self.buffer = queue.deque() self.brand = brand self.type = type self.lock = threading.RLock() self._comm_count = 0 self._comm_success_count = 0 self._reset_counts = False
def __cacheGetBones(self): from queue import deque result = [] queue = deque(self.roots) while len(queue) > 0: bone = queue.popleft() bone.index = len(result) result.append(bone) queue.extend(bone.children) self.boneslist = result
def __init__(self, grid_width=1920, grid_height=1080): # Queue which orders are showed self.ingredient_orders = queue.deque(maxlen=4) # Queue which orders are should be showed if place self.ingredient_orders_buffer = queue.Queue() #Queue which order is new and appears as overlay self.ingredient_order_new = None config = configparser.ConfigParser() config.read('settings.cfg') self.seconds_to_show = config.get('General', 'SecondsShowOrder') self.seconds_to_show_big = config.get('General', 'SecondsShowNewOrderBig') self.images_path = config.get('General', 'ImagesPath') self.ingredients_file = config.get('General', 'IngredientFile') self.alert_sound_file = config.get('General', 'AlertSoundFile') self.rpc_port = config.get('General', 'Port') self.grid_width = grid_width self.grid_height = grid_height print('Setting up GUI...') Gtk.Window.__init__(self, title="KitchenCommander - Server") self.fullscreen() self.main_grid = Gtk.Grid() self.main_grid.set_size_request(self.grid_width, self.grid_height) self.boxes = [Gtk.Image(), Gtk.Image(), Gtk.Image(), Gtk.Image()] self.main_grid.attach(self.boxes[0], 0, 0, 1, 1) self.main_grid.attach(self.boxes[1], 1, 0, 1, 1) self.main_grid.attach(self.boxes[2], 0, 1, 1, 1) self.main_grid.attach(self.boxes[3], 1, 1, 1, 1) self.overlay = Gtk.Overlay() self.add(self.overlay) self.overlay.add(self.main_grid) self.overlay.show_all() self.show_all() print("Loading ingredients...") self.ingredients = {} self._load_ingredients() print('Trying to start RPC server...l') self.rpc = rpcserverthread.RPCServerThread(self.ingredient_orders_buffer, self.ingredients, self.rpc_port) self.rpc.start() print('Started server, running on ' + [(s.connect(('8.8.8.8', 80)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1] + ':' + self.rpc_port) print('Starting update timer') GObject.timeout_add_seconds(1, self._update)
def __init__(self, game_state: GameState, player: Player, target: Pose=Pose, args: List[str]=None, cruise_speed=DEFAULT_SPEED): super().__init__(game_state, player, target, args) self.current_state = self.next_corner self.next_state = self.next_corner self.cruise_speed = cruise_speed self.iteration = 0 self.x_sign = 1 self.y_sign = 1 self.coord_x = game_state.field.field_length/3 self.coord_y = game_state.field.field_width/3 self.points = [WayPoint(Position(self.coord_x, self.coord_y)), WayPoint(Position(-self.coord_x, self.coord_y)), WayPoint(Position(-self.coord_x, -self.coord_y)), WayPoint(Position(self.coord_x, -self.coord_y))] self.points = deque(self.points)
def transform(self, X): g, edges = X res = [] for (u, v) in edges: # bfs search score = 0 q = deque([u]) cur_depth = 0 while q and cur_depth < self.depth: cur_depth += 1 node = q.popleft() for neighbor in g.out_dict[node]: if neighbor == v: score += self.beta**cur_depth q.append(neighbor) res.append(score) return printFeature('katz',np.vstack(res))
def __init__(self, port=None, baud=9600, debug=False, vid=None, pid=None): self.debug = debug self.port = port self.baud = baud self.vid = vid or self.VID self.pid = pid or self.PID self.num_channels = 8 self.queue = queue.deque(maxlen=50) if self.port is None: self.port = self._get_flotilla_port() else: log.debug('Overriding port: {}'.format(self.port)) self.serial = serial.Serial(port=self.port.device, baudrate=self.baud, timeout=None) log.info('Connection established with Flotilla Dock') self._get_modules()
def bfs(maze, start, stop): visited = set() nodequeue = deque() nodequeue.append([start]) cnt = 0 while nodequeue: path = nodequeue.popleft() current = path[-1] if current not in visited: visited.add(current) print(current[0], current[1], cnt) for neighbor in neighbors(maze, current[0], current[1]) - visited: if neighbor == stop: print(neighbor[0], neighbor[1], cnt+1) return path[:-1] + [(current, cnt)] + [(neighbor, cnt)] elif maze[neighbor[0]][neighbor[1]] == ' ': nodequeue.append(path[:-1] + [(current, cnt)] + [neighbor]) cnt += 1 return [[]]
def shortestPath(start, end): # Intialize queue of paths to process # Append start node queue = deque([[start]]) visited = set() # While there are still items in the queue to process while queue: # Get the next path list path = queue.popleft() # Get the last node from the path node = path[-1] # If the end node is encountered if node == end: return path # If the node has not yet been visited elif node not in visited: # Add the node to the visited set visited.add(node) # Get neighbors of current node nextNode = graph[node] # Sort by proximity to bias point if variable-difficulty is selected # Runtime # O(n log(n)), however, n is at most 3 so runtime is # effectively constant nextNode.sort(key=lambda n: \ abs(n[0]-biasPoint[0]) + abs(n[1]-biasPoint[1]) ) # Iterate through the neighbors of the current in sorted ordrer for succ in nextNode: # Create new path containing path to the neighboring node # + the neighboring node newPath = list(path) newPath.append(succ) # Add the new path to the queue to process queue.append(newPath) # Return AI path (list of nodes) return path
def isPalindrome(string): string = str(string) d = deque() for i in range(len(string)): d.append(string[i]) while len(d) > 0: if len(d) == 1: return True rear = d.pop() front = d.popleft() if rear != front: return False return True
def make_inner_paths_for_table(selected_table, tables, relationships): q = queue.deque([(selected_table, ())]) used_tables = set() paths = [] while q: table_name, table_tree_path = q.popleft() used_tables.add(table_name) columns = tables[table_name].columns relations = relationships.get(table_name, []) for x in columns: table_tree_full_path = table_tree_path + (x, ) paths.append(table_tree_full_path) for x in relations: relation_table = x.relation_table visited = {r.table for r in table_tree_path} if relation_table not in visited: q.append((relation_table, table_tree_path + (x, ))) return paths, used_tables
# Initialize with uniform probability prob_trans = np.ones((num_states, num_actions, num_states))/num_states # Reward as a function of state reward = np.zeros(num_states) reward_count = np.zeros(num_states) reward_sum = np.zeros(num_states) # Policy pi(s) policy = np.random.randint(num_actions, size=num_states) count_trans = np.zeros((num_states, num_actions, num_states)) total_count = np.zeros((num_actions, num_states)) num_episodes = 0 reward_history = queue.deque(maxlen=SOLVING_THRESH_CONSEC_TRIALS) average_reward = 0 reward_curr_ep = 0 problem_solved = False def sub2ind(array_shape, sub): return np.ravel_multi_index(sub, dims=array_shape, order='F') def obs2state(obs, st_brk_pts, st_shape): if obs.shape[0] != st_brk_pts.shape[1]: raise ValueError('Number of observations must be equal to number of columns in break points matrix...') st = np.zeros(obs.shape[0], dtype=int) for i in range(obs.shape[0]): st[i] = np.nonzero(np.logical_and((obs[i] < st_brk_pts[0:-1,i]) , (obs[i] >= st_brk_pts[1:,i]) ))[0] st_ind = sub2ind(st_shape, st)
def __init__(self, logLock): self.logLock_ = logLock self.urlcv_ = threading.Condition() self.urlQueue_ = queue.deque()
def reset(self): self.source.reset() self.queue = queue.deque() self.is_source_empty = False
def __init__(self, source): self.source = source self.queue = queue.deque() self.is_source_empty = False
check = groups[y % 3] elif x % 3 == 1: check = groups[2] else: check = groups[1] return concat(x, y) in check and concat(y, x) in check if __name__ == '__main__': print('starting') adjacency = defaultdict(set) for p, q in combinations(primes_less_than(10000), 2): if is_adjacent(p, q): adjacency[p].add(q) print('finished adjacency') Q = deque([[p] for p in primes_less_than(10000)]) results = list() while Q: cur = Q.pop() test = True for q in cur[:-1]: if cur[-1] not in adjacency[q]: test = False break if test is True: if len(cur) == 5: results.append(cur) break for x in adjacency[cur[-1]]: toAdd = cur + [x] Q.appendleft(toAdd)
# print(q.get()) # print(q.get(timeout=2)) # import queue #先进先出 # q = queue.LifoQueue() # q.put(123) # q.put(456) # print(q.get()) # q = queue.PriorityQueue() # 根据优先级处理,数字最小的优先级最高 # # put() 参数一为优先级,第二个参数是value # q.put((3, "alex3")) # q.put((2, "alex2")) # q.put((1, "alex1")) # print(q.get()) q= queue.deque() #双向队列 q.append((123)) q.append(234) q.appendleft(456) print(list(q)) q.pop() q.popleft() print(list(q))
def __init__(self, gateway, behaviour, settings, global_config): composer = globals().get(settings.get('composer', 'baroq')) if not composer: raise RuntimeError("Composer is not configured correctly") self.composer = composer.Composer(gateway, settings, behaviour) self.global_config = global_config self.behaviour = behaviour self.playing = None self.stopped = False self.style_name = None self.force_caesura = False self.caesura_count = 0 self.settings = settings self.gateway = self.composer.gateway # keep this between 0 and MAX_SHUFFLE self.shuffle_delay = behaviour["shuffle_delay"] self.meter = self.composer.applied_meter self.metronome = metronome.Metronome(self.meter) self.automate_binaural_diffs = behaviour["automate_binaural_diffs"] self.automate_meters = behaviour["automate_meters"] self.speed_change = behaviour["speed_change"] self.MIN_SPEED = behaviour["min_speed"] self.MAX_SPEED = behaviour["max_speed"] self.MAX_SHUFFLE = behaviour["max_shuffle"] musical_logger = logging.getLogger('musical') self.musical_logger = StyleLoggerAdapter(musical_logger, None) behaviour_logger = logging.getLogger('behaviour') self.behaviour_logger = StyleLoggerAdapter(behaviour_logger, None) self.style_logger = logging.getLogger('style') self.gui_logger = logging.getLogger('gui') self.add_setters() if behaviour['automate_microspeed_change']: self.new_microspeed_sine() self.state = {"comp": self.composer, "speed": behaviour["speed"]} self.speed_target = behaviour["speed_target"] self.speed = self.state["speed"] if behaviour['follow_bar_sequence']: self.state.update({ 'bar_sequence': behaviour['bar_sequence'], 'bar_sequence_current_position': 0}) for voice in list(self.composer.voices.values()): self.apply_voice_adsr(voice) self.has_gui = settings['gui'] self.gui_sender = self.has_gui and GuiConnect() or None self.allowed_incoming_messages = ( self.has_gui and list(self.behaviour.keys()) + ['play', 'sys', 'scale', 'force_caesura', 'trigger_wavetable'] or None) if self.has_gui: self.incoming = deque() self.gui_sender.update_gui(self) # start the reader thread thre = threading.Thread(target=self.gui_sender.read_incoming_messages, args=(self.incoming,)) thre.daemon = True thre.start() self.set_wavetables(voices=list(self.composer.voices.values()))
import pickle import re from pyquery import PyQuery as pq from queue import deque # proxy_handler = urllib.request.ProxyHandler({'http':'zhangld:([email protected]:8080'}) # proxy_auth_handler = urllib.request.ProxyBasicAuthHandler() # proxy_auth_handler.add_password(None, 'http://proxy.neusoft.com', 'zhangld', '(TImeold9') # opener = urllib.request.build_opener(urllib.request.HTTPHandler, proxy_handler) url = 'http://news.sciencenet.cn/indexyaowen.aspx' # page_src = opener.open(url) page_src = urllib.request.urlopen(url) page = page_src.read().decode('utf-8') data_source = pq(page) m = 1 queue = deque() visited = set() queue.append(url) file_title = open('title.txt', 'w+') #while page!=None: while queue: try: #page_num = 'http://news.sciencenet.cn/indexyaowen-' + str(m) + '.aspx' page_num = queue.popleft() #print(page_num) visited.add(page_num) #print('visited:',visited) #page_src_num = opener.open(page_num) page_src_num = urllib.request.urlopen(page_num) page_num = page_src_num.read().decode('utf-8') data_source = pq(page_num)
##### global variables ##### first_exec = True # whether setting up objects or editing them streaming = False prev_streaming_state = False head_movement = False show_webcam = False # TODO: Does not work due to specific settings on my system. show_ultrasound = False menu_overlaying = False ticks_since_stream_toggle = 5 # streaming repetitions if looping, starting value key_pace = 20 # number of logic ticks before registering a second keypress from queue import deque bsh.gs_answers = deque() # store responses from gameserver (deque to can restrict length if req'd) # persistent sockets that connects to the gameserver print('Initialising sockets') gs_soc_blocking = bn.setup_socket_to_gameserver(blocking=True) gs_soc_nonblocking = bn.setup_socket_to_gameserver() gs_soc_nonblocking.settimeout(0) print('Testing sockets') bn.send_to_gameserver(gs_soc_blocking, mode='TEST_ALIVE') time.sleep(1) reply = bn.recv_from_gameserver(gs_soc_blocking) assert reply is not None print('Alive reply:', reply, '\n') bn.send_to_gameserver(gs_soc_nonblocking, mode='PARAMETERS') time.sleep(1)
#2.后进先出 import queue q = queue.LifoQueue() q.put(123) q.put(456) print(q.get()) print(q.get()) ''' #3.优先级队列 import queue q = queue.PriorityQueue() q.put((0,"test1")) q.put((3,"test3")) q.put((4,"test4")) print(q.get()) print(q.get()) print(q.get()) #4.双向队列 import queue q = queue.deque() q.append(123) q.append(444) q.appendleft(555) print(q.pop()) print(q.pop()) print(q.popleft())
#encoding:UTF-8 import urllib.request import re import sys import io import tools import queue import threading import random import threadPoolManager import myout wait_url= queue.deque() get_url = set() web_domain = str() def process(now_url): # 抓取该url中的网页,并获取网页中url #myout.log("抓取:"+now_url) links=tools.get_links(now_url,web_domain) # 处理新的url,判断网页中的url是否已经抓取过 for link in links: if(link not in get_url): #如果没有爬到过url,则放入finish_url中,并进行爬取 myout.log("加入:"+link) get_url.add(link) wait_url.append(link) def main(url):