def insert_at_tail(self, data): node = Node(data) curr = self.head while curr.next: curr = curr.next curr.next = node node.prev = curr
def p_parameter(p): '''parameter : type ID | BYREF type ID''' if len(p) == 3: p[0] = Node("parameter", [p[1]], p[2]) else: p[0] = Node("byref_parameter", [p[2]], p[3])
def prepend(self, data): if self.head == None: self.head = Node(data) else: new_head = Node(data) new_head.next = self.head self.head = new_head
def add_trnas(my_orfs, G): f = tempfile.NamedTemporaryFile(mode='wt') f.write(">temp\n") f.write(my_orfs.seq) f.seek(0) try: output = Popen(["tRNAscan-SE", "-B", "-q", "-b", f.name], stdout=PIPE, stdin=PIPE, stderr=PIPE).stdout.read() except: sys.stderr.write("Warning: tRNAscan not found, proceding without tRNA masking.\n") return [] # Iterate over the trnas for line in output.splitlines(): # Add in trna column = line.split('\t') start = int(column[2]) stop = int(column[3]) if(start < stop): source = Node('tRNA', 'start', 4, start) target = Node('tRNA', 'stop', 4, stop-2) my_orfs.other_end['t'+str(stop-2)] = start my_orfs.other_end['t'+str(start)] = stop-2 else: source = Node('tRNA', 'stop', -4, stop) target = Node('tRNA', 'start', -4, start-2) my_orfs.other_end['t'+str(start-2)] = stop my_orfs.other_end['t'+str(stop)] = start-2 G.add_edge(Edge(source, target, -Decimal(20)))
def p_label_maybe(p): '''label_maybe : ID COLON | ''' if len(p) == 3: p[0] = Node('label', leaf=p[1]) else: p[0] = Node('no_label')
def p_mult_T(p): '''mult_T : TIMES | mult_T TIMES''' if len(p) == 2: p[0] = Node("times", leaf='*') else: p[0] = Node("times", leaf='*' + p[1].leaf)
def p_includes(p): '''includes : INCLUDE program END_INCLUDE includes | INCLUDE program END_INCLUDE''' if len(p) == 5: p[0] = Node("include", [p[2], p[4]], p[1]) else: p[0] = Node("include", [p[2]], p[1])
def push(self, new_data): # Create new node new_node = Node(new_data) # Make next of new node as head new_node.next = self.head # Point new node the head node self.head = new_node
def insert_after(self, locdata, data): node = Node(data) curr = self.head while curr.data != locdata and curr.next: curr = curr.next node.next = curr.next curr.next = node
def process(self): token = self.token if token.type == "sep": if token.val == "{": self.push_container("object", token) elif token.val == "}": self.pop_container("object") elif token.val == "[": self.push_container("array", token) elif token.val == "]": # print_ast_stack(self.stack) self.pop_container("array") elif token.val == "~": self.process_collection() else: self.push_value(Node.from_token(token)) elif token.type == "datasep": self.process_datasep() else: self.push_value(Node.from_token(token))
def create_tree(self, frequency_list): node_list = [] tree_nodes = [] #cria a lista com os nós da base for node in frequency_list: frequency = node[0] letter = node[1] node_list.append(Node(frequency, letter)) #junta os nós até o topo da árvore e armazena todos os nós na lista tree while len(node_list) > 1: node_list.sort() node1 = node_list.pop(0) node2 = node_list.pop(0) frequency = node1.get_frequency() + node2.get_frequency() letter = node1.get_letter() + node2.get_letter() #cria o novo nó a partir dos dois anteriores new_node = Node(frequency=frequency, letter=letter, left_child=node1, right_child=node2) node_list.append(new_node) tree_nodes.append(node1) tree_nodes.append(node2) root = node_list.pop(0) tree_nodes.append(root) #cria e retorna um objeto tipo árvore tree = Tree(tree_nodes=tree_nodes) return tree
def append(self, data): if self.head == None: self.head = Node(data) else: current = self.head while current.next != None: current = current.next current.next = Node(data)
def push(self, value): if self.has_space(): item = Node(value) item.set_next_node(self.top_item) self.top_item = item self.size += 1 else: print("No more room!")
def p_function_definition(p): '''function_definition : type ID LPAREN parameter_list_maybe RPAREN LBRACE declarations_maybe statements_maybe RBRACE | VOID ID LPAREN parameter_list_maybe RPAREN LBRACE declarations_maybe statements_maybe RBRACE''' if p[1] == "void": temp = Node("void", leaf="void") p[0] = Node("function_definition", [temp, p[4], p[7], p[8]], p[2]) else: p[0] = Node("function_definition", [p[1], p[4], p[7], p[8]], p[2])
def p_function_declaration(p): '''function_declaration : type ID LPAREN parameter_list_maybe RPAREN SEMICOLON | VOID ID LPAREN parameter_list_maybe RPAREN SEMICOLON''' if p[1] == 'void': temp = Node("void", leaf="void") p[0] = Node("function_declaration", [temp, p[4]], p[2]) else: p[0] = Node("function_declaration", [p[1], p[4]], p[2])
def insert_at_head(self, data): if self.head is None: self.head = Node(data) return node = Node(data) self.head.prev = node node.next = self.head self.head = node
def push(self, value): if self.stack_size == self.limit: raise ValueError('the stack is full') new_node = Node(value) new_node.set_next_node(self.top_item) self.top_item = new_node self.stack_size += 1
def initplacement(self, tls, x, y, level): key = (x, y, level) if key in self.placementcache: return # was created while this task was queued (name, url, minsize) = self.provider_url(*key) filename = self.filecache.fetch(self.session, name, url, minsize) if not filename: # Couldn't fetch image if filename is False: # Definitively unavailable self.placementcache[key] = False self.canvas.Refresh() # Probably wanting to know this return try: if __debug__: clock = time.clock() texdata = self.canvas.vertexcache.texcache.get(filename, alpha=False, wrap=False, downsample=False, fixsize=True, defer=True) except: if __debug__: print_exc() self.placementcache[key] = False # Couldn't load image self.canvas.Refresh() # Probably wanting to know this return # Make a new placement (north, west) = self.xy2latlon(x, y, level) (south, east) = self.xy2latlon(x + 1, y + 1, level) placement = DrapedImage(name, 65535, [[ Node([west, north, 0, 1]), Node([east, north, 1, 1]), Node([east, south, 1, 0]), Node([west, south, 0, 0]) ]]) placement.load(self.canvas.lookup, self.canvas.defs, self.canvas.vertexcache) if isinstance(texdata, tuple): placement.texdata = texdata else: placement.definition.texture = texdata # already in the cache if __debug__: clock = time.clock() placement.layout(self.tile, tls=tls) if not placement.dynamic_data.size: if __debug__: print "DrapedImage layout failed for %s - no tris" % placement.name placement = False else: if __debug__: print "%6.3f time in imagery read & layout for %s" % ( time.clock() - clock, placement.name) self.canvas.Refresh( ) # Probably wanting to display this - will be allocated during OnPaint self.placementcache[key] = placement return
def p_block(self, p): ''' block : LBRACKET RBRACKET | LBRACKET questions RBRACKET ''' if len(p) == 4: p[0] = Node('question-list', p[2]) else: p[0] = Node('question-list', [])
def insert_at_pos(self, pos, data): node = Node(data) curr = self.head count = 1 while count != pos and curr.next: curr = curr.next count += 1 node.next = curr.next curr.next = node
def push(self, value): if self.has_space(): item = Node(value) item.set_link_node(self.top_item) self.top_item = item self.size += 1 print("Adding {} to the Stack!".format(value)) else: print("Oops. Stack is full. Cant add {}!".format(value))
def push(self, value): if self.has_space(): item = Node(value) item.set_next_node(self.top_item) self.top_item = item self.size += 1 print("Adding {} to the stack!".format(value)) else: print("No room for {}!".format(value))
def testNode(): coordinates = [1, 1] key = '11' symbol = '-' newNode = Node(coordinates[0], coordinates[1]) newNodeX = newNode.x newNodeY = newNode.y print('coordinates: {}\n'.format(coordinates)) # Coordinates Test print("Coordinates Test") if newNodeX == coordinates[0] and newNodeY == coordinates[1]: print("PASS: Coordinates for node have" " been set correctly at {}, {}\n".format(newNodeX, newNodeY)) else: print("FAIL: Expected" " coordinates -> {}, {}".format(coordinates[0], coordinates[1])) print("Actual coordinates: {}, {}\n".format(newNodeX, newNodeY)) # Key Test print("Key Test") if newNode.key == key: print("PASS: node key has been set correctly at {}\n").format( newNode.key) else: print("FAIL: Expected" " key -> {}".format(key)) print("Actual key: {}\n".format(newNode.key)) # Symbol Test print("Symbol Test") print("Default Symbol Test") if newNode.symbol == symbol: print( "PASS: node symbol has been set correctly to default {}\n").format( newNode.symbol) else: print("FAIL: Expected" " symbol -> {}".format(symbol)) print("Actual symbol: {}\n".format(newNode.symbol)) newSymbol = 'x' newNode.symbol = 'x' print("Changed Symbol Test") if newNode.symbol == newSymbol: print("PASS: node symbol has been changed correctly to {}\n").format( newNode.symbol) else: print("FAIL: Expected" " new symbol -> {}".format(newSymbol)) print("Actual symbol: {}\n".format(newNode.symbol)) # Neighbors Test print("Neighbors Test") if isinstance(newNode.neighbors, list): print("PASS: newNode neighbors attribute is of type list") else: print("FAIL: newNode neighbors attribute is not of type list")
def addNode(self, name, host, port=22, user="******", password=None): node = Node(name, host, port) node.assignCredential(user, self.default_key, password) self.discoverQueue.append(node) if self.useKey: self.cleanUp.append(node.keyPath) return node
def add_to_front(self, item): temp = Node(item) if self.back == None: self.back = self.front = temp return oldfront = self.front self.front = temp temp.next = oldfront self.n += 1
def addNode(self, name, host, port=22, user='******', password = None): node = Node(name, host, port) node.assignCredential(user, self.default_key, password) self.discoverQueue.append(node) if (self.useKey): self.cleanUp.append(node.keyPath) return node
def p_program(p): '''program : declaration program | includes program | declaration includes | declaration''' if len(p) == 3: if p[2].type == 'program': p[0] = p[2].insert_in_children(0, p[1]) else: p[0] = Node("program", [p[1], p[2]], "program") else: p[0] = Node("program", [p[1]], "program")
def test_best_child(self): """ it should pick the child with the highest probability of winning.""" root_node = Node(self.state, self.bot.hand, 0) q_vals = (5, 0, 0) for i in range(3): node, _ = self.bot.expand_node(root_node) node.N = 5 node.Q = q_vals[i] root_node.N = 15 best, _ = self.bot.best_child(root_node) self.assertEqual(best.Q, 5)
def createList(iterator) -> Node: ''' Create a link list with None head and keep the order. ''' head = Node(None, None) head.next = head probe = head for data in iterator: probe.next = Node(data, head) probe = probe.next # node head return head
class TestNodes(unittest.TestCase): def setUp(self): state = GameState(game_mode="Herz Solo", offensive_player=1, active=0) p_hand = ['EK_', 'EU_', 'G10', 'SA_', 'HK_', 'H7_', 'S7_', 'H10'] p_id = 0 self.node = Node(state, p_hand, p_id) self.node.add_child("EK_") def test_hand(self): result = self.node.children["EK_"].p_hand expected = set(['EU_', 'G10', 'SA_', 'HK_', 'H7_', 'S7_', 'H10']) self.assertEqual(result, expected)
def insertAfter(self, prev_node, new_data): # Check if the given prev_node exists if prev_node is None: print("Prev node must be in list") return # Create a new node new_node = Node(new_data) # Make next of new node as next of prev_node new_node.next = prev_node.next prev_node.next = new_node
def worker(self): self.run_condition.acquire() while True: with self.lock: self.paused = False self.topics['events'].publish(Event('idle', 0)) self.run_condition.wait() with self.lock: nodes = [Node.createNode(node, self, self.start_time) for node in self.running_nodes] self.topics['events'].publish(Event('running', self.start_time)) if len(nodes) == 0: continue running = True while running: with self.lock: run_time = self.get_run_time() if not self.running: self.topics['events'].publish(Event('finished', run_time)) break elif self.paused: continue running = False # checks if any nodes still running for node in nodes: running = node.run(run_time) or running self.run_condition.release()
def run(self, start_time, nodes): # Create nodes nodes = [Node.createNode(node, self, start_time) for node in nodes] # Stop running first if performance is running size = len(nodes) if size > 0: self.stop() with self.lock: if size > 0: self.running = True self.start_time = start_time self.start_timestamp = time.time() logger.info("Put nodes {} to queue".format(nodes)) self.queue.put(nodes) return True else: return False
def convert_children(node): converted_children = [convert_node(child) for child in node.children] result = Node() result.children = converted_children return result
def build_position_graph(games, victory_node, all_nodes=None): ''' Creates a graph of nodes and movements. :param games: :param victory_node: :param all_nodes: :return: ''' first_movement = Movement.ALL_MOVEMENTS[0] Nod.ALLNODES = all_nodes new_node = None g = games.itervalues().next() fen = g.fen[0] score = g.fen_eval[0] res = g.result if fen in Nod.ALLNODES: root = Nod.ALLNODES[fen] # root.add_result(res) else: root = victory_node.init(g.fen[0], res, g.fen_eval[0]) root.results = [] game_length = len(g.fen) if len(Movement.ALL_MOVEMENTS) > game_length: Movement.init_last(game_length,g.fen[game_length-2], Movement.ALL_MOVEMENTS[game_length-1]) # print "%d games"%len(games) for g in games.values()[:]: # print "G>>>> %s: %d :: %s"%(g.name, len(g.fen),"") res = g.result fen = g.fen[0] if fen != "rnbqkbnr/pppppppp/......../......../......../......../PPPPPPPP/RNBQKBNR": # print "error: %s <> %d <> %s"%(g.name, len(g.fen), fen) print "err" else: root.add_result(res) root.add_movement(0) first_movement.add_node(fen) first_movement.add_result(res) for i in range(1, len(g.fen)): fen = g.fen[i] b_node = Nod.ALLNODES[g.fen[i - 1]] if fen not in Nod.ALLNODES: score = g.fen_eval[i] new_node = Nod.init_back_node(fen, res, b_node.name, score) else: new_node = Nod.ALLNODES[fen] new_node.add_result(res) b_node.add_node(b_node.forward_nodes, new_node.name) new_node.add_node(new_node.back_nodes,b_node.name) new_node.add_movement(i) movement = Movement.ALL_MOVEMENTS[i] movement.add_node(new_node.name) movement.add_result(res) new_node.add_node(new_node.forward_nodes, victory_node.name) victory_node.add_node(victory_node.back_nodes, new_node.name) victory_node.add_result(res) victory_node.add_movement(i) # root.test_added_nodes() root.save_all_nodes() first_movement.save_all_movements() return [root,first_movement]
def AddNode(self, address=""): newNode = Node(self) newNode.address = address self.mainScene.addItem(newNode) self.mainScene.addItem(Edge(newNode, self.centerNode)) newNode.setPos(random.randint(-100, 100),random.randint(-100, 100))
relative one like '../examples_cbnets/tempo.dot' Returns ------- Graph """ nx_graph = nx.read_dot(path) return cls.new_from_nx_graph(nx_graph) from nodes.Node import * if __name__ == "__main__": p1 = Node(0, "p1") p2 = Node(1, "p2") center = Node(2, "center") c1 = Node(3, "c1") c2 = Node(4, "c2") g = Graph({p1}) g.add_nodes({p2, center, c1, c2}) assert(g.has_node(p1)) assert(g.contains({p1, center, c2})) center.add_neighbor(p1) center.add_neighbor(p2) center.add_neighbor(c1) center.add_neighbor(c2) g.draw(algo_num=1)
def createMap1(): # Define nodes. n0 = Node([0, 0]) # n1 = Node([0, 1]) n2 = Node([0, 2]) n3 = Node([0, 3]) n4 = Node([0, 4]) n5 = Node([1, 0]) # n6 = Node([1, 1]) n7 = Node([1, 2]) # n8 = Node([1, 3]) n9 = Node([1, 4]) n10 = Node([2, 0]) n11 = Node([2, 1]) n12 = Node([2, 2]) # n13 = Node([2, 3]) n14 = Node([2, 4]) n15 = Node([3, 0]) n16 = Node([3, 1]) n17 = Node([3, 2]) n18 = Node([3, 3]) n19 = Node([3, 4]) # Build map. n0.add_neighbor(n5) n5.add_neighbor(n0) n5.add_neighbor(n10) n10.add_neighbor(n5) n10.add_neighbor(n11) n10.add_neighbor(n15) n15.add_neighbor(n10) n15.add_neighbor(n16) n11.add_neighbor(n10) n11.add_neighbor(n12) n11.add_neighbor(n16) n16.add_neighbor(n11) n16.add_neighbor(n17) n16.add_neighbor(n15) n12.add_neighbor(n7) n12.add_neighbor(n17) n12.add_neighbor(n11) n17.add_neighbor(n12) n17.add_neighbor(n18) n17.add_neighbor(n16) n18.add_neighbor(n17) n18.add_neighbor(n19) n19.add_neighbor(n18) n19.add_neighbor(n14) n14.add_neighbor(n19) n14.add_neighbor(n9) n9.add_neighbor(n4) n9.add_neighbor(n14) n4.add_neighbor(n9) n4.add_neighbor(n3) n3.add_neighbor(n4) n3.add_neighbor(n2) n2.add_neighbor(n3) n2.add_neighbor(n7) n7.add_neighbor(n2) n7.add_neighbor(n12) return [n0, n2, n3, n4, n5, n7, n9, n10, n11, n12, n14, n15, n16, n17, n18, n19]
def __init__(self,mod,name): Node.__init__(self,mod.site,name,mod)
def CreateContactNodes(self, contactList): """ @param contactList - list - all email addresses """ #initially here the nodes should be created based on the contacts list of the user #use the contact data and create nodes node1 = Node(self) node2 = Node(self) node3 = Node(self) node4 = Node(self) self.centerNode = UserNode(self) node6 = Node(self) node7 = Node(self) node8 = Node(self) node9 = Node(self) self.mainScene.addItem(node1) self.mainScene.addItem(node2) self.mainScene.addItem(node3) self.mainScene.addItem(node4) self.mainScene.addItem(self.centerNode) self.mainScene.addItem(node6) self.mainScene.addItem(node7) self.mainScene.addItem(node8) self.mainScene.addItem(node9) self.mainScene.addItem(Edge(node1, node2)) self.mainScene.addItem(Edge(node2, node3)) self.mainScene.addItem(Edge(node2, self.centerNode)) self.mainScene.addItem(Edge(node3, node6)) self.mainScene.addItem(Edge(node4, node1)) self.mainScene.addItem(Edge(node4, self.centerNode)) self.mainScene.addItem(Edge(self.centerNode, node6)) self.mainScene.addItem(Edge(self.centerNode, node8)) self.mainScene.addItem(Edge(node6, node9)) self.mainScene.addItem(Edge(node7, node4)) self.mainScene.addItem(Edge(node8, node7)) self.mainScene.addItem(Edge(node9, node8)) node1.setPos(-50, -50) node2.setPos(0, -50) node3.setPos(50, -50) node4.setPos(-50, 0) self.centerNode.setPos(0, 0) node6.setPos(50, 0) node7.setPos(-50, 50) node8.setPos(0, 50) node9.setPos(50, 50) #create nodes by number of contacts i=0 for c in contactList["contacts"]: #print c if i < 10: self.AddNode(c) i += 1