コード例 #1
0
ファイル: day11.py プロジェクト: khoi/pytudes
def next_pos(curr_pos, curr_dir):
    if curr_dir == 0:
        return Point(curr_pos.x, curr_pos.y - 1)
    if curr_dir == 1:
        return Point(curr_pos.x + 1, curr_pos.y)
    if curr_dir == 2:
        return Point(curr_pos.x, curr_pos.y + 1)
    if curr_dir == 3:
        return Point(curr_pos.x - 1, curr_pos.y)
コード例 #2
0
    def run2(self):
        df = pd.read_csv(self.fileName)
        df = df[pd.notnull(df['tags'])]
        df['post'] = df['post'].apply(cleanText)
        df = df.sort_values(by='tags')
        self.numberLabels = df['tags'].value_counts().size
        df['tags'] = pd.factorize(df.tags)[0]
        self.labels = df['tags']

        vec = TfidfVectorizer(stop_words="english", max_features=100)
        vec.fit(df.post.values)
        features = vec.transform(df.post.values)

        objects = []
        ind = 0
        for coordinates in features.toarray():
            point = Point()
            point.coordinates = coordinates.tolist()
            point.orgLabel = df.tags.values[ind]
            objects.append(point)
            ind += 1

        self.objects = objects
        self.pointIndexes = len(self.objects)
        self.distanceMatrix = np.asmatrix(
            np.zeros((self.numOfMedoids, self.pointIndexes)))
        medoids, objects = self.execute()

        pca = PCA(n_components=2, random_state=random_state)
        reduced_features = pca.fit_transform(features.toarray())
        reduced_cluster_centers = pca.transform(self.getCenters(medoids))

        plt.scatter(reduced_features[:, 0],
                    reduced_features[:, 1],
                    c=self.getPredicted())
        plt.scatter(reduced_cluster_centers[:, 0],
                    reduced_cluster_centers[:, 1],
                    marker='o',
                    s=100,
                    c='b')

        plt.show()

        ind = 0
        for obj in reduced_features:
            self.objects[ind].x = obj[0]
            self.objects[ind].y = obj[1]
            ind += 1

        print("ScikitLearn Homogenity:" +
              str(homogeneity_score(df.tags, self.getPredicted())))
        print("ScikitLearn Completeness:" +
              str(completeness_score(df.tags, self.getPredicted())))
        print("ScikitLearn Silhouette Score:" +
              str(silhouette_score(features, labels=self.getPredicted())))

        return medoids, objects
コード例 #3
0
ファイル: part1.py プロジェクト: jabbalaci/AdventOfCode2020
    def get_result(self) -> int:
        topleft_x = min(x for x, y in self.d.keys())
        topleft_y = min(y for x, y in self.d.keys())
        offset = self.number_of_rows - 1    # number_of_rows == number_of_columns

        topleft = self.d[Point(topleft_x, topleft_y)]
        topright = self.d[Point(topleft_x + offset, topleft_y)]
        bottomleft = self.d[Point(topleft_x, topleft_y + offset)]
        bottomright = self.d[Point(topleft_x + offset, topleft_y + offset)]

        return topleft._id * topright._id * bottomleft._id * bottomright._id
コード例 #4
0
ファイル: part1.py プロジェクト: jabbalaci/AdventOfCode2020
 def get_input_for_part2(self) -> str:
     """
     Transform each tile: remove the borders.
     Leave no gap between the tiles.
     """
     result = ""
     topleft_x = min(x for x, y in self.d.keys())
     topleft_y = min(y for x, y in self.d.keys())
     for row in range(topleft_y, topleft_y + self.number_of_rows):
         tiles_in_row = []
         for col in range(topleft_x, topleft_x + self.number_of_columns):
             tile = self.d.get(Point(x=col, y=row), Tile.empty(TILE_WIDTH))
             # matrix = tile.get_selected_variation()
             matrix = tile.get_tile_without_margins()
             tiles_in_row.append(matrix)
             # print(tile._id, end="; ")
         #
         for i in range(len(tiles_in_row[0])):
             line = ""
             for j in range(len(tiles_in_row)):
                 curr_row = tiles_in_row[j][i]
                 line += "".join(curr_row)
                 # line += " "
             #
             # full_map.append(tuple(list(line)))
             result += line.rstrip()
             result += "\n"
         #
         # result += "\n"
     #
     return result.rstrip()
コード例 #5
0
ファイル: part1.py プロジェクト: jabbalaci/AdventOfCode2020
    def find_empty_places(self) -> List[Point]:
        places: List[Point] = []
        bag: Set[Point] = set()

        for key in self.d.keys():
            x, y = key
            neighbors = self.get_four_neighbor_positions(x, y)
            for x, y in neighbors:
                if (x, y) not in self.d:
                    if (x, y) not in bag:
                        places.append(Point(x, y))
                        bag.add(Point(x, y))
                    #
                #
            #
        #
        return places
コード例 #6
0
 def __init__(self, width, height, players):
     self.width = width
     self.height = height
     self.players = players
     self.walls = set()
     self.resources = dict()
     self.resources_neighbours = set()
     self.weights = dict()
     self.house = Point()
コード例 #7
0
ファイル: part1.py プロジェクト: jabbalaci/AdventOfCode2020
 def show_ids(self):
     topleft_x = min(x for x, y in self.d.keys())
     topleft_y = min(y for x, y in self.d.keys())
     for row in range(topleft_y, topleft_y + self.number_of_rows):
         for col in range(topleft_x, topleft_x + self.number_of_columns):
             tile = self.d[Point(x=col, y=row)]
             print(tile._id, end=" ")
         #
         print()
コード例 #8
0
    def doActionInPath(gameMap, currentPosition, direction, triggeringTileContent, action):

        # To cut down a tree, you must be on the tree instead of beside. 
        nextPosition = Point(currentPosition.x + direction.x, currentPosition.y + direction.y)

        # If there is a wall at the given position, destroy it.
        if gameMap.getTileAt(nextPosition) == triggeringTileContent:
            return action(direction)
        else:
            return create_move_action(direction)
コード例 #9
0
def deserialize(data):
    if "x" in data and "y" in data:
        return Point(data["x"], data["y"])
    elif "Name" in data:
        return Player(data["Health"], data["MaxHealth"], data["CarriedResources"],
                      data["CarryingCapacity"], data["CollectingSpeed"], data["TotalResources"],
                      data["AttackPower"], data["Defence"], data["Position"],
                      data["HouseLocation"], data["CarriedItems"], data["Score"], data["Name"],
                      data["UpgradeLevels"])
    elif "CustomSerializedMap" in data:
        data["GameMap"] = GameMap(
            data["CustomSerializedMap"], data["xMin"], data["yMin"], data["WallsAreBreakable"])
    return data
コード例 #10
0
ファイル: maze.py プロジェクト: jabbalaci/AdventOfCode2020
def main() -> None:
    drawing = """
#####
#..E#
#...#
#...#
#S#.#
#.#.#
#####
""".strip()
    maze = Maze(drawing)
    #
    pf = Pathfinder(maze)
    # pf.show()
    start = Point(x=1, y=4)
    end = Point(x=3, y=1)
    pf.set_start_point(start)
    pf.set_end_point(end)
    # pf.show_maze_with_distance_values()
    pf.start_bfs_discovery()
    pf.show_maze_with_distance_values()
    path = pf.find_shortest_path()
    print(path)
コード例 #11
0
    def __init__(self, eve_html, topology=None):
        self.uuid = uuid.uuid4()
        self.topology = topology

        self.eve_parsed_html = BeautifulSoup(eve_html, 'lxml')
        for br in self.eve_parsed_html.find_all("br"):
            br.replace_with("\n")
        css = self.eve_parsed_html.div['style']

        self.eve_coordinates = Point(
            int(CSS_LEFT_RE.search(css).group('eve_x')),
            int(CSS_TOP_RE.search(css).group('eve_y')))

        self.text = self.eve_parsed_html.text.strip()
コード例 #12
0
    def parse_node_dict(node_dict, gns_default_scene_size):
        """
        Parses dictionary from xmltodict and returns a new dictionary with different variable names

        Args:
            node_dict: dictionary obtained from xmltodict and containing information about nodes

        Returns:
            dictionary containing class Node attribute names with their values
        """
        params = dict()
        params['name'] = node_dict['@name']
        params['eve_node_id'] = node_dict['@id']
        params['node_type'] = node_dict['@type']  # iol, qemu
        params['template'] = node_dict['@template']  # vios, viosl2, iol
        params['image_path'] = node_dict['@image']
        params['eve_icon'] = node_dict['@icon']

        eve_x = node_dict['@left']
        if '%' in eve_x:
            eve_x = gns_default_scene_size.width * int(eve_x.strip('%')) * 0.01
        else:
            eve_x = int(eve_x)

        eve_y = node_dict['@top']
        if '%' in eve_y:
            eve_y = gns_default_scene_size.height * int(
                eve_y.strip('%')) * 0.01
        else:
            eve_y = int(eve_y)

        params['eve_coordinates'] = Point(eve_x, eve_y)
        if params['node_type'] == 'iol':
            params['ethernet_adapters_number'] = int(node_dict['@ethernet'])
            params['serial_adapters_number'] = int(node_dict['@serial'])
        elif params['node_type'] == 'qemu':
            params['console_type'] = node_dict['@console']
            params['cpus'] = int(node_dict['@cpu'])
            params['ram'] = int(node_dict['@ram'])
            params['adapters'] = int(node_dict['@ethernet'])
        else:
            raise NotImplementedError(
                f'Parser for the node type {params["node_type"]} is not implemented'
            )

        return params
コード例 #13
0
ファイル: part1.py プロジェクト: jabbalaci/AdventOfCode2020
    def start(self) -> None:
        self.insert_first_puzzle()

        # cnt = 0

        while not self.finished():

            # cnt += 1
            # if cnt == 2:
            #     self.debug()
            #     exit(1)

            empty_places: List[Point] = self.find_empty_places()
            for empty_place in empty_places:
                x, y = empty_place
                neighbor_positions = self.get_four_neighbor_positions(x, y)
                tile = self.find_matching_tile(x, y, neighbor_positions)
                if tile:
                    self.d[Point(x, y)] = tile
                    # self.show_dictionary()
                    break
コード例 #14
0
ファイル: part1.py プロジェクト: jabbalaci/AdventOfCode2020
 def show_content(self) -> None:
     topleft_x = min(x for x, y in self.d.keys())
     topleft_y = min(y for x, y in self.d.keys())
     for row in range(topleft_y, topleft_y + self.number_of_rows):
         tiles_in_row = []
         for col in range(topleft_x, topleft_x + self.number_of_columns):
             tile = self.d.get(Point(x=col, y=row), Tile.empty(TILE_WIDTH))
             matrix = tile.get_selected_variation()
             # matrix = tile.get_tile_without_margins()
             tiles_in_row.append(matrix)
             # print(tile._id, end="; ")
         #
         for i in range(len(tiles_in_row[0])):
             line = ""
             for j in range(len(tiles_in_row)):
                 curr_row = tiles_in_row[j][i]
                 line += "".join(curr_row)
                 line += " "
             #
             # full_map.append(tuple(list(line)))
             print(line)
         #
         print()
コード例 #15
0
 def __init__(self):
     self.normal = Point(0, 0, -1.0)
     self.center = Point(0, 0, -0.06)
コード例 #16
0
 def __init__(self):
     self.center = Point(0.0, -0.1, -0.25)
     self.radius = 0.1
コード例 #17
0
 def __init__(self):
     self.center = Point(0, 0.1, -0.1)
     self.radius = 0.05
コード例 #18
0
ファイル: part1.py プロジェクト: jabbalaci/AdventOfCode2020
 def insert_first_puzzle(self) -> None:
     tile = self.tiles.list_of_tiles[0]
     tile.index_of_selected_variation = 0
     self.d[Point(0, 0)] = tile
コード例 #19
0
ファイル: day11.py プロジェクト: khoi/pytudes

def next_pos(curr_pos, curr_dir):
    if curr_dir == 0:
        return Point(curr_pos.x, curr_pos.y - 1)
    if curr_dir == 1:
        return Point(curr_pos.x + 1, curr_pos.y)
    if curr_dir == 2:
        return Point(curr_pos.x, curr_pos.y + 1)
    if curr_dir == 3:
        return Point(curr_pos.x - 1, curr_pos.y)


grid = defaultdict(lambda: 0)
c = IntCode(program)
curr_pos = Point(0, 0)
curr_dir = 0

while not c.halt:
    output_paint, output_dir = c.run([grid[curr_pos]])
    grid[curr_pos] = output_paint
    curr_dir = next_dir(curr_dir, output_dir)
    curr_pos = next_pos(curr_pos, curr_dir)

print("part 1")
print(len(grid))

print("part 2")

grid = defaultdict(lambda: 0)
c = IntCode(program)
コード例 #20
0
class Node(object):
    """
    TODO
    @DynamicAttrs
    """
    L2_IOL_LABEL_COORDINATES = Point(-4, 46)
    L3_IOL_LABEL_COORDINATES = Point(15, 46)
    DEFAULT_LABEL_COORDINATES = Point(5, -25)
    SWITCH_SYMBOL_SIZE = Size(51, 48)
    ROUTER_SYMBOL_SIZE = Size(66, 45)

    def __init__(self, interfaces_dict=None, **kwargs):
        self.uuid = uuid.uuid4()

        for attr_name, attr_value in kwargs.items():
            setattr(self, attr_name, attr_value)

        # self.eve_node_id = eve_node_id
        # self.name = name
        # self.node_type = node_type
        # self.image_path = image_path
        # self.eve_icon = eve_icon
        # self.eve_coordinates = eve_coordinates
        #
        # self.serial_adapters_number = serial_adapters_number
        # self.ethernet_adapters_number = ethernet_adapters_number

        self.config = None
        self.interfaces = []
        self.id_to_interface = {}

        # self.topology = topology
        self.topology.id_to_node[self.eve_node_id] = self

        if interfaces_dict is not None:
            self.parse_interfaces(interfaces_dict)

    @classmethod
    def from_dict(cls, node_dict, topology=None):
        """
        TODO
        Creates a Node object if it does exist based on the node_dict

        Args:
            node_dict: dictionary, obtained from xmltodict representing the node
            id_to_network: dictionary, containing mapping from Network id to Network object
            id_to_node: dictionary, containing mapping from Node id to Node object

        Returns:
            instance of the class Node

        Examples:
            node_dict = {'@name': 'R1', '@eve_node_id': '123'}
            node = Node.from_dict(node_dict, {}, {})
        """
        params = cls.parse_node_dict(node_dict,
                                     topology.GNS_DEFAULT_SCENE_SIZE)
        node = topology.id_to_node.get(params['eve_node_id'])
        params['topology'] = topology
        interfaces_dict = node_dict.get('interface', [])

        if node is None:
            params['interfaces_dict'] = interfaces_dict
            # if the node does not yet exist, create a new one using class constructor
            return cls(**params)
        else:
            # if node already exists go through each attribute and set it for the existing object
            for attr_name, attr_value in params.items():
                setattr(node, attr_name, attr_value)
            node.parse_interfaces(interfaces_dict)
            return node

    @staticmethod
    def parse_node_dict(node_dict, gns_default_scene_size):
        """
        Parses dictionary from xmltodict and returns a new dictionary with different variable names

        Args:
            node_dict: dictionary obtained from xmltodict and containing information about nodes

        Returns:
            dictionary containing class Node attribute names with their values
        """
        params = dict()
        params['name'] = node_dict['@name']
        params['eve_node_id'] = node_dict['@id']
        params['node_type'] = node_dict['@type']  # iol, qemu
        params['template'] = node_dict['@template']  # vios, viosl2, iol
        params['image_path'] = node_dict['@image']
        params['eve_icon'] = node_dict['@icon']

        eve_x = node_dict['@left']
        if '%' in eve_x:
            eve_x = gns_default_scene_size.width * int(eve_x.strip('%')) * 0.01
        else:
            eve_x = int(eve_x)

        eve_y = node_dict['@top']
        if '%' in eve_y:
            eve_y = gns_default_scene_size.height * int(
                eve_y.strip('%')) * 0.01
        else:
            eve_y = int(eve_y)

        params['eve_coordinates'] = Point(eve_x, eve_y)
        if params['node_type'] == 'iol':
            params['ethernet_adapters_number'] = int(node_dict['@ethernet'])
            params['serial_adapters_number'] = int(node_dict['@serial'])
        elif params['node_type'] == 'qemu':
            params['console_type'] = node_dict['@console']
            params['cpus'] = int(node_dict['@cpu'])
            params['ram'] = int(node_dict['@ram'])
            params['adapters'] = int(node_dict['@ethernet'])
        else:
            raise NotImplementedError(
                f'Parser for the node type {params["node_type"]} is not implemented'
            )

        return params

    @property
    def role(self):
        if 'router' in self.eve_icon.lower():
            return 'router'
        elif 'switch' in self.eve_icon.lower():
            return 'switch'
        else:
            return None

    def __repr__(self):
        return f'Node(eve_node_id={self.eve_node_id}, name={self.name})'

    def parse_interfaces(self, interfaces_dict):
        """
        TODO
        Goes through each interface in the dictionary and creates Interface objects for them

        Args:
            interfaces_dict: dictionary retrieved from xmltodict containing information about interfaces
            id_to_network: dictionary containing Network id to Network object mapping
            id_to_node: dictionary containing Node id to Node object mapping

        Modifies:
            self.interfaces - adds a new Interface to the list
            id_to_node - adds an id to Node object mapping to the dictionary
            May create a remote Node object and Interface if needed
        """
        def parse_interface_dict(int_dict):
            link_type = int_dict['@type']
            eve_interface_id = int(int_dict['@id'])
            eve_interface_name = int_dict['@name']
            try:
                interface = self.get_interface(eve_interface_id)
                interface.eve_name = eve_interface_name
            except exceptions.MissingInterface:
                if link_type == 'ethernet':
                    eve_network_id = int_dict['@network_id']
                    eve_network = self.topology.id_to_network.get(
                        eve_network_id)
                    self.create_interface(
                        eve_interface_id=eve_interface_id,
                        eve_interface_name=eve_interface_name,
                        eve_network=eve_network)

                elif link_type == 'serial':
                    eve_remote_node_id = int_dict['@remote_id']
                    eve_remote_interface_id = int(int_dict['@remote_if'])
                    remote_node = self.topology.id_to_node.get(
                        eve_remote_node_id)

                    if remote_node is None:
                        # remote node does not exist yet
                        remote_node = Node(eve_node_id=eve_remote_node_id,
                                           topology=self.topology)
                    try:
                        remote_interface = remote_node.get_interface(
                            eve_remote_interface_id)
                    except exceptions.MissingInterface:
                        remote_interface = remote_node.create_interface(
                            eve_interface_id=eve_remote_interface_id,
                            remote_node=self)
                        # I do not update interface details later!

                    local_interface = self.create_interface(
                        eve_interface_id=eve_interface_id,
                        eve_interface_name=eve_interface_name,
                        remote_node=remote_node)

                    remote_interface.remote_node = self

                    # link interfaces between each other
                    local_interface.remote_interface = remote_interface
                    remote_interface.remote_interface = local_interface

                    # create Link object if the link is point to point
                    link = Link(interfaces=(local_interface, remote_interface))
                    local_interface.link = link
                    remote_interface.link = link
                    self.topology.links.append(link)

        for interface_dict in interfaces_dict:
            parse_interface_dict(interface_dict)

    def get_interface(self, interface_id):
        """
        Gets an Interface object based on interface_id

        Args:
            interface_id: string, id of the interface in source xml file

        Returns:
            Interface object having this interface_id if exists

        Raises:
            errors.MissingInterface if interface was not found
        """
        try:
            return self.id_to_interface[interface_id]
        except KeyError:
            raise exceptions.MissingInterface(
                f'Interface with id {interface_id} does not exist on node with id {self.eve_node_id}'
            )

    def create_interface(self,
                         eve_interface_id,
                         eve_interface_name=None,
                         eve_network=None,
                         remote_node=None,
                         remote_interface=None):
        """
        Creates an Interfaces object and stored it in self.interfaces list

        Args:
            eve_interface_id: string, interface id in source XML file
            eve_interface_name: string, interface name in source XML file
            eve_network: Network object to which an interface is connected
            remote_node: Node object, a Node to which an interface is connected if the link is serial
            remote_interface: Interface object, which belongs to
                a Node to which an interface is connected if the link is serial

        Returns:
            Interface object

        Modifies:
            self.interfaces - adds an Interface object to this list
            self.id_to_interface - adds id to Interface object mapping for quick access
        """
        interface = Interface(eve_id=eve_interface_id,
                              eve_name=eve_interface_name,
                              eve_network=eve_network,
                              node=self,
                              remote_node=remote_node,
                              remote_interface=remote_interface)
        self.id_to_interface[eve_interface_id] = interface
        self.interfaces.append(interface)
        return interface

    @property
    def gns_coordinates(self):
        return self.topology.get_gns_coordinates(self.eve_coordinates)

    @property
    def gns_image(self):
        if self.node_type == 'iol' and self.role == 'switch' and self.topology.args.l2_iol_image:
            return self.topology.args.l2_iol_image
        elif self.node_type == 'iol' and self.role == 'router' and self.topology.args.l3_iol_image:
            return self.topology.args.l3_iol_image
        else:
            return self.image_path

    @property
    def gns_label_coordinates(self):
        if self.node_type == 'iol' and self.role == 'switch':
            return self.L2_IOL_LABEL_COORDINATES
        elif self.node_type == 'iol' and self.role == 'router':
            return self.L3_IOL_LABEL_COORDINATES
        else:
            return self.DEFAULT_LABEL_COORDINATES

    @property
    def gns_icon(self):
        if self.role == 'switch':
            return ':/symbols/multilayer_switch.svg'
        elif self.role == 'router':
            return ':/symbols/router.svg'

    @property
    def gns_icon_size(self):
        if self.role == 'switch':
            return self.SWITCH_SYMBOL_SIZE
        elif self.role == 'router':
            return self.ROUTER_SYMBOL_SIZE

    @property
    def gns_icon_center_coordinates(self):
        return self.gns_coordinates + self.gns_icon_size / 2

    def write_config_to_dir(self, dst_dir):
        """
        Creates a config file for the node in the specified directory on disk

        Args:
            dst_dir: string, destination directory where the file should be written

        Returns:
            None
        """
        if self.config:
            filename = f'{self.name}_startup-config.cfg'
            path = os.path.join(dst_dir, filename)
            with open(path, 'wb') as f:
                f.write(self.config)

    def build_gns_topology_json(self):
        if self.node_type == 'iol':
            node_json = copy.deepcopy(json_templates.IOL_JSON_TEMPLATE)
            node_json['properties'][
                'ethernet_adapters'] = self.ethernet_adapters_number
            node_json['properties'][
                'serial_adapters'] = self.serial_adapters_number
            node_json['properties']['path'] = self.gns_image
        elif self.node_type == 'qemu':
            node_json = copy.deepcopy(json_templates.QEMU_JSON_TEMPLATE)
            node_json['properties']['adapters'] = self.adapters
            node_json['properties']['cpus'] = self.cpus
            node_json['properties']['ram'] = self.ram
            node_json['properties']['hda_disk_image'] = self.gns_image
            if self.template == 'vios':
                node_json['port_name_format'] = 'Gi0/{0}'
                node_json['properties'][
                    'hdb_disk_image'] = 'IOSv_startup_config.img'
                node_json['properties']['hdb_disk_interface'] = 'virtio'
            elif self.template == 'viosl2':
                node_json['port_name_format'] = 'Gi{1}/{0}'
                node_json['properties']['port_segment_size'] = 4
            else:
                node_json['port_name_format'] = 'Gi0/{0}'
        else:
            raise NotImplementedError(
                "There is no template for the node type {self.node_type}")

        node_json['console'] = self.topology.console_start_port + int(
            self.eve_node_id)
        node_json['label']['text'] = self.name
        node_json['name'] = self.name
        node_json['node_id'] = str(self.uuid)

        node_json['symbol'] = self.gns_icon

        gns_coordinates = self.gns_coordinates
        node_json['x'] = gns_coordinates.x
        node_json['y'] = gns_coordinates.y
        node_json['width'] = self.gns_icon_size.x
        node_json['height'] = self.gns_icon_size.y

        gns_label_coordinates = self.gns_label_coordinates
        node_json['label']['x'] = gns_label_coordinates.x
        node_json['label']['y'] = gns_label_coordinates.y

        return node_json