_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q260800
ContentDumper.temporary_path
validation
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 time you can use the method :meth:`temporary_file`. :param str extension: the ending ot the file name e.g. ``".png"`` :return: a path to the temporary file :rtype: str """ path = NamedTemporaryFile(delete=False, suffix=extension).name self.path(path) return path
python
{ "resource": "" }
q260801
AYABPNGBuilder._set_pixel_and_convert_color
validation
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)
python
{ "resource": "" }
q260802
AYABPNGBuilder._set_pixel
validation
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._convert_rrggbb_to_image_color(color) x -= self._min_x y -= self._min_y self._image.putpixel((x, y), rgb)
python
{ "resource": "" }
q260803
InstructionSVGCache.get_instruction_id
validation
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 """ if isinstance(instruction_or_id, tuple): return _InstructionId(instruction_or_id) return _InstructionId(instruction_or_id.type, instruction_or_id.hex_color)
python
{ "resource": "" }
q260804
InstructionSVGCache.to_svg
validation
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 bool i_promise_not_to_change_the_result: - :obj:`False`: the result is copied, you can alter it. - :obj:`True`: the result is directly from the cache. If you change the result, other calls of this function get the changed result. :return: an SVGDumper :rtype: knittingpattern.Dumper.SVGDumper """ return self._new_svg_dumper(lambda: self.instruction_to_svg_dict( instruction_or_id, not i_promise_not_to_change_the_result))
python
{ "resource": "" }
q260805
InstructionSVGCache.instruction_to_svg_dict
validation
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 result is cached. """ instruction_id = self.get_instruction_id(instruction_or_id) if instruction_id in self._cache: result = self._cache[instruction_id] else: result = self._instruction_to_svg_dict(instruction_id) self._cache[instruction_id] = result if copy_result: result = deepcopy(result) return result
python
{ "resource": "" }
q260806
Row._instructions_changed
validation
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) self.instructions[index] = in_row else: instruction.transfer_to_row(self)
python
{ "resource": "" }
q260807
Row.last_produced_mesh
validation
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): if instruction.produces_meshes(): return instruction.last_produced_mesh raise IndexError("{} produces no meshes".format(self))
python
{ "resource": "" }
q260808
Row.last_consumed_mesh
validation
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): if instruction.consumes_meshes(): return instruction.last_consumed_mesh raise IndexError("{} consumes no meshes".format(self))
python
{ "resource": "" }
q260809
Row.first_produced_mesh
validation
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: if instruction.produces_meshes(): return instruction.first_produced_mesh raise IndexError("{} produces no meshes".format(self))
python
{ "resource": "" }
q260810
Row.first_consumed_mesh
validation
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: if instruction.consumes_meshes(): return instruction.first_consumed_mesh raise IndexError("{} consumes no meshes".format(self))
python
{ "resource": "" }
q260811
Row.rows_before
validation
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 = [] for mesh in self.consumed_meshes: if mesh.is_produced(): row = mesh.producing_row if rows_before not in rows_before: rows_before.append(row) return rows_before
python
{ "resource": "" }
q260812
Row.rows_after
validation
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 = [] for mesh in self.produced_meshes: if mesh.is_consumed(): row = mesh.consuming_row if rows_after not in rows_after: rows_after.append(row) return rows_after
python
{ "resource": "" }
q260813
PathLoader.folder
validation
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 :return: a list of the results of the processing steps of the loaded files """ result = [] for root, _, files in os.walk(folder): for file in files: path = os.path.join(root, file) if self._chooses_path(path): result.append(self.path(path)) return result
python
{ "resource": "" }
q260814
PathLoader.relative_folder
validation
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 :paramref:`module` :return: a list of the results of the processing :rtype: list Depending on :meth:`chooses_path` some paths may not be loaded. Every loaded path is processed and returned part of the returned list. You can use :meth:`choose_paths` to find out which paths are chosen to load. """ folder = self._relative_to_absolute(module, folder) return self.folder(folder)
python
{ "resource": "" }
q260815
PathLoader.relative_file
validation
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 processing """ path = self._relative_to_absolute(module, file) return self.path(path)
python
{ "resource": "" }
q260816
PathLoader.example
validation
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. """ example_path = os.path.join("examples", relative_path) return self.relative_file(__file__, example_path)
python
{ "resource": "" }
q260817
ContentLoader.url
validation
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 encoding is UTF-8. """ import urllib.request with urllib.request.urlopen(url) as file: webpage_content = file.read() webpage_content = webpage_content.decode(encoding) return self.string(webpage_content)
python
{ "resource": "" }
q260818
JSONLoader.string
validation
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_)
python
{ "resource": "" }
q260819
AYABPNGDumper._dump_knitting_pattern
validation
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_colors_in_grid(layout.walk_instructions()) builder.write_to_file(file)
python
{ "resource": "" }
q260820
unique
validation
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 included(element): result = element in included_elements included_elements.add(element) return result return [element for elements in iterables for element in elements if not included(element)]
python
{ "resource": "" }
q260821
KnittingPatternToSVG.build_SVG_dict
validation
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 bbox = list(map(lambda f: f * zoom, layout.bounding_box)) builder.bounding_box = bbox flip_x = bbox[2] + bbox[0] * 2 flip_y = bbox[3] + bbox[1] * 2 instructions = list(layout.walk_instructions( lambda i: (flip_x - (i.x + i.width) * zoom, flip_y - (i.y + i.height) * zoom, i.instruction))) instructions.sort(key=lambda x_y_i: x_y_i[2].render_z) for x, y, instruction in instructions: render_z = instruction.render_z z_id = ("" if not render_z else "-{}".format(render_z)) layer_id = "row-{}{}".format(instruction.row.id, z_id) def_id = self._register_instruction_in_defs(instruction) scale = self._symbol_id_to_scale[def_id] group = { "@class": "instruction", "@id": "instruction-{}".format(instruction.id), "@transform": "translate({},{}),scale({})".format( x, y, scale) } builder.place_svg_use(def_id, layer_id, group) builder.insert_defs(self._instruction_type_color_to_symbol.values()) return builder.get_svg_dict()
python
{ "resource": "" }
q260822
KnittingPatternToSVG._register_instruction_in_defs
validation
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 is created and saved using :meth:`_make_symbol`. """ type_ = instruction.type color_ = instruction.color instruction_to_svg_dict = \ self._instruction_to_svg.instruction_to_svg_dict instruction_id = "{}:{}".format(type_, color_) defs_id = instruction_id + ":defs" if instruction_id not in self._instruction_type_color_to_symbol: svg_dict = instruction_to_svg_dict(instruction) self._compute_scale(instruction_id, svg_dict) symbol = self._make_definition(svg_dict, instruction_id) self._instruction_type_color_to_symbol[defs_id] = \ symbol[DEFINITION_HOLDER].pop("defs", {}) self._instruction_type_color_to_symbol[instruction_id] = symbol return instruction_id
python
{ "resource": "" }
q260823
KnittingPatternToSVG._compute_scale
validation
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 identifying a symbol in the defs :param dict svg_dict: dictionary containing the SVG for the instruction currently processed """ bbox = list(map(float, svg_dict["svg"]["@viewBox"].split())) scale = self._zoom / (bbox[3] - bbox[1]) self._symbol_id_to_scale[instruction_id] = scale
python
{ "resource": "" }
q260824
KnittingPatternSet.to_svg
validation
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_pattern_set.to_svg(25).temporary_path(".svg") "/the/path/to/the/file.svg" """ def on_dump(): """Dump the knitting pattern to the file. :return: the SVG XML structure as dictionary. """ knitting_pattern = self.patterns.at(0) layout = GridLayout(knitting_pattern) instruction_to_svg = default_instruction_svg_cache() builder = SVGBuilder() kp_to_svg = KnittingPatternToSVG(knitting_pattern, layout, instruction_to_svg, builder, zoom) return kp_to_svg.build_SVG_dict() return XMLDumper(on_dump)
python
{ "resource": "" }
q260825
KnittingPatternSet.add_new_pattern
validation
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: knittingpattern.KnittingPattern.KnittingPattern """ if name is None: name = id_ pattern = self._parser.new_pattern(id_, name) self._patterns.append(pattern) return pattern
python
{ "resource": "" }
q260826
Instruction.to_svg
validation
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.default_svg_cache` is used. :rtype: knittingpattern.Dumper.SVGDumper """ if converter is None: from knittingpattern.convert.InstructionSVGCache import \ default_svg_cache converter = default_svg_cache() return converter.to_svg(self)
python
{ "resource": "" }
q260827
InstructionInRow.transfer_to_row
validation
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: self._row.instructions.pop(index) self._row = new_row
python
{ "resource": "" }
q260828
InstructionInRow.get_index_in_row
validation
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`, :meth:`is_in_row` """ expected_index = self._cached_index_in_row instructions = self._row.instructions if expected_index is not None and \ 0 <= expected_index < len(instructions) and \ instructions[expected_index] is self: return expected_index for index, instruction_in_row in enumerate(instructions): if instruction_in_row is self: self._cached_index_in_row = index return index return None
python
{ "resource": "" }
q260829
InstructionInRow.next_instruction_in_row
validation
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. .. seealso:: :attr:`previous_instruction_in_row` """ index = self.index_in_row + 1 if index >= len(self.row_instructions): return None return self.row_instructions[index]
python
{ "resource": "" }
q260830
InstructionInRow.index_of_first_produced_mesh_in_row
validation
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>`, this is the index of the first mesh the instruction produces in all the meshes of the row. If the instruction does not produce meshes, the index of the mesh is returned as if the instruction had produced a mesh. .. code:: if instruction.produces_meshes(): index = instruction.index_of_first_produced_mesh_in_row """ index = 0 for instruction in self.row_instructions: if instruction is self: break index += instruction.number_of_produced_meshes else: self._raise_not_found_error() return index
python
{ "resource": "" }
q260831
InstructionInRow.index_of_first_consumed_mesh_in_row
validation
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 instruction is self: break index += instruction.number_of_consumed_meshes else: self._raise_not_found_error() return index
python
{ "resource": "" }
q260832
Parser._start
validation
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._instruction_todos = []
python
{ "resource": "" }
q260833
Parser.knitting_pattern_set
validation
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` does not fulfill the :ref:`specification <FileFormatSpecification>`. """ self._start() pattern_collection = self._new_pattern_collection() self._fill_pattern_collection(pattern_collection, values) self._create_pattern_set(pattern_collection, values) return self._pattern_set
python
{ "resource": "" }
q260834
Parser._fill_pattern_collection
validation
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)
python
{ "resource": "" }
q260835
Parser._row
validation
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] = row return row
python
{ "resource": "" }
q260836
Parser.instruction_in_row
validation
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) return self._spec.new_instruction_in_row(row, whole_instruction_)
python
{ "resource": "" }
q260837
Parser._pattern
validation
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_pattern(id_, name, rows)
python
{ "resource": "" }
q260838
Parser.new_pattern
validation
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)
python
{ "resource": "" }
q260839
Parser._rows
validation
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
python
{ "resource": "" }
q260840
Parser._connect_rows
validation
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) from_row_number_of_possible_meshes = \ from_row.number_of_produced_meshes - from_row_start_index to_row_id = self._to_id(connection[TO][ID]) to_row = self._id_cache[to_row_id] to_row_start_index = connection[TO].get(START, DEFAULT_START) to_row_number_of_possible_meshes = \ to_row.number_of_consumed_meshes - to_row_start_index meshes = min(from_row_number_of_possible_meshes, to_row_number_of_possible_meshes) # TODO: test all kinds of connections number_of_meshes = connection.get(MESHES, meshes) from_row_stop_index = from_row_start_index + number_of_meshes to_row_stop_index = to_row_start_index + number_of_meshes assert 0 <= from_row_start_index <= from_row_stop_index produced_meshes = from_row.produced_meshes[ from_row_start_index:from_row_stop_index] assert 0 <= to_row_start_index <= to_row_stop_index consumed_meshes = to_row.consumed_meshes[ to_row_start_index:to_row_stop_index] assert len(produced_meshes) == len(consumed_meshes) mesh_pairs = zip(produced_meshes, consumed_meshes) for produced_mesh, consumed_mesh in mesh_pairs: produced_mesh.connect_to(consumed_mesh)
python
{ "resource": "" }
q260841
Parser._create_pattern_set
validation
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 )
python
{ "resource": "" }
q260842
KnittingPattern.add_row
validation
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
python
{ "resource": "" }
q260843
BytesWrapper.write
validation
def write(self, bytes_): """Write bytes to the file.""" string = bytes_.decode(self._encoding) self._file.write(string)
python
{ "resource": "" }
q260844
TextWrapper.write
validation
def write(self, string): """Write a string to the file.""" bytes_ = string.encode(self._encoding) self._file.write(bytes_)
python
{ "resource": "" }
q260845
SVGDumper.kivy_svg
validation
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) finally: remove_file(path)
python
{ "resource": "" }
q260846
SVGBuilder.insert_defs
validation
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: for key, value in def_.items(): if key.startswith("@"): continue if key not in self._svg["defs"]: self._svg["defs"][key] = [] if not isinstance(value, list): value = [value] self._svg["defs"][key].extend(value)
python
{ "resource": "" }
q260847
InstructionInGrid._width
validation
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
python
{ "resource": "" }
q260848
RowInGrid.instructions
validation
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: instruction_in_grid = InstructionInGrid(instruction, Point(x, y)) x += instruction_in_grid.width result.append(instruction_in_grid) return result
python
{ "resource": "" }
q260849
_RecursiveWalk._step
validation
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(" " * len(passed), row, position, # passed)) for i, produced_mesh in enumerate(row.produced_meshes): self._expand_produced_mesh(produced_mesh, i, position, passed) for i, consumed_mesh in enumerate(row.consumed_meshes): self._expand_consumed_mesh(consumed_mesh, i, position, passed)
python
{ "resource": "" }
q260850
_RecursiveWalk._expand_consumed_mesh
validation
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_position.y - INSTRUCTION_HEIGHT ) self._expand(row, position, passed)
python
{ "resource": "" }
q260851
_RecursiveWalk._expand_produced_mesh
validation
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_position.y + INSTRUCTION_HEIGHT ) self._expand(row, position, passed)
python
{ "resource": "" }
q260852
_RecursiveWalk._place_row
validation
def _place_row(self, row, position): """place the instruction on a grid""" self._rows_in_grid[row] = RowInGrid(row, position)
python
{ "resource": "" }
q260853
_RecursiveWalk._walk
validation
def _walk(self): """Loop through all the instructions that are `_todo`.""" while self._todo: args = self._todo.pop(0) self._step(*args)
python
{ "resource": "" }
q260854
_RecursiveWalk.instruction_in_grid
validation
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 InstructionInGrid(instruction, position)
python
{ "resource": "" }
q260855
GridLayout.walk_instructions
validation
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.xy, i.color)): print("color {} at {}".format(c, pos)) """ instructions = chain(*self.walk_rows(lambda row: row.instructions)) return map(mapping, instructions)
python
{ "resource": "" }
q260856
GridLayout.walk_rows
validation
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(lambda row: mapping(row_in_grid(row)), self._rows)
python
{ "resource": "" }
q260857
GridLayout.walk_connections
validation
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_instructions` for an example usage """ for start in self.walk_instructions(): for stop_instruction in start.instruction.consuming_instructions: if stop_instruction is None: continue stop = self._walk.instruction_in_grid(stop_instruction) connection = Connection(start, stop) if connection.is_visible(): # print("connection:", # connection.start.instruction, # connection.stop.instruction) yield mapping(connection)
python
{ "resource": "" }
q260858
GridLayout.bounding_box
validation
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))) return min(min_x), min(min_y), max(max_x), max(max_y)
python
{ "resource": "" }
q260859
XMLDumper._dump_to_file
validation
def _dump_to_file(self, file): """dump to the file""" xmltodict.unparse(self.object(), file, pretty=True)
python
{ "resource": "" }
q260860
InstructionLibrary.add_instruction
validation
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) self._type_to_instruction[instruction.type] = instruction
python
{ "resource": "" }
q260861
InstructionLibrary.as_instruction
validation
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` """ instruction = self._instruction_class(specification) type_ = instruction.type if type_ in self._type_to_instruction: instruction.inherit_from(self._type_to_instruction[type_]) return instruction
python
{ "resource": "" }
q260862
FreeFormCov.eigh
validation
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 import svd if self._cache["eig"] is not None: return self._cache["eig"] U, S = svd(self.L)[:2] S *= S S += self._epsilon self._cache["eig"] = S, U return self._cache["eig"]
python
{ "resource": "" }
q260863
FreeFormCov.gradient
validation
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[0])): row = self._tril1[0][i] col = self._tril1[1][i] self._grad_Lu[row, :, i] = L[:, col] self._grad_Lu[:, row, i] += L[:, col] m = len(self._tril1[0]) for i in range(len(self._diag[0])): row = self._diag[0][i] col = self._diag[1][i] self._grad_Lu[row, :, m + i] = L[row, col] * L[:, col] self._grad_Lu[:, row, m + i] += L[row, col] * L[:, col] return {"Lu": self._grad_Lu}
python
{ "resource": "" }
q260864
Kron2SumCov.listen
validation
def listen(self, func): """ Listen to parameters change. Parameters ---------- func : callable Function to be called when a parameter changes. """ self._C0.listen(func) self._C1.listen(func)
python
{ "resource": "" }
q260865
Kron2SumCov.gradient
validation
def gradient(self): """ Gradient of K. Returns ------- C0 : ndarray Derivative of C₀ over its parameters. C1 : ndarray Derivative of C₁ over its parameters. """ self._init_svd() C0 = self._C0.gradient()["Lu"].T C1 = self._C1.gradient()["Lu"].T grad = {"C0.Lu": kron(C0, self._X).T, "C1.Lu": kron(C1, self._I).T} return grad
python
{ "resource": "" }
q260866
rsolve
validation
def rsolve(A, y): """ Robust solve Ax=y. """ from numpy_sugar.linalg import rsolve as _rsolve try: beta = _rsolve(A, y) except LinAlgError: msg = "Could not converge to solve Ax=y." msg += " Setting x to zero." warnings.warn(msg, RuntimeWarning) beta = zeros(A.shape[0]) return beta
python
{ "resource": "" }
q260867
multivariate_normal
validation
def multivariate_normal(random, mean, cov): """ Draw random samples from a multivariate normal distribution. Parameters ---------- random : np.random.RandomState instance Random state. mean : array_like Mean of the n-dimensional distribution. cov : array_like Covariance matrix of the distribution. It must be symmetric and positive-definite for proper sampling. Returns ------- out : ndarray The drawn sample. """ from numpy.linalg import cholesky L = cholesky(cov) return L @ random.randn(L.shape[0]) + mean
python
{ "resource": "" }
q260868
SumCov.gradient
validation
def gradient(self): """ Sum of covariance function derivatives. Returns ------- dict ∂K₀ + ∂K₁ + ⋯ """ grad = {} for i, f in enumerate(self._covariances): for varname, g in f.gradient().items(): grad[f"{self._name}[{i}].{varname}"] = g return grad
python
{ "resource": "" }
q260869
KronMean.B
validation
def B(self): """ Effect-sizes parameter, B. """ return unvec(self._vecB.value, (self.X.shape[1], self.A.shape[0]))
python
{ "resource": "" }
q260870
bernoulli_sample
validation
def bernoulli_sample( offset, G, heritability=0.5, causal_variants=None, causal_variance=0, random_state=None, ): r"""Bernoulli likelihood sampling. Sample according to .. math:: \mathbf y \sim \prod_{i=1}^n \text{Bernoulli}(\mu_i = \text{logit}(z_i)) \mathcal N(~ o \mathbf 1 + \mathbf a^\intercal \boldsymbol\alpha; ~ (h^2 - v_c)\mathrm G^\intercal\mathrm G + (1-h^2-v_c)\mathrm I ~) using the canonical Logit link function to define the conditional Bernoulli mean :math:`\mu_i`. The causal :math:`\mathbf a` covariates and the corresponding effect-sizes are randomly draw according to the following idea. The ``causal_variants``, if given, are first mean-zero and std-one normalized and then having its elements divided by the squared-root the the number of variances:: causal_variants = _stdnorm(causal_variants, axis=0) causal_variants /= sqrt(causal_variants.shape[1]) The causal effect-sizes :math:`\boldsymbol\alpha` are draw from :math:`\{-1, +1\}` and subsequently normalized for mean-zero and std-one"" Parameters ---------- random_state : random_state Set the initial random state. Example ------- .. doctest:: >>> from glimix_core.random import bernoulli_sample >>> from numpy.random import RandomState >>> offset = 5 >>> G = [[1, -1], [2, 1]] >>> bernoulli_sample(offset, G, random_state=RandomState(0)) array([1., 1.]) """ link = LogitLink() mean, cov = _mean_cov( offset, G, heritability, causal_variants, causal_variance, random_state ) lik = BernoulliProdLik(link) sampler = GGPSampler(lik, mean, cov) return sampler.sample(random_state)
python
{ "resource": "" }
q260871
poisson_sample
validation
def poisson_sample( offset, G, heritability=0.5, causal_variants=None, causal_variance=0, random_state=None, ): """Poisson likelihood sampling. Parameters ---------- random_state : random_state Set the initial random state. Example ------- .. doctest:: >>> from glimix_core.random import poisson_sample >>> from numpy.random import RandomState >>> offset = -0.5 >>> G = [[0.5, -1], [2, 1]] >>> poisson_sample(offset, G, random_state=RandomState(0)) array([0, 6]) """ mean, cov = _mean_cov( offset, G, heritability, causal_variants, causal_variance, random_state ) link = LogLink() lik = PoissonProdLik(link) sampler = GGPSampler(lik, mean, cov) return sampler.sample(random_state)
python
{ "resource": "" }
q260872
GLMM.covariance
validation
def covariance(self): r"""Covariance of the prior. Returns ------- :class:`numpy.ndarray` :math:`v_0 \mathrm K + v_1 \mathrm I`. """ from numpy_sugar.linalg import ddot, sum2diag Q0 = self._QS[0][0] S0 = self._QS[1] return sum2diag(dot(ddot(Q0, self.v0 * S0), Q0.T), self.v1)
python
{ "resource": "" }
q260873
GLMM.posteriori_mean
validation
def posteriori_mean(self): r""" Mean of the estimated posteriori. This is also the maximum a posteriori estimation of the latent variable. """ from numpy_sugar.linalg import rsolve Sigma = self.posteriori_covariance() eta = self._ep._posterior.eta return dot(Sigma, eta + rsolve(GLMM.covariance(self), self.mean()))
python
{ "resource": "" }
q260874
GLMM.posteriori_covariance
validation
def posteriori_covariance(self): r""" Covariance of the estimated posteriori.""" K = GLMM.covariance(self) tau = self._ep._posterior.tau return pinv(pinv(K) + diag(1 / tau))
python
{ "resource": "" }
q260875
FastScanner.fast_scan
validation
def fast_scan(self, M, verbose=True): """ LMLs, fixed-effect sizes, and scales for single-marker scan. Parameters ---------- M : array_like Matrix of fixed-effects across columns. verbose : bool, optional ``True`` for progress information; ``False`` otherwise. Defaults to ``True``. Returns ------- lmls : ndarray Log of the marginal likelihoods. effsizes0 : ndarray Covariate fixed-effect sizes. effsizes1 : ndarray Candidate set fixed-effect sizes. scales : ndarray Scales. """ from tqdm import tqdm if M.ndim != 2: raise ValueError("`M` array must be bidimensional.") p = M.shape[1] lmls = empty(p) effsizes0 = empty((p, self._XTQ[0].shape[0])) effsizes0_se = empty((p, self._XTQ[0].shape[0])) effsizes1 = empty(p) effsizes1_se = empty(p) scales = empty(p) if verbose: nchunks = min(p, 30) else: nchunks = min(p, 1) chunk_size = (p + nchunks - 1) // nchunks for i in tqdm(range(nchunks), desc="Scanning", disable=not verbose): start = i * chunk_size stop = min(start + chunk_size, M.shape[1]) r = self._fast_scan_chunk(M[:, start:stop]) lmls[start:stop] = r["lml"] effsizes0[start:stop, :] = r["effsizes0"] effsizes0_se[start:stop, :] = r["effsizes0_se"] effsizes1[start:stop] = r["effsizes1"] effsizes1_se[start:stop] = r["effsizes1_se"] scales[start:stop] = r["scale"] return { "lml": lmls, "effsizes0": effsizes0, "effsizes0_se": effsizes0_se, "effsizes1": effsizes1, "effsizes1_se": effsizes1_se, "scale": scales, }
python
{ "resource": "" }
q260876
GGPSampler.sample
validation
def sample(self, random_state=None): r"""Sample from the specified distribution. Parameters ---------- random_state : random_state Set the initial random state. Returns ------- numpy.ndarray Sample. """ from numpy_sugar import epsilon from numpy_sugar.linalg import sum2diag from numpy_sugar.random import multivariate_normal if random_state is None: random_state = RandomState() m = self._mean.value() K = self._cov.value().copy() sum2diag(K, +epsilon.small, out=K) return self._lik.sample(multivariate_normal(m, K, random_state), random_state)
python
{ "resource": "" }
q260877
economic_qs_zeros
validation
def economic_qs_zeros(n): """Eigen decomposition of a zero matrix.""" Q0 = empty((n, 0)) Q1 = eye(n) S0 = empty(0) return ((Q0, Q1), S0)
python
{ "resource": "" }
q260878
GLMMExpFam.gradient
validation
def gradient(self): r"""Gradient of the log of the marginal likelihood. Returns ------- dict Map between variables to their gradient values. """ self._update_approx() g = self._ep.lml_derivatives(self._X) ed = exp(-self.logitdelta) es = exp(self.logscale) grad = dict() grad["logitdelta"] = g["delta"] * (ed / (1 + ed)) / (1 + ed) grad["logscale"] = g["scale"] * es grad["beta"] = g["mean"] return grad
python
{ "resource": "" }
q260879
LRFreeFormCov.gradient
validation
def gradient(self): """ Derivative of the covariance matrix over the lower triangular, flat part of L. It is equal to ∂K/∂Lᵢⱼ = ALᵀ + LAᵀ, where Aᵢⱼ is an n×m matrix of zeros except at [Aᵢⱼ]ᵢⱼ=1. Returns ------- Lu : ndarray Derivative of K over the lower-triangular, flat part of L. """ L = self.L n = self.L.shape[0] grad = {"Lu": zeros((n, n, n * self._L.shape[1]))} for ii in range(self._L.shape[0] * self._L.shape[1]): row = ii // self._L.shape[1] col = ii % self._L.shape[1] grad["Lu"][row, :, ii] = L[:, col] grad["Lu"][:, row, ii] += L[:, col] return grad
python
{ "resource": "" }
q260880
LMM.beta
validation
def beta(self): """ Fixed-effect sizes. Returns ------- effect-sizes : numpy.ndarray Optimal fixed-effect sizes. Notes ----- Setting the derivative of log(p(𝐲)) over effect sizes equal to zero leads to solutions 𝜷 from equation :: (QᵀX)ᵀD⁻¹(QᵀX)𝜷 = (QᵀX)ᵀD⁻¹(Qᵀ𝐲). """ from numpy_sugar.linalg import rsolve return rsolve(self._X["VT"], rsolve(self._X["tX"], self.mean()))
python
{ "resource": "" }
q260881
LMM.beta_covariance
validation
def beta_covariance(self): """ Estimates the covariance-matrix of the optimal beta. Returns ------- beta-covariance : ndarray (Xᵀ(s((1-𝛿)K + 𝛿I))⁻¹X)⁻¹. References ---------- .. Rencher, A. C., & Schaalje, G. B. (2008). Linear models in statistics. John Wiley & Sons. """ from numpy_sugar.linalg import ddot tX = self._X["tX"] Q = concatenate(self._QS[0], axis=1) S0 = self._QS[1] D = self.v0 * S0 + self.v1 D = D.tolist() + [self.v1] * (len(self._y) - len(D)) D = asarray(D) A = inv(tX.T @ (Q @ ddot(1 / D, Q.T @ tX))) VT = self._X["VT"] H = lstsq(VT, A, rcond=None)[0] return lstsq(VT, H.T, rcond=None)[0]
python
{ "resource": "" }
q260882
LMM.fix
validation
def fix(self, param): """ Disable parameter optimization. Parameters ---------- param : str Possible values are ``"delta"``, ``"beta"``, and ``"scale"``. """ if param == "delta": super()._fix("logistic") else: self._fix[param] = True
python
{ "resource": "" }
q260883
LMM.unfix
validation
def unfix(self, param): """ Enable parameter optimization. Parameters ---------- param : str Possible values are ``"delta"``, ``"beta"``, and ``"scale"``. """ if param == "delta": self._unfix("logistic") else: self._fix[param] = False
python
{ "resource": "" }
q260884
LMM.fit
validation
def fit(self, verbose=True): """ Maximise the marginal likelihood. Parameters ---------- verbose : bool, optional ``True`` for progress output; ``False`` otherwise. Defaults to ``True``. """ if not self._isfixed("logistic"): self._maximize_scalar(desc="LMM", rtol=1e-6, atol=1e-6, verbose=verbose) if not self._fix["beta"]: self._update_beta() if not self._fix["scale"]: self._update_scale()
python
{ "resource": "" }
q260885
LMM.value
validation
def value(self): """ Internal use only. """ if not self._fix["beta"]: self._update_beta() if not self._fix["scale"]: self._update_scale() return self.lml()
python
{ "resource": "" }
q260886
LMM.delta
validation
def delta(self): """ Variance ratio between ``K`` and ``I``. """ v = float(self._logistic.value) if v > 0.0: v = 1 / (1 + exp(-v)) else: v = exp(v) v = v / (v + 1.0) return min(max(v, epsilon.tiny), 1 - epsilon.tiny)
python
{ "resource": "" }
q260887
LMM._lml_optimal_scale
validation
def _lml_optimal_scale(self): """ Log of the marginal likelihood for optimal scale. Implementation for unrestricted LML:: Returns ------- lml : float Log of the marginal likelihood. """ assert self._optimal["scale"] n = len(self._y) lml = -self._df * log2pi - self._df - n * log(self.scale) lml -= sum(npsum(log(D)) for D in self._D) return lml / 2
python
{ "resource": "" }
q260888
LMM._lml_arbitrary_scale
validation
def _lml_arbitrary_scale(self): """ Log of the marginal likelihood for arbitrary scale. Returns ------- lml : float Log of the marginal likelihood. """ s = self.scale D = self._D n = len(self._y) lml = -self._df * log2pi - n * log(s) lml -= sum(npsum(log(d)) for d in D) d = (mTQ - yTQ for (mTQ, yTQ) in zip(self._mTQ, self._yTQ)) lml -= sum((i / j) @ i for (i, j) in zip(d, D)) / s return lml / 2
python
{ "resource": "" }
q260889
LMM._df
validation
def _df(self): """ Degrees of freedom. """ if not self._restricted: return self.nsamples return self.nsamples - self._X["tX"].shape[1]
python
{ "resource": "" }
q260890
GLMMNormal.value
validation
def value(self): r"""Log of the marginal likelihood. Formally, .. math:: - \frac{n}{2}\log{2\pi} - \frac{1}{2} \log{\left| v_0 \mathrm K + v_1 \mathrm I + \tilde{\Sigma} \right|} - \frac{1}{2} \left(\tilde{\boldsymbol\mu} - \mathrm X\boldsymbol\beta\right)^{\intercal} \left( v_0 \mathrm K + v_1 \mathrm I + \tilde{\Sigma} \right)^{-1} \left(\tilde{\boldsymbol\mu} - \mathrm X\boldsymbol\beta\right) Returns ------- float :math:`\log{p(\tilde{\boldsymbol\mu})}` """ from numpy_sugar.linalg import ddot, sum2diag if self._cache["value"] is not None: return self._cache["value"] scale = exp(self.logscale) delta = 1 / (1 + exp(-self.logitdelta)) v0 = scale * (1 - delta) v1 = scale * delta mu = self.eta / self.tau n = len(mu) if self._QS is None: K = zeros((n, n)) else: Q0 = self._QS[0][0] S0 = self._QS[1] K = dot(ddot(Q0, S0), Q0.T) A = sum2diag(sum2diag(v0 * K, v1), 1 / self.tau) m = mu - self.mean() v = -n * log(2 * pi) v -= slogdet(A)[1] v -= dot(m, solve(A, m)) self._cache["value"] = v / 2 return self._cache["value"]
python
{ "resource": "" }
q260891
Posterior._initialize
validation
def _initialize(self): r"""Initialize the mean and covariance of the posterior. Given that :math:`\tilde{\mathrm T}` is a matrix of zeros right before the first EP iteration, we have .. math:: \boldsymbol\mu = \mathrm K^{-1} \mathbf m ~\text{ and }~ \Sigma = \mathrm K as the initial posterior mean and covariance. """ if self._mean is None or self._cov is None: return Q = self._cov["QS"][0][0] S = self._cov["QS"][1] if S.size > 0: self.tau[:] = 1 / npsum((Q * sqrt(S)) ** 2, axis=1) else: self.tau[:] = 0.0 self.eta[:] = self._mean self.eta[:] *= self.tau
python
{ "resource": "" }
q260892
build_engine_session
validation
def build_engine_session(connection, echo=False, autoflush=None, autocommit=None, expire_on_commit=None, scopefunc=None): """Build an engine and a session. :param str connection: An RFC-1738 database connection string :param bool echo: Turn on echoing SQL :param Optional[bool] autoflush: Defaults to True if not specified in kwargs or configuration. :param Optional[bool] autocommit: Defaults to False if not specified in kwargs or configuration. :param Optional[bool] expire_on_commit: Defaults to False if not specified in kwargs or configuration. :param scopefunc: Scoped function to pass to :func:`sqlalchemy.orm.scoped_session` :rtype: tuple[Engine,Session] From the Flask-SQLAlchemy documentation: An extra key ``'scopefunc'`` can be set on the ``options`` dict to specify a custom scope function. If it's not provided, Flask's app context stack identity is used. This will ensure that sessions are created and removed with the request/response cycle, and should be fine in most cases. """ if connection is None: raise ValueError('can not build engine when connection is None') engine = create_engine(connection, echo=echo) autoflush = autoflush if autoflush is not None else False autocommit = autocommit if autocommit is not None else False expire_on_commit = expire_on_commit if expire_on_commit is not None else True log.debug('auto flush: %s, auto commit: %s, expire on commmit: %s', autoflush, autocommit, expire_on_commit) #: A SQLAlchemy session maker session_maker = sessionmaker( bind=engine, autoflush=autoflush, autocommit=autocommit, expire_on_commit=expire_on_commit, ) #: A SQLAlchemy session object session = scoped_session( session_maker, scopefunc=scopefunc ) return engine, session
python
{ "resource": "" }
q260893
ConnectionManager._get_connection
validation
def _get_connection(cls, connection: Optional[str] = None) -> str: """Get a default connection string. Wraps :func:`bio2bel.utils.get_connection` and passing this class's :data:`module_name` to it. """ return get_connection(cls.module_name, connection=connection)
python
{ "resource": "" }
q260894
setup_smtp_factory
validation
def setup_smtp_factory(**settings): """ expects a dictionary with 'mail.' keys to create an appropriate smtplib.SMTP instance""" return CustomSMTP( host=settings.get('mail.host', 'localhost'), port=int(settings.get('mail.port', 25)), user=settings.get('mail.user'), password=settings.get('mail.password'), timeout=float(settings.get('mail.timeout', 60)), )
python
{ "resource": "" }
q260895
sendMultiPart
validation
def sendMultiPart(smtp, gpg_context, sender, recipients, subject, text, attachments): """ a helper method that composes and sends an email with attachments requires a pre-configured smtplib.SMTP instance""" sent = 0 for to in recipients: if not to.startswith('<'): uid = '<%s>' % to else: uid = to if not checkRecipient(gpg_context, uid): continue msg = MIMEMultipart() msg['From'] = sender msg['To'] = to msg['Subject'] = subject msg["Date"] = formatdate(localtime=True) msg.preamble = u'This is an email in encrypted multipart format.' attach = MIMEText(str(gpg_context.encrypt(text.encode('utf-8'), uid, always_trust=True))) attach.set_charset('UTF-8') msg.attach(attach) for attachment in attachments: with open(attachment, 'rb') as fp: attach = MIMEBase('application', 'octet-stream') attach.set_payload(str(gpg_context.encrypt_file(fp, uid, always_trust=True))) attach.add_header('Content-Disposition', 'attachment', filename=basename('%s.pgp' % attachment)) msg.attach(attach) # TODO: need to catch exception? # yes :-) we need to adjust the status accordingly (>500 so it will be destroyed) smtp.begin() smtp.sendmail(sender, to, msg.as_string()) smtp.quit() sent += 1 return sent
python
{ "resource": "" }
q260896
CustomSMTP.begin
validation
def begin(self): """ connects and optionally authenticates a connection.""" self.connect(self.host, self.port) if self.user: self.starttls() self.login(self.user, self.password)
python
{ "resource": "" }
q260897
make_downloader
validation
def make_downloader(url: str, path: str) -> Callable[[bool], str]: # noqa: D202 """Make a function that downloads the data for you, or uses a cached version at the given path. :param url: The URL of some data :param path: The path of the cached data, or where data is cached if it does not already exist :return: A function that downloads the data and returns the path of the data """ def download_data(force_download: bool = False) -> str: """Download the data. :param force_download: If true, overwrites a previously cached file """ if os.path.exists(path) and not force_download: log.info('using cached data at %s', path) else: log.info('downloading %s to %s', url, path) urlretrieve(url, path) return path return download_data
python
{ "resource": "" }
q260898
make_df_getter
validation
def make_df_getter(data_url: str, data_path: str, **kwargs) -> Callable[[Optional[str], bool, bool], pd.DataFrame]: """Build a function that handles downloading tabular data and parsing it into a pandas DataFrame. :param data_url: The URL of the data :param data_path: The path where the data should get stored :param kwargs: Any other arguments to pass to :func:`pandas.read_csv` """ download_function = make_downloader(data_url, data_path) def get_df(url: Optional[str] = None, cache: bool = True, force_download: bool = False) -> pd.DataFrame: """Get the data as a pandas DataFrame. :param url: The URL (or file path) to download. :param cache: If true, the data is downloaded to the file system, else it is loaded from the internet :param force_download: If true, overwrites a previously cached file """ if url is None and cache: url = download_function(force_download=force_download) return pd.read_csv( url or data_url, **kwargs ) return get_df
python
{ "resource": "" }
q260899
decode_timestamp
validation
def decode_timestamp(data: str) -> datetime.datetime: """ Decode timestamp using bespoke decoder. Cannot use simple strptime since the ness panel contains a bug that P199E zone and state updates emitted on the hour cause a minute value of `60` to be sent, causing strptime to fail. This decoder handles this edge case. """ year = 2000 + int(data[0:2]) month = int(data[2:4]) day = int(data[4:6]) hour = int(data[6:8]) minute = int(data[8:10]) second = int(data[10:12]) if minute == 60: minute = 0 hour += 1 return datetime.datetime(year=year, month=month, day=day, hour=hour, minute=minute, second=second)
python
{ "resource": "" }