Search is not available for this dataset
text
stringlengths
75
104k
def _binary_file(self, file): """Dump the ocntent into the `file` in binary mode. """ if self.__text_is_expected: file = TextWrapper(file, self.__encoding) self.__dump_to_file(file)
def _path(self, path): """Saves the dump in a file named `path`.""" mode, encoding = self._mode_and_encoding_for_open() with open(path, mode, encoding=encoding) as file: self.__dump_to_file(file)
def _temporary_file(self, delete): """:return: a temporary file where the content is dumped to.""" file = NamedTemporaryFile("w+", delete=delete, encoding=self.__encoding) self._file(file) return file
def temporary_path(self, extension=""): """Saves the dump in a temporary file and returns its path. .. warning:: The user of this method is responsible for deleting this file to save space on the hard drive. If you only need a file object for a short period of ...
def _binary_temporary_file(self, delete): """:return: a binary temporary file where the content is dumped to.""" file = NamedTemporaryFile("wb+", delete=delete) self._binary_file(file) return file
def _convert_to_image_color(self, color): """:return: a color that can be used by the image""" rgb = self._convert_color_to_rrggbb(color) return self._convert_rrggbb_to_image_color(rgb)
def _set_pixel_and_convert_color(self, x, y, color): """set the pixel but convert the color before.""" if color is None: return color = self._convert_color_to_rrggbb(color) self._set_pixel(x, y, color)
def _set_pixel(self, x, y, color): """set the color of the pixel. :param color: must be a valid color in the form of "#RRGGBB". If you need to convert color, use `_set_pixel_and_convert_color()`. """ if not self.is_in_bounds(x, y): return rgb = self._conver...
def set_pixel(self, x, y, color): """set the pixel at ``(x, y)`` position to :paramref:`color` If ``(x, y)`` is out of the :ref:`bounds <png-builder-bounds>` this does not change the image. .. seealso:: :meth:`set_color_in_grid` """ self._set_pixel_and_convert_color(x, ...
def is_in_bounds(self, x, y): """ :return: whether ``(x, y)`` is inside the :ref:`bounds <png-builder-bounds>` :rtype: bool """ lower = self._min_x <= x and self._min_y <= y upper = self._max_x > x and self._max_y > y return lower and upper
def set_color_in_grid(self, color_in_grid): """Set the pixel at the position of the :paramref:`color_in_grid` to its color. :param color_in_grid: must have the following attributes: - ``color`` is the :ref:`color <png-color>` to set the pixel to - ``x`` is the x position of...
def set_colors_in_grid(self, some_colors_in_grid): """Same as :meth:`set_color_in_grid` but with a collection of colors in grid. :param iterable some_colors_in_grid: a collection of colors in grid for :meth:`set_color_in_grid` """ for color_in_grid in some_colors_in_gr...
def get_instruction_id(self, instruction_or_id): """The id that identifies the instruction in this cache. :param instruction_or_id: an :class:`instruction <knittingpattern.Instruction.Instruction>` or an instruction id :return: a :func:`hashable <hash>` object :rtype: tuple ...
def to_svg(self, instruction_or_id, i_promise_not_to_change_the_result=False): """Return the SVG for an instruction. :param instruction_or_id: either an :class:`~knittingpattern.Instruction.Instruction` or an id returned by :meth:`get_instruction_id` :param bo...
def instruction_to_svg_dict(self, instruction_or_id, copy_result=True): """Return the SVG dict for the SVGBuilder. :param instruction_or_id: the instruction or id, see :meth:`get_instruction_id` :param bool copy_result: whether to copy the result :rtype: dict The resu...
def _instructions_changed(self, change): """Call when there is a change in the instructions.""" if change.adds(): for index, instruction in change.items(): if isinstance(instruction, dict): in_row = self._parser.instruction_in_row(self, instruction) ...
def last_produced_mesh(self): """The last produced mesh. :return: the last produced mesh :rtype: knittingpattern.Mesh.Mesh :raises IndexError: if no mesh is produced .. seealso:: :attr:`number_of_produced_meshes` """ for instruction in reversed(self.instructions...
def last_consumed_mesh(self): """The last consumed mesh. :return: the last consumed mesh :rtype: knittingpattern.Mesh.Mesh :raises IndexError: if no mesh is consumed .. seealso:: :attr:`number_of_consumed_meshes` """ for instruction in reversed(self.instructions...
def first_produced_mesh(self): """The first produced mesh. :return: the first produced mesh :rtype: knittingpattern.Mesh.Mesh :raises IndexError: if no mesh is produced .. seealso:: :attr:`number_of_produced_meshes` """ for instruction in self.instructions: ...
def first_consumed_mesh(self): """The first consumed mesh. :return: the first consumed mesh :rtype: knittingpattern.Mesh.Mesh :raises IndexError: if no mesh is consumed .. seealso:: :attr:`number_of_consumed_meshes` """ for instruction in self.instructions: ...
def rows_before(self): """The rows that produce meshes for this row. :rtype: list :return: a list of rows that produce meshes for this row. Each row occurs only once. They are sorted by the first occurrence in the instructions. """ rows_before = [] fo...
def rows_after(self): """The rows that consume meshes from this row. :rtype: list :return: a list of rows that consume meshes from this row. Each row occurs only once. They are sorted by the first occurrence in the instructions. """ rows_after = [] fo...
def at(self, index): """Get the object at an :paramref:`index`. :param int index: the index of the object :return: the object at :paramref:`index` """ keys = list(self._items.keys()) key = keys[index] return self[key]
def folder(self, folder): """Load all files from a folder recursively. Depending on :meth:`chooses_path` some paths may not be loaded. Every loaded path is processed and returned part of the returned list. :param str folder: the folder to load the files from :rtype: list ...
def _relative_to_absolute(self, module_location, folder): """:return: the absolute path for the `folder` relative to the module_location. :rtype: str """ if os.path.isfile(module_location): path = os.path.dirname(module_location) elif os.path.isdir(module_loca...
def relative_folder(self, module, folder): """Load a folder located relative to a module and return the processed result. :param str module: can be - a path to a folder - a path to a file - a module name :param str folder: the path of a folder relative to...
def relative_file(self, module, file): """Load a file relative to a module. :param str module: can be - a path to a folder - a path to a file - a module name :param str folder: the path of a folder relative to :paramref:`module` :return: the result of the...
def example(self, relative_path): """Load an example from the knitting pattern examples. :param str relative_path: the path to load :return: the result of the processing You can use :meth:`knittingpattern.Loader.PathLoader.examples` to find out the paths of all examples. ...
def url(self, url, encoding="UTF-8"): """load and process the content behind a url :return: the processed result of the :paramref:`url's <url>` content :param str url: the url to retrieve the content from :param str encoding: the encoding of the retrieved content. The default ...
def string(self, string): """Load an object from a string and return the processed JSON content :return: the result of the processing step :param str string: the string to load the JSON from """ object_ = json.loads(string) return self.object(object_)
def get(self, key, default=None): """ :return: the value behind :paramref:`key` in the specification. If no value was found, :paramref:`default` is returned. :param key: a :ref:`specification key <prototype-key>` """ for base in self.__specification: if key ...
def _dump_knitting_pattern(self, file): """dump a knitting pattern to a file.""" knitting_pattern_set = self.__on_dump() knitting_pattern = knitting_pattern_set.patterns.at(0) layout = GridLayout(knitting_pattern) builder = AYABPNGBuilder(*layout.bounding_box) builder.set...
def unique(iterables): """Create an iterable from the iterables that contains each element once. :return: an iterable over the iterables. Each element of the result appeared only once in the result. They are ordered by the first occurrence in the iterables. """ included_elements = set() ...
def build_SVG_dict(self): """Go through the layout and build the SVG. :return: an xml dict that can be exported using a :class:`~knittingpattern.Dumper.XMLDumper` :rtype: dict """ zoom = self._zoom layout = self._layout builder = self._builder b...
def _register_instruction_in_defs(self, instruction): """Create a definition for the instruction. :return: the id of a symbol in the defs for the specified :paramref:`instruction` :rtype: str If no symbol yet exists in the defs for the :paramref:`instruction` a symbol...
def _make_definition(self, svg_dict, instruction_id): """Create a symbol out of the supplied :paramref:`svg_dict`. :param dict svg_dict: dictionary containing the SVG for the instruction currently processed :param str instruction_id: id that will be assigned to the symbol """ ...
def _compute_scale(self, instruction_id, svg_dict): """Compute the scale of an instruction svg. Compute the scale using the bounding box stored in the :paramref:`svg_dict`. The scale is saved in a dictionary using :paramref:`instruction_id` as key. :param str instruction_id: id...
def to_svg(self, zoom): """Create an SVG from the knitting pattern set. :param float zoom: the height and width of a knit instruction :return: a dumper to save the svg to :rtype: knittingpattern.Dumper.XMLDumper Example: .. code:: python >>> knitting_patte...
def add_new_pattern(self, id_, name=None): """Add a new, empty knitting pattern to the set. :param id_: the id of the pattern :param name: the name of the pattern to add or if :obj:`None`, the :paramref:`id_` is used :return: a new, empty knitting pattern :rtype: knitt...
def to_svg(self, converter=None): """Return a SVGDumper for this instruction. :param converter: a :class:` knittingpattern.convert.InstructionSVGCache.InstructionSVGCache` or :obj:`None`. If :obj:`None` is given, the :func:` knittingpattern.convert.InstructionSVGCache.defa...
def transfer_to_row(self, new_row): """Transfer this instruction to a new row. :param knittingpattern.Row.Row new_row: the new row the instruction is in. """ if new_row != self._row: index = self.get_index_in_row() if index is not None: ...
def get_index_in_row(self): """Index of the instruction in the instructions of the row or None. :return: index in the :attr:`row`'s instructions or None, if the instruction is not in the row :rtype: int .. seealso:: :attr:`row_instructions`, :attr:`index_in_row`, :m...
def next_instruction_in_row(self): """The instruction after this one or None. :return: the instruction in :attr:`row_instructions` after this or :obj:`None` if this is the last :rtype: knittingpattern.Instruction.InstructionInRow This can be used to traverse the instructions....
def index_of_first_produced_mesh_in_row(self): """Index of the first produced mesh in the row that consumes it. :return: an index of the first produced mesh of rows produced meshes :rtype: int .. note:: If the instruction :meth:`produces meshes <Instruction.produces_meshes>`,...
def index_of_first_consumed_mesh_in_row(self): """The index of the first consumed mesh of this instruction in its row. Same as :attr:`index_of_first_produced_mesh_in_row` but for consumed meshes. """ index = 0 for instruction in self.row_instructions: if inst...
def convert_color_to_rrggbb(color): """The color in "#RRGGBB" format. :return: the :attr:`color` in "#RRGGBB" format """ if not color.startswith("#"): rgb = webcolors.html5_parse_legacy_color(color) hex_color = webcolors.html5_serialize_simple_color(rgb) else: hex_color = co...
def _start(self): """Initialize the parsing process.""" self._instruction_library = self._spec.new_default_instructions() self._as_instruction = self._instruction_library.as_instruction self._id_cache = {} self._pattern_set = None self._inheritance_todos = [] self...
def knitting_pattern_set(self, values): """Parse a knitting pattern set. :param dict value: the specification of the knitting pattern set :rtype: knittingpattern.KnittingPatternSet.KnittingPatternSet :raises knittingpattern.KnittingPatternSet.ParsingError: if :paramref:`value`...
def _finish_inheritance(self): """Finish those who still need to inherit.""" while self._inheritance_todos: prototype, parent_id = self._inheritance_todos.pop() parent = self._id_cache[parent_id] prototype.inherit_from(parent)
def _finish_instructions(self): """Finish those who still need to inherit.""" while self._instruction_todos: row = self._instruction_todos.pop() instructions = row.get(INSTRUCTIONS, []) row.instructions.extend(instructions)
def _fill_pattern_collection(self, pattern_collection, values): """Fill a pattern collection.""" pattern = values.get(PATTERNS, []) for pattern_to_parse in pattern: parsed_pattern = self._pattern(pattern_to_parse) pattern_collection.append(parsed_pattern)
def _row(self, values): """Parse a row.""" row_id = self._to_id(values[ID]) row = self._spec.new_row(row_id, values, self) if SAME_AS in values: self._delay_inheritance(row, self._to_id(values[SAME_AS])) self._delay_instructions(row) self._id_cache[row_id] = r...
def instruction_in_row(self, row, specification): """Parse an instruction. :param row: the row of the instruction :param specification: the specification of the instruction :return: the instruction in the row """ whole_instruction_ = self._as_instruction(specification) ...
def _pattern(self, base): """Parse a pattern.""" rows = self._rows(base.get(ROWS, [])) self._finish_inheritance() self._finish_instructions() self._connect_rows(base.get(CONNECTIONS, [])) id_ = self._to_id(base[ID]) name = base[NAME] return self.new_patter...
def new_pattern(self, id_, name, rows=None): """Create a new knitting pattern. If rows is :obj:`None` it is replaced with the :meth:`new_row_collection`. """ if rows is None: rows = self.new_row_collection() return self._spec.new_pattern(id_, name, rows, self...
def _rows(self, spec): """Parse a collection of rows.""" rows = self.new_row_collection() for row in spec: rows.append(self._row(row)) return rows
def _connect_rows(self, connections): """Connect the parsed rows.""" for connection in connections: from_row_id = self._to_id(connection[FROM][ID]) from_row = self._id_cache[from_row_id] from_row_start_index = connection[FROM].get(START, DEFAULT_START) fro...
def _get_type(self, values): """:return: the type of a knitting pattern set.""" if TYPE not in values: self._error("No pattern type given but should be " "\"{}\"".format(KNITTING_PATTERN_TYPE)) type_ = values[TYPE] if type_ != KNITTING_PATTERN_TYPE: ...
def _create_pattern_set(self, pattern, values): """Create a new pattern set.""" type_ = self._get_type(values) version = self._get_version(values) comment = values.get(COMMENT) self._pattern_set = self._spec.new_pattern_set( type_, version, pattern, self, comment ...
def add_row(self, id_): """Add a new row to the pattern. :param id_: the id of the row """ row = self._parser.new_row(id_) self._rows.append(row) return row
def write(self, bytes_): """Write bytes to the file.""" string = bytes_.decode(self._encoding) self._file.write(string)
def write(self, string): """Write a string to the file.""" bytes_ = string.encode(self._encoding) self._file.write(bytes_)
def kivy_svg(self): """An SVG object. :return: an SVG object :rtype: kivy.graphics.svg.Svg :raises ImportError: if the module was not found """ from kivy.graphics.svg import Svg path = self.temporary_path(".svg") try: return Svg(path) ...
def bounding_box(self): """the bounding box of this SVG ``(min_x, min_y, max_x, max_y)``. .. code:: python svg_builder10x10.bounding_box = (0, 0, 10, 10) assert svg_builder10x10.bounding_box == (0, 0, 10, 10) ``viewBox``, ``width`` and ``height`` are computed f...
def place(self, x, y, svg, layer_id): """Place the :paramref:`svg` content at ``(x, y)`` position in the SVG, in a layer with the id :paramref:`layer_id`. :param float x: the x position of the svg :param float y: the y position of the svg :param str svg: the SVG to place at ``(x...
def place_svg_dict(self, x, y, svg_dict, layer_id, group=None): """Same as :meth:`place` but with a dictionary as :paramref:`svg_dict`. :param dict svg_dict: a dictionary returned by `xmltodict.parse() <https://github.com/martinblech/xmltodict>`__ :param dict group: a dictionary of va...
def place_svg_use_coords(self, x, y, symbol_id, layer_id, group=None): """Similar to :meth:`place` but with an id as :paramref:`symbol_id`. :param str symbol_id: an id which identifies an svg object defined in the defs :param dict group: a dictionary of values to add to the group the ...
def place_svg_use(self, symbol_id, layer_id, group=None): """Same as :meth:`place_svg_use_coords`. With implicit `x` and `y` which are set to `0` in this method and then :meth:`place_svg_use_coords` is called. """ self.place_svg_use_coords(0, 0, symbol_id, layer_id, group)
def _get_layer(self, layer_id): """ :return: the layer with the :paramref:`layer_id`. If the layer does not exist, it is created. :param str layer_id: the id of the layer """ if layer_id not in self._layer_id_to_layer: self._svg.setdefault("g", []) ...
def insert_defs(self, defs): """Adds the defs to the SVG structure. :param defs: a list of SVG dictionaries, which contain the defs, which should be added to the SVG structure. """ if self._svg["defs"] is None: self._svg["defs"] = {} for def_ in defs: ...
def write_to_file(self, file): """Writes the current SVG to the :paramref:`file`. :param file: a file-like object """ xmltodict.unparse(self._structure, file, pretty=True)
def _width(self): """For ``self.width``.""" layout = self._instruction.get(GRID_LAYOUT) if layout is not None: width = layout.get(WIDTH) if width is not None: return width return self._instruction.number_of_consumed_meshes
def instructions(self): """The instructions in a grid. :return: the :class:`instructions in a grid <InstructionInGrid>` of this row :rtype: list """ x = self.x y = self.y result = [] for instruction in self._row.instructions: instruc...
def _expand(self, row, consumed_position, passed): """Add the arguments `(args, kw)` to `_walk` to the todo list.""" self._todo.append((row, consumed_position, passed))
def _step(self, row, position, passed): """Walk through the knitting pattern by expanding an row.""" if row in passed or not self._row_should_be_placed(row, position): return self._place_row(row, position) passed = [row] + passed # print("{}{} at\t{} {}".format(" " *...
def _expand_consumed_mesh(self, mesh, mesh_index, row_position, passed): """expand the consumed meshes""" if not mesh.is_produced(): return row = mesh.producing_row position = Point( row_position.x + mesh.index_in_producing_row - mesh_index, row_positi...
def _expand_produced_mesh(self, mesh, mesh_index, row_position, passed): """expand the produced meshes""" if not mesh.is_consumed(): return row = mesh.consuming_row position = Point( row_position.x - mesh.index_in_consuming_row + mesh_index, row_positi...
def _row_should_be_placed(self, row, position): """:return: whether to place this instruction""" placed_row = self._rows_in_grid.get(row) return placed_row is None or placed_row.y < position.y
def _place_row(self, row, position): """place the instruction on a grid""" self._rows_in_grid[row] = RowInGrid(row, position)
def _walk(self): """Loop through all the instructions that are `_todo`.""" while self._todo: args = self._todo.pop(0) self._step(*args)
def instruction_in_grid(self, instruction): """Returns an `InstructionInGrid` object for the `instruction`""" row_position = self._rows_in_grid[instruction.row].xy x = instruction.index_of_first_consumed_mesh_in_row position = Point(row_position.x + x, row_position.y) return Inst...
def is_visible(self): """:return: is this connection is visible :rtype: bool A connection is visible if it is longer that 0.""" if self._start.y + 1 < self._stop.y: return True return False
def walk_instructions(self, mapping=identity): """Iterate over instructions. :return: an iterator over :class:`instructions in grid <InstructionInGrid>` :param mapping: funcion to map the result .. code:: python for pos, c in layout.walk_instructions(lambda i: (i...
def walk_rows(self, mapping=identity): """Iterate over rows. :return: an iterator over :class:`rows <RowsInGrid>` :param mapping: funcion to map the result, see :meth:`walk_instructions` for an example usage """ row_in_grid = self._walk.row_in_grid return map(l...
def walk_connections(self, mapping=identity): """Iterate over connections between instructions. :return: an iterator over :class:`connections <Connection>` between :class:`instructions in grid <InstructionInGrid>` :param mapping: funcion to map the result, see :meth:`walk_in...
def bounding_box(self): """The minimum and maximum bounds of this layout. :return: ``(min_x, min_y, max_x, max_y)`` the bounding box of this layout :rtype: tuple """ min_x, min_y, max_x, max_y = zip(*list(self.walk_rows( lambda row: row.bounding_box))) ...
def _process_loaded_object(self, path): """process the :paramref:`path`. :param str path: the path to load an svg from """ file_name = os.path.basename(path) name = os.path.splitext(file_name)[0] with open(path) as file: string = file.read() self....
def instruction_to_svg_dict(self, instruction): """ :return: an xml-dictionary with the same content as :meth:`instruction_to_svg`. """ instruction_type = instruction.type if instruction_type in self._instruction_type_to_file_content: svg = self._instruction...
def _set_fills_in_color_layer(self, svg_string, color): """replaces fill colors in ``<g inkscape:label="color" inkscape:groupmode="layer">`` with :paramref:`color` :param color: a color fill the objects in the layer with """ structure = xmltodict.parse(svg_string) if col...
def default_instruction_to_svg(self, instruction): """As :meth:`instruction_to_svg` but it only takes the ``default.svg`` file into account. In case no file is found for an instruction in :meth:`instruction_to_svg`, this method is used to determine the default svg for it. ...
def default_instruction_to_svg_dict(self, instruction): """Returns an xml-dictionary with the same content as :meth:`default_instruction_to_svg` If no file ``default.svg`` was loaded, an empty svg-dict is returned. """ instruction_type = instruction.type default_type = "...
def _dump_to_file(self, file): """dump to the file""" xmltodict.unparse(self.object(), file, pretty=True)
def add_instruction(self, specification): """Add an instruction specification :param specification: a specification with a key :data:`knittingpattern.Instruction.TYPE` .. seealso:: :meth:`as_instruction` """ instruction = self.as_instruction(specification) sel...
def as_instruction(self, specification): """Convert the specification into an instruction :param specification: a specification with a key :data:`knittingpattern.Instruction.TYPE` The instruction is not added. .. seealso:: :meth:`add_instruction` """ instruct...
def eigh(self): """ Eigen decomposition of K. Returns ------- S : ndarray The eigenvalues in ascending order, each repeated according to its multiplicity. U : ndarray Normalized eigenvectors. """ from numpy.linalg impor...
def L(self): """ Lower-triangular matrix L such that K = LLᵀ + ϵI. Returns ------- L : (d, d) ndarray Lower-triangular matrix. """ m = len(self._tril1[0]) self._L[self._tril1] = self._Lu.value[:m] self._L[self._diag] = exp(self._Lu.val...
def logdet(self): """ Log of |K|. Returns ------- float Log-determinant of K. """ from numpy.linalg import slogdet K = self.value() sign, logdet = slogdet(K) if sign != 1.0: msg = "The estimated determinant of K i...
def value(self): """ Covariance matrix. Returns ------- K : ndarray Matrix K = LLᵀ + ϵI, for a very small positive number ϵ. """ K = dot(self.L, self.L.T) return K + self._epsilon * eye(K.shape[0])
def gradient(self): """ Derivative of the covariance matrix over the parameters of L. Returns ------- Lu : ndarray Derivative of K over the lower triangular part of L. """ L = self.L self._grad_Lu[:] = 0 for i in range(len(self._tril1...
def Ge(self): """ Result of US from the SVD decomposition G = USVᵀ. """ from scipy.linalg import svd from numpy_sugar.linalg import ddot U, S, _ = svd(self._G, full_matrices=False, check_finite=False) if U.shape[1] < self._G.shape[1]: return ddot(U, ...