Example #1
0
def bfstree(s0):
    # s0 = initial state

    # create the initial node
    n0 = node(s0, None, None, 0, 0) 

    # initizlize #visited nodes
    nvisited = 0
    
    # initialize the frontier list
    frontier = deque([n0])

    while True:
        # the search fails when the frontier is empty
        if not frontier:
            return (None, nvisited)
        else:
            # get one node from the frontier
            n = frontier.popleft()
            # count the number of visited nodes
            nvisited+=1
            # check if the state in n is a goal
            if n.state.isgoal():
                return (n, nvisited)
            else:
                # generate successor states
                S = n.state.successors()
                # create new nodes and add to the frontier
                for (s, a, c) in S:
                    p = node(s, n, a, n.cost+c, n.depth+1)
                    frontier.append(p)
Example #2
0
 def prepend(self, num):
     if self.head == None:
         self.head = node.node(num)
     else:
         temp = node.node(num)
         temp.set_next(self.head)
         self.head = temp
Example #3
0
def sum_by_bit(e,t):
    mod = 0
    i = 1
    while e != None or t != None:
       if e != None:
           e_data = e.data
       else: e_data = 0
       if t != None:
           t_data = t.data
       else: t_data = 0
       (mod,remain) = divmod(e_data+t_data+mod,10)
       if i == 1:
           head = node(remain)
           tail = head
       else:
           tail.next_element = node(remain)
           tail = tail.next_element
       if e != None:
        e = e.next_element
       if t != None:
        t = t.next_element
       i = i+1
    if mod != 0:
        tail.next_element = node(mod)
    return head
Example #4
0
def gen():
    '''
    The nodeList of type 'node' will be created, including numNode sensors
    the root node is located at the center of the area
    :return:
    '''
    nodeList = []
    root = node.node(0, 0)
    nodeList.append(root)
    for i in range(1, numNode):
        while True:
            #generata new pair of (x,y) until it's not same with any added node
            newPos = (random.randint(0, xRange), random.randint(0, yRange))
            if not checkPosDup(newPos, nodeList):
                break
        newNode = node.node(*newPos)
        nodeList.append(newNode)

    # open file for outputing the topology information
    topoFile = open('topo.txt', 'w')
    for i in range(0, numNode-1):
        for j in range(i+1, numNode):
            if distance(nodeList[i], nodeList[j]) == 0:
                # should remove one of the two, but becareful with the 'out of range' loop
                print "Oh, there are two nodes with same location..."
                print nodeList[i].x, nodeList[i].y, "|||", nodeList[j].x, nodeList[j].y
            else:
                # write to file: [node1 , node2, link quality, node1.x, node1.y, node2.x, node2.y]
                topoFile.write("%u, %u, %f, %u, %u, %u, %u\n" % (
                i, j, quality(nodeList[i], nodeList[j]), nodeList[i].x, nodeList[i].y, nodeList[j].x, nodeList[j].y))
Example #5
0
    def get_map(self, n, set_x, set_y, exclude):

        # print(n,set_x,set_y)
        children = []
        next_exclude = exclude
        if n == 1:
            for x in set_x:
                for y in set_y:
                    print("exclude: {}".format(exclude))
                    if self.Point_valid((x,y), exclude):
                        node_child = node((x,y))
                        children.append(node_child)
            return children
        else:
            for x in set_x:
                for y in set_y:
                    s_x = set([x])
                    s_y = set([y])
                    # print("gaaga")
                    # print(set_x,set_y,s_x,s_y)
                    if self.Point_valid((x,y),exclude):
                        if exclude:
                            print("get exclude")
                            print(exclude)
                            next_exclude.append((x,y))
                            print("next exclude: {}".format(next_exclude))
                        else:
                            next_exclude = [(x,y)]
                        print("next exclude: {}".format(next_exclude))
                        node_child = node((x, y))
                        if n-1 >0:
                            node_child.add_child(*self.get_map(n-1, set_x - s_x, set_y - s_y, next_exclude))
                        children.append(node_child)
            return children
Example #6
0
 def append(self, num):
     if self.head == None:
         self.head = node.node(num)
     else:
         current = self.head
         while(current.get_next() != None):
             current = current.get_next()
         temp = node.node(num)
         current.set_next(temp)
         temp.set_next(None)
Example #7
0
def sum(e, t):
    e_sum = assemble(e)
    t_sum = assemble(t)
    sum =  e_sum + t_sum
    head = node(str(sum)[-1])
    tail = head
    for i in str(sum)[-2::-1]:
        temp = node(i)
        tail.next_element = temp
        tail = temp
    return head
Example #8
0
 def jump_step(self, n):
     children = []
     if n == 1 :
         node_child = node(1)
         children.append(node_child)
         return children
     if n >=2 :
         for i in [1,2]:
             node_child = node(i)
             if self.jump_step(n-i):
                 node_child.add_child(*self.jump_step(n-i))
             children.append(node_child)
         return children
Example #9
0
def f(s1, s2):
    if not s1:
        return s2
    if not s2:
        return s1

    it1 = s1
    it2 = s2

    res = None
    carry = 0

    while it1 and it2:
        curr = it1.value + it2.value + carry
        carry = curr / 10
        value = curr % 10
        if not res:
            res = node(value)
            prev = res
        else:
            prev.next = node(value)
            prev = prev.next
        it1 = it1.next
        it2 = it2.next

    while it1:
        curr = it1.value + carry
        carry = curr / 10
        value = curr % 10
        prev.next = node(value)
        prev = prev.next
        it1 = it1.next

    while it2:
        curr = it2.value + carry
        carry = curr / 10
        value = curr % 10
        prev.next = node(value)
        prev = prev.next
        it2 = it2.next

    if carry:
        prev.next = node(carry)

    it = res
    while it:
        print it.value
        it = it.next
    return res
Example #10
0
def get_node_fcb():
    name = pal_get_platform_name()
    info = {
            "Description": name + " Fan Control Board",
           }

    return node(info)
Example #11
0
def get_node_peb():
    name = pal_get_platform_name()
    info = {
            "Description": name + " PCIe Expansion Board",
    }

    return node(info)
Example #12
0
def makeNode(line, d, adata):   
    ''' makes a object of type node from a string '''
    closing = line.find('</')
    if(closing != -1):
        d.depth = d.depth - 1
        line = line[2:len(line)-1]
    else:
        d.depth = d.depth + 1
        line = line[1:len(line)-1]        

    entities = line.split(' ')    
    if entities[0].find(':') != -1:
        tempName = entities[0].split(':')
        elementName = tempName[1]
        namespace  = tempName[0]
    else:
        elementName = entities[0]
        namespace = ""
        
        
    data = adata
    attrDict = {}
    childList = []
    i=1
    while(i<len(entities)):
        try:
            tempattr = entities[i].split('=')   
        except:
            print('Syntax Error in XSD :' + entities[i])
            exit(-1)        
        attrDict[tempattr[0]] = tempattr[1]
        i = i + 1
    
    newnode = node.node(elementName, namespace, data, attrDict, childList, d.depth)
    return newnode
Example #13
0
 def copynode( self, parent, nod ):
     thisnode = node( self, parent, leaf=nod.isLeaf, op=nod.operator, copy=True )
     parent.children.append( thisnode )
     
     if not thisnode.isLeaf:
         self.copynode( thisnode, nod.children[0] )
         self.copynode( thisnode, nod.children[1] )
Example #14
0
	def test_indexNeighbor(self):
		neighbors = []
		n = node("0xfaca", "12:34:56:78:9a:bc:de:ff", "0xffff")
		
		nei_nwk = ["0x0001", "0x0002", "0x0003"]
		nei_in = [7, 5, 3]
		nei_out = [7, 5, 3]

		for i in range(0,3):
			neighbors.append({"nwkAdr" : nei_nwk[i], "in_cost" : int(nei_in[i]), "out_cost" : int(nei_out[i])})
	
		nei_nwk = ["0x0001", "0x0002", "0x0003", "0x0004"]
		nei_in = [1, 3, 5, 1]
		nei_out = [1, 3, 5, 3]

		for i in range(0,4):
			neighbors.append({"nwkAdr" : nei_nwk[i], "in_cost" : int(nei_in[i]), "out_cost" : int(nei_out[i])})
	
		n.setCurNeighbors(neighbors)
		n.addNpPreNeighbors()
		n.processPreNeighbors()
		listOfDicts = n.getHistoricalNeighbors()

		nwk_list = ["0x0001", "0x0002", "0x0003", "0x0004"]
		for nwkAdr in nwk_list:
			index = n.indexNeighbor(nwkAdr, listOfDicts)
			assert index != -1
			dic = listOfDicts[index]
			assert dic["nwkAdr"] == nwkAdr 

		nwk_list = ["0x0005", "0x0006", "0xFFFF", "0xFFFE"]
		for nwkAdr in nwk_list:
			index = n.indexNeighbor(nwkAdr, listOfDicts)
			assert index == -1
Example #15
0
def control(fileObjectXML, fileObjectXSD):
    '''the main control of the tree builder and validator'''
    lineXML = ""
    for line in fileObjectXML:
        lineXML = lineXML + line
                
    lineXSD = ""
    for line in fileObjectXSD:
        lineXSD = lineXSD + line
    
    lineXML = remove_comments(lineXML)
    lineXSD = remove_comments(lineXSD)
    lineXML = remove_extra_spaces(lineXML)
    lineXSD = remove_extra_spaces(lineXSD)
    lineXML = lineXML.replace('\n','')
    lineXSD = lineXSD.replace('\n','')  
      
    listXMLTags = makeNodeList(lineXML)  
    listXSDTags = makeNodeList(lineXSD)         
    
    rootXML = makeTree(listXMLTags)    
    rootXSD = makeTree(listXSDTags)    
    
    newrootXSD = node.node("","","",{},[],0)
    augmentXSDTree(rootXSD,newrootXSD, 0)
    #printTree(newrootXSD)
    tree_validator.treeCompare(rootXML.childList[0],newrootXSD.childList[0])  
    
    print("Successfully matched!!")
    print("No errors found")
  def generate_children(self, current):
    """ Generate the child nodes of the current node. This will
        apply the transformations listed above to the blank
        tile in the order specified in self.moves. The
        legal ones will be kept and states that have not
        been explored will be returned.
    """

    children = []
    blank_tile_index = None

    # Find the blank tile we will use to create new states
    for index in range(len(current.state)):
      if current.state[index] == "0":
        blank_tile_index = index
    
    # Get legal operations -
    operations = [blank_tile_index + move for move in self.moves if
                  self.test_operator(blank_tile_index, move)]
      
    # Create the new states
    for transformation in operations:

      child_state = copy.deepcopy(current.state)
      child_state[transformation] = "0"
      child_state[blank_tile_index] = current.state[transformation]

      # If these have not been explored, create the node
      if tuple(child_state) not in self._explored:
        child = node(child_state)
        child.parent = current
        child.operator = transformation - blank_tile_index
        children.append(child)
 
    return children
Example #17
0
 def copy( self, other ):
     self.root = None
     self.root = node( self, None, leaf=other.root.isLeaf, op=other.root.operator, copy=True )
             
     if not self.root.isLeaf:
         self.copynode( self.root, other.root.children[0] )
         self.copynode( self.root, other.root.children[1] )
Example #18
0
def get_node_pdpb():
    name = pal_get_platform_name()
    info = {
            "Description": name + " PCIe Drive Plane Board",
    }

    return node(info)
Example #19
0
def main():
    #Declaring global variables                                                                                                                                                                                                                                                                                                                     
    global date
    global temp
    global nodes
    global f

    #Setting variables                                                                                                                                                                                                                                                                                                                              
    date = datetime.datetime.now()
    nodes = []
    f = open('data/time table', 'ar+')

    for line in f:
        nodes.append(node(str(line)))

    difference = calcdifference()

    print "The date is " + str(date) + " coffee was last brewed " + str(difference) + " hour(s) ago"

    temp = gettemp(difference)
    print "[Coffee is " + temp + "]"

    #Set up the GPIO                                                                                                                                                                                                                                                                                                                                
    GPIO.setmode(GPIO.BOARD)
    GPIO.setup(18, GPIO.OUT)

    print "Welcome to WOU Coffee! Your request is being processed..."

    findargs()

    #Close file                                                                                                                                                                                                                                                                                                                                     
    f.close()

    #Clean up GPIO                                                                                                                                                                                                                                                                                                                                  
    GPIO.cleanup()
Example #20
0
    def rootify(self,center_branch):

	# remember the old branch:
	self.root_branch = center_branch

	# create a new node
	center_name = center_branch.ends[0].name
	center_name += "-" + center_branch.ends[1].name
	center_node = node.node(center_name,self)
	self.root = center_node
	
	# give it children branches
	child1 = branch.branch(center_branch.length/2)
	child1.addNode(center_node)
	child1.addNode(center_branch.ends[0])
	child2 = branch.branch(center_branch.length/2)
	child2.addNode(center_node)
	child2.addNode(center_branch.ends[1])
	center_node.child_branches.append(child1)
	center_node.child_branches.append(child2)

	# erase the original branch from the child nodes branch_list
	for kids in center_branch.ends:
	    kids.branch_list.remove(center_branch)

	# impose a hierarchy from the root
	center_node.imposeHierarchy()
        self.labelSubtrees()
        self.Get_Subnodes()
        self.root.Fill_Node_Dict()
Example #21
0
def extract_title(url):
    page = urllib2.urlopen(url)
    if not page:
     print "Error down page" + url
    else:
        soup = BeautifulSoup(page, 'lxml')

        # get head title, this title is noisy
        head_title = soup.find('title').string

        # append h1 ~ h6 p a
        node_list = []
        for tag in tags:
            all_content = soup.find_all(tag)
            for content in all_content:
                if type(content) == None:
                    continue
                tmp = content.string
                if tmp == None:
                    continue
                else:
                    nod = node.node(tmp.rstrip('\n').lstrip('\n').rstrip(' ').lstrip(' '))
                    node_list.append(nod)

        for nod in node_list:
            nod.calculate_LCS(head_title)
            nod.calculate_pureness(head_title)
            nod.calculate_prefix_ratio()
        node_list.sort(key=lambda x: x.lcs_length, reverse=True)

        nod = node_list[0]
        if float(nod.pureness) > 0.5 and float(nod.prefix_ratio) == 0:
            return nod.lcs
        else:
            return head_title
Example #22
0
	def test_hasNeighbor(self):
		neighbors = []
		n = node("0xfaca", "00:00:00:00:00:00:00:00", "0xffff")
		
		nei_nwk = ["0x0001", "0x0002", "0x0003"]
		nei_in = [7, 5, 3]
		nei_out = [7, 5, 3]

		for i in range(0,3):
			neighbors.append({"nwkAdr" : nei_nwk[i], "in_cost" : int(nei_in[i]), "out_cost" : int(nei_out[i])})
	
		nei_nwk = ["0x0001", "0x0002", "0x0003", "0x0004"]
		nei_in = [1, 3, 5, 1]
		nei_out = [1, 3, 5, 3]

		for i in range(0,4):
			neighbors.append({"nwkAdr" : nei_nwk[i], "in_cost" : int(nei_in[i]), "out_cost" : int(nei_out[i])})
	
		n.setCurNeighbors(neighbors)
		n.addNpPreNeighbors()
		n.processPreNeighbors()

		assert n.hasNeighbor("0x0001", n.getHistoricalNeighbors()) == True
		assert n.hasNeighbor("0x0002", n.getHistoricalNeighbors()) == True
		assert n.hasNeighbor("0x0003", n.getHistoricalNeighbors()) == True
		assert n.hasNeighbor("0x0004", n.getHistoricalNeighbors()) == True
		assert n.hasNeighbor("0x0005", n.getHistoricalNeighbors()) == False
		assert n.hasNeighbor("0x0000", n.getHistoricalNeighbors()) == False
		assert n.hasNeighbor("0xFFFF", n.getHistoricalNeighbors()) == False
Example #23
0
def partition(n, value):
    head = node(n.data)
    tail = head
    if n != None:
        n = n.next_element
    else:
        return head
    while n is not None:
        if n.data >= value:
            tail.next_element = node(n.data)
            tail = tail.next_element
        else:
            temp = node(n.data)
            temp.next_element = head.next_element
            head.next_element = temp
        n = n.next_element
    return head
Example #24
0
        def doCrawl(self):
                initial_node = node(None, self.config.location, 1)
                self.links.append(initial_node)

                results = self.doScrape(initial_node)
                if results != "NULL":
                        self.send_result(results)

                while (self.links[0].get_currentDepth() < int(self.config.maxDepth)):
                        for child in self.links[0].get_children():
                                next_node = node(self.links[0].get_url(), child, self.links[0].get_currentDepth()+1)
                                self.links.append(next_node)
                                time.sleep(float(self.config.speed))
                                results = self.doScrape(next_node)
                                if results != "NULL":
                                        self.send_result(results)
                        dummy = self.links.pop(0)
Example #25
0
def get_node_api():

    name = pal_get_platform_name().decode()
    info = {
        "Description": name + " RESTful API Entry",
    }

    return node(info)
Example #26
0
def main():
    parser = argparse.ArgumentParser(description='Band Protocol Layer')
    parser.add_argument('instruction', help='Instruction sets')
    parser.add_argument('--debug', dest='debug', action='store_true')
    parser.add_argument('--key', help='Key to find value')
    args = parser.parse_args()

    if args.instruction == 'node':
        node(args.debug)
    elif args.instruction == 'init':
        init()
    elif args.instruction == 'clear':
        clear()
    elif args.instruction == 'info':
        info(args.key)
    else:
        raise Exception("This instruction is not supported")
Example #27
0
def p_for(t):
    r'''for : FOR '(' statements ';' condition ';' statements ')' '{' statements '}' '''
    if len(t) == 12:
        t[0] = node('[FOR]')
        t[0].add(t[3])
        t[0].add(t[5])
        t[0].add(t[7])
        t[0].add(t[10])
Example #28
0
def get_node_api():

    name = pal_get_platform_name()
    info = {
        "Description": name + " RESTful API Entry",
        }

    return node(info)
    def insertAtEnd(self, data):
        newnode = node(data)
        current = self.head

        while current.next != None:
            current = current.next

        current.next = newnode
def p_expression(t):
    '''expression : expression '+' term
                  | expression '-' term
                  | term
                  | LEN '(' factor ')' '''
    if len(t) == 4:
        t[0] = node('[EXPRESSION]')
        t[0].add(t[1])
        t[0].add(node(t[2]))
        t[0].add(t[3])
    elif len(t) == 2:
        t[0] = node('[EXPRESSION]')
        t[0].add(t[1])
    elif len(t) == 5:
        t[0] = node('[EXPRESSION]')
        t[0].add(node('[LEN]'))
        t[0].add(t[3])
Example #31
0
 def __init__(self, name, data):
     self.name = name
     self.root = None
     for anime in data:
         if self.root == None:
             self.root = node(anime["title"], anime["score"])
         else:
             self.insert(self.root, anime["title"], anime["score"])
Example #32
0
def initialize_nodes():
    """Initializes the nodes and their connections."""

    # Below is an example (P.3 in chapter 5 from Computer Networking - 
    # a top down approach by Kuruse & Ross).

    x = node('x')
    y = node('y')
    z = node('z')
    w = node('w')
    u = node('u')
    v = node('v')
    t = node('t')

    initial_nodes = [x, y, z, w, u, v, t]
    initial_nodes.sort(key=lambda x: x.name)

    connect(x, z, 8)
    connect(x, y, 6)
    connect(x, v, 3)
    connect(x, w, 6)

    connect(y, z, 12)
    connect(y, t, 7)
    connect(y, v, 8)

    connect(v, w, 4)
    connect(v, u, 3)
    connect(v, t, 4)

    connect(u, w, 3)
    connect(u, t, 2)
    return initial_nodes
Example #33
0
    def __init__(self, inputs = [], outputs = [], hidden = [], size = 1, numin = 1, numout = 1, mutaterate = .5, depth = 1):
        self.inputs = inputs
        self.outputs = outputs
        self.size = size
        self.numin = numin
        self.numout = numout
        self.mutaterate = mutaterate
        self.hidden = hidden
        self.depth = depth

        if self.inputs == []:
            i = 0
            while(i < numin):
                n = node.node()
                n.inputNodes = []
                n.outputNodes = []
                n.inputs = []
                self.inputs.append(n)
                n.isInput = True
                i += 1

        if self.outputs == []:
            i = 0
            while(i < numout):
                n = node.node()
                n.inputNodes = []
                n.outputNodes = []
                n.inputs = []
                self.outputs.append(n)
                n.isOutput = True
                i += 1

        if self.hidden == []:
            i = 0
            while(i < size):
                n = node.node()
                n.inputNodes = []
                n.outputNodes = []
                n.inputs = []
                self.hidden.append(n)
                i += 1

        if depth > size:
            print('Warning:  Depth greater than the number of total nodes, reducing depth to accomodate the number of nodes.')
            depth = size
    def random_state(self):
        a = []
        for i in range(0, self.number):
            r = random.randint(0, 1)
            a.append(r)

        y = node(a, None, 1)

        return y
    def insertAtBeginning(self, data):
        newnode = node(data)
        newnode.data = data

        if self.length() == 0:
            self.head = newnode
        else:
            newnode.next = self.head
            self.head = newnode
Example #36
0
    def add_from_begin(self, data):
        self.count = self.count + 1
        new_node = node.node(data)

        if self.head == None:
            self.head = new_node
        else:
            new_node.next = self.head
            self.head = new_node
Example #37
0
def create_grid(n, m):
    grid =[]
    for i in range(n):
        pygame.event.pump()
        row = []
        for j in range(m):
            row.append(node(i,j))
        grid.append(row)
    return grid
Example #38
0
def a_algorithm():
    ''' Search algorithm '''
    step = 0

    opened = []
    closed = []
    nodes = []

    new_node = node()
    new_node.state = START
    new_node.parent = None
    new_node.operator = None
    new_node.cost = 0
    new_node.heuristic = heuristic(START)
    nodes.append(new_node)

    opened.append(0)

    while True:
        print("[{}{}. lépés] Keresés folyamatban...".format(
            (10 - len(str(step))) * '-', step),
              end='\r')

        if len(opened) == 0:
            break

        #selected = choose_node( nodes, opened )
        selected = opened.pop(0)
        '''if step==1000:
            write_nodes( opened, closed, nodes, step, selected )
            exit(0)'''
        step += 1

        #print( nodes[ selected ].get_state() )

        if is_goal(nodes[selected].state, GOAL_ROWS):
            break

        extend(selected, opened, closed, nodes)

    print('')

    if len(opened) != 0:
        solution = get_solution(nodes, selected, ['op', 'he', 'co'])

        with open('solution.txt', 'w') as f:
            for i in range(len(solution)):
                f.write('{i:2d}. {node}'.format(i=i, node=solution[i]))

        print("Megoldás: solution.txt")
    else:
        solution = get_solution(nodes, selected, ['op', 'he', 'co'])

        with open('solution.txt', 'w') as f:
            for i in range(len(solution)):
                f.write('{i:2d}. {node}'.format(i=i, node=solution[i]))
        print("Nincs megoldás")
Example #39
0
    def create_node(self, _id=None, label=""):
        '''
        Convenience routine for quickly creating and adding a node in one step.
        '''

        n = node(_id, label)
        self.add_node(n)

        return n
Example #40
0
    def create_node (self, _id=None, label=""):
        '''
        Convenience routine for quickly creating and adding a node in one step.
        '''

        n = node(_id, label)
        self.add_node(n)

        return n
def insert_at_head(list, value):
    temp_node = node(value)
    if list.is_empty():
        list.header = temp_node
        return
    temp_node.next_element = list.header
    list.header.prev_element = temp_node
    list.header = temp_node
    return
Example #42
0
    def doCrawl(self):
        initial_node = node(None, self.config.location, 1)
        self.links.append(initial_node)

        results = self.doScrape(initial_node)
        if results != "NULL":
            self.send_result(results)

        while (self.links[0].get_currentDepth() < int(self.config.maxDepth)):
            for child in self.links[0].get_children():
                next_node = node(self.links[0].get_url(), child,
                                 self.links[0].get_currentDepth() + 1)
                self.links.append(next_node)
                time.sleep(float(self.config.speed))
                results = self.doScrape(next_node)
                if results != "NULL":
                    self.send_result(results)
            dummy = self.links.pop(0)
Example #43
0
    def initialstate(self):

        a=[]
        while len(a)<self.number_of_cities:
            l=(random.randint(0,self.number_of_cities-1))
            if(l not in a):
                a.append(l)
        y=node(a,None,1)
        return y
Example #44
0
File: tree.py Project: cbonnett/HBC
 def __init__(self,rawData,diffFunction):
     self.rawData = rawData
     self.diffFunction = diffFunction
     self.iterNodes={}
     self.nodes=[]
     self.activeNodes=[]
     self.node1=[node() for i,d in enumerate(rawData)]
     self.alpha =0.1
     print self.node1
Example #45
0
 def createGrid(self):
     for i in range(0, self.gridSizeX):
         for j in range(0, self.gridSizeY):
             walkable = 1
             worldPosition = [
                 i * self.nodeRadius * 2 + self.nodeRadius,
                 j * self.nodeRadius * 2 + self.nodeRadius
             ]
             self.gridArr[i][j] = node.node(walkable, worldPosition, i, j)
Example #46
0
	def test_setSN(self):
		n = node("0xfaca", "00:00:00:00:00:00:00:00", "0xffff")
		with pytest.raises(ValueError):
			n.setSN("230432")
			n.setSN("ABCFF34454545")
			n.setSN("20145D34454545")

		n.setSN("2014030000855")
		assert 2014030000855 == n.getSN()
Example #47
0
def p_statement(t):
    ''' statement : assignment
                  | operation
                  | print
                  | if
                  | while'''
    if len(t) == 2:
        t[0] = node(['STATEMENT'])
        t[0].add(t[1])
Example #48
0
    def result(self,node1,action):

        temp=[]
        for i in range(0,self.number_of_cities):
            temp.append(node1.state[i])
        temp[int(action[0])]=node1.state[int(action[1])]
        temp[action[1]]=node1.state[action[0]]
        y=node(temp,node1,1)
        return y
Example #49
0
	def __init__(self, modelPath = "model.yml"):
		with open(modelPath) as modelFile:
			self.modelData = yaml.safe_load(modelFile) or {}

		self.rootNode = node.node(game.gameState(), self)
		self.rootNode.isRoot = True
		self.nodePath = []

		return
Example #50
0
    def __init__(self, init_model=None):
        # 设置棋盘和游戏的参数
        
        
        self.node1 = node({'cpu':20, 'memory':20, 'gpu':0})
        self.node2 = node({'cpu':20, 'memory':20, 'gpu':0})
        self.node3 = node({'cpu':50, 'memory':50, 'gpu':50})
        self.node_dict = {'node1':self.node1, 'node2':self.node2, 'node3':self.node3}
        self.data_name = 'ideal'
        self.c_puct_list = [3]
        self.n_job_thread_list = [4]
        self.probability_1_list = [0]
        self.probability_2_list = [1]
        '''
        self.node1 = node({'cpu':30, 'memory':30, 'gpu':30, 'fpga':0})
        self.node2 = node({'cpu':30, 'memory':30, 'gpu':0, 'fpga':30})
        self.node3 = node({'cpu':50, 'memory':50, 'gpu':50, 'fpga':50})
        self.node4 = node({'cpu':30, 'memory':30, 'gpu':0, 'fpga':0})
        self.node5 = node({'cpu':30, 'memory':30, 'gpu':0, 'fpga':0})
        #按比例应该是越大越明显
        self.node_dict = {'node1':self.node1, 'node2':self.node2, 'node3':self.node3, 'node4':self.node4, 'node5':self.node5}
        self.data_name = 'fpga_gpu'
        self.c_puct_list = [0.03,0.3,3]
        self.n_job_thread_list = [0,5]
        self.probability_1_list = [0,0.03,0.3]
        self.probability_2_list = [0.3,0.6,0.9]
        '''

        #self.weight = {'cpu':0.3, 'memory':0.2, 'gpu':0.5}
        self.weight = None
        self.state = State(self.node_dict)
        self.game = Game(self.node_dict, self.weight)
        # 设置训练参数
        self.n_playout = 1000  # 每下一步棋,模拟的步骤数
        self.c_puct = 1 # exploitation和exploration之间的折中系数
        self.game_batch_num = 3
        self.n_job_thread = 6 #0
        self.probability_1 = 0 #0
        self.probability_2 = 0.2 #0.2
        #self.path = r'D:\科研\论文\High effient resource scheduling for cloud based on modified MCTS\programing\parameter_check_on_have_fpga.pkl'
        # AI Player,设置is_selfplay=1 自我对弈,因为是在进行训练
        self.mcts_player = MCTSPlayer(c_puct=self.c_puct,
                                      n_playout=self.n_playout,
                                      is_selfplay=1)          
Example #51
0
def on_input(_input):
    if (_input == 'exit'):
        loop.stop()
        exit()
    command = _input.split(' ', 1)
    if (len(command) < 2):
        return
    if command[0] == 'roll':
        #roller
        statusLine.set_text(_tools.roll(command[1]))
    elif command[0] == 'mod':
        #calc mod
        statusLine.set_text(_tools.mod(command[1]))
    elif command[0].startswith('p'):
        #print
        currentNode = _list.findByName(command[1])
        if currentNode != 'not found':
            box, height, width = currentNode.getdisplay()
            bg.open_box(urwid.Filler(box), command[1], height, width)
        else:
            statusLine.set_text(command[1] + ' does not exist.')
    elif command[0].startswith('a'):
        #add
        test = _list.findByName(command[1])
        if test != 'not found':
            statusLine.set_text(command[1] + ' already exists.')
        else:
            params = command[1].split('|')
            _list.add(node(params[0], params[1]))
    elif command[0].startswith('s'):
        #set
        params = command[1].split('|')
        currentNode = _list.findByName(params[0])
        if currentNode != 'not found':
            currentNode.set(params[1], params[2])
        else:
            statusLine.set_text(command[1] + ' does not exist.')
    elif command[0].startswith('d'):
        _file.write(_list, command[1])
    elif command[0].startswith('l'):
        newNodes = _file.read(command[1], statusLine)
        statusLine.set_text(str(len(newNodes)))
        for n in newNodes:
            statusLine.set_text(str(n))
            _list.add(n)
    elif command[0].startswith('q'):
        statusLine.set_text(str(len(_list.getlist())))
        for n in _list.getlist():
            bg.open_box(urwid.SolidFill(u'#'), n.name)
    elif command[0].startswith('!'):
        result = ''
        try:
            result = eval(command[1])
        except:
            result = 'an error occurred'
        statusLine.set_text(str(result))
Example #52
0
def build_huffman_tree(aDict):
    """
    This method is used to create the huffman tree using the node class and the the priority queue class.
    :param aDict:
    :return:
    """
    queue1 = pq()
    for key, value in aDict.items():
        queue1.insert_node(node(key, value))
    # print(queue1)
    while (queue1.get_size() > 1):
        left = queue1.extract_min()
        right = queue1.extract_min()
        root = node("NON_CHAR", left.get_value() + right.get_value())
        root.set_left(left)
        root.set_right(right)
        queue1.insert_node(root)
    huffman_root = queue1.extract_min()
    return huffman_root
Example #53
0
 def add_gate(self, cur_node, gate):
     self.add_node(node(gate.get_name(), gate.get_matrix()))
     added_node = None
     for v in self.nodes:
         if v.get_name() == cur_node.get_name():
             added_node = v
             break
     for (v, idx) in zip(self.nodes, range(len(self.nodes))):
         if v.get_name() == gate.get_name():
             self.nodes[idx].add_gate(added_node)
Example #54
0
File: 9_8.py Project: tj---/ba1
def main():
	lines = [line.strip() for line in open(sys.argv[1])]
	Text = lines[0]
	SuffixArray = [int(numeric_string) for numeric_string in lines[1].split(", ")]
	LCP = [int(numeric_string) for numeric_string in lines[2].split(", ")]
	length = len(SuffixArray)

	first = node.node(Text[SuffixArray[0]:], LCP[1])
	temp = first
	for index in xrange(1, length - 1):
		suffix = Text[SuffixArray[index]:]
		new_node = node.node(suffix, LCP[index + 1])
		temp.next = new_node
		temp = new_node

	temp.next = node.node(Text[SuffixArray[length - 1]:], -1)

	# topMost row is ready

	while True:
		max_node = find_max(first)
		diff_len = max_node.next_diff
		size = diff_len
		if size <= 0:
			break

		node1 = node.node(max_node.data[size:], 0)

		max_node.data = max_node.data[:size]
		add_to_list(max_node, node1)
		# Try to put everyone closeby that is at the same level together in a group
		while(size == diff_len):
			next_node = max_node.next
			diff_len = next_node.next_diff

			node2 = node.node(next_node.data[size:], 0)
			node2.down = next_node.down
			add_to_list(max_node, node2)

			max_node.next_diff = next_node.next_diff
			max_node.next = next_node.next

	print_formatted(first)
Example #55
0
 def addconditions(self, filename):
     fi = open(filename, 'r')
     buf = fi.readlines()
     for line in buf:
         i = line.split(',')
         x = int(i[0], 10)
         y = int(i[1], 10)
         v = int(i[2], 10)
         n = node(x=x, y=y, value=v, iscondition=True)
         self.table[x][y] = n
Example #56
0
 def run(ID):
     sys.stdout.write("run started\n")
     sys.stdout.flush()
     socket_obj = init_server(ID)
     n = node.node(ID, 0, N)
     # n.init_keys(N)
     n.init_replica_map(socket_obj)
     n.server_loop()
     sys.stdout.write("run exited\n")
     sys.stdout.flush()
def create_node(id,parent,cost,open,close):
    new_node = node.node()
    new_node.map_key = create_key(id)
    new_node.cost = copy.deepcopy(cost)
    new_node.is_open = copy.deepcopy( open )
    new_node.is_closed = close
    new_node.id = copy.deepcopy ([id[0], id[1]])
    if(parent!=None):
        new_node.parent_id = copy.deepcopy([parent[0],parent[1]])
    return new_node
Example #58
0
def p_list(t):
    ''' list : '*'
             | NAME
             | NAME DOT NAME 
             | list COMMA list
             | list AND NAME
             | list OR NAME        
             | agg '''
    if len(t)==2:
        t[0]=node('[FIELD]')
        t[0].add(node(t[1]))
    elif t[2]==',':
        t[0]=node('[FIELDS]')
        t[0].add(t[1])
        t[0].add(t[3])
    else:
        temp='%s.%s'%(t[1],t[3])
        t[0]=node('[FIELD]')
        t[0].add(node(temp))
Example #59
0
def p_subsection(t):
    r'''subsection : SUBSECTION LB TEXT RB TEXT
    '''
    if len(t)==6:       #可以匹配
        t[0]=node('[SUBSECTION](%s)' %t[3])
        # print(t[3])
        # print("===============")
        t[0].add(node(t[5]))
        # print(t[5])
        # print("+++++++++++++++++++++++++++++")
    elif(len(t) == 8):
        t[0] = node('[SUBSECTION](%s)' % t[3])
        print(t[3])
        #print("===============")
        t[0].add(node(t[5]))
        t[0].add(t[6])
        #print(t[5])
        #print("***************************")
        t[0].add(node(t[7]))
def p_operation(t):
    '''operation : VARIABLE '+' VARIABLE
                 | VARIABLE '-' VARIABLE
                 | VARIABLE '-' NUMBER
                 | VARIABLE '+' NUMBER
                 | '[' commaexpression ']'
                 | LEN '(' VARIABLE ')'
                 | '(' VARIABLE '+' VARIABLE ')' GDIV NUMBER '''
    if len(t)==4 and t.slice[2].type!='commaexpression':
        t[0]=simple_node(t,'[OPERATION]')
    elif len(t)==4 and t.slice[2].type=='commaexpression':
        t[0] = node('[OPERATION]')
        t[0].add(node(t[1]))
        t[0].add(t[2])
        t[0].add(node(t[3]))
    elif len(t) == 5:
        t[0]=simple_node(t,'[OPERATION]')
    elif len(t) == 8:
        t[0]=simple_node(t,'[OPERATION]')