def initializeNodesFromJson(self, nodesJsonStr): nodesObj= json.loads(nodesJsonStr) if nodesObj is None: Utils.Print("ERROR: Invalid Json string.") return False if "keys" in nodesObj: keysMap=nodesObj["keys"] if "defproduceraPrivateKey" in keysMap: defproduceraPrivateKey=keysMap["defproduceraPrivateKey"] self.defproduceraAccount.ownerPrivateKey=defproduceraPrivateKey if "defproducerbPrivateKey" in keysMap: defproducerbPrivateKey=keysMap["defproducerbPrivateKey"] self.defproducerbAccount.ownerPrivateKey=defproducerbPrivateKey nArr=nodesObj["nodes"] nodes=[] for n in nArr: port=n["port"] host=n["host"] node=Node(host, port) node.setWalletEndpointArgs(self.walletEndpointArgs) if Utils.Debug: Utils.Print("Node:", node) node.checkPulse() nodes.append(node) self.nodes=nodes return True
def ID3(X, Y, attrs, currentDepth, maxDepth=7): currentDepth += 1 # If all examples are positive, Return the single-node tree Root, with label = +. # If all examples are negative, Return the single-node tree Root, with label = -. if len(set(Y)) == 1: return Leaf(Y[0]) # If the number of predicting attributes is empty, then return a single node tree with # Label = most common value of the target attribute in the examples if len(attrs) == 0 or currentDepth == maxDepth: return Leaf(majorityElement(Y)) # A = The Attribute that best classifies examples. A = findBestFeatureIndex(X, Y, attrs) newAttrs = [attr for attr in attrs if attr != A] # Decision Tree attribute for Root = A. root = Node(A) # For each possible value, vi, of A for possible_value in [0, 1]: # Let Examples(vi) be the subset of examples that have the value vi for A X_s, Y_s = splitData(X, Y, A, possible_value) if len(X_s) == 0 or len(Y_s) == 0: # Then below this new branch add a leaf node with label = most common target value in the examples root.addChild(possible_value, Leaf(majorityElement(Y))) else: # Else below this node add a subtree ID3(Examples_vi, TargetAttr, Attrs - {A}) root.addChild(possible_value, ID3(X_s, Y_s, newAttrs, currentDepth, maxDepth)) return root
def initFunction(self, fnNode, functionIndex, statements, functionType): fnNode.itsFunctionType = functionType fnNode.addChildToBack(statements) functionCount = fnNode.getFunctionCount() if (functionCount != 0): fnNode.itsNeedsActivation = True ## for-while i = 0 while (i != functionCount): fn = fnNode.getFunctionNode(i) if (fn.getFunctionType() == FunctionNode.FUNCTION_EXPRESSION_STATEMENT): name = fn.getFunctionName() if name is not None and (len(name) != 0): fnNode.removeParamOrVar(name) i += 1 if (functionType == FunctionNode.FUNCTION_EXPRESSION): name = fnNode.getFunctionName() if (name is not None) and \ len(name) != 0 \ and (not fnNode.hasParamOrVar(name)): if (fnNode.addVar(name) == ScriptOrFnNode.DUPLICATE_CONST): self.parser.addError("msg.const.redecl", name) setFn = Node(Token.EXPR_VOID, Node(Token.SETNAME, Node.newString(Token.BINDNAME, name), Node(Token.THISFN))) statements.addChildrenToFront(setFn) lastStmt = statements.getLastChild() if lastStmt is None or (lastStmt.getType() != Token.RETURN): statements.addChildToBack(Node(Token.RETURN)) result = Node.newString(Token.FUNCTION, fnNode.getFunctionName()) result.putIntProp(Node.FUNCTION_PROP, functionIndex) return result
def __init__(self, LexNode): Node.__init__(self, LexNode) self.text = self.tokens.get('STRING', "") self.type = self.tokens.get('TYPE', "boolean") self.ID = self.tokens.get('ID', uuid.uuid4()) self.function = self.tokens.get('function', None)
def main(): new_tree = Tree() new_node = Node(url='ma suka', score=33, matchings={}, tree=new_tree) node_id = new_tree.add_node(new_node) new_node.set_node_id(node_id) new_node.add_parent(parent_id=0)
def construct(self, slice): Node.construct(self, slice) self.parent_index=self.parents_1[0] assert(len(self.parents_0)==0) assert(len(self.parents_1)==1) parent_size=self.parents_1_sizes[0] assert(self.node_size==parent_size) self.mus_shape=(self.node_size,1) self.kappas_shape=(self.node_size), # Check or construct means rnd_mus, rnd_kappas=self._make_rnd_kms(self.node_size) # If the user has specified some values these are used if not self.user_mus is None: self.mus=self.user_mus for i in range(0, self.node_size): # Make sure we have angles in [0,2pi[ self.mus[i]=mod2pi(self.mus[i]) assert(self.mus.shape==self.mus_shape) del self.user_mus else: # Otherwise the means are set to random values self.mus=rnd_mus # Check or construct kappa values if not self.user_kappas is None: self.kappas=self.user_kappas assert(self.kappas.shape==self.kappas_shape) del self.user_kappas else: self.kappas=rnd_kappas self.vm_list, self.samplers=self._make_vm_list(self.mus, self.kappas, self.node_size)
def __init__(self, logp, doc, name, parents, cache_depth=2, plot=None, verbose=None, logp_partial_gradients = {}): self.ParentDict = ParentDict # This function gets used to evaluate self's value. self._logp_fun = logp self._logp_partial_gradients_functions = logp_partial_gradients self.errmsg = "Potential %s forbids its parents' current values"%name Node.__init__( self, doc=doc, name=name, parents=parents, cache_depth = cache_depth, verbose=verbose) self._plot = plot # self._logp.force_compute() # Check initial value if not isinstance(self.logp, float): raise ValueError, "Potential " + self.__name__ + "'s initial log-probability is %s, should be a float." %self.logp.__repr__()
def __init__(self, LexNode=None, value=None, operator=None): Node.__init__(self, LexNode) self.value = value self.operator = operator self._setOperation(operator)
def __init__(self, x=0.0, y=0.0, w=0.0, h=0.0): Translator.__init__(self) Node.__init__(self) self.x = x self.y = y self.w = w self.h = h
def main(): #Test case 1 root = Node("Max", 23) john = root.setLeft(Node("John", 18)) mark = john.setRight(Node("Ann", 22)).setRight(Node("Mark", 2)) rob = john.setLeft(Node("Rob", 12)) rob.setRight(Node("Bob", 4)).setLeft(Node("Mie", 6)) rob.setLeft(Node("Steven", 3)).setRight(Node("Sarah", 2)) annie = mark.setLeft(Node("Annie", 9)) annie.setRight(Node("Barnie", 42)) annie.setLeft(Node("Malcolm", 7)).setRight(Node("Susan", 5)).setRight(Node("Terry", 4)) assert root.left.right.right.left.right.name == "Barnie" assert root.left.left.left.name == "Steven" assert root.left.right.name == "Ann" assert root.left.right.left == None assert root.left.left.right.left.name == "Mie" maxRating, invitedPeople = FindMaxRating(root) assert maxRating == 109 assert [n.name for n in invitedPeople] == ['Steven', 'Sarah', 'Mie', 'John', 'Ann', 'Malcolm', 'Susan', 'Terry', 'Barnie'] print "Max rating for people {" + ", ".join(root.allChildren()) + "}: \n" + str(maxRating) print "People invited: " print [n.name for n in invitedPeople]
def __init__(self, number_of_nodes, transmission_range, speed_sink, size_area, sink_route, strategy, duty_cycle): """ :type number_of_nodes: a integer number :type transmission_range: a number, given in meters :type speed_sink: a number, speed given in meters per second :type size_area: a list of two numbers, the values in meters :type sink_route: a list of list of two numbers referring to the each target position :type strategy: a string, use static variable on class Environment :type duty_cycle: a boolean, enable duty-cicle on nodes """ self.sink = None self.define_sink_route(sink_route, speed_sink) self.transmission_range = transmission_range self.size_x = size_area[0] self.size_y = size_area[1] self.sink_route = sink_route self.strategy = strategy self.duty_cicle = duty_cycle self.nodes = [] Node.is_run = True for i in range(number_of_nodes): x_pos = randint(0, self.size_x) y_pos = randint(0, self.size_y) pos = (x_pos, y_pos) node = Node(pos, duty_cycle) node.start() self.nodes.append(node)
def harvest(self, vf): if not Harvester.harvest(self, vf): return mvf = vf.getMeta() # determine grouping groupTag = self.opts['group'] if groupTag == None: # no grouping - stuff into root node target = self.root else: # get the grouping value if groupTag not in mvf: grp = OTHER else: grp = mvf[groupTag] if type(grp) is list: raise ConfigError("Configuration Error - grouping item must not be a list") if grp in self.nodeMap: # if we've seen this group, then just reuse the # same node target = self.nodeMap[grp] else: # Otherwise create a new node and link it in path=os.path.join(self.hpath, Legalize(grp)) target = Node(grp, self.opts, path=path, title = "%s: %s" %(metaTranslate(groupTag), grp)) self.pathMap[os.path.join(self.name, grp)] = path self.nodeMap[grp] = target self.root.addDir(target) self.gcount += 1 target.addVideo(vf) self.count += 1
def simulate(self): currentNode = Node(Sudoku(self.m_sudokuProblem, self.m_fixedNodes)) currentNode.m_sudoku.populate() found = False while not found: self.m_temperature = self.scheduleTemp() if currentNode.getValue() <= 0 and currentNode.m_sudoku.validateSudoku(): found = True return currentNode if self.m_temperature < 0.00027: currentNode = self.reheat() print "REHEAT" nextNode = currentNode.getRandomSucessor() deltaE = currentNode.getValue() - nextNode.getValue() print nextNode.getValue() probability = self.getProbability(deltaE) if random.random() < probability: currentNode = nextNode
def r(): root = Node("Max", 10000) john = root.setLeft(Node("John", 1)) annie = john.setLeft(Node("Annie", 1)) jens = annie.setLeft(Node("Jens", 10000)) FindMaxRating(root)
def test_delete(): bs_tree = BinarySearchTree() keys = [5, 2, -4, 3, 12, 9 ,21, 19, 25] for key in keys: node = Node() node.key = key bs_tree.insert(node) # delete leaf bs_tree.delete(bs_tree.search(-4)) assert(bs_tree.search(-4) is None) assert(bs_tree.search(2).left is None) # delete node with one child bs_tree.delete(bs_tree.search(2)) assert(bs_tree.search(2) is None) assert(bs_tree.root.left.key == 3) # delete node with two children bs_tree.delete(bs_tree.search(12)) assert(bs_tree.root.right.key == 19) assert(bs_tree.search(19).left.key == 9) assert(bs_tree.search(19).right.key == 21) # delete root bs_tree.delete(bs_tree.root) assert(bs_tree.root.key == 9) assert(bs_tree.root.left.key == 3) assert(bs_tree.root.right.key == 19)
def createChildNodes(self, sortedVarValues, currentNode, currentVariable): newChildren = [] for value in sortedVarValues: # make new node and set currentNode as the parent newChild = Node(currentNode) # grab the assignment from the parent node newChild.assignment = copy.deepcopy(currentNode.assignment) # newChild.printAssignment() newChild.currentcsp = copy.deepcopy(currentNode.currentcsp) # grab the value we wanted to change and put it in the assignment of the new child newChild.assignment[currentVariable.name] = value # add the child to the list, we will use this list later newChildren.append(copy.deepcopy(newChild)) # now that we've made all the children, set their parent nodes, and altered their assignment # with the proper value, now we're gonna set all their right sibling pointers #basically, this pointer makes printing the tree easier i = 1 for child in newChildren: child.rightSibling = newChildren[i] if i is len(newChildren): child.rightSibling is None currentNode.children = newChildren return newChildren
def __init__(self, nodeType): Node.__init__(self, nodeType) self.itsVariableNames = ObjToIntMap(11) self.itsVariables = [] self.itsConst = [] self.functions = [] self.regexps = []
class BinarySearchTree(object): def __init__(self): self.rootNode = None def insert(self, data): if not self.rootNode: # first element self.rootNode = Node(data) else: self.rootNode.insert(data) def remove(self, dataToRemove): if self.rootNode: if self.rootNode == dataToRemove: tempNode = Node(None) tempNode.leftChild = self.rootNode self.rootNode.remove(dataToRemove, tempNode) else: self.rootNode.remove(dataToRemove, None) def getMax(self): if self.rootNode: return self.rootNode.getMax() def getMin(self): if self.rootNode: return self.rootNode.minValue() def traverseInOrder(self): if self.rootNode: self.rootNode.traverseInOrder()
def __init__(self, LexNode, ifChildren=None, elseChildren=None): Node.__init__(self, LexNode) self.expression = self.tokens.get('expr') self.ifChildren = ifChildren or list() self.elseChildren = elseChildren or list()
def push(self, value): """ Add value to top of Stack """ new_node = Node(value) new_node.next = self.head self.head = new_node
def check_availablespace(self, maxinputsize, files): """ Verify that enough local space is available to stage in and run the job """ if not self.shouldVerifyStageIn(): return totalsize = reduce(lambda x, y: x + y.filesize, files, 0) # verify total filesize if maxinputsize and totalsize > maxinputsize: error = "Too many/too large input files (%s). Total file size=%s B > maxinputsize=%s B" % (len(files), totalsize, maxinputsize) raise PilotException(error, code=PilotErrors.ERR_SIZETOOLARGE) self.log("Total input file size=%s B within allowed limit=%s B (zero value means unlimited)" % (totalsize, maxinputsize)) # get available space wn = Node() wn.collectWNInfo(self.workDir) available_space = int(wn.disk)*1024**2 # convert from MB to B self.log("Locally available space: %d B" % available_space) # are we wihin the limit? if totalsize > available_space: error = "Not enough local space for staging input files and run the job (need %d B, but only have %d B)" % (totalsize, available_space) raise PilotException(error, code=PilotErrors.ERR_NOLOCALSPACE)
class LinkedList: def __init__(self): self.head = Node(-1) self.tail = self.head self.curr = self.head self.size = 0 def add(self, data): self.link_after(data) def link_after(self, data): val_to_add = Node(data) if self.head.nextNode is None: self.head.nextNode = val_to_add val_to_add.prevNode = self.head self.tail = self.head.nextNode else: self.tail.nextNode = val_to_add val_to_add.prevNode = self.tail self.tail = self.tail.nextNode self.size += 1 def remove(self): self.unlink_before() def unlink_before(self): temp = self.head.get_data() self.head = self.head.nextNode self.head.prevNode = None self.curr = self.head self.size -= 1 return temp def get_size(self): return self.size def head(self): return self.head def change_head(self, val): self.head.set_data(val) def tail(self): return self.tail def to_string(self): string = "" while self.curr.nextNode is not None: string += str(self.curr.nextNode.get_data()) + " --> " self.curr = self.curr.nextNode self.curr = self.head # remove the last 5 characters to remove the last --> return string[0:len(string)-5]
def addAtIndex(self, index, data): # Continue if index is valid if index >= 0 and index <= self.__numberNodes: if index == 0: # Push element to front of list if index is 0 self.push(data) elif index == self.__numberNodes: # Add element to end of list if index is last element self.add(data) else: # Continue if list is not empty if self.__head is not None and self.__tail is not None: addNode = Node(data) currentNode = self.__head.getNext() previousNode = self.__head count = 1 while currentNode is not None: # Traverse list to find element at index # Insert element when index is found if count == index: previousNode.setNext(addNode) addNode.setNext(currentNode) self.__numberNodes = self.__numberNodes + 1 break # Prepare for next iteration previousNode = currentNode currentNode = currentNode.getNext() count = count + 1
def push(self, value): new_node = Node(value, None, None) new_node.previous = self.end.previous new_node.next = self.end self.end.previous.next = new_node self.end.previous = new_node self.size += 1
def build(self, array): if len(array) > 0: # counting the median, which is the key median = IntervalTree.get_median_point(self, array) # current Node n = Node(median) left = [] right = [] overlap = [] for i in range(0, len(array)): if array[i].begin <= median <= array[i].end: overlap.append(array[i]) elif array[i].end < median: left.append(array[i]) elif array[i].begin > median: right.append(array[i]) n.overlap_begin_sort = sorted(overlap, key=operator.attrgetter("begin")) n.overlap_end_sort = sorted(overlap, key=operator.attrgetter("end"), reverse=True) if self.root is None: self.root = n n.left = self.build(left) n.right = self.build(right) return n else: return None
def __init__(self, function_name, given_type): Node.__init__(self, function_name) self.number_of_params = 0 self.return_type = None self.type = given_type # We only want to allow parameters to be added to each green node one time. self.param_flag = False
class WaveletTree(object): def __init__(self, data=None): if data == None: print "Please give correct parameters" return self.__root = Node(data) #Create the parent node """ Query Functions """ def rank_query(self,character=None, position=None): if character==None or position==None or position <= 0: print "Please give correct parameters" return -1 return self.__root.get_rank_query(position,character) def select_query(self,character=None, position=None): if character==None or position==None or position <= 0: print "Please give correct parameters" return -1 return self.__root.get_select_query(position, character) def track_symbol(self,position=None): if position==None or position <= 0: print "Please give correct parameters" return -1 return self.__root.get_track_symbol(position) """
def genPoints(self,Community_Coordinate): """ gen n Points """ #Test #print Community_Coordinate #raw_input() #generator Points for i in range(self.nPoints): Random_Comm = random.choice(Community_Coordinate.keys()) XmaxNo = max(Community_Coordinate[Random_Comm][1]) XminNo = min(Community_Coordinate[Random_Comm][1]) YmaxNo = max(Community_Coordinate[Random_Comm][2]) YminNo = min(Community_Coordinate[Random_Comm][2]) node=Node() node.id=i node.x=random.randrange(XminNo+1,XmaxNo-20) node.y=random.randrange(YminNo+1,YmaxNo-20) self.pAll.append(node) #print i, Random_Comm, node.x,node.y '''self.genPointType(0.5,0.2,5,2)'''
def __init__(self, lineCalc, lineDecorator, parent, name, img, x = 0, y = 0, w = 100, h = 100): Node.__init__(self, lineCalc, lineDecorator, parent, name, x, y, w, h) self.img = img if img is not None and (img.width() != self.w or img.height() != self.h): self.img = img.scaled(self.w, self.h) self.bitmap_lock = threading.Lock()
def remove(self, dataToRemove): if self.rootNode: if self.rootNode == dataToRemove: tempNode = Node(None) tempNode.leftChild = self.rootNode self.rootNode.remove(dataToRemove, tempNode) else: self.rootNode.remove(dataToRemove, None)
def train(self): root_node = Node() self.grow_tree(root_node, self.patches, self.labels) print('training completed')
if game not in hasChildren: hasChildren.append(game.matrix) search( frontier[0]) # calls the function again with the new frontier # pieces = [[1,8,2], # [0,4,3], # [7,6,5]] pieces = [[], [], []] print("Enter a valid initial combination separated by space") pieces[0] = input('1st line: ') pieces[1] = input('2nd line: ') pieces[2] = input('3rd line: ') print("\n") # Splits the string entered by comma and maps each element to int for line in range(3): pieces[line] = pieces[line].split(" ") pieces[line] = list(map(int, pieces[line])) puzzle = Node(pieces, None) # (matrix, parent) print("INITIAL STATE") puzzle.print() search(puzzle)
from Child import Child from Node import Node # noqa: I201 STMT_NODES = [ # continue-stmt -> 'continue' label? ';'? Node('ContinueStmt', kind='Stmt', children=[ Child('ContinueKeyword', kind='ContinueToken'), Child('Label', kind='IdentifierToken', is_optional=True), ]), # while-stmt -> label? ':'? 'while' condition-list code-block ';'? Node('WhileStmt', kind='Stmt', traits=['WithCodeBlock', 'Labeled'], children=[ Child('LabelName', kind='IdentifierToken', is_optional=True), Child('LabelColon', kind='ColonToken', is_optional=True), Child('WhileKeyword', kind='WhileToken'), Child('Conditions', kind='ConditionElementList'), Child('Body', kind='CodeBlock'), ]), # defer-stmt -> 'defer' code-block ';'? Node('DeferStmt', kind='Stmt', traits=['WithCodeBlock'], children=[ Child('DeferKeyword', kind='DeferToken'), Child('Body', kind='CodeBlock'),
def __init__(self, index, node_serial_obj): Node.__init__(self) self.index = index self.serial = node_serial_obj
nonce = HexEncoder.encode(b'Hello World!') # create the genesis block genesis = Block(firstTX, prev, nonce, pow) threadID = 0 threads = [] # Create all of the broadcast queues while threadID < numNodes: broadcastQueue.append(queue.Queue()) threadID += 1 threadID = 0 while threadID < numNodes: #place holder for actual node constructor node = Node(genesis) thread = nodeThread(threadID, node, txQueue, broadcastQueue) thread.start() threads.append(thread) threadID += 1 node = None txID = 0 # Read in the transactions and populate the queue for trans in txList: if trans != txList[0]: trans['input'] = fixPKInput(trans['input']) trans['output'] = fixPKOutput(trans['output']) newTX = Transaction(trans['number'], trans['input'], trans['output'], trans['sig']) txQueue.add(newTX, txID)
def __init__(self): self.nodeTail = Node(binTail=True) self.nodeHead = Node(binHead=True, nodeNext=self.nodeTail)
def printTree(initialNode, tabs): space = "" for i in range(0, tabs): space = space + "\t" if (initialNode != None): printTree(initialNode.right, tabs + 1) print(space + str(initialNode.number)) print("") printTree(initialNode.left, tabs + 1) print( "Input the data. The numbers must be introduced in one line separated by commas." ) print("Example: 11, 6, 8, 19, 4, 10, 5, 17, 43, 49, 31") numbers = [int(number) for number in input().split(',')] #numbers = [11, 6, 8, 19, 4, 10, 5, 17, 43, 49, 31] initial = Node(numbers[0]) #print(numbers[0]) numbers.pop(0) print("") for x in numbers: initial = insertar(initial, x) printTree(initial, 0)
from LinkedList import LinkedList from Node import Node from StackClass import StackClass from Queue import Queue import datetime stacki = StackClass() queue = Queue() print(str(queue.isEmpty)) print(str(stacki.isEmpty)) #for i in range(10): #stacki.push(Node(i)) #queue.add(Node(i)) #print(Node(i)) #for i in range(10): #print(stacki.pop()) #print(queue.remove()) linked = LinkedList() for i in range(10): linked.add(Node(i), i) for i in range(10): print(linked.remove(i))
def __init__(self, doc, tag): self.tag = tag self.tag._node = self Node.__init__(self, doc) self.__init_personality()
def previousSibling(self): return Node.wrap(self.doc, self.tag.previous_sibling)
def nextSibling(self): return Node.wrap(self.doc, self.tag.next_sibling)
def lastChild(self): return Node.wrap(self.doc, self.tag.contents[-1]) if len(self.tag) > 0 else None
def parentNode(self): return Node.wrap(self.doc, self.tag.parent) if self.tag.parent else None
from Child import Child from Node import Node # noqa: I201 EXPR_NODES = [ # An inout expression. # &x Node('InOutExpr', kind='Expr', children=[ Child('Ampersand', kind='PrefixAmpersandToken'), Child('Expression', kind='Expr'), ]), # A #column expression. Node('PoundColumnExpr', kind='Expr', children=[ Child('PoundColumn', kind='PoundColumnToken'), ]), Node('FunctionCallArgumentList', kind='SyntaxCollection', element='FunctionCallArgument'), Node('TupleElementList', kind='SyntaxCollection', element='TupleElement'), Node('ArrayElementList', kind='SyntaxCollection', element='ArrayElement'), Node('DictionaryElementList', kind='SyntaxCollection', element='DictionaryElement'), Node('StringInterpolationSegments', kind='SyntaxCollection', element='Syntax', element_name='Segment',
def connectRRT(env, screen, extendNode): for e in pygame.event.get(): if e.type == QUIT or (e.type == KEYUP and e.type == K_ESCAPE): sys.exit("Leaving") extendNodeXY = extendNode.XY minDist = 99999999 nearestConnectNode = None for node in connectTree: d = getDistance(node.XY, extendNodeXY) if d < minDist: minDist = d nearestConnectNode = node nearestConnectNodeXY = node.XY # Create new node in the direction of the random node based on stepSize newXY = None dist = minDist while True: #print "stuck connectTree" if dist > stepSize: theta = atan2(extendNodeXY[1] - nearestConnectNodeXY[1], extendNodeXY[0] - nearestConnectNodeXY[0]) x = (int)(nearestConnectNodeXY[0] + stepSize * cos(theta)) y = (int)(nearestConnectNodeXY[1] + stepSize * sin(theta)) newXY = (x, y) dist = stepSize else: newXY = extendNodeXY if env[newXY[0]][newXY[1]] == 0: nearNodes = getNearNodes(newXY, connectTree, nearestNodesRadius) parent, dist = getBestParent(newXY, nearNodes) newNode = Node(newXY, dist, parent) connectTree.append(newNode) pygame.draw.line(screen, red, newXY, parent.XY) rewire(newNode, nearNodes, connectTree) pygame.display.update() if newXY == extendNodeXY: return newNode else: return None dist = (int)(getDistance(newXY, extendNodeXY)) nearestConnectNodeXY = newXY
def __init__(self, index, addr, i2c_helper): Node.__init__(self) self.index = index self.i2c_addr = addr self.i2c_helper = i2c_helper
from Node import Node import threading import time # ordem: coinServer, test_script5 # resultado esperado: nó se conecta ao servidor na AWS e recebe uma lista de peers Node.SERVER = '18.231.174.232' a = Node('1', 63153) t_a = threading.Thread(target=a.start_node, kwargs={}) t_a.start() t_a.join()
import random from Node import Node, NodeManager bst_nums = set() while len(bst_nums) < 100: bst_nums.add(random.randint(0, 999)) # print(bst_nums) root = Node(500) bst = NodeManager(root) for x in bst_nums: bst.insert(x) for x in bst_nums: assert bst.search(x) is True print('search success') # delete 10 nodes delete_nums = set() bst_nums = list(bst_nums) while len(delete_nums) < 10: delete_nums.add(bst_nums[random.randint(0, 99)]) for del_num in delete_nums: assert bst.delete(del_num) is not False # research tree
# flake8: noqa I201 from Child import Child from Node import Node DECL_NODES = [ # type-assignment -> '=' type Node('TypeInitializerClause', kind='Syntax', children=[ Child('Equal', kind='EqualToken'), Child('Value', kind='Type'), ]), # typealias-declaration -> attributes? access-level-modifier? 'typealias' # typealias-name generic-parameter-clause? # type-assignment # typealias-name -> identifier Node('TypealiasDecl', kind='Decl', children=[ Child('Attributes', kind='AttributeList', is_optional=True), Child('AccessLevelModifier', kind='DeclModifier', is_optional=True), Child('TypealiasKeyword', kind='TypealiasToken'), Child('Identifier', kind='IdentifierToken'), Child('GenericParameterClause', kind='GenericParameterClause', is_optional=True), Child('Initializer', kind='TypeInitializerClause',
if root is None: return 0 cnt = 1 q = [] q.append([root]) while (len(q) > 0): curQ = [] items = q.pop(0) for item in items: if item.left is None and item.right is None: return cnt if item.right is None: curQ.append(item.left) elif item.left is None: curQ.append(item.right) else: curQ.extend([item.left, item.right]) q.append(curQ[:]) cnt += 1 return cnt root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) root.left.right.left = Node(6) root.right.right = Node(7) print(minDepth(root))
from Child import Child from Node import Node # noqa: I201 EXPR_NODES = [ # An inout expression. # &x Node('InOutExpr', kind='Expr', children=[ Child('Ampersand', kind='AmpersandToken'), Child('Identifier', kind='IdentifierToken'), ]), # A #column expression. Node('PoundColumnExpr', kind='Expr', children=[ Child('PoundColumn', kind='PoundColumnToken'), ]), Node('FunctionCallArgumentList', kind='SyntaxCollection', element='FunctionCallArgument'), Node('TupleElementList', kind='SyntaxCollection', element='TupleElement'), Node('ArrayElementList', kind='SyntaxCollection', element='ArrayElement'), Node('DictionaryElementList', kind='SyntaxCollection', element='DictionaryElement'), # The try operator. # try foo() # try? foo()
def __init__(self): self.inicio = Node() self.inicio = None
def check_win_condition(agents): # check if there are undiscovered nodes if len(agents[0].maze.undiscovered) > 0: return False # check if all undiscovered nodes have been reached for agent in agents: if agent.goal != agent.current_node: return False return True node1 = Node(False, False, False, False, (0, -2), True) node2 = Node(False, False, False, False, (0, -1), True) node3 = Node(False, False, False, False, (0, 0), True) node4 = Node(False, False, False, False, (0, 1), True) node5 = Node(False, False, False, False, (0, 2), False) node6 = Node(False, False, False, False, (-2, 0), True) node7 = Node(False, False, False, False, (-1, 0), True) node8 = Node(False, False, False, False, (1, 0), True) node9 = Node(False, False, False, False, (2, 0), False) node1.set_up(node2) node2.set_down(node1) node2.set_up(node3) node3.set_down(node2) node3.set_up(node4) node4.set_down(node3)
def push(self, element): self._top += 1 node = Node(element) self._list.insert_as_head(node)
from Child import Child from Node import Node # noqa: I201 TYPE_NODES = [ # simple-type-identifier -> identifier generic-argument-clause? Node('SimpleTypeIdentifier', kind='Type', children=[ Child('Name', kind='Token', classification='TypeIdentifier', token_choices=[ 'IdentifierToken', 'CapitalSelfToken', 'AnyToken', ]), Child('GenericArgumentClause', kind='GenericArgumentClause', is_optional=True), ]), # member-type-identifier -> type '.' identifier generic-argument-clause? Node('MemberTypeIdentifier', kind='Type', children=[ Child('BaseType', kind='Type'), Child('Period', kind='Token', token_choices=[ 'PeriodToken', 'PrefixPeriodToken',
def __init__(self, memory, node_item): Node.__init__(self, memory, node_item) self._next = None
def append(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node
from Child import Child from Node import Node # noqa: I201 STMT_NODES = [ # continue-stmt -> 'continue' label? ';'? Node('ContinueStmt', kind='Stmt', children=[ Child('ContinueKeyword', kind='ContinueToken'), Child('Label', kind='IdentifierToken', is_optional=True), Child('Semicolon', kind='SemicolonToken', is_optional=True), ]), # while-stmt -> label? ':'? 'while' condition-list code-block ';'? Node('WhileStmt', kind='Stmt', children=[ Child('LabelName', kind='IdentifierToken', is_optional=True), Child('LabelColon', kind='ColonToken', is_optional=True), Child('WhileKeyword', kind='WhileToken'), Child('Conditions', kind='ConditionList'), Child('Body', kind='CodeBlock'), Child('Semicolon', kind='SemicolonToken', is_optional=True), ]), # defer-stmt -> 'defer' code-block ';'? Node('DeferStmt', kind='Stmt', children=[ Child('DeferKeyword', kind='DeferToken'), Child('Body', kind='CodeBlock'),
def __eq__(self, other): return Node.__eq__(self, other) and hasattr( other, "tag") and self.tag == other.tag
def generate_1_pos_neg_cyc(): """ generate a graph with a positive and a negative cycle linked at a shared node :return: Graph, nodes """ s0 = Node(0) s1 = Node(1) s2 = Node(2) s3 = Node(3) s1.set_disequalities([60]) s2.set_disequalities([58]) s3.set_disequalities([4]) s0.add_edge(s1, 12) s1.add_edge(s2, -12) s2.add_edge(s1, 18) s1.add_edge(s3, -50) s3.add_edge(s1, 49) g = Graph(s0) g.set_nodes([s0, s1, s2, s3]) return g