def add_node(self, node: Node): label_ids = [self.get_node_label_id(node, _id) for _id in node.ids] matches = [self.nodes[x] for x in label_ids if x in self.nodes] for match in matches: node.merge(match) label_ids = [self.get_node_label_id(node, _id) for _id in node.ids] for x in label_ids: self.nodes[x] = node
def parse_read_stmt(cls): try: node = Node(Node.READ_STMT) cls.read_token(Token.READ) node.set_left(cls.identifier()) cls.read_token(Token.SEMI) return node except ErrorParse(cls.get_next_token().get_line_num(), cls.get_next_token().get_type()) as e: print e.content
def parse_write_stmt(cls): try: node = Node(Node.WRITE_STMT) cls.read_token(Token.WRITE) node.set_left(cls.parse_exp()) cls.read_token(Token.SEMI) return node except ErrorParse(cls.get_next_token().get_line_num(), cls.get_next_token().get_type()) as e: print e.content
def init_network(self, network_address,loc): Node.__init__(self) self.loc = loc self.network_address = network_address self.neighbor_map = {} self.socket = None self.ip = IP self.listener = Thread(target=self.listen, name = "listen") self.heartbeat_generator = Thread(target=self.send_heartbeat, name= "send_heartbeat")
def parse_assign_stmt(cls): try: node = Node(Node.ASSIGN_STMT) node.set_left(cls.identifier()) cls.read_token(Token.ASSIGN) node.set_middle(cls.parse_exp()) cls.read_token(Token.SEMI) return node except ErrorParse(cls.get_next_token().get_line_num(), cls.get_next_token().get_type()) as e: print e.content
def parse_while_stmt(cls): try: node = Node(Node.WHILE_STMT) cls.read_token(Token.WHILE) cls.read_token(Token.LPARENT) node.set_left(cls.parse_exp()) cls.read_token(Token.RPARENT) node.set_middle(cls.switch_stmt()) return node except ErrorParse(cls.get_next_token().get_line_num(), cls.get_next_token().get_type()) as e: print e.content
def parse_logic_op(cls): try: if cls.iterator.has_next(): cls.currentToken = cls.iterator.next() current_token_type = cls.currentToken.get_type() if current_token_type in [Token.GT, Token.GET, Token.LT, Token.LET, Token.EQ, Token.NEQ]: node = Node(Node.OP) node.set_data_type(current_token_type) return node ErrorParse(cls.get_next_token().get_line_num(), "logical operation!") except ErrorParse as e: print e.content
def parse_add_minus_op(cls): try: if cls.iterator.has_next(): cls.currentToken = cls.iterator.next() current_token_type = cls.currentToken.get_type() if current_token_type in [Token.PLUS, Token.MINUS]: node = Node(Node.OP) node.set_data_type(current_token_type) return node raise ErrorParse(cls.get_next_token().get_line_num(), "additive operation") except ErrorParse as e: print e.content
def parse_mul_div_op(cls): try: if cls.iterator.has_next(): cls.currentToken = cls.iterator.next() current_token_type = cls.currentToken.get_type() if current_token_type in [Token.MUL, Token.DIV]: node = Node(Node.OP) node.set_data_type(current_token_type) return node raise ErrorParse(cls.get_next_token().get_line_num(), "multiple operation") except ErrorParse as e: print e.content
def parse_block_stmt(cls): try: node = Node(Node.NULL) header = node cls.read_token(Token.LBRACE) while cls.get_next_token().get_type() != Token.RBRACE: temp = cls.switch_stmt() node.set_next(temp) node = temp cls.read_token(Token.RBRACE) return header except ErrorParse(cls.get_next_token().get_line_num(), cls.get_next_token().get_type()) as e: print e.content
def parse_literal(cls): try: if cls.iterator.has_next(): cls.currentToken = cls.iterator.next() current_token_type = cls.currentToken.get_type() node = Node(Node.LITERAL) node.set_data_type(current_token_type) node.set_value(cls.currentToken.get_value()) if current_token_type in [Token.LITERAL_INT, Token.LITERAL_DOU]: return node raise ErrorParse(cls.get_next_token().get_line_num(), "literal") except ErrorParse as e: print e.content
def parse_term_exp(cls): try: node = Node(Node.EXP) node.set_data_type(Token.TERM_EXP) left_node = cls.parse_factor() if cls.get_next_token().get_type() in [Token.MUL, Token.DIV]: node.set_left(left_node) node.set_middle(cls.parse_mul_div_op()) node.set_right(cls.parse_term_exp()) return node return left_node except ErrorParse(cls.get_next_token().get_line_num(), cls.get_next_token().get_type()) as e: print e.content
def parse_exp(cls): try: node = Node(Node.EXP) node.set_data_type(Token.LOGIC_EXP) left_node = cls.parse_multi_term_exp() if cls.get_next_token().get_type() in [Token.GT, Token.GET, Token.LT, Token.LET, Token.EQ, Token.NEQ]: node.set_left(left_node) node.set_middle(cls.parse_logic_op()) node.set_right(cls.parse_multi_term_exp()) return node return left_node except ErrorParse(cls.get_next_token().get_line_num(), cls.get_next_token().get_type()) as e: print e.content
def __init__(self, possibleValues, parents, CPTs): """ parents - dictionary mapping each variable to its direct parents CPTs - list of dictionary mapping the current variable name to another dictionary mapping the dependencies value to a prob. e.g. 'Result' : { 'Result = good | Intelligence = high, hasHelp = True': 0.5, ... } possibleValues - dictionary of variables mapped to their possible values """ self.possibleValues = possibleValues # Build up the adjacency list self.adjList = [] self.nodes = dict() self.nodeToIndex = dict() self.indexToNode = dict() for index, cpt in enumerate(CPTs): key = list(cpt.keys())[0] # adjList[index] contains the nodes that this node maps to self.adjList.append(list()) self.nodeToIndex[key] = index self.indexToNode[index] = key currVals = dict() # Map the variable to an index currVals[key] = possibleValues[key] parent = parents[key] parentVals = dict() for p in parent: parentVals[p] = possibleValues[p] newNode = Node(index, currVals, parentVals) newNode.fillTable(cpt[key]) self.nodes[key] = newNode # Fill up the adjacency list for index, cpt in enumerate(CPTs): varName = list(cpt.keys())[0] parent = parents[varName] for p in parent: pIndex = self.nodeToIndex[p] self.adjList[pIndex].append(index)
def identifier(cls): try: node = Node(Node.VAR) next_token_type = cls.get_next_token().get_type() if next_token_type == Token.ID: node.set_value(cls.iterator.next().get_value()) else: raise ErrorParse(cls.get_next_token().get_line_num(), "identifier") if cls.get_next_token().get_type() == Token.LBRACKET: cls.read_token(Token.LBRACKET) node.set_left(cls.parse_exp()) cls.read_token(Token.RBRACKET) return node except ErrorParse as e: print e.content
def add_node(self, name, player=None, power=1): assert self.get_node_from_name( name) is None, "Attempting to add second node with name {}".format( name) node = Node(name, player=player, power=power) self._nodes.append(node) return node
def test_add_unique_pattern(): # test adding first unique pattern node = Node() pattern_1 = {(0, 1), (0, 2)} assert_equal(node.add_unique_pattern(pattern_1), True) expected_memory = [pattern_1] assert_equal(node.memory, expected_memory) # test adding second unique pattern pattern_2 = {(0, 2), (0, 3)} assert_equal(node.add_unique_pattern(pattern_2), True) expected_memory_2 = [pattern_1, pattern_2] assert_equal(node.memory, expected_memory_2) # test adding same pattern pattern_3 = {(0, 1), (0, 2)} assert_equal(node.add_unique_pattern(pattern_3), False) assert_equal(node.memory, expected_memory_2)
def exist_in(self, graph, from_systematic_review=None): query = 'select * from PS' if from_systematic_review: query += " where '%s' not in in()" % from_systematic_review.get_id() results_odb = graph.execute(query) for orientdb_object in results_odb: primary_study = Node.new_by_orientdb_object(orientdb_object) if self.equal_to(primary_study): return primary_study return False
def readNodes(nodefile, network): """ This function reads NODE from Nodefile in network :param nodefile: path :param network: :return: Node """ f = csv.reader(nodefile) for row in f: (id, type, x, y) = (row[0], row[1], row[3], row[4]) Node(id, type, x, y, network)
def makeNodes(df): """ This function creates the nodes from rows on dataset""" nodes = [] rows = df.select(["state", "modeldate", "winstate_inc", "winstate_chal"]) counter = 0 for row in rows.collect(): row = row.asDict() row['var'] = "poll{}".format(counter) nodes.append(Node(**row)) counter += 1 return nodes[:300]
def __init__(self, warehouse: str = "collector"): """ 数据采集任务 """ self._config = Config() self._logger = getLogger() self._mongo_pool = MongoPool()[warehouse] self._rabbitmq_pool = RabbitmqPool() self._task: Task = None self._nodes = Node()
class GenerateTest(unittest.TestCase): matrix = [ [1, 2, 3], [8, 0, 4], [7, 6, 5]] matrix_copy = [ [1, 2, 3], [8, 0, 4], [7, 6, 5]] another_matrix = [ [1, 2, 3], [8, 4, 0], [7, 6, 5]] node = None def setUp(self): self.node = Node(self.matrix) def test_new_node(self): print self.node def test_add_node(self): another_node = Node(self.another_matrix) self.node.add(another_node) self.node.add(another_node) for node in self.node.children: print node.parent def test_null_parent(self): self.assertEquals(self.node.parent,None) def test_equals(self): another_node = Node(self.matrix_copy) print another_node == self.node self.assertEquals(another_node, self.node) def test_node_in_list(self): list = [self.node] another_node = Node(self.matrix_copy) print (another_node in list)
def parse_if_stmt(cls): try: node = Node(Node.IF_STMT) cls.read_token(Token.IF) cls.read_token(Token.LPARENT) node.set_left(cls.parse_exp()) cls.read_token(Token.RPARENT) node.set_middle(cls.switch_stmt()) if cls.iterator.has_next() and cls.get_next_token().get_type() == Token.ELSE: cls.read_token(Token.ELSE) node.set_right(cls.switch_stmt()) return node except ErrorParse(cls.get_next_token().get_line_num(), cls.get_next_token().get_type()) as e: print e.content
def copy(self): nodes = {} loop = self.head prev_node = None while loop: new_node = Node(loop.data) nodes[loop] = new_node if prev_node: prev_node.next = new_node prev_node = new_node loop = loop.next for node in list(nodes.keys()): nodes.get(node).random = nodes.get(node.random) return LinkedList(nodes.get(self.head))
def test_copy(self): nodes = [] for i in range(SIZE): nodes.append(Node(i)) if i: nodes[i - 1].next = nodes[i] for i in range(SIZE): number = randint(0, SIZE) if number < SIZE: nodes[i].random = nodes[number] if nodes: linked_list = LinkedList(nodes[0]) linked_list_copy = linked_list.copy() loop = linked_list.head loop_copy = linked_list_copy.head while loop: self.assertEqual(loop.data, loop_copy.data) if loop.next: self.assertEqual(loop.next.data, loop_copy.next.data) if loop.random: self.assertEqual(loop.random.data, loop_copy.random.data) loop = loop.next loop_copy = loop_copy.next print('----------------------------------------') print('Original') print('----------------------------------------') print(linked_list) print('----------------------------------------') print('Copia') print('----------------------------------------') print(linked_list_copy)
from model.util.activation_fun import sigmoid from model.node import Node import numpy as np inputs = [1, 2, 3, 4, 5] len = len(inputs) node = Node(sigmoid) node.rand_weights(len) print(node.calc_net(inputs))
def parse_factor(cls): try: if cls.iterator.has_next(): node = Node(Node.FACTOR) next_token_type = cls.get_next_token().get_type() if next_token_type in [Token.LITERAL_INT, Token.LITERAL_DOU]: node.set_left(cls.parse_literal()) elif next_token_type == Token.LPARENT: cls.read_token(Token.LBRACKET) node.set_middle(cls.parse_exp()) cls.read_token(Token.RPARENT) elif next_token_type == Token.MINUS: node.set_data_type(Token.MINUS) cls.currentToken = cls.iterator.next() node.set_left(cls.parse_term_exp()) elif next_token_type == Token.PLUS: cls.currentToken == cls.iterator.next() node.set_left(cls.parse_term_exp()) elif next_token_type == Token.ID: return cls.identifier() return node raise ErrorParse(cls.get_next_token().get_line_num(), "factor") except ErrorParse as e: print e.content
class TestState(unittest.TestCase): rows = 2 cols = 2 board1 = Board([Node(0), Node(1), Node(2), Node(3)], rows, cols) board2 = Board([Node(1), Node(0), Node(2), Node(3)], rows, cols) board3 = Board([Node(1), Node(3), Node(0), Node(2)], rows, cols) board33 = Board([ Node(0), Node(2), Node(3), Node(4), Node(6), Node(5), Node(7), Node(8), Node(1) ], 3, 3) state1 = State(board1) state2 = State(board2) state3 = State(board3) state33 = State(board33) def test_board_only(self): # given start_state = self.state2 # when solved_state = IDFS().solve(start_state, h0) # then self.assertListEqual(self.board1.content, solved_state.current_board.content) def test_whole_state(self): # given start_state = self.state2 target_state = State(self.board1, [MoveLeft()], [self.board2]) # when solved_state = IDFS().solve(start_state, h0) # then self.assertEqual(target_state, solved_state) def test_longer(self): start_state = self.state3 # when solved_state = IDFS().solve(start_state, h0) # then self.assertEqual(sorted(start_state.current_board.content), solved_state.current_board.content) def test_3x3(self): start_state = self.state33 # when solved_state = IDFS().solve(start_state, h0) # then self.assertEqual(sorted(start_state.current_board.content), solved_state.current_board.content)
def osm_to_csv(osmfile): global local path = os.path.abspath(os.path.dirname(__file__)) + f"/data/{osmfile}" context = etree.iterparse(path, events=('end', ), tag=['node', 'way'], encoding="utf8") # Tags que excluem node's representando ruas, semáforos e outros elementos de tráfego tag_to_ignore = { "maxspeed", "place", "waterway", "noexit", "natural", "barrier", "railway", "crossing", "highway", "traffic_calming", "direction" } header = [ "_id", '_lat', '_lon', "_name", "_street", "_number", "_city", "_suburb", "_state", "_country", "_postcode", "_landuse", "_amenity", "_phone", "_email", '_building' ] with open('data/points_of_interest.csv', 'a', encoding='utf-8', newline='') as csv_file: writer = csv.DictWriter(csv_file, delimiter=';', fieldnames=header) writer.writeheader() for _, elem in context: if elem.tag == 'node': local = Node(elem.attrib.get('lat'), elem.attrib.get('lon')) filter_tags = tag_to_ignore else: local = Local() filter_tags = {"addr:street", "addr:housenumber"} # minimal_tags if is_point_of_interest(elem, filter_tags): local._id = elem.attrib.get("id") for tag in elem.iter("tag"): if tag.attrib['k'] == "name": local.name = tag.attrib.get('v') if tag.attrib['k'] == "addr:street": local.street = tag.attrib.get('v') if tag.attrib['k'] == "addr:housenumber": local._number = tag.attrib.get('v') if tag.attrib['k'] == "addr:city": local.city = tag.attrib.get('v') if tag.attrib['k'] == "addr:suburb": local.suburb = tag.attrib.get('v') if tag.attrib['k'] == "addr:state": local.state = tag.attrib.get('v') # if tag.attrib['k'] == "addr:country": local.country = tag.attrib['v'] local.country = "BR" if tag.attrib['k'] == "addr:postcode": local.postcode = tag.attrib['v'] if tag.attrib['k'] == "building" and tag.attrib['v'] != "no": local._building = True if tag.attrib['k'] == "landuse": local.landuse = tag.attrib.get('v') if tag.attrib['k'] == "amenity": local.amenity = tag.attrib.get('v') if tag.attrib['k'] == "phone" or tag.attrib[ 'k'] == "contact:phone": local.phone = tag.attrib.get('v') if tag.attrib['k'] == "email": local.email = tag.attrib.get('v') with open('data/points_of_interest.csv', 'a', encoding='UTF-8', newline='') as csv_file: writer = csv.DictWriter(csv_file, delimiter=';', fieldnames=header) d = local.to_row() writer.writerow(d) print(d['_id']) local.clean() elem.clear()
class TestState(unittest.TestCase): rows = 4 cols = 4 board1 = Board( [ Node(0), Node(1), Node(2), Node(3), Node(4), Node(5), Node(6), Node(7), Node(8), Node(9), Node(10), Node(11), Node(12), Node(13), Node(14), Node(15), ], rows, cols ) board2 = Board( [ Node(1), Node(2), Node(6), Node(3), Node(5), Node(0), Node(10), Node(7), Node(4), Node(8), Node(9), Node(15), Node(12), Node(13), Node(11), Node(14), ], rows, cols ) board3 = Board( [Node(3), Node(1), Node(2), Node(4), Node(5), Node(8), Node(6), Node(0), Node(7), ], 3, 3 ) state1 = State(board1) state2 = State(board2) state3 = State(board3) def test_board_only_h0(self): # given start_state = self.state2 # when solved_state = AStar().solve(start_state, h0) # then self.assertEqual(self.state1.current_board.content, solved_state.current_board.content) def test_board_only_h1(self): # given start_state = self.state2 print(start_state.is_solvable()) # when solved_state = AStar().solve(start_state, h1) # then self.assertEqual(self.state1.current_board.content, solved_state.current_board.content)
def setUp(self): self.node = Node(self.matrix)
def parse_declare_stmt(cls): try: node = Node(Node.DECLARE_STMT) var_node = Node(Node.VAR) if cls.get_next_token().get_type() in [Token.INT, Token.DOUBLE]: current_token = cls.iterator.next() data_type = Token.INT if current_token.get_type() == Token.INT else Token.DOUBLE var_node.set_data_type(data_type) else: next_token = cls.get_next_token() raise ErrorParse(next_token.get_line_num(), next_token.get_type()) if cls.get_next_token().get_type() == Token.ID: current_token = cls.iterator.next() var_node.set_value(current_token.get_value()) else: next_token = cls.get_next_token() raise ErrorParse(next_token.get_line_num(), next_token.get_type()) if cls.get_next_token().get_type() == Token.ASSIGN: cls.read_token(Token.ASSIGN) node.set_middle(cls.parse_exp()) elif cls.get_next_token().get_type() == Token.LBRACKET: cls.read_token(Token.LBRACKET) var_node.set_left(cls.parse_exp()) cls.read_token(Token.RBRACKET) cls.read_token(Token.SEMI) node.set_left(var_node) return node except ErrorParse(cls.get_next_token().get_line_num(), cls.get_next_token().get_type()) as e: print e.content
def __init__(self, length, name): self.length = length self.nodes = [[Node() for i in range(0, length)] for j in range(0, length)] self.name = name
def parse_multi_term_exp(cls): try: node = Node(Node.EXP) node.set_data_type(Token.MULTI_TERM_EXP) left_node = cls.parse_term_exp() next_token_type = cls.get_next_token().get_type() if next_token_type == Token.PLUS: node.set_left(left_node) node.set_middle(cls.parse_add_minus_op()) node.set_right(cls.parse_multi_term_exp()) elif next_token_type == Token.MINUS: node.set_left(left_node) node.set_middle(Node(Node.OP, m_data_type=Token.PLUS)) node.set_right(cls.parse_multi_term_exp()) else: return left_node return node except ErrorParse(cls.get_next_token().get_line_num(), cls.get_next_token().get_type()) as e: print e.content
class TestState(unittest.TestCase): rows = 2 cols = 2 board1 = Board([Node(2), Node(1), Node(0), Node(3)], rows, cols) board2 = Board([Node(2), Node(1), Node(3), Node(0)], rows, cols) board3 = Board([ Node(1), Node(2), Node(5), Node(3), Node(4), Node(8), Node(6), Node(7), Node(0) ], 3, 3) board4 = Board([ Node(0), Node(2), Node(1), Node(3), Node(4), Node(5), Node(6), Node(7), Node(8) ], 3, 3) def test_solvable(self): # given initial_state = State(self.board1) # when solvability = initial_state.is_solvable() # then self.assertEqual(solvability, True) def test_unsolvable(self): # given initial_state = State(self.board2) # when solvability = initial_state.is_solvable() # then self.assertEqual(solvability, False) def test_solvable_3x3(self): # given initial_state = State(self.board3) # when solvability = initial_state.is_solvable() # then self.assertEqual(solvability, True) def test_unsolvable_3x3(self): # given initial_state = State(self.board4) # when solvability = initial_state.is_solvable() # then self.assertEqual(solvability, False)
class TestState(unittest.TestCase): rows = 2 cols = 2 board1 = Board([Node(0), Node(1), Node(2), Node(3)], rows, cols) board11 = Board([Node(1), Node(0), Node(2), Node(3)], rows, cols) board12 = Board([Node(2), Node(1), Node(0), Node(3)], rows, cols) board111 = Board([Node(0), Node(1), Node(2), Node(3)], rows, cols) board112 = Board([Node(1), Node(3), Node(2), Node(0)], rows, cols) board121 = Board([Node(0), Node(1), Node(2), Node(3)], rows, cols) board122 = Board([Node(2), Node(1), Node(3), Node(0)], rows, cols) def test_single_iteration(self): # given initial_state = State(self.board1) expected_states = [ State(self.board12, [MoveDown()], [self.board1]), State(self.board11, [MoveRight()], [self.board1]), ] # when states = self._iterate(initial_state) # then self.assertListEqual(states, expected_states) def test_two_iterations(self): # given initial_state = State(self.board1) expected_states = [ State(self.board121, [MoveDown(), MoveUp()], [self.board1, self.board12]), State(self.board122, [MoveDown(), MoveRight()], [self.board1, self.board12]), State(self.board112, [MoveRight(), MoveDown()], [self.board1, self.board11]), State(self.board111, [MoveRight(), MoveLeft()], [self.board1, self.board11]), ] # when states1 = self._iterate(initial_state) states2 = [s for states in states1 for s in self._iterate(states)] # then self.assertListEqual(states2, expected_states) def _iterate(self, state: State) -> List[State]: states = [] for s in state.next_states(): states.append(s) return states