signature stringlengths 8 3.44k | body stringlengths 0 1.41M | docstring stringlengths 1 122k | id stringlengths 5 17 |
|---|---|---|---|
@property<EOL><INDENT>@abstractmethod<EOL>def rowcount(self) -> int:<DEDENT> | pass<EOL> | See https://www.python.org/dev/peps/pep-0249/#cursor-objects | f14561:c2:m5 |
@abstractmethod<EOL><INDENT>def callproc(self, procname: str, *args, **kwargs) -> None:<DEDENT> | pass<EOL> | See https://www.python.org/dev/peps/pep-0249/#cursor-objects | f14561:c2:m6 |
@abstractmethod<EOL><INDENT>def close(self) -> None:<DEDENT> | pass<EOL> | See https://www.python.org/dev/peps/pep-0249/#cursor-objects | f14561:c2:m7 |
@abstractmethod<EOL><INDENT>def execute(self, operation: str, *args, **kwargs) -> None:<DEDENT> | pass<EOL> | See https://www.python.org/dev/peps/pep-0249/#cursor-objects | f14561:c2:m8 |
@abstractmethod<EOL><INDENT>def executemany(self, operation: str, *args, **kwargs) -> None:<DEDENT> | pass<EOL> | See https://www.python.org/dev/peps/pep-0249/#cursor-objects | f14561:c2:m9 |
@abstractmethod<EOL><INDENT>def fetchone(self) -> Optional[_DATABASE_ROW_TYPE]:<DEDENT> | pass<EOL> | See https://www.python.org/dev/peps/pep-0249/#cursor-objects | f14561:c2:m10 |
@abstractmethod<EOL><INDENT>def fetchmany(self, size: int = None) -> Sequence[_DATABASE_ROW_TYPE]:<DEDENT> | pass<EOL> | See https://www.python.org/dev/peps/pep-0249/#cursor-objects | f14561:c2:m11 |
@abstractmethod<EOL><INDENT>def fetchall(self) -> Sequence[_DATABASE_ROW_TYPE]:<DEDENT> | pass<EOL> | See https://www.python.org/dev/peps/pep-0249/#cursor-objects | f14561:c2:m12 |
@abstractmethod<EOL><INDENT>def nextset(self) -> Optional[bool]:<DEDENT> | pass<EOL> | See https://www.python.org/dev/peps/pep-0249/#cursor-objects | f14561:c2:m13 |
@property<EOL><INDENT>@abstractmethod<EOL>def arraysize(self) -> int:<DEDENT> | <EOL>pass<EOL> | See https://www.python.org/dev/peps/pep-0249/#cursor-objects | f14561:c2:m14 |
@arraysize.setter<EOL><INDENT>@abstractmethod<EOL>def arraysize(self, val: int) -> None:<DEDENT> | <EOL>pass<EOL> | See https://www.python.org/dev/peps/pep-0249/#cursor-objects | f14561:c2:m15 |
@abstractmethod<EOL><INDENT>def setinputsizes(self, sizes: Sequence[Union[Type, int]]) -> None:<DEDENT> | pass<EOL> | See https://www.python.org/dev/peps/pep-0249/#cursor-objects | f14561:c2:m16 |
@abstractmethod<EOL><INDENT>def setoutputsize(self, size: int, column: Optional[int]) -> None:<DEDENT> | pass<EOL> | See https://www.python.org/dev/peps/pep-0249/#cursor-objects | f14561:c2:m17 |
@property<EOL><INDENT>@abstractmethod<EOL>def connection(self) -> Pep249DatabaseConnectionType:<DEDENT> | pass<EOL> | See
https://www.python.org/dev/peps/pep-0249/#optional-db-api-extensions | f14561:c2:m18 |
@property<EOL><INDENT>@abstractmethod<EOL>def lastrowid(self) -> Optional[int]:<DEDENT> | pass<EOL> | See
https://www.python.org/dev/peps/pep-0249/#optional-db-api-extensions | f14561:c2:m19 |
@property<EOL><INDENT>@abstractmethod<EOL>def rownumber(self) -> Optional[int]:<DEDENT> | pass<EOL> | See
https://www.python.org/dev/peps/pep-0249/#optional-db-api-extensions | f14561:c2:m20 |
@abstractmethod<EOL><INDENT>def scroll(self, value: int, mode: str = '<STR_LIT>') -> None:<DEDENT> | pass<EOL> | See
https://www.python.org/dev/peps/pep-0249/#optional-db-api-extensions | f14561:c2:m21 |
@property<EOL><INDENT>@abstractmethod<EOL>def messages(self) -> List[Tuple[Type, Any]]:<DEDENT> | pass<EOL> | See
https://www.python.org/dev/peps/pep-0249/#optional-db-api-extensions | f14561:c2:m22 |
@abstractmethod<EOL><INDENT>def next(self) -> _DATABASE_ROW_TYPE:<DEDENT> | pass<EOL> | See
https://www.python.org/dev/peps/pep-0249/#optional-db-api-extensions | f14561:c2:m23 |
def repr_result(obj: Any, elements: List[str],<EOL>with_addr: bool = False, joiner: str = COMMA_SPACE) -> str: | if with_addr:<EOL><INDENT>return "<STR_LIT>".format(<EOL>qualname=obj.__class__.__qualname__,<EOL>elements=joiner.join(elements),<EOL>addr=hex(id(obj)))<EOL><DEDENT>else:<EOL><INDENT>return "<STR_LIT>".format(<EOL>qualname=obj.__class__.__qualname__,<EOL>elements=joiner.join(elements))<EOL><DEDENT> | Internal function to make a :func:`repr`-style representation of an object.
Args:
obj: object to display
elements: list of object ``attribute=value`` strings
with_addr: include the memory address of ``obj``
joiner: string with which to join the elements
Returns:
string: :func:`repr`-style representation | f14562:m0 |
def auto_repr(obj: Any, with_addr: bool = False,<EOL>sort_attrs: bool = True, joiner: str = COMMA_SPACE) -> str: | if sort_attrs:<EOL><INDENT>keys = sorted(obj.__dict__.keys())<EOL><DEDENT>else:<EOL><INDENT>keys = obj.__dict__.keys()<EOL><DEDENT>elements = ["<STR_LIT>".format(k, repr(getattr(obj, k))) for k in keys]<EOL>return repr_result(obj, elements, with_addr=with_addr, joiner=joiner)<EOL> | Convenience function for :func:`__repr__`.
Works its way through the object's ``__dict__`` and reports accordingly.
Args:
obj: object to display
with_addr: include the memory address of ``obj``
sort_attrs: sort the attributes into alphabetical order?
joiner: string with which to join the elements
Returns:
string: :func:`repr`-style representation | f14562:m1 |
def simple_repr(obj: Any, attrnames: List[str],<EOL>with_addr: bool = False, joiner: str = COMMA_SPACE) -> str: | elements = ["<STR_LIT>".format(name, repr(getattr(obj, name)))<EOL>for name in attrnames]<EOL>return repr_result(obj, elements, with_addr=with_addr, joiner=joiner)<EOL> | Convenience function for :func:`__repr__`.
Works its way through a list of attribute names, and creates a ``repr()``
representation assuming that parameters to the constructor have the same
names.
Args:
obj: object to display
attrnames: names of attributes to include
with_addr: include the memory address of ``obj``
joiner: string with which to join the elements
Returns:
string: :func:`repr`-style representation | f14562:m2 |
def mapped_repr(obj: Any, attributes: List[Tuple[str, str]],<EOL>with_addr: bool = False, joiner: str = COMMA_SPACE) -> str: | elements = ["<STR_LIT>".format(init_param_name, repr(getattr(obj, attr_name)))<EOL>for attr_name, init_param_name in attributes]<EOL>return repr_result(obj, elements, with_addr=with_addr, joiner=joiner)<EOL> | Convenience function for :func:`__repr__`.
Takes attribute names and corresponding initialization parameter names
(parameters to :func:`__init__`).
Args:
obj: object to display
attributes: list of tuples, each ``(attr_name, init_param_name)``.
with_addr: include the memory address of ``obj``
joiner: string with which to join the elements
Returns:
string: :func:`repr`-style representation | f14562:m3 |
def mapped_repr_stripping_underscores(<EOL>obj: Any, attrnames: List[str],<EOL>with_addr: bool = False, joiner: str = COMMA_SPACE) -> str: | attributes = []<EOL>for attr_name in attrnames:<EOL><INDENT>if attr_name.startswith('<STR_LIT:_>'):<EOL><INDENT>init_param_name = attr_name[<NUM_LIT:1>:]<EOL><DEDENT>else:<EOL><INDENT>init_param_name = attr_name<EOL><DEDENT>attributes.append((attr_name, init_param_name))<EOL><DEDENT>return mapped_repr(obj, attributes, with_addr=with_addr, joiner=joiner)<EOL> | Convenience function for :func:`__repr__`.
Here, you pass a list of internal attributes, and it assumes that the
:func:`__init__` parameter names have the leading underscore dropped.
Args:
obj: object to display
attrnames: list of attribute names
with_addr: include the memory address of ``obj``
joiner: string with which to join the elements
Returns:
string: :func:`repr`-style representation | f14562:m4 |
def ordered_repr(obj: object, attrlist: Iterable[str],<EOL>joiner: str = COMMA_SPACE) -> str: | return "<STR_LIT>".format(<EOL>classname=type(obj).__name__,<EOL>kvp=joiner.join("<STR_LIT>".format(a, repr(getattr(obj, a)))<EOL>for a in attrlist)<EOL>)<EOL> | Shortcut to make :func:`repr` functions ordered.
Define your :func:`__repr__` like this:
.. code-block:: python
def __repr__(self):
return ordered_repr(self, ["field1", "field2", "field3"])
Args:
obj: object to display
attrlist: iterable of attribute names
joiner: string with which to join the elements
Returns:
string: :func:`repr`-style representation | f14562:m5 |
def auto_str(obj: Any, indent: int = <NUM_LIT:4>, width: int = <NUM_LIT>, depth: int = None,<EOL>compact: bool = False) -> str: | return pprint.pformat(obj.__dict__, indent=indent, width=width,<EOL>depth=depth, compact=compact)<EOL> | Make a pretty :func:`str()` representation using :func:`pprint.pformat`
and the object's ``__dict__`` attribute.
Args:
obj: object to display
indent: see
https://docs.python.org/3/library/pprint.html#pprint.PrettyPrinter
width: as above
depth: as above
compact: as above
Returns:
string: :func:`str`-style representation | f14562:m6 |
def get_fieldnames_from_cursor(cursor: Cursor) -> List[str]: | return [i[<NUM_LIT:0>] for i in cursor.description]<EOL> | Get a list of fieldnames from an executed cursor. | f14563:m0 |
def genrows(cursor: Cursor, arraysize: int = <NUM_LIT:1000>)-> Generator[List[Any], None, None]: | <EOL>while True:<EOL><INDENT>results = cursor.fetchmany(arraysize)<EOL>if not results:<EOL><INDENT>break<EOL><DEDENT>for result in results:<EOL><INDENT>yield result<EOL><DEDENT><DEDENT> | Generate all rows from a cursor.
Args:
cursor: the cursor
arraysize: split fetches into chunks of this many records
Yields:
each row | f14563:m1 |
def genfirstvalues(cursor: Cursor, arraysize: int = <NUM_LIT:1000>)-> Generator[Any, None, None]: | return (row[<NUM_LIT:0>] for row in genrows(cursor, arraysize))<EOL> | Generate the first value in each row.
Args:
cursor: the cursor
arraysize: split fetches into chunks of this many records
Yields:
the first value of each row | f14563:m2 |
def fetchallfirstvalues(cursor: Cursor) -> List[Any]: | return [row[<NUM_LIT:0>] for row in cursor.fetchall()]<EOL> | Return a list of the first value in each row. | f14563:m3 |
def gendicts(cursor: Cursor, arraysize: int = <NUM_LIT:1000>)-> Generator[Dict[str, Any], None, None]: | columns = get_fieldnames_from_cursor(cursor)<EOL>return (<EOL>OrderedDict(zip(columns, row))<EOL>for row in genrows(cursor, arraysize)<EOL>)<EOL> | Generate all rows from a cursor as :class:`OrderedDict` objects.
Args:
cursor: the cursor
arraysize: split fetches into chunks of this many records
Yields:
each row, as an :class:`OrderedDict` whose key are column names
and whose values are the row values | f14563:m4 |
def dictfetchall(cursor: Cursor) -> List[Dict[str, Any]]: | columns = get_fieldnames_from_cursor(cursor)<EOL>return [<EOL>OrderedDict(zip(columns, row))<EOL>for row in cursor.fetchall()<EOL>]<EOL> | Return all rows from a cursor as a list of :class:`OrderedDict` objects.
Args:
cursor: the cursor
Returns:
a list (one item per row) of :class:`OrderedDict` objects whose key are
column names and whose values are the row values | f14563:m5 |
def dictfetchone(cursor: Cursor) -> Optional[Dict[str, Any]]: | columns = get_fieldnames_from_cursor(cursor)<EOL>row = cursor.fetchone()<EOL>if not row:<EOL><INDENT>return None<EOL><DEDENT>return OrderedDict(zip(columns, row))<EOL> | Return the next row from a cursor as an :class:`OrderedDict`, or ``None``. | f14563:m6 |
def is_integer(s: Any) -> bool: | try:<EOL><INDENT>int(s)<EOL>return True<EOL><DEDENT>except ValueError:<EOL><INDENT>return False<EOL><DEDENT> | Is the parameter an integer? | f14564:m0 |
def raise_if_attr_blank(obj: Any, attrs: Iterable[str]) -> None: | for a in attrs:<EOL><INDENT>value = getattr(obj, a)<EOL>if value is None or value is "<STR_LIT>":<EOL><INDENT>raise Exception("<STR_LIT>".format(a))<EOL><DEDENT><DEDENT> | Raise an :exc:`Exception` if any of the attributes of ``obj`` named in
``attrs`` is ``None`` or is ``''``. | f14564:m1 |
def is_false(x: Any) -> bool: | <EOL>return not x and x is not None<EOL> | Positively false? Evaluates: ``not x and x is not None``. | f14564:m2 |
def assert_version_lt(version_str: str) -> None: | assert CARDINAL_PYTHONLIB_VERSION < Version(version_str), (<EOL>_get_version_failure_msg("<STR_LIT:<>", version_str)<EOL>)<EOL> | Asserts that the cardinal_pythonlib version is less than the value supplied
(as a semantic version string, e.g. "1.0.2"). | f14565:m1 |
def assert_version_le(version_str: str) -> None: | assert CARDINAL_PYTHONLIB_VERSION <= Version(version_str), (<EOL>_get_version_failure_msg("<STR_LIT>", version_str)<EOL>)<EOL> | Asserts that the cardinal_pythonlib version is less than or equal to the
value supplied (as a semantic version string, e.g. "1.0.2"). | f14565:m2 |
def assert_version_eq(version_str: str) -> None: | assert CARDINAL_PYTHONLIB_VERSION == Version(version_str), (<EOL>_get_version_failure_msg("<STR_LIT>", version_str)<EOL>)<EOL> | Asserts that the cardinal_pythonlib version is equal to the value supplied
(as a semantic version string, e.g. "1.0.2"). | f14565:m3 |
def assert_version_ge(version_str: str) -> None: | assert CARDINAL_PYTHONLIB_VERSION >= Version(version_str), (<EOL>_get_version_failure_msg("<STR_LIT>", version_str)<EOL>)<EOL> | Asserts that the cardinal_pythonlib version is greater than or equal to the
value supplied (as a semantic version string, e.g. "1.0.2"). | f14565:m4 |
def assert_version_gt(version_str: str) -> None: | assert CARDINAL_PYTHONLIB_VERSION > Version(version_str), (<EOL>_get_version_failure_msg("<STR_LIT:>>", version_str)<EOL>)<EOL> | Asserts that the cardinal_pythonlib version is greater than the value
supplied (as a semantic version string, e.g. "1.0.2"). | f14565:m5 |
@contextmanager<EOL>def smart_open(filename: str, mode: str = '<STR_LIT>', buffering: int = -<NUM_LIT:1>,<EOL>encoding: str = None, errors: str = None, newline: str = None,<EOL>closefd: bool = True) -> IO: | <EOL>if filename == '<STR_LIT:->':<EOL><INDENT>if mode is None or mode == '<STR_LIT>' or '<STR_LIT:r>' in mode:<EOL><INDENT>fh = sys.stdin<EOL><DEDENT>else:<EOL><INDENT>fh = sys.stdout<EOL><DEDENT><DEDENT>else:<EOL><INDENT>fh = open(filename, mode=mode,<EOL>buffering=buffering, encoding=encoding, errors=errors,<EOL>newline=newline, closefd=closefd)<EOL><DEDENT>try:<EOL><INDENT>yield fh<EOL><DEDENT>finally:<EOL><INDENT>if filename is not '<STR_LIT:->':<EOL><INDENT>fh.close()<EOL><DEDENT><DEDENT> | Context manager (for use with ``with``) that opens a filename and provides
a :class:`IO` object. If the filename is ``'-'``, however, then
``sys.stdin`` is used for reading and ``sys.stdout`` is used for writing. | f14566:m0 |
def writeline_nl(fileobj: TextIO, line: str) -> None: | fileobj.write(line + '<STR_LIT:\n>')<EOL> | Writes a line plus a terminating newline to the file. | f14566:m1 |
def writelines_nl(fileobj: TextIO, lines: Iterable[str]) -> None: | <EOL>bj.write('<STR_LIT:\n>'.join(lines) + '<STR_LIT:\n>')<EOL> | Writes lines, plus terminating newline characters, to the file.
(Since :func:`fileobj.writelines` doesn't add newlines...
http://stackoverflow.com/questions/13730107/writelines-writes-lines-without-newline-just-fills-the-file) | f14566:m2 |
def write_text(filename: str, text: str) -> None: | with open(filename, '<STR_LIT:w>') as f: <EOL><INDENT>print(text, file=f)<EOL><DEDENT> | Writes text to a file. | f14566:m3 |
def write_gzipped_text(basefilename: str, text: str) -> None: | <EOL>lename = basefilename + '<STR_LIT>'<EOL>esslevel = <NUM_LIT:9><EOL><INDENT>= <NUM_LIT:0><EOL><DEDENT>open(zipfilename, '<STR_LIT:wb>') as f:<EOL>ith gzip.GzipFile(basefilename, '<STR_LIT:wb>', compresslevel, f, mtime) as gz:<EOL><INDENT>with io.TextIOWrapper(gz) as tw:<EOL><INDENT>tw.write(text)<EOL><DEDENT><DEDENT> | Writes text to a file compressed with ``gzip`` (a ``.gz`` file).
The filename is used directly for the "inner" file and the extension
``.gz`` is appended to the "outer" (zipped) file's name.
This function exists primarily because Lintian wants non-timestamped gzip
files, or it complains:
- https://lintian.debian.org/tags/package-contains-timestamped-gzip.html
- See http://stackoverflow.com/questions/25728472/python-gzip-omit-the-original-filename-and-timestamp | f14566:m4 |
def get_lines_without_comments(filename: str) -> List[str]: | lines = []<EOL>with open(filename) as f:<EOL><INDENT>for line in f:<EOL><INDENT>line = line.partition('<STR_LIT:#>')[<NUM_LIT:0>] <EOL>line = line.rstrip()<EOL>line = line.lstrip()<EOL>if line:<EOL><INDENT>lines.append(line)<EOL><DEDENT><DEDENT><DEDENT>return lines<EOL> | Reads a file, and returns all lines as a list, left- and right-stripping
the lines and removing everything on a line after the first ``#``.
NOTE: does not cope well with quoted ``#`` symbols! | f14566:m5 |
def gen_textfiles_from_filenames(<EOL>filenames: Iterable[str]) -> Generator[TextIO, None, None]: | for filename in filenames:<EOL><INDENT>with open(filename) as f:<EOL><INDENT>yield f<EOL><DEDENT><DEDENT> | Generates file-like objects from a list of filenames.
Args:
filenames: iterable of filenames
Yields:
each file as a :class:`TextIO` object | f14566:m6 |
def gen_lines_from_textfiles(<EOL>files: Iterable[TextIO]) -> Generator[str, None, None]: | for file in files:<EOL><INDENT>for line in file:<EOL><INDENT>yield line<EOL><DEDENT><DEDENT> | Generates lines from file-like objects.
Args:
files: iterable of :class:`TextIO` objects
Yields:
each line of all the files | f14566:m7 |
def gen_lower(x: Iterable[str]) -> Generator[str, None, None]: | for string in x:<EOL><INDENT>yield string.lower()<EOL><DEDENT> | Args:
x: iterable of strings
Yields:
each string in lower case | f14566:m8 |
def gen_lines_from_binary_files(<EOL>files: Iterable[BinaryIO],<EOL>encoding: str = UTF8) -> Generator[str, None, None]: | for file in files:<EOL><INDENT>for byteline in file:<EOL><INDENT>line = byteline.decode(encoding).strip()<EOL>yield line<EOL><DEDENT><DEDENT> | Generates lines from binary files.
Strips out newlines.
Args:
files: iterable of :class:`BinaryIO` file-like objects
encoding: encoding to use
Yields:
each line of all the files | f14566:m9 |
def gen_files_from_zipfiles(<EOL>zipfilenames_or_files: Iterable[Union[str, BinaryIO]],<EOL>filespec: str,<EOL>on_disk: bool = False) -> Generator[BinaryIO, None, None]: | for zipfilename_or_file in zipfilenames_or_files:<EOL><INDENT>with zipfile.ZipFile(zipfilename_or_file) as zf:<EOL><INDENT>infolist = zf.infolist() <EOL>infolist.sort(key=attrgetter('<STR_LIT:filename>'))<EOL>for zipinfo in infolist:<EOL><INDENT>if not fnmatch.fnmatch(zipinfo.filename, filespec):<EOL><INDENT>continue<EOL><DEDENT>log.debug("<STR_LIT>", zipinfo.filename)<EOL>if on_disk:<EOL><INDENT>with tempfile.TemporaryDirectory() as tmpdir:<EOL><INDENT>zf.extract(zipinfo.filename, tmpdir)<EOL>diskfilename = os.path.join(tmpdir, zipinfo.filename)<EOL>with open(diskfilename, '<STR_LIT:rb>') as subfile:<EOL><INDENT>yield subfile<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>with zf.open(zipinfo.filename) as subfile:<EOL><INDENT>yield subfile<EOL><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT> | Args:
zipfilenames_or_files: iterable of filenames or :class:`BinaryIO`
file-like objects, giving the ``.zip`` files
filespec: filespec to filter the "inner" files against
on_disk: if ``True``, extracts inner files to disk yields file-like
objects that access disk files (and are therefore seekable); if
``False``, extracts them in memory and yields file-like objects to
those memory files (which will not be seekable; e.g.
https://stackoverflow.com/questions/12821961/)
Yields:
file-like object for each inner file matching ``filespec``; may be
in memory or on disk, as per ``on_disk`` | f14566:m10 |
def gen_part_from_line(lines: Iterable[str],<EOL>part_index: int,<EOL>splitter: str = None) -> Generator[str, None, None]: | for line in lines:<EOL><INDENT>parts = line.split(splitter)<EOL>yield parts[part_index]<EOL><DEDENT> | Splits lines with ``splitter`` and yields a specified part by index.
Args:
lines: iterable of strings
part_index: index of part to yield
splitter: string to split the lines on
Yields:
the specified part for each line | f14566:m11 |
def gen_part_from_iterables(iterables: Iterable[Any],<EOL>part_index: int) -> Generator[Any, None, None]: | <EOL>for iterable in iterables:<EOL><INDENT>yield iterable[part_index]<EOL><DEDENT> | r"""
Yields the *n*\ th part of each thing in ``iterables``.
Args:
iterables: iterable of anything
part_index: part index
Yields:
``item[part_index] for item in iterable`` | f14566:m12 |
def gen_rows_from_csv_binfiles(<EOL>csv_files: Iterable[BinaryIO],<EOL>encoding: str = UTF8,<EOL>skip_header: bool = False,<EOL>**csv_reader_kwargs) -> Generator[Iterable[str], None, None]: | dialect = csv_reader_kwargs.pop('<STR_LIT>', None)<EOL>for csv_file_bin in csv_files:<EOL><INDENT>csv_file = io.TextIOWrapper(csv_file_bin, encoding=encoding)<EOL>thisfile_dialect = dialect<EOL>if thisfile_dialect is None:<EOL><INDENT>thisfile_dialect = csv.Sniffer().sniff(csv_file.read(<NUM_LIT>))<EOL>csv_file.seek(<NUM_LIT:0>)<EOL><DEDENT>reader = csv.reader(csv_file, dialect=thisfile_dialect,<EOL>**csv_reader_kwargs)<EOL>first = True<EOL>for row in reader:<EOL><INDENT>if first:<EOL><INDENT>first = False<EOL>if skip_header:<EOL><INDENT>continue<EOL><DEDENT><DEDENT>yield row<EOL><DEDENT><DEDENT> | Iterate through binary file-like objects that are CSV files in a specified
encoding. Yield each row.
Args:
csv_files: iterable of :class:`BinaryIO` objects
encoding: encoding to use
skip_header: skip the header (first) row of each file?
csv_reader_kwargs: arguments to pass to :func:`csv.reader`
Yields:
rows from the files | f14566:m13 |
def webify_file(srcfilename: str, destfilename: str) -> None: | with open(srcfilename) as infile, open(destfilename, '<STR_LIT:w>') as ofile:<EOL><INDENT>for line_ in infile:<EOL><INDENT>ofile.write(escape(line_))<EOL><DEDENT><DEDENT> | Rewrites a file from ``srcfilename`` to ``destfilename``, HTML-escaping it
in the process. | f14566:m14 |
def remove_gzip_timestamp(filename: str,<EOL>gunzip_executable: str = "<STR_LIT>",<EOL>gzip_executable: str = "<STR_LIT>",<EOL>gzip_args: List[str] = None) -> None: | gzip_args = gzip_args or [<EOL>"<STR_LIT>", <EOL>"<STR_LIT>",<EOL>]<EOL>with tempfile.TemporaryDirectory() as dir_:<EOL><INDENT>basezipfilename = os.path.basename(filename)<EOL>newzip = os.path.join(dir_, basezipfilename)<EOL>with open(newzip, '<STR_LIT:wb>') as z:<EOL><INDENT>log.info(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>",<EOL>basezipfilename, newzip)<EOL>p1 = subprocess.Popen([gunzip_executable, "<STR_LIT:-c>", filename],<EOL>stdout=subprocess.PIPE)<EOL>p2 = subprocess.Popen([gzip_executable] + gzip_args,<EOL>stdin=p1.stdout, stdout=z)<EOL>p2.communicate()<EOL><DEDENT>shutil.copyfile(newzip, filename)<EOL><DEDENT> | Uses external ``gunzip``/``gzip`` tools to remove a ``gzip`` timestamp.
Necessary for Lintian. | f14566:m15 |
def replace_in_file(filename: str, text_from: str, text_to: str) -> None: | log.info("<STR_LIT>",<EOL>filename, repr(text_from), repr(text_to))<EOL>with open(filename) as infile:<EOL><INDENT>contents = infile.read()<EOL><DEDENT>contents = contents.replace(text_from, text_to)<EOL>with open(filename, '<STR_LIT:w>') as outfile:<EOL><INDENT>outfile.write(contents)<EOL><DEDENT> | Replaces text in a file.
Args:
filename: filename to process (modifying it in place)
text_from: original text to replace
text_to: replacement text | f14566:m16 |
def replace_multiple_in_file(filename: str,<EOL>replacements: List[Tuple[str, str]]) -> None: | with open(filename) as infile:<EOL><INDENT>contents = infile.read()<EOL><DEDENT>for text_from, text_to in replacements:<EOL><INDENT>log.info("<STR_LIT>",<EOL>filename, repr(text_from), repr(text_to))<EOL>contents = contents.replace(text_from, text_to)<EOL><DEDENT>with open(filename, '<STR_LIT:w>') as outfile:<EOL><INDENT>outfile.write(contents)<EOL><DEDENT> | Replaces multiple from/to string pairs within a single file.
Args:
filename: filename to process (modifying it in place)
replacements: list of ``(from_text, to_text)`` tuples | f14566:m17 |
def convert_line_endings(filename: str, to_unix: bool = False,<EOL>to_windows: bool = False) -> None: | assert to_unix != to_windows<EOL>with open(filename, "<STR_LIT:rb>") as f:<EOL><INDENT>contents = f.read()<EOL><DEDENT>windows_eol = b"<STR_LIT:\r\n>" <EOL>unix_eol = b"<STR_LIT:\n>" <EOL>if to_unix:<EOL><INDENT>log.info("<STR_LIT>",<EOL>filename)<EOL>src = windows_eol<EOL>dst = unix_eol<EOL><DEDENT>else: <EOL><INDENT>log.info("<STR_LIT>",<EOL>filename)<EOL>src = unix_eol<EOL>dst = windows_eol<EOL>if windows_eol in contents:<EOL><INDENT>log.info("<STR_LIT>"<EOL>"<STR_LIT>")<EOL>return<EOL><DEDENT><DEDENT>contents = contents.replace(src, dst)<EOL>with open(filename, "<STR_LIT:wb>") as f:<EOL><INDENT>f.write(contents)<EOL><DEDENT> | Converts a file (in place) from UNIX to Windows line endings, or the
reverse.
Args:
filename: filename to modify (in place)
to_unix: convert Windows (CR LF) to UNIX (LF)
to_windows: convert UNIX (LF) to Windows (CR LF) | f14566:m18 |
def is_line_in_file(filename: str, line: str) -> bool: | assert "<STR_LIT:\n>" not in line<EOL>with open(filename, "<STR_LIT:r>") as file:<EOL><INDENT>for fileline in file:<EOL><INDENT>if fileline == line:<EOL><INDENT>return True<EOL><DEDENT><DEDENT>return False<EOL><DEDENT> | Detects whether a line is present within a file.
Args:
filename: file to check
line: line to search for (as an exact match) | f14566:m19 |
def add_line_if_absent(filename: str, line: str) -> None: | assert "<STR_LIT:\n>" not in line<EOL>if not is_line_in_file(filename, line):<EOL><INDENT>log.info("<STR_LIT>", line, filename)<EOL>with open(filename, "<STR_LIT:a>") as file:<EOL><INDENT>file.writelines([line])<EOL><DEDENT><DEDENT> | Adds a line (at the end) if it's not already in the file somewhere.
Args:
filename: filename to modify (in place)
line: line to append (which must not have a newline in) | f14566:m20 |
def process_file(filename: str,<EOL>filetypes: List[str],<EOL>move_to: str,<EOL>delete_if_not_specified_file_type: bool,<EOL>show_zip_output: bool) -> None: | <EOL>try:<EOL><INDENT>reader = CorruptedOpenXmlReader(filename,<EOL>show_zip_output=show_zip_output)<EOL>if reader.file_type in filetypes:<EOL><INDENT>log.info("<STR_LIT>", reader.description, filename)<EOL>if move_to:<EOL><INDENT>dest_file = os.path.join(move_to, os.path.basename(filename))<EOL>_, ext = os.path.splitext(dest_file)<EOL>if ext != reader.suggested_extension():<EOL><INDENT>dest_file += reader.suggested_extension()<EOL><DEDENT>reader.move_to(destination_filename=dest_file)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>log.info("<STR_LIT>" + filename)<EOL>if delete_if_not_specified_file_type:<EOL><INDENT>log.info("<STR_LIT>" + filename)<EOL>os.remove(filename)<EOL><DEDENT><DEDENT><DEDENT>except Exception as e:<EOL><INDENT>log.critical("<STR_LIT>", e,<EOL>traceback.format_exc())<EOL>raise<EOL><DEDENT> | Deals with an OpenXML, including if it is potentially corrupted.
Args:
filename: filename to process
filetypes: list of filetypes that we care about, e.g.
``['docx', 'pptx', 'xlsx']``.
move_to: move matching files to this directory
delete_if_not_specified_file_type: if ``True``, and the file is **not**
a type specified in ``filetypes``, then delete the file.
show_zip_output: show the output from the external ``zip`` tool? | f14567:m0 |
def main() -> None: | parser = ArgumentParser(<EOL>formatter_class=RawDescriptionHelpFormatter,<EOL>description="""<STR_LIT>""".format(<EOL>DOCX_CONTENTS_REGEX_STR=DOCX_CONTENTS_REGEX_STR,<EOL>PPTX_CONTENTS_REGEX_STR=PPTX_CONTENTS_REGEX_STR,<EOL>XLSX_CONTENTS_REGEX_STR=XLSX_CONTENTS_REGEX_STR,<EOL>)<EOL>)<EOL>parser.add_argument(<EOL>"<STR_LIT:filename>", nargs="<STR_LIT:+>",<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>)<EOL>parser.add_argument(<EOL>"<STR_LIT>", action="<STR_LIT:store_true>",<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>)<EOL>parser.add_argument(<EOL>"<STR_LIT>", nargs="<STR_LIT:*>", default=[],<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>)<EOL>parser.add_argument(<EOL>"<STR_LIT>", nargs="<STR_LIT:+>", default=FILETYPES,<EOL>help="<STR_LIT>".format(FILETYPES)<EOL>)<EOL>parser.add_argument(<EOL>"<STR_LIT>",<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>)<EOL>parser.add_argument(<EOL>"<STR_LIT>", action="<STR_LIT:store_true>",<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>)<EOL>parser.add_argument(<EOL>"<STR_LIT>", type=int,<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>)<EOL>parser.add_argument(<EOL>"<STR_LIT>", type=int, default=multiprocessing.cpu_count(),<EOL>help="<STR_LIT>"<EOL>)<EOL>parser.add_argument(<EOL>"<STR_LIT>", action="<STR_LIT:store_true>",<EOL>help="<STR_LIT>"<EOL>)<EOL>parser.add_argument(<EOL>"<STR_LIT>", action="<STR_LIT:store_true>",<EOL>help="<STR_LIT>"<EOL>)<EOL>args = parser.parse_args()<EOL>main_only_quicksetup_rootlogger(<EOL>level=logging.DEBUG if args.verbose else logging.INFO,<EOL>with_process_id=True<EOL>)<EOL>if args.move_to:<EOL><INDENT>if not os.path.isdir(args.move_to):<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>".format(args.move_to))<EOL><DEDENT><DEDENT>if not args.filetypes:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>filetypes = [ft.lower() for ft in args.filetypes]<EOL>if any(ft not in FILETYPES for ft in filetypes):<EOL><INDENT>raise ValueError("<STR_LIT>".format(FILETYPES))<EOL><DEDENT>assert shutil.which("<STR_LIT>"), "<STR_LIT>"<EOL>while True:<EOL><INDENT>log.info("<STR_LIT>")<EOL>log.info("<STR_LIT>", filetypes)<EOL>log.info("<STR_LIT>",<EOL>args.filename,<EOL>"<STR_LIT>" if args.recursive else "<STR_LIT>")<EOL>log.info("<STR_LIT>", args.skip_files)<EOL>log.info("<STR_LIT>", args.nprocesses)<EOL>if args.move_to:<EOL><INDENT>log.info("<STR_LIT>" + args.move_to)<EOL><DEDENT>if args.delete_if_not_specified_file_type:<EOL><INDENT>log.info("<STR_LIT>")<EOL><DEDENT>pool = multiprocessing.Pool(processes=args.nprocesses)<EOL>for filename in gen_filenames(starting_filenames=args.filename,<EOL>recursive=args.recursive):<EOL><INDENT>src_basename = os.path.basename(filename)<EOL>if any(fnmatch.fnmatch(src_basename, pattern)<EOL>for pattern in args.skip_files):<EOL><INDENT>log.info("<STR_LIT>" + filename)<EOL>continue<EOL><DEDENT>exists, locked = exists_locked(filename)<EOL>if locked or not exists:<EOL><INDENT>log.info("<STR_LIT>" + filename)<EOL>continue<EOL><DEDENT>kwargs = {<EOL>'<STR_LIT:filename>': filename,<EOL>'<STR_LIT>': filetypes,<EOL>'<STR_LIT>': args.move_to,<EOL>'<STR_LIT>':<EOL>args.delete_if_not_specified_file_type,<EOL>'<STR_LIT>': args.show_zip_output,<EOL>}<EOL>pool.apply_async(process_file, [], kwargs)<EOL><DEDENT>pool.close()<EOL>pool.join()<EOL>log.info("<STR_LIT>")<EOL>if args.run_repeatedly is None:<EOL><INDENT>break<EOL><DEDENT>log.info("<STR_LIT>", args.run_repeatedly)<EOL>sleep(args.run_repeatedly)<EOL><DEDENT> | Command-line handler for the ``find_recovered_openxml`` tool.
Use the ``--help`` option for help. | f14567:m1 |
def __init__(self, filename: str, show_zip_output: bool = False) -> None: | self.src_filename = filename<EOL>self.rescue_filename = "<STR_LIT>"<EOL>self.tmp_dir = "<STR_LIT>"<EOL>self.contents_filenames = [] <EOL>try:<EOL><INDENT>with ZipFile(self.src_filename, '<STR_LIT:r>') as zip_ref:<EOL><INDENT>self.contents_filenames = zip_ref.namelist()<EOL><DEDENT><DEDENT>except (BadZipFile, OSError) as e:<EOL><INDENT>log.debug("<STR_LIT>", filename, e)<EOL>self._fix_zip(show_zip_output=show_zip_output)<EOL>try:<EOL><INDENT>with ZipFile(self.rescue_filename, '<STR_LIT:r>') as zip_ref:<EOL><INDENT>self.contents_filenames = zip_ref.namelist()<EOL><DEDENT><DEDENT>except (BadZipFile, OSError, struct.error) as e:<EOL><INDENT>log.debug("<STR_LIT>",<EOL>e)<EOL><DEDENT>if self.contents_filenames:<EOL><INDENT>log.debug("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>log.debug("<STR_LIT>")<EOL><DEDENT><DEDENT> | Args:
filename: filename of the ``.zip`` file (or corrupted ``.zip``
file) to open
show_zip_output: show the output of the external ``zip`` tool? | f14567:c0:m0 |
def move_to(self, destination_filename: str,<EOL>alter_if_clash: bool = True) -> None: | if not self.src_filename:<EOL><INDENT>return<EOL><DEDENT>if alter_if_clash:<EOL><INDENT>counter = <NUM_LIT:0><EOL>while os.path.exists(destination_filename):<EOL><INDENT>root, ext = os.path.splitext(destination_filename)<EOL>destination_filename = "<STR_LIT>".format(<EOL>r=root, c=counter, e=ext)<EOL>counter += <NUM_LIT:1><EOL><DEDENT><DEDENT>else:<EOL><INDENT>if os.path.exists(destination_filename):<EOL><INDENT>src = self.rescue_filename or self.src_filename<EOL>log.warning("<STR_LIT>",<EOL>src, destination_filename)<EOL>return<EOL><DEDENT><DEDENT>if self.rescue_filename:<EOL><INDENT>shutil.move(self.rescue_filename, destination_filename)<EOL>os.remove(self.src_filename)<EOL>log.info("<STR_LIT>"<EOL>"<STR_LIT>",<EOL>self.rescue_filename,<EOL>destination_filename,<EOL>self.src_filename)<EOL>self.rescue_filename = "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>shutil.move(self.src_filename, destination_filename)<EOL>log.info("<STR_LIT>", self.src_filename,<EOL>destination_filename)<EOL><DEDENT>self.src_filename = "<STR_LIT>"<EOL> | Move the file to which this class refers to a new location.
The function will not overwrite existing files (but offers the option
to rename files slightly to avoid a clash).
Args:
destination_filename: filename to move to
alter_if_clash: if ``True`` (the default), appends numbers to
the filename if the destination already exists, so that the
move can proceed. | f14567:c0:m2 |
def is_running(process_id: int) -> bool: | pstr = str(process_id)<EOL>encoding = sys.getdefaultencoding()<EOL>s = subprocess.Popen(["<STR_LIT>", "<STR_LIT>", pstr], stdout=subprocess.PIPE)<EOL>for line in s.stdout:<EOL><INDENT>strline = line.decode(encoding)<EOL>if pstr in strline:<EOL><INDENT>return True<EOL><DEDENT><DEDENT>return False<EOL> | Uses the Unix ``ps`` program to see if a process is running. | f14568:m0 |
def main() -> None: | parser = ArgumentParser(<EOL>description="<STR_LIT>"<EOL>)<EOL>parser.add_argument(<EOL>"<STR_LIT>", type=int,<EOL>help="<STR_LIT>"<EOL>)<EOL>parser.add_argument(<EOL>"<STR_LIT>", required=True,<EOL>help="<STR_LIT>"<EOL>)<EOL>parser.add_argument(<EOL>"<STR_LIT>", type=str, required=True,<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>)<EOL>parser.add_argument(<EOL>"<STR_LIT>", type=str, required=True,<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>)<EOL>parser.add_argument(<EOL>"<STR_LIT>", type=int, required=True,<EOL>help="<STR_LIT>"<EOL>)<EOL>parser.add_argument(<EOL>"<STR_LIT>", action="<STR_LIT:store_true>",<EOL>help="<STR_LIT>"<EOL>)<EOL>args = parser.parse_args()<EOL>main_only_quicksetup_rootlogger(<EOL>level=logging.DEBUG if args.verbose else logging.INFO)<EOL>minimum = human2bytes(args.pause_when_free_below)<EOL>maximum = human2bytes(args.resume_when_free_above)<EOL>path = args.path<EOL>process_id = args.process_id<EOL>period = args.check_every<EOL>pause_args = ["<STR_LIT>", "<STR_LIT>", str(process_id)]<EOL>resume_args = ["<STR_LIT>", "<STR_LIT>", str(process_id)]<EOL>assert minimum < maximum, "<STR_LIT>"<EOL>log.info(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(<EOL>proc=process_id,<EOL>period=period,<EOL>path=path,<EOL>minimum=sizeof_fmt(minimum),<EOL>maximum=sizeof_fmt(maximum),<EOL>pause=pause_args,<EOL>resume=resume_args,<EOL>))<EOL>log.debug("<STR_LIT>")<EOL>paused = False<EOL>while True:<EOL><INDENT>if not is_running(process_id):<EOL><INDENT>log.info("<STR_LIT>", process_id)<EOL>sys.exit(<NUM_LIT:0>)<EOL><DEDENT>space = shutil.disk_usage(path).free<EOL>log.debug("<STR_LIT>", path, sizeof_fmt(space))<EOL>if space < minimum and not paused:<EOL><INDENT>log.info("<STR_LIT>",<EOL>sizeof_fmt(space), process_id)<EOL>subprocess.check_call(pause_args)<EOL>paused = True<EOL><DEDENT>elif space >= maximum and paused:<EOL><INDENT>log.info("<STR_LIT>",<EOL>sizeof_fmt(space), process_id)<EOL>subprocess.check_call(resume_args)<EOL>paused = False<EOL><DEDENT>log.debug("<STR_LIT>", period)<EOL>sleep(period)<EOL><DEDENT> | Command-line handler for the ``pause_process_by_disk_space`` tool.
Use the ``--help`` option for help. | f14568:m1 |
def gen_from_stdin() -> Generator[str, None, None]: | for line in stdin.readlines():<EOL><INDENT>yield line.strip()<EOL><DEDENT> | Yields stripped lines from stdin. | f14570:m0 |
def is_openxml_good(filename: str) -> bool: | try:<EOL><INDENT>log.debug("<STR_LIT>", filename)<EOL>with ZipFile(filename, '<STR_LIT:r>') as zip_ref:<EOL><INDENT>namelist = zip_ref.namelist() <EOL>for mandatory_filename in MANDATORY_FILENAMES:<EOL><INDENT>if mandatory_filename not in namelist:<EOL><INDENT>log.debug("<STR_LIT>",<EOL>mandatory_filename, filename)<EOL>return False<EOL><DEDENT><DEDENT>infolist = zip_ref.infolist() <EOL>contains_docx = False<EOL>contains_pptx = False<EOL>contains_xlsx = False<EOL>for info in infolist:<EOL><INDENT>if (not contains_docx and<EOL>DOCX_CONTENTS_REGEX.search(info.filename)):<EOL><INDENT>contains_docx = True<EOL><DEDENT>if (not contains_pptx and<EOL>PPTX_CONTENTS_REGEX.search(info.filename)):<EOL><INDENT>contains_pptx = True<EOL><DEDENT>if (not contains_xlsx and<EOL>XLSX_CONTENTS_REGEX.search(info.filename)):<EOL><INDENT>contains_xlsx = True<EOL><DEDENT>if sum([contains_docx, contains_pptx, contains_xlsx]) > <NUM_LIT:1>:<EOL><INDENT>log.debug("<STR_LIT>",<EOL>filename)<EOL>return False<EOL><DEDENT><DEDENT>return True<EOL><DEDENT><DEDENT>except (BadZipFile, OSError) as e:<EOL><INDENT>log.debug("<STR_LIT>",<EOL>filename, e)<EOL>return False<EOL><DEDENT> | Determines whether an OpenXML file appears to be good (not corrupted). | f14570:m1 |
def process_openxml_file(filename: str,<EOL>print_good: bool,<EOL>delete_if_bad: bool) -> None: | print_bad = not print_good<EOL>try:<EOL><INDENT>file_good = is_openxml_good(filename)<EOL>file_bad = not file_good<EOL>if (print_good and file_good) or (print_bad and file_bad):<EOL><INDENT>print(filename)<EOL><DEDENT>if delete_if_bad and file_bad:<EOL><INDENT>log.warning("<STR_LIT>", filename)<EOL>os.remove(filename)<EOL><DEDENT><DEDENT>except Exception as e:<EOL><INDENT>log.critical("<STR_LIT>", e,<EOL>traceback.format_exc())<EOL>raise<EOL><DEDENT> | Prints the filename of, or deletes, an OpenXML file depending on whether
it is corrupt or not.
Args:
filename: filename to check
print_good: if ``True``, then prints the filename if the file
appears good.
delete_if_bad: if ``True``, then deletes the file if the file
appears corrupt. | f14570:m2 |
def main() -> None: | parser = ArgumentParser(<EOL>formatter_class=RawDescriptionHelpFormatter,<EOL>description="""<STR_LIT>"""<EOL>)<EOL>parser.add_argument(<EOL>"<STR_LIT:filename>", nargs="<STR_LIT:*>",<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>)<EOL>parser.add_argument(<EOL>"<STR_LIT>", "<STR_LIT>", action="<STR_LIT:store_true>",<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>)<EOL>parser.add_argument(<EOL>"<STR_LIT>", action="<STR_LIT:store_true>",<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>)<EOL>parser.add_argument(<EOL>"<STR_LIT>", nargs="<STR_LIT:*>", default=[],<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>)<EOL>parser.add_argument(<EOL>"<STR_LIT>", action="<STR_LIT:store_true>",<EOL>help="<STR_LIT>"<EOL>)<EOL>parser.add_argument(<EOL>"<STR_LIT>", action="<STR_LIT:store_true>",<EOL>help="<STR_LIT>"<EOL>)<EOL>parser.add_argument(<EOL>"<STR_LIT>", type=int,<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>)<EOL>parser.add_argument(<EOL>"<STR_LIT>", type=int, default=multiprocessing.cpu_count(),<EOL>help="<STR_LIT>"<EOL>)<EOL>parser.add_argument(<EOL>"<STR_LIT>", action="<STR_LIT:store_true>",<EOL>help="<STR_LIT>"<EOL>)<EOL>args = parser.parse_args()<EOL>main_only_quicksetup_rootlogger(<EOL>level=logging.DEBUG if args.verbose else logging.INFO,<EOL>with_process_id=True<EOL>)<EOL>if bool(args.filenames_from_stdin) == bool(args.filename):<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>if args.filenames_from_stdin and args.run_repeatedly:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>while True:<EOL><INDENT>log.debug("<STR_LIT>")<EOL>log.debug("<STR_LIT>",<EOL>args.filename,<EOL>"<STR_LIT>" if args.recursive else "<STR_LIT>")<EOL>log.debug("<STR_LIT>", args.skip_files)<EOL>log.debug("<STR_LIT>", args.nprocesses)<EOL>log.debug("<STR_LIT>", "<STR_LIT>" if args.good else "<STR_LIT>")<EOL>if args.delete_if_bad:<EOL><INDENT>log.warning("<STR_LIT>")<EOL><DEDENT>pool = multiprocessing.Pool(processes=args.nprocesses)<EOL>if args.filenames_from_stdin:<EOL><INDENT>generator = gen_from_stdin()<EOL><DEDENT>else:<EOL><INDENT>generator = gen_filenames(starting_filenames=args.filename,<EOL>recursive=args.recursive)<EOL><DEDENT>for filename in generator:<EOL><INDENT>src_basename = os.path.basename(filename)<EOL>if any(fnmatch.fnmatch(src_basename, pattern)<EOL>for pattern in args.skip_files):<EOL><INDENT>log.debug("<STR_LIT>" + filename)<EOL>continue<EOL><DEDENT>exists, locked = exists_locked(filename)<EOL>if locked or not exists:<EOL><INDENT>log.debug("<STR_LIT>" + filename)<EOL>continue<EOL><DEDENT>kwargs = {<EOL>'<STR_LIT:filename>': filename,<EOL>'<STR_LIT>': args.good,<EOL>'<STR_LIT>': args.delete_if_bad,<EOL>}<EOL>pool.apply_async(process_openxml_file, [], kwargs)<EOL><DEDENT>pool.close()<EOL>pool.join()<EOL>log.debug("<STR_LIT>")<EOL>if args.run_repeatedly is None:<EOL><INDENT>break<EOL><DEDENT>log.info("<STR_LIT>", args.run_repeatedly)<EOL>sleep(args.run_repeatedly)<EOL><DEDENT> | Command-line handler for the ``find_bad_openxml`` tool.
Use the ``--help`` option for help. | f14570:m3 |
def report_hit_filename(zipfilename: str, contentsfilename: str,<EOL>show_inner_file: bool) -> None: | if show_inner_file:<EOL><INDENT>print("<STR_LIT>".format(zipfilename, contentsfilename))<EOL><DEDENT>else:<EOL><INDENT>print(zipfilename)<EOL><DEDENT> | For "hits": prints either the ``.zip`` filename, or the ``.zip`` filename
and the inner filename.
Args:
zipfilename: filename of the ``.zip`` file
contentsfilename: filename of the inner file
show_inner_file: if ``True``, show both; if ``False``, show just the
``.zip`` filename
Returns: | f14571:m0 |
def report_miss_filename(zipfilename: str) -> None: | print(zipfilename)<EOL> | For "misses": prints the zip filename. | f14571:m1 |
def report_line(zipfilename: str, contentsfilename: str, line: str,<EOL>show_inner_file: bool) -> None: | if show_inner_file:<EOL><INDENT>print("<STR_LIT>".format(zipfilename, contentsfilename, line))<EOL><DEDENT>else:<EOL><INDENT>print("<STR_LIT>".format(zipfilename, line))<EOL><DEDENT> | Prints a line from a file, with the ``.zip`` filename and optionally also
the inner filename.
Args:
zipfilename: filename of the ``.zip`` file
contentsfilename: filename of the inner file
line: the line from the inner file
show_inner_file: if ``True``, show both filenames; if ``False``, show
just the ``.zip`` filename | f14571:m2 |
def parse_zip(zipfilename: str,<EOL>regex: Pattern,<EOL>invert_match: bool,<EOL>files_with_matches: bool,<EOL>files_without_match: bool,<EOL>grep_inner_file_name: bool,<EOL>show_inner_file: bool) -> None: | assert not (files_without_match and files_with_matches)<EOL>report_lines = (not files_without_match) and (not files_with_matches)<EOL>report_hit_lines = report_lines and not invert_match<EOL>report_miss_lines = report_lines and invert_match<EOL>log.debug("<STR_LIT>" + zipfilename)<EOL>found_in_zip = False<EOL>try:<EOL><INDENT>with ZipFile(zipfilename, '<STR_LIT:r>') as zf:<EOL><INDENT>for contentsfilename in zf.namelist():<EOL><INDENT>log.debug("<STR_LIT>" + contentsfilename)<EOL>if grep_inner_file_name:<EOL><INDENT>found_in_filename = bool(regex.search(contentsfilename))<EOL>found_in_zip = found_in_zip or found_in_filename<EOL>if files_with_matches and found_in_zip:<EOL><INDENT>report_hit_filename(zipfilename, contentsfilename,<EOL>show_inner_file)<EOL>return<EOL><DEDENT>if ((report_hit_lines and found_in_filename) or<EOL>(report_miss_lines and not found_in_filename)):<EOL><INDENT>report_line(zipfilename, contentsfilename,<EOL>contentsfilename, show_inner_file)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>with zf.open(contentsfilename, '<STR_LIT:r>') as file:<EOL><INDENT>try:<EOL><INDENT>for line in file.readlines():<EOL><INDENT>found_in_line = bool(regex.search(line))<EOL>found_in_zip = found_in_zip or found_in_line<EOL>if files_with_matches and found_in_zip:<EOL><INDENT>report_hit_filename(zipfilename,<EOL>contentsfilename,<EOL>show_inner_file)<EOL>return<EOL><DEDENT>if ((report_hit_lines and found_in_line) or<EOL>(report_miss_lines and<EOL>not found_in_line)):<EOL><INDENT>report_line(zipfilename,<EOL>contentsfilename,<EOL>line, show_inner_file)<EOL><DEDENT><DEDENT><DEDENT>except EOFError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT><DEDENT>except RuntimeError as e:<EOL><INDENT>log.warning(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>",<EOL>zipfilename, contentsfilename, e)<EOL><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT>except (zlib.error, BadZipFile) as e:<EOL><INDENT>log.debug("<STR_LIT>", zipfilename, e)<EOL><DEDENT>if files_without_match and not found_in_zip:<EOL><INDENT>report_miss_filename(zipfilename)<EOL><DEDENT> | Implement a "grep within an OpenXML file" for a single OpenXML file, which
is by definition a ``.zip`` file.
Args:
zipfilename: name of the OpenXML (zip) file
regex: regular expression to match
invert_match: find files that do NOT match, instead of ones that do?
files_with_matches: show filenames of files with a match?
files_without_match: show filenames of files with no match?
grep_inner_file_name: search the names of "inner" files, rather than
their contents?
show_inner_file: show the names of the "inner" files, not just the
"outer" (OpenXML) file? | f14571:m3 |
def main() -> None: | parser = ArgumentParser(<EOL>formatter_class=RawDescriptionHelpFormatter,<EOL>description= | Command-line handler for the ``grep_in_openxml`` tool.
Use the ``--help`` option for help. | f14571:m4 |
def calc_n_sheets(n_pages: int) -> int: | <EOL>return math.ceil(n_pages / <NUM_LIT:2>)<EOL> | How many sheets does this number of pages need, on the basis of 2 pages
per sheet? | f14572:m0 |
def calc_n_virtual_pages(n_sheets: int) -> int: | if n_sheets % <NUM_LIT:2> == <NUM_LIT:0>:<EOL><INDENT>return n_sheets * <NUM_LIT:2><EOL><DEDENT>else:<EOL><INDENT>return (n_sheets + <NUM_LIT:1>) * <NUM_LIT:2><EOL><DEDENT> | Converts #sheets to #pages, but rounding up to a multiple of 4. | f14572:m1 |
def page_sequence(n_sheets: int, one_based: bool = True) -> List[int]: | n_pages = calc_n_virtual_pages(n_sheets)<EOL>assert n_pages % <NUM_LIT:4> == <NUM_LIT:0><EOL>half_n_pages = n_pages // <NUM_LIT:2><EOL>firsthalf = list(range(half_n_pages))<EOL>secondhalf = list(reversed(range(half_n_pages, n_pages)))<EOL>sequence = [] <EOL>top = True<EOL>for left, right in zip(secondhalf, firsthalf):<EOL><INDENT>if not top:<EOL><INDENT>left, right = right, left<EOL><DEDENT>sequence += [left, right]<EOL>top = not top<EOL><DEDENT>if one_based:<EOL><INDENT>sequence = [x + <NUM_LIT:1> for x in sequence]<EOL><DEDENT>log.debug("<STR_LIT>", n_sheets, sequence)<EOL>return sequence<EOL> | Generates the final page sequence from the starting number of sheets. | f14572:m2 |
def require(executable: str, explanation: str = "<STR_LIT>") -> None: | assert shutil.which(executable), "<STR_LIT>".format(<EOL>executable, "<STR_LIT:\n>" + explanation if explanation else "<STR_LIT>")<EOL> | Ensures that the external tool is available.
Asserts upon failure. | f14572:m3 |
def run(args: List[str],<EOL>get_output: bool = False,<EOL>encoding: str = sys.getdefaultencoding()) -> Tuple[str, str]: | printable = "<STR_LIT:U+0020>".join(shlex.quote(x) for x in args).replace("<STR_LIT:\n>", r"<STR_LIT:\n>")<EOL>log.debug("<STR_LIT>", printable)<EOL>if get_output:<EOL><INDENT>p = subprocess.run(args, stdout=subprocess.PIPE,<EOL>stderr=subprocess.PIPE, check=True)<EOL>stdout, stderr = p.stdout.decode(encoding), p.stderr.decode(encoding)<EOL><DEDENT>else:<EOL><INDENT>subprocess.check_call(args)<EOL>stdout, stderr = "<STR_LIT>", "<STR_LIT>"<EOL><DEDENT>return stdout, stderr<EOL> | Run an external command +/- return the results.
Returns a ``(stdout, stderr)`` tuple (both are blank strings if the output
wasn't wanted). | f14572:m4 |
def get_page_count(filename: str) -> int: | log.debug("<STR_LIT>", filename)<EOL>require(PDFTK, HELP_MISSING_PDFTK)<EOL>stdout, _ = run([PDFTK, filename, "<STR_LIT>"], get_output=True)<EOL>regex = re.compile(r"<STR_LIT>", re.MULTILINE)<EOL>m = regex.search(stdout)<EOL>if m:<EOL><INDENT>return int(m.group(<NUM_LIT:1>))<EOL><DEDENT>raise ValueError("<STR_LIT>".format(filename))<EOL> | How many pages are in a PDF? | f14572:m5 |
def make_blank_pdf(filename: str, paper: str = "<STR_LIT>") -> None: | <EOL>require(CONVERT, HELP_MISSING_IMAGEMAGICK)<EOL>run([CONVERT, "<STR_LIT>", "<STR_LIT>", paper, filename])<EOL> | NOT USED.
Makes a blank single-page PDF, using ImageMagick's ``convert``. | f14572:m6 |
def slice_pdf(input_filename: str, output_filename: str,<EOL>slice_horiz: int, slice_vert: int) -> str: | if slice_horiz == <NUM_LIT:1> and slice_vert == <NUM_LIT:1>:<EOL><INDENT>log.debug("<STR_LIT>")<EOL>return input_filename <EOL><DEDENT>log.info("<STR_LIT>",<EOL>slice_horiz, slice_vert)<EOL>log.debug("<STR_LIT>", input_filename, output_filename)<EOL>require(MUTOOL, HELP_MISSING_MUTOOL)<EOL>run([<EOL>MUTOOL,<EOL>"<STR_LIT>",<EOL>"<STR_LIT>", str(slice_horiz),<EOL>"<STR_LIT>", str(slice_vert),<EOL>input_filename,<EOL>output_filename<EOL>])<EOL>return output_filename<EOL> | Slice each page of the original, to convert to "one real page per PDF
page". Return the output filename. | f14572:m7 |
def booklet_nup_pdf(input_filename: str, output_filename: str,<EOL>latex_paper_size: str = LATEX_PAPER_SIZE_A4) -> str: | log.info("<STR_LIT>")<EOL>log.debug("<STR_LIT>", input_filename, output_filename)<EOL>require(PDFJAM, HELP_MISSING_PDFJAM)<EOL>n_pages = get_page_count(input_filename)<EOL>n_sheets = calc_n_sheets(n_pages)<EOL>log.debug("<STR_LIT>", n_pages, n_sheets)<EOL>pagenums = page_sequence(n_sheets, one_based=True)<EOL>pagespeclist = [str(p) if p <= n_pages else "<STR_LIT:{}>"<EOL>for p in pagenums]<EOL>pagespec = "<STR_LIT:U+002C>".join(pagespeclist)<EOL>pdfjam_tidy = True <EOL>args = [<EOL>PDFJAM,<EOL>"<STR_LIT>", latex_paper_size,<EOL>"<STR_LIT>",<EOL>"<STR_LIT>", "<STR_LIT>",<EOL>"<STR_LIT>", <EOL>"<STR_LIT>", output_filename,<EOL>"<STR_LIT>" if pdfjam_tidy else "<STR_LIT>",<EOL>"<STR_LIT>", <EOL>input_filename, pagespec<EOL>]<EOL>run(args)<EOL>return output_filename<EOL> | Takes a PDF (e.g. A4) and makes a 2x1 booklet (e.g. 2xA5 per A4).
The booklet can be folded like a book and the final pages will be in order.
Returns the output filename. | f14572:m8 |
def rotate_even_pages_180(input_filename: str, output_filename: str) -> str: | log.info("<STR_LIT>"<EOL>"<STR_LIT>")<EOL>log.debug("<STR_LIT>", input_filename, output_filename)<EOL>require(PDFTK, HELP_MISSING_PDFTK)<EOL>args = [<EOL>PDFTK,<EOL>"<STR_LIT>" + input_filename, <EOL>"<STR_LIT>",<EOL>"<STR_LIT>", <EOL>"<STR_LIT>", <EOL>"<STR_LIT>", output_filename,<EOL>]<EOL>run(args)<EOL>return output_filename<EOL> | Rotates even-numbered pages 180 degrees.
Returns the output filename. | f14572:m9 |
def convert_to_foldable(input_filename: str,<EOL>output_filename: str,<EOL>slice_horiz: int,<EOL>slice_vert: int,<EOL>overwrite: bool = False,<EOL>longedge: bool = False,<EOL>latex_paper_size: str = LATEX_PAPER_SIZE_A4) -> bool: | if not os.path.isfile(input_filename):<EOL><INDENT>log.warning("<STR_LIT>")<EOL>return False<EOL><DEDENT>if not overwrite and os.path.isfile(output_filename):<EOL><INDENT>log.error("<STR_LIT>"<EOL>"<STR_LIT>")<EOL>return False<EOL><DEDENT>log.info("<STR_LIT>", input_filename)<EOL>with tempfile.TemporaryDirectory() as tmpdir:<EOL><INDENT>log.debug("<STR_LIT>", tmpdir)<EOL>intermediate_num = <NUM_LIT:0><EOL>def make_intermediate() -> str:<EOL><INDENT>nonlocal intermediate_num<EOL>intermediate_num += <NUM_LIT:1><EOL>return os.path.join(tmpdir,<EOL>"<STR_LIT>".format(intermediate_num))<EOL><DEDENT>input_filename = slice_pdf(<EOL>input_filename=input_filename,<EOL>output_filename=make_intermediate(),<EOL>slice_horiz=slice_horiz,<EOL>slice_vert=slice_vert<EOL>)<EOL>input_filename = booklet_nup_pdf(<EOL>input_filename=input_filename,<EOL>output_filename=make_intermediate(),<EOL>latex_paper_size=latex_paper_size<EOL>)<EOL>if longedge:<EOL><INDENT>input_filename = rotate_even_pages_180(<EOL>input_filename=input_filename,<EOL>output_filename=make_intermediate(),<EOL>)<EOL><DEDENT>log.info("<STR_LIT>", output_filename)<EOL>shutil.move(input_filename, output_filename)<EOL><DEDENT>return True<EOL> | Runs a chain of tasks to convert a PDF to a useful booklet PDF. | f14572:m10 |
def main() -> None: | main_only_quicksetup_rootlogger(level=logging.DEBUG)<EOL>parser = argparse.ArgumentParser(<EOL>formatter_class=argparse.ArgumentDefaultsHelpFormatter<EOL>)<EOL>parser.add_argument(<EOL>"<STR_LIT>",<EOL>help="<STR_LIT>")<EOL>parser.add_argument(<EOL>"<STR_LIT>",<EOL>help="<STR_LIT>")<EOL>parser.add_argument(<EOL>"<STR_LIT>", type=int, default=<NUM_LIT:1>,<EOL>help="<STR_LIT>")<EOL>parser.add_argument(<EOL>"<STR_LIT>", type=int, default=<NUM_LIT:1>,<EOL>help="<STR_LIT>")<EOL>parser.add_argument(<EOL>"<STR_LIT>", action="<STR_LIT:store_true>",<EOL>help="<STR_LIT>")<EOL>parser.add_argument(<EOL>"<STR_LIT>", action="<STR_LIT:store_true>",<EOL>help="<STR_LIT>")<EOL>parser.add_argument(<EOL>"<STR_LIT>", action="<STR_LIT:store_true>",<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>args = parser.parse_args()<EOL>if args.unittest:<EOL><INDENT>log.warning("<STR_LIT>")<EOL>unittest.main(argv=[sys.argv[<NUM_LIT:0>]])<EOL>sys.exit(EXIT_SUCCESS)<EOL><DEDENT>success = convert_to_foldable(<EOL>input_filename=os.path.abspath(args.input_file),<EOL>output_filename=os.path.abspath(args.output_file),<EOL>slice_horiz=args.slice_horiz,<EOL>slice_vert=args.slice_vert,<EOL>overwrite=args.overwrite,<EOL>longedge=args.longedge<EOL>)<EOL>sys.exit(EXIT_SUCCESS if success else EXIT_FAILURE)<EOL> | Command-line processor. See ``--help`` for details. | f14572:m11 |
def deduplicate(directories: List[str], recursive: bool,<EOL>dummy_run: bool) -> None: | <EOL>files_by_size = {} <EOL>num_considered = <NUM_LIT:0><EOL>for filename in gen_filenames(directories, recursive=recursive):<EOL><INDENT>if not os.path.isfile(filename):<EOL><INDENT>continue<EOL><DEDENT>size = os.stat(filename)[stat.ST_SIZE]<EOL>a = files_by_size.setdefault(size, [])<EOL>a.append(filename)<EOL>num_considered += <NUM_LIT:1><EOL><DEDENT>log.debug("<STR_LIT>", pformat(files_by_size))<EOL>log.info("<STR_LIT>")<EOL>potential_duplicate_sets = []<EOL>potential_count = <NUM_LIT:0><EOL>sizes = list(files_by_size.keys())<EOL>sizes.sort()<EOL>for k in sizes:<EOL><INDENT>files_of_this_size = files_by_size[k]<EOL>out_files = [] <EOL>hashes = {} <EOL>if len(files_of_this_size) == <NUM_LIT:1>:<EOL><INDENT>continue<EOL><DEDENT>log.info("<STR_LIT>", len(files_of_this_size), k)<EOL>for filename in files_of_this_size:<EOL><INDENT>if not os.path.isfile(filename):<EOL><INDENT>continue<EOL><DEDENT>log.debug("<STR_LIT>", filename)<EOL>with open(filename, '<STR_LIT:rb>') as fd:<EOL><INDENT>hasher = md5()<EOL>hasher.update(fd.read(INITIAL_HASH_SIZE))<EOL>hash_value = hasher.digest()<EOL>if hash_value in hashes:<EOL><INDENT>first_file_or_true = hashes[hash_value]<EOL>if first_file_or_true is not True:<EOL><INDENT>out_files.append(first_file_or_true)<EOL>hashes[hash_value] = True<EOL><DEDENT>out_files.append(filename)<EOL><DEDENT>else:<EOL><INDENT>hashes[hash_value] = filename<EOL><DEDENT><DEDENT><DEDENT>if out_files:<EOL><INDENT>potential_duplicate_sets.append(out_files)<EOL>potential_count = potential_count + len(out_files)<EOL><DEDENT><DEDENT>del files_by_size<EOL>log.info("<STR_LIT>"<EOL>"<STR_LIT>", potential_count, INITIAL_HASH_SIZE)<EOL>log.debug("<STR_LIT>",<EOL>pformat(potential_duplicate_sets))<EOL>log.info("<STR_LIT>")<EOL>num_scanned = <NUM_LIT:0><EOL>num_to_scan = sum(len(one_set) for one_set in potential_duplicate_sets)<EOL>duplicate_sets = [] <EOL>for one_set in potential_duplicate_sets:<EOL><INDENT>out_files = [] <EOL>hashes = {}<EOL>for filename in one_set:<EOL><INDENT>num_scanned += <NUM_LIT:1><EOL>log.info("<STR_LIT>",<EOL>num_scanned, num_to_scan, filename)<EOL>with open(filename, '<STR_LIT:rb>') as fd:<EOL><INDENT>hasher = md5()<EOL>while True:<EOL><INDENT>r = fd.read(MAIN_READ_CHUNK_SIZE)<EOL>if len(r) == <NUM_LIT:0>:<EOL><INDENT>break<EOL><DEDENT>hasher.update(r)<EOL><DEDENT><DEDENT>hash_value = hasher.digest()<EOL>if hash_value in hashes:<EOL><INDENT>if not out_files:<EOL><INDENT>out_files.append(hashes[hash_value])<EOL><DEDENT>out_files.append(filename)<EOL><DEDENT>else:<EOL><INDENT>hashes[hash_value] = filename<EOL><DEDENT><DEDENT>if len(out_files):<EOL><INDENT>duplicate_sets.append(out_files)<EOL><DEDENT><DEDENT>log.debug("<STR_LIT>", pformat(duplicate_sets))<EOL>num_originals = <NUM_LIT:0><EOL>num_deleted = <NUM_LIT:0><EOL>for d in duplicate_sets:<EOL><INDENT>print("<STR_LIT>".format(d[<NUM_LIT:0>]))<EOL>num_originals += <NUM_LIT:1><EOL>for f in d[<NUM_LIT:1>:]:<EOL><INDENT>if dummy_run:<EOL><INDENT>print("<STR_LIT>".format(f))<EOL><DEDENT>else:<EOL><INDENT>print("<STR_LIT>".format(f))<EOL>os.remove(f)<EOL><DEDENT>num_deleted += <NUM_LIT:1><EOL><DEDENT>print()<EOL><DEDENT>num_unique = num_considered - (num_originals + num_deleted)<EOL>print(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(<EOL>action="<STR_LIT>" if dummy_run else "<STR_LIT>",<EOL>d=num_deleted,<EOL>o=num_originals,<EOL>u=num_unique,<EOL>c=num_considered<EOL>)<EOL>)<EOL> | De-duplicate files within one or more directories. Remove files
that are identical to ones already considered.
Args:
directories: list of directories to process
recursive: process subdirectories (recursively)?
dummy_run: say what it'll do, but don't do it | f14573:m0 |
def main() -> None: | parser = ArgumentParser(<EOL>description="<STR_LIT>"<EOL>)<EOL>parser.add_argument(<EOL>"<STR_LIT>", nargs="<STR_LIT:+>",<EOL>help="<STR_LIT>"<EOL>)<EOL>parser.add_argument(<EOL>"<STR_LIT>", action="<STR_LIT:store_true>",<EOL>help="<STR_LIT>"<EOL>)<EOL>parser.add_argument(<EOL>"<STR_LIT>", action="<STR_LIT:store_true>",<EOL>help="<STR_LIT>"<EOL>)<EOL>parser.add_argument(<EOL>"<STR_LIT>", type=int,<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>)<EOL>parser.add_argument(<EOL>"<STR_LIT>", action="<STR_LIT:store_true>",<EOL>help="<STR_LIT>"<EOL>)<EOL>args = parser.parse_args()<EOL>main_only_quicksetup_rootlogger(<EOL>level=logging.DEBUG if args.verbose else logging.INFO)<EOL>while True:<EOL><INDENT>deduplicate(args.directory,<EOL>recursive=args.recursive,<EOL>dummy_run=args.dummy_run)<EOL>if args.run_repeatedly is None:<EOL><INDENT>break<EOL><DEDENT>log.info("<STR_LIT>", args.run_repeatedly)<EOL>sleep(args.run_repeatedly)<EOL><DEDENT> | Command-line processor. See ``--help`` for details. | f14573:m1 |
def merge_csv(filenames: List[str],<EOL>outfile: TextIO = sys.stdout,<EOL>input_dialect: str = '<STR_LIT>',<EOL>output_dialect: str = '<STR_LIT>',<EOL>debug: bool = False,<EOL>headers: bool = True) -> None: | writer = csv.writer(outfile, dialect=output_dialect)<EOL>written_header = False<EOL>header_items = [] <EOL>for filename in filenames:<EOL><INDENT>log.info("<STR_LIT>" + repr(filename))<EOL>with open(filename, '<STR_LIT:r>') as f:<EOL><INDENT>reader = csv.reader(f, dialect=input_dialect)<EOL>if headers:<EOL><INDENT>if not written_header:<EOL><INDENT>header_items = next(reader)<EOL>if debug:<EOL><INDENT>log.debug("<STR_LIT>", header_items)<EOL><DEDENT>writer.writerow(header_items)<EOL>written_header = True<EOL><DEDENT>else:<EOL><INDENT>new_headers = next(reader)<EOL>if new_headers != header_items:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(<EOL>filename=repr(filename),<EOL>new=repr(new_headers),<EOL>old=repr(header_items),<EOL>))<EOL><DEDENT>if debug:<EOL><INDENT>log.debug("<STR_LIT>")<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>if debug:<EOL><INDENT>log.debug("<STR_LIT>")<EOL><DEDENT><DEDENT>for row in reader:<EOL><INDENT>if debug:<EOL><INDENT>log.debug("<STR_LIT>", row)<EOL><DEDENT>writer.writerow(row)<EOL><DEDENT><DEDENT><DEDENT> | Amalgamate multiple CSV/TSV/similar files into one.
Args:
filenames: list of filenames to process
outfile: file-like object to write output to
input_dialect: dialect of input files, as passed to ``csv.reader``
output_dialect: dialect to write, as passed to ``csv.writer``
debug: be verbose?
headers: do the files have header lines? | f14574:m0 |
def main(): | main_only_quicksetup_rootlogger()<EOL>parser = argparse.ArgumentParser()<EOL>parser.add_argument(<EOL>"<STR_LIT>",<EOL>nargs="<STR_LIT:+>",<EOL>help="<STR_LIT>"<EOL>)<EOL>parser.add_argument(<EOL>"<STR_LIT>",<EOL>default="<STR_LIT:->",<EOL>help="<STR_LIT>",<EOL>)<EOL>parser.add_argument(<EOL>"<STR_LIT>",<EOL>default="<STR_LIT>",<EOL>help="<STR_LIT>",<EOL>choices=csv.list_dialects(),<EOL>)<EOL>parser.add_argument(<EOL>"<STR_LIT>",<EOL>default="<STR_LIT>",<EOL>help="<STR_LIT>",<EOL>choices=csv.list_dialects(),<EOL>)<EOL>parser.add_argument(<EOL>"<STR_LIT>",<EOL>action="<STR_LIT:store_true>",<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>",<EOL>)<EOL>parser.add_argument(<EOL>"<STR_LIT>",<EOL>action="<STR_LIT:store_true>",<EOL>help="<STR_LIT>",<EOL>)<EOL>progargs = parser.parse_args()<EOL>kwargs = {<EOL>"<STR_LIT>": progargs.filenames,<EOL>"<STR_LIT>": progargs.inputdialect,<EOL>"<STR_LIT>": progargs.outputdialect,<EOL>"<STR_LIT>": progargs.debug,<EOL>"<STR_LIT>": not progargs.noheaders,<EOL>}<EOL>if progargs.outfile == '<STR_LIT:->':<EOL><INDENT>log.info("<STR_LIT>")<EOL>merge_csv(outfile=sys.stdout, **kwargs)<EOL><DEDENT>else:<EOL><INDENT>log.info("<STR_LIT>" + repr(progargs.outfile))<EOL>with open(progargs.outfile, '<STR_LIT:w>') as outfile:<EOL><INDENT>merge_csv(outfile=outfile, **kwargs)<EOL><DEDENT><DEDENT> | Command-line processor. See ``--help`` for details. | f14574:m1 |
def get_mysql_vars(mysql: str,<EOL>host: str,<EOL>port: int,<EOL>user: str) -> Dict[str, str]: | cmdargs = [<EOL>mysql,<EOL>"<STR_LIT>", host,<EOL>"<STR_LIT>", str(port),<EOL>"<STR_LIT>", "<STR_LIT>",<EOL>"<STR_LIT>", user,<EOL>"<STR_LIT>" <EOL>]<EOL>log.info("<STR_LIT>", user)<EOL>log.debug(cmdargs)<EOL>process = subprocess.Popen(cmdargs, stdout=subprocess.PIPE)<EOL>out, err = process.communicate()<EOL>lines = out.decode("<STR_LIT:utf8>").splitlines()<EOL>mysqlvars = {}<EOL>for line in lines:<EOL><INDENT>var, val = line.split("<STR_LIT:\t>")<EOL>mysqlvars[var] = val<EOL><DEDENT>return mysqlvars<EOL> | Asks MySQL for its variables and status.
Args:
mysql: ``mysql`` executable filename
host: host name
port: TCP/IP port number
user: username
Returns:
dictionary of MySQL variables/values | f14575:m0 |
def val_mb(valstr: Union[int, str]) -> str: | try:<EOL><INDENT>return "<STR_LIT>".format(int(valstr) / (<NUM_LIT> * <NUM_LIT>))<EOL><DEDENT>except (TypeError, ValueError):<EOL><INDENT>return '<STR_LIT:?>'<EOL><DEDENT> | Converts a value in bytes (in string format) to megabytes. | f14575:m1 |
def val_int(val: int) -> str: | return str(val) + "<STR_LIT:U+0020>" * <NUM_LIT:4><EOL> | Formats an integer value. | f14575:m2 |
def add_var_mb(table: PrettyTable,<EOL>vardict: Dict[str, str],<EOL>varname: str) -> None: | valstr = vardict.get(varname, None)<EOL>table.add_row([varname, val_mb(valstr), UNITS_MB])<EOL> | Adds a row to ``table`` for ``varname``, in megabytes. | f14575:m3 |
def add_blank_row(table: PrettyTable) -> None: | table.add_row(['<STR_LIT>'] * <NUM_LIT:3>)<EOL> | Adds a blank row to ``table``. | f14575:m4 |
def main(): | main_only_quicksetup_rootlogger(level=logging.DEBUG)<EOL>parser = argparse.ArgumentParser()<EOL>parser.add_argument(<EOL>"<STR_LIT>", default="<STR_LIT>",<EOL>help="<STR_LIT>")<EOL>parser.add_argument(<EOL>"<STR_LIT>", default="<STR_LIT:127.0.0.1>",<EOL>help="<STR_LIT>")<EOL>parser.add_argument(<EOL>"<STR_LIT>", type=int, default=MYSQL_DEFAULT_PORT,<EOL>help="<STR_LIT>".format(MYSQL_DEFAULT_PORT))<EOL>parser.add_argument(<EOL>"<STR_LIT>", default=MYSQL_DEFAULT_USER,<EOL>help="<STR_LIT>".format(MYSQL_DEFAULT_USER))<EOL>args = parser.parse_args()<EOL>vardict = get_mysql_vars(<EOL>mysql=args.mysql,<EOL>host=args.host,<EOL>port=args.port,<EOL>user=args.user,<EOL>)<EOL>max_conn = int(vardict["<STR_LIT>"])<EOL>max_used_conn = int(vardict["<STR_LIT>"])<EOL>base_mem = (<EOL>int(vardict["<STR_LIT>"]) +<EOL>int(vardict["<STR_LIT>"]) +<EOL>int(vardict["<STR_LIT>"]) +<EOL>int(vardict["<STR_LIT>"])<EOL>)<EOL>mem_per_conn = (<EOL>int(vardict["<STR_LIT>"]) +<EOL>int(vardict["<STR_LIT>"]) +<EOL>int(vardict["<STR_LIT>"]) +<EOL>int(vardict["<STR_LIT>"]) +<EOL>int(vardict["<STR_LIT>"]) +<EOL>int(vardict["<STR_LIT>"]) +<EOL>int(vardict["<STR_LIT>"])<EOL>)<EOL>mem_total_min = base_mem + mem_per_conn * max_used_conn<EOL>mem_total_max = base_mem + mem_per_conn * max_conn<EOL>table = PrettyTable(["<STR_LIT>", "<STR_LIT>", "<STR_LIT>"])<EOL>table.align["<STR_LIT>"] = "<STR_LIT:l>"<EOL>table.align["<STR_LIT>"] = "<STR_LIT:r>"<EOL>table.align["<STR_LIT>"] = "<STR_LIT:l>"<EOL>add_var_mb(table, vardict, "<STR_LIT>")<EOL>add_var_mb(table, vardict, "<STR_LIT>")<EOL>add_var_mb(table, vardict, "<STR_LIT>")<EOL>add_var_mb(table, vardict, "<STR_LIT>")<EOL>add_blank_row(table)<EOL>table.add_row(["<STR_LIT>", val_mb(base_mem), UNITS_MB])<EOL>add_blank_row(table)<EOL>add_var_mb(table, vardict, "<STR_LIT>")<EOL>add_var_mb(table, vardict, "<STR_LIT>")<EOL>add_var_mb(table, vardict, "<STR_LIT>")<EOL>add_var_mb(table, vardict, "<STR_LIT>")<EOL>add_var_mb(table, vardict, "<STR_LIT>")<EOL>add_var_mb(table, vardict, "<STR_LIT>")<EOL>add_var_mb(table, vardict, "<STR_LIT>")<EOL>add_blank_row(table)<EOL>table.add_row(["<STR_LIT>", val_mb(mem_per_conn), UNITS_MB])<EOL>add_blank_row(table)<EOL>table.add_row(["<STR_LIT>", val_int(max_used_conn), '<STR_LIT>'])<EOL>table.add_row(["<STR_LIT>", val_int(max_conn), '<STR_LIT>'])<EOL>add_blank_row(table)<EOL>table.add_row(["<STR_LIT>", val_mb(mem_total_min), UNITS_MB])<EOL>table.add_row(["<STR_LIT>", val_mb(mem_total_max), UNITS_MB])<EOL>print(table.get_string())<EOL> | Command-line processor. See ``--help`` for details. | f14575:m5 |
def cmdargs(mysqldump: str,<EOL>username: str,<EOL>password: str,<EOL>database: str,<EOL>verbose: bool,<EOL>with_drop_create_database: bool,<EOL>max_allowed_packet: str,<EOL>hide_password: bool = False) -> List[str]: | ca = [<EOL>mysqldump,<EOL>"<STR_LIT>", username,<EOL>"<STR_LIT>".format("<STR_LIT>" if hide_password else password),<EOL>"<STR_LIT>".format(max_allowed_packet),<EOL>"<STR_LIT>", <EOL>]<EOL>if verbose:<EOL><INDENT>ca.append("<STR_LIT>")<EOL><DEDENT>if with_drop_create_database:<EOL><INDENT>ca.extend([<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>database<EOL>])<EOL><DEDENT>else:<EOL><INDENT>ca.append(database)<EOL>pass<EOL><DEDENT>return ca<EOL> | Returns command arguments for a ``mysqldump`` call.
Args:
mysqldump: ``mysqldump`` executable filename
username: user name
password: password
database: database name
verbose: verbose output?
with_drop_create_database: produce commands to ``DROP`` the database
and recreate it?
max_allowed_packet: passed to ``mysqldump``
hide_password: obscure the password (will break the arguments but
provide a safe version to show the user)?
Returns:
list of command-line arguments | f14577:m0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.