text stringlengths 81 112k |
|---|
Process an iterable of dictionaries. For each dictionary ``d``, convert
(in place) ``d[key]`` to a float. If that fails, convert it to ``None``.
def dictlist_convert_to_float(dict_list: Iterable[Dict], key: str) -> None:
"""
Process an iterable of dictionaries. For each dictionary ``d``, convert
(in pl... |
Process an iterable of dictionaries. For each dictionary ``d``, convert
(in place) ``d[key]`` to a bool. If that fails, convert it to ``None``.
def dictlist_convert_to_bool(dict_list: Iterable[Dict], key: str) -> None:
"""
Process an iterable of dictionaries. For each dictionary ``d``, convert
(in plac... |
Process an iterable of dictionaries. For each dictionary ``d``, change
(in place) ``d[key]`` to ``value``.
def dictlist_replace(dict_list: Iterable[Dict], key: str, value: Any) -> None:
"""
Process an iterable of dictionaries. For each dictionary ``d``, change
(in place) ``d[key]`` to ``value``.
""... |
Process an iterable of dictionaries. For each dictionary ``d``, delete
``d[key]`` if it exists.
def dictlist_wipe_key(dict_list: Iterable[Dict], key: str) -> None:
"""
Process an iterable of dictionaries. For each dictionary ``d``, delete
``d[key]`` if it exists.
"""
for d in dict_list:
... |
Takes a function and its args/kwargs, and produces a string description
of the function call (the call signature) suitable for use indirectly as a
cache key. The string is a JSON representation. See ``make_cache_key`` for
a more suitable actual cache key.
def get_call_signature(fn: FunctionType,
... |
Takes a function and its args/kwargs, and produces a string description
of the function call (the call signature) suitable for use as a cache key.
The string is an MD5 hash of the JSON-encoded call signature.
The logic behind these decisions is as follows:
- We have a bunch of components of arbitrary t... |
Decorator to add caching to a function in Django.
Uses the Django default cache.
Args:
timeout: timeout in seconds; use None for "never expire", as 0 means
"do not cache".
cache_key: optional cache key to use (if falsy, we'll invent one)
debug_cache: show hits/misses?
def... |
Create an affine transformation matrix that maps vector 1
onto vector 2
https://math.stackexchange.com/questions/293116/rotating-one-3d-vector-to-another
def transform(v1, v2):
"""
Create an affine transformation matrix that maps vector 1
onto vector 2
https://math.stackexchange.com/questions... |
Converts spherical positions in (lon, lat) to cartesian coordiantes [x,y,z].
For the purposes of this library's focus on orientations, this operates in a
*north = vertical* framework. That is, positions around the equator are in the
[x,y] plane, and dipping planes occur with higher latitudes.
This is i... |
Calculate the authentication headers to be sent with a request to the API.
:param app_id:
:param secret:
:param context
:param utc:
:return: array a map with the Authorization and Date headers needed to sign a Latch API request
def x_11paths_authorization(app_id, secret, context, utc=None):
""... |
Sign data.
:param data: the string to sign
:return: string base64 encoding of the HMAC-SHA1 hash of the data parameter using {@code secretKey} as cipher key.
def _sign_data(secret, data):
"""
Sign data.
:param data: the string to sign
:return: string base64 encoding of the HMAC-SHA1 hash of t... |
Prepares and returns a string ready to be signed from the 11-paths specific HTTP headers received.
:param x_headers: a non necessarily ordered map (array without duplicates) of the HTTP headers to be ordered.
:return: string The serialized headers, an empty string if no headers are passed, or None if there's a... |
Returns a 2x2 transformation matrix to rotate
by an angle in two dimensions
def rotate_2D(angle):
"""
Returns a 2x2 transformation matrix to rotate
by an angle in two dimensions
"""
return N.array([[N.cos(angle),-N.sin(angle)],
[N.sin(angle),N.cos(angle)]]) |
Produces a two-dimensional rotation matrix that
rotates a projected dataset to correct for apparent dip
def apparent_dip_correction(axes):
"""
Produces a two-dimensional rotation matrix that
rotates a projected dataset to correct for apparent dip
"""
a1 = axes[0].copy()
a1[-1] = 0
cosa ... |
Returns a function that can be used to create a view of the
hyperbolic error ellipse from a specific direction.
This creates a hyperbolic quadric and slices it to form a conic
on a 2d cartesian plane aligned with the requested direction.
A function is returned that takes x values (distance along nomin... |
kwargs:
transformation rotation to apply to quadric prior to slicing
(e.g. transformation into 'world' coordinates
axes axes on which to slice the data
def hyperbola_values(hyp_axes, xvals):
"""
kwargs:
transformation rotation to apply to quadric pri... |
Formats a number of bytes in a human-readable binary format (e.g. ``2048``
becomes ``'2 KiB'``); from http://stackoverflow.com/questions/1094841.
def sizeof_fmt(num: float, suffix: str = 'B') -> str:
"""
Formats a number of bytes in a human-readable binary format (e.g. ``2048``
becomes ``'2 KiB'``); fr... |
Converts a number of bytes into a human-readable format.
From http://code.activestate.com/recipes/578019-bytes-to-human-human-to-bytes-converter/.
Args:
n: number of bytes
format: a format specification string
symbols: can be one of ``"customary"``, ``"customary_ext"``, ``"iec"``
... |
Modified from
http://code.activestate.com/recipes/578019-bytes-to-human-human-to-bytes-converter/.
Attempts to guess the string format based on default symbols
set and return the corresponding bytes as an integer.
When unable to recognize the format, :exc:`ValueError` is raised.
>>> human2by... |
Describes how the tables found in the metadata depend on each other.
(If table B contains a foreign key to table A, for example, then B depends
on A.)
Args:
metadata: the metadata to inspect
extra_dependencies: additional table dependencies to specify manually
sort: sort into alphab... |
Inspects a metadata object (optionally adding other specified dependencies)
and returns a list of objects describing their dependencies.
Args:
metadata: the :class:`MetaData` to inspect
extra_dependencies: additional dependencies
sort: sort the results by table name?
Returns:
... |
Copies an entire database as far as it is described by ``metadata`` and
``base_class``, from SQLAlchemy ORM session ``src_session`` to
``dst_session``, and in the process:
- creates new primary keys at the destination, or raises an error if it
doesn't know how (typically something like: ``Field 'name... |
Sets the metadata for the parent and child tables.
def set_metadata(self, metadata: MetaData) -> None:
"""
Sets the metadata for the parent and child tables.
"""
self._parent.set_metadata(metadata)
self._child.set_metadata(metadata) |
Sets the metadata for the parent and child tables, unless they were
set already.
def set_metadata_if_none(self, metadata: MetaData) -> None:
"""
Sets the metadata for the parent and child tables, unless they were
set already.
"""
self._parent.set_metadata_if_none(metadat... |
Mark this table as circular (or not).
Args:
circular: is it circular?
chain: if it's circular, this should be the list of tables
participating in the circular chain
def set_circular(self, circular: bool, chain: List[Table] = None) -> None:
"""
Mark this ... |
Short description.
def description(self) -> str:
"""
Short description.
"""
if self.is_parent and self.is_child:
desc = "parent+child"
elif self.is_parent:
desc = "parent"
elif self.is_child:
desc = "child"
else:
de... |
Obtain a binary version of an :class:`openpyxl.Workbook` representation of
an Excel file.
def excel_to_bytes(wb: Workbook) -> bytes:
"""
Obtain a binary version of an :class:`openpyxl.Workbook` representation of
an Excel file.
"""
memfile = io.BytesIO()
wb.save(memfile)
return memfile.g... |
No error is propagated
def spherical(coordinates):
"""No error is propagated"""
c = coordinates
r = N.linalg.norm(c,axis=0)
theta = N.arccos(c[2]/r)
phi = N.arctan2(c[1],c[0])
return N.column_stack((r,theta,phi)) |
Centers coordinate distribution with respect to its
mean on all three axes. This is used as the input to
the regression model, so it can be converted easily
into radial coordinates.
def centered(coordinates):
"""
Centers coordinate distribution with respect to its
mean on all three axes. This i... |
Add HTTP headers to a Django response class object.
Args:
response: ``HttpResponse`` instance
offered_filename: filename that the client browser will suggest
content_type: HTTP content type
as_attachment: if True, browsers will generally save to disk.
If False, they may... |
Serve up a file from disk.
Two methods (chosen by ``settings.XSENDFILE``):
(a) serve directly
(b) serve by asking the web server to do so via the X-SendFile directive.
def serve_file(path_to_file: str,
offered_filename: str = None,
content_type: str = None,
as_a... |
Serve up binary data from a buffer.
Options as for ``serve_file()``.
def serve_buffer(data: bytes,
offered_filename: str = None,
content_type: str = None,
as_attachment: bool = True,
as_inline: bool = False) -> HttpResponse:
"""
Serve up b... |
Adds a ``Content-Disposition`` header to the HTTP response to say that
there is an attachment with the specified filename.
def add_download_filename(response: HttpResponse, filename: str) -> None:
"""
Adds a ``Content-Disposition`` header to the HTTP response to say that
there is an attachment with the... |
Returns an ``HttpResponse`` with an attachment containing the specified
data with the specified filename as an attachment.
def file_response(data: Union[bytes, str], # HttpResponse encodes str if req'd
content_type: str,
filename: str) -> HttpResponse:
"""
Returns an ``... |
Concatenates PDFs from disk and serves them.
def serve_concatenated_pdf_from_disk(
filenames: Iterable[str],
offered_filename: str = "crate_download.pdf",
**kwargs) -> HttpResponse:
"""
Concatenates PDFs from disk and serves them.
"""
pdf = get_concatenated_pdf_from_disk(filenam... |
Same args as ``pdf_from_html()``.
WATCH OUT: may not apply e.g. wkhtmltopdf options as you'd wish.
def serve_pdf_from_html(html: str,
offered_filename: str = "test.pdf",
**kwargs) -> HttpResponse:
"""
Same args as ``pdf_from_html()``.
WATCH OUT: may not a... |
Concatenates PDFs into memory and serves it.
WATCH OUT: may not apply e.g. wkhtmltopdf options as you'd wish.
def serve_concatenated_pdf_from_memory(
pdf_plans: Iterable[PdfPlan],
start_recto: bool = True,
offered_filename: str = "crate_download.pdf") -> HttpResponse:
"""
Concatenat... |
Deletes files from filesystem when object is deleted.
def auto_delete_files_on_instance_delete(instance: Any,
fieldnames: Iterable[str]) -> None:
"""
Deletes files from filesystem when object is deleted.
"""
for fieldname in fieldnames:
filefield = getat... |
Deletes files from filesystem when object is changed.
model_class: ``Type[Model]``
... only the type checker in Py3.5 is broken; v.s.
def auto_delete_files_on_instance_change(
instance: Any,
fieldnames: Iterable[str],
model_class) -> None:
"""
Deletes files from filesystem whe... |
Creates an affine transformation matrix to
rotate data in PCA axes into Cartesian plane
def axis_transform(pca_axes):
"""
Creates an affine transformation matrix to
rotate data in PCA axes into Cartesian plane
"""
from_ = N.identity(3)
to_ = pca_axes
# Find inverse transform for forwar... |
Constructs the covariance matrix of
input data from
the singular value decomposition. Note
that this is different than a covariance
matrix of residuals, which is what we want
for calculating fit errors.
Using SVD output to compute covariance matrix
X=UΣV⊤
XX⊤XX⊤=(UΣV⊤)(UΣV⊤)⊤=(UΣV⊤)(VΣU... |
Property to support lazy evaluation of residuals
def U(self):
"""
Property to support lazy evaluation of residuals
"""
if self._U is None:
sinv = N.diag(1/self.singular_values)
self._U = dot(self.arr,self.V.T,sinv)
return self._U |
Returns residuals of fit against all
three data axes (singular values 1, 2,
and 3). This takes the form of data along
singular axis 3 (axes 1 and 2 define the plane)
def residuals(self):
"""
Returns residuals of fit against all
three data axes (singular values 1, 2,
... |
The angular error for an in-plane axis of
given length (either a PCA major axis or
an intermediate direction).
def angular_error(self, axis_length):
"""
The angular error for an in-plane axis of
given length (either a PCA major axis or
an intermediate direction).
... |
Minimum and maximum angular errors
corresponding to 1st and 2nd axes
of PCA distribution.
def angular_errors(self, degrees=True):
"""
Minimum and maximum angular errors
corresponding to 1st and 2nd axes
of PCA distribution.
"""
hyp_axes = self.method(self... |
Constructs the covariance matrix from PCA
residuals
def _covariance_matrix(self, type='noise'):
"""
Constructs the covariance matrix from PCA
residuals
"""
if type == 'sampling':
return self.sigma**2/(self.n-1)
elif type == 'noise':
return... |
Proportion of variance that is explained by the
first two principal components (which together
represent the planar fit). Analogous to R^2 of
linear least squares.
def explained_variance(self):
"""
Proportion of variance that is explained by the
first two principal compo... |
Computes strike and dip from a normal vector.
Results are usually the same as LLSQ
in strike (to a few decimal places) and close in dip.
Sometimes, dips are greater by as much as 45 degrees,
reflecting inclusion of errors in x-y plane.
def strike_dip(self, degrees=True):
"""
... |
Hyperbolic error area
def as_hyperbola(self, rotated=False):
"""
Hyperbolic error area
"""
idx = N.diag_indices(3)
_ = 1/self.covariance_matrix[idx]
d = list(_)
d[-1] *= -1
arr = N.identity(4)*-1
arr[idx] = d
hyp = conic(arr)
if r... |
Extract words from tweet
1. Remove non-ascii characters
2. Split line into individual words
3. Clean up puncuation characters
def run(self, line):
"""
Extract words from tweet
1. Remove non-ascii characters
2. Split line into individual words
3. Clean u... |
Returns results and column names from a query.
Args:
session: SQLAlchemy :class:`Session`, :class:`Engine`, or
:class:`Connection` object
query: SQLAlchemy :class:`Query`
Returns:
``(rows, fieldnames)`` where ``rows`` is the usual set of results and
``fieldnames`` a... |
Database dialects are not consistent in how ``EXISTS`` clauses can be
converted to a boolean answer. This function manages the inconsistencies.
See:
- https://bitbucket.org/zzzeek/sqlalchemy/issues/3212/misleading-documentation-for-queryexists
- http://docs.sqlalchemy.org/en/latest/orm/query.html#... |
Detects whether a database record exists for the specified ``ormclass``
and ``criteria``.
Example usage:
.. code-block:: python
bool_exists = exists_orm(session, MyClass, MyClass.myfield == value)
def exists_orm(session: Session,
ormclass: DeclarativeMeta,
*criteria... |
Fetches an ORM object from the database, or creates one if none existed.
Args:
session: an SQLAlchemy :class:`Session`
model: an SQLAlchemy ORM class
defaults: default initialization arguments (in addition to relevant
filter criteria) if we have to create a new instance
... |
Implements the ``COUNT(*)`` specialization.
def count_star(self) -> int:
"""
Implements the ``COUNT(*)`` specialization.
"""
count_query = (self.statement.with_only_columns([func.count()])
.order_by(None))
return self.session.execute(count_query).scalar() |
Download GeoJSON file of US counties from url (S3 bucket)
def read(self, src):
""" Download GeoJSON file of US counties from url (S3 bucket) """
geojson = None
if not self.is_valid_src(src):
error = "File < {0} > does not exists or does start with 'http'."
raise ValueErr... |
Create and return ``num_bytes`` of random data.
The result is encoded in a string with URL-safe ``base64`` encoding.
Used (for example) to generate session tokens.
Which generator to use? See
https://cryptography.io/en/latest/random-numbers/.
Do NOT use these methods:
.. code-block:: python... |
Returns a SQLAlchemy :class:`Table` object. This is either the
:class:`Table` object that was used for initialization, or one that
was constructed from the ``tablename`` plus the ``metadata``.
def table(self) -> Table:
"""
Returns a SQLAlchemy :class:`Table` object. This is either the
... |
Returns the string name of the table.
def tablename(self) -> str:
"""
Returns the string name of the table.
"""
if self._tablename:
return self._tablename
return self.table.name |
Uses the Unix ``ps`` program to see if a process is running.
def is_running(process_id: int) -> bool:
"""
Uses the Unix ``ps`` program to see if a process is running.
"""
pstr = str(process_id)
encoding = sys.getdefaultencoding()
s = subprocess.Popen(["ps", "-p", pstr], stdout=subprocess.PIPE)
... |
Command-line handler for the ``pause_process_by_disk_space`` tool.
Use the ``--help`` option for help.
def main() -> None:
"""
Command-line handler for the ``pause_process_by_disk_space`` tool.
Use the ``--help`` option for help.
"""
parser = ArgumentParser(
description="Pauses and resu... |
Bootstrap by adding noise
def bootstrap_noise(data, func, n=10000, std=1, symmetric=True):
"""
Bootstrap by adding noise
"""
boot_dist = []
arr = N.zeros(data.shape)
for i in range(n):
if symmetric:
# Noise on all three axes
arr = N.random.randn(*data.shape)*std
... |
Default ``repr`` version of a Django model object, for debugging.
def modelrepr(instance) -> str:
"""
Default ``repr`` version of a Django model object, for debugging.
"""
elements = []
# noinspection PyProtectedMember
for f in instance._meta.get_fields():
# https://docs.djangoproject.c... |
Assert that a specific PDF processor is available.
Args:
processor: a PDF processor type from :class:`Processors`
Raises:
AssertionError: if bad ``processor``
RuntimeError: if requested processor is unavailable
def assert_processor_available(processor: str) -> None:
"""
Assert... |
Takes HTML and either returns a PDF in memory or makes one on disk.
For preference, uses ``wkhtmltopdf`` (with ``pdfkit``):
- faster than ``xhtml2pdf``
- tables not buggy like ``Weasyprint``
- however, doesn't support CSS Paged Media, so we have the
``header_html`` and ``footer_html`` options to... |
Takes HTML and returns a PDF.
See the arguments to :func:`make_pdf_from_html` (except ``on_disk``).
Returns:
the PDF binary as a ``bytes`` object
def get_pdf_from_html(html: str,
header_html: str = None,
footer_html: str = None,
wkhtml... |
Extracts a PDF (as binary data) from a PyPDF2 writer or merger object.
def pdf_from_writer(writer: Union[PdfFileWriter, PdfFileMerger]) -> bytes:
"""
Extracts a PDF (as binary data) from a PyPDF2 writer or merger object.
"""
memfile = io.BytesIO()
writer.write(memfile)
memfile.seek(0)
retur... |
Appends a PDF (as bytes in memory) to a PyPDF2 writer.
Args:
input_pdf: the PDF, as ``bytes``
writer: the writer
start_recto: start a new right-hand page?
def append_memory_pdf_to_writer(input_pdf: bytes,
writer: PdfFileWriter,
... |
Appends a PDF to a pyPDF writer. Legacy interface.
def append_pdf(input_pdf: bytes, output_writer: PdfFileWriter):
"""
Appends a PDF to a pyPDF writer. Legacy interface.
"""
append_memory_pdf_to_writer(input_pdf=input_pdf,
writer=output_writer) |
Concatenates PDFs from disk and returns them as an in-memory binary PDF.
Args:
filenames: iterable of filenames of PDFs to concatenate
start_recto: start a new right-hand page for each new PDF?
Returns:
concatenated PDF, as ``bytes``
def get_concatenated_pdf_from_disk(filenames: Itera... |
Concatenates PDFs and returns them as an in-memory binary PDF.
Args:
pdf_plans: iterable of :class:`PdfPlan` objects
start_recto: start a new right-hand page for each new PDF?
Returns:
concatenated PDF, as ``bytes``
def get_concatenated_pdf_in_memory(
pdf_plans: Iterable[PdfPl... |
Add the PDF described by this class to a PDF writer.
Args:
writer: a :class:`PyPDF2.PdfFileWriter`
start_recto: start a new right-hand page?
def add_to_writer(self,
writer: PdfFileWriter,
start_recto: bool = True) -> None:
"""
... |
Truncates floats that are integers to their integer representation.
That is, converts ``1.0`` to ``1``, etc.
Otherwise, returns the starting value.
Will raise an exception if the input cannot be converted to ``int``.
def trunc_if_integer(n: Any) -> Any:
"""
Truncates floats that are integers to the... |
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:... |
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... |
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: ... |
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 o... |
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 addres... |
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
join... |
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
compac... |
Convert a duration in days to a NumPy ``timedelta64`` object.
def timedelta_days(days: int) -> timedelta64:
"""
Convert a duration in days to a NumPy ``timedelta64`` object.
"""
int_days = int(days)
if int_days != days:
raise ValueError("Fractional days passed to timedelta_days: "
... |
Create a results row for this application.
def _get_generic_two_antidep_episodes_result(
rowdata: Tuple[Any, ...] = None) -> DataFrame:
"""
Create a results row for this application.
"""
# Valid data types... see:
# - pandas.core.dtypes.common.pandas_dtype
# - https://pandas.pydata.org/... |
Processes a single patient for ``two_antidepressant_episodes()`` (q.v.).
Implements the key algorithm.
def two_antidepressant_episodes_single_patient(
patient_id: str,
patient_drug_date_df: DataFrame,
patient_colname: str = DEFAULT_SOURCE_PATIENT_COLNAME,
drug_colname: str = DEFAUL... |
Takes a *pandas* ``DataFrame``, ``patient_drug_date_df`` (or, via
``reticulate``, an R ``data.frame`` or ``data.table``). This should contain
dated present-tense references to antidepressant drugs (only).
Returns a set of result rows as a ``DataFrame``.
def two_antidepressant_episodes(
patient_dru... |
The unrtf tool supports the '--quiet' argument from a version that I'm not
quite sure of, where ``0.19.3 < version <= 0.21.9``. We check against
0.21.9 here.
def does_unrtf_support_quiet() -> bool:
"""
The unrtf tool supports the '--quiet' argument from a version that I'm not
quite sure of, where `... |
Open a file-like object.
Guard the use of this function with ``with``.
Args:
filename: for specifying via a filename
blob: for specifying via an in-memory ``bytes`` object
Returns:
a :class:`BinaryIO` object
def get_filelikeobject(filename: str = None,
blob... |
Returns the binary contents of a file, or of a BLOB.
def get_file_contents(filename: str = None, blob: bytes = None) -> bytes:
"""
Returns the binary contents of a file, or of a BLOB.
"""
if not filename and not blob:
raise ValueError("no filename and no blob")
if filename and blob:
... |
Guess the character set encoding of the specified ``binary_contents``.
def get_chardet_encoding(binary_contents: bytes) -> Optional[str]:
"""
Guess the character set encoding of the specified ``binary_contents``.
"""
if not binary_contents:
return None
if chardet is None or UniversalDetecto... |
Returns the string contents of a file, or of a BLOB.
def get_file_contents_text(
filename: str = None, blob: bytes = None,
config: TextProcessingConfig = _DEFAULT_CONFIG) -> str:
"""
Returns the string contents of a file, or of a BLOB.
"""
binary_contents = get_file_contents(filename=fi... |
Returns text output of a command.
def get_cmd_output(*args, encoding: str = SYS_ENCODING) -> str:
"""
Returns text output of a command.
"""
log.debug("get_cmd_output(): args = {!r}", args)
p = subprocess.Popen(args, stdout=subprocess.PIPE)
stdout, stderr = p.communicate()
return stdout.deco... |
Returns text output of a command, passing binary data in via stdin.
def get_cmd_output_from_stdin(stdint_content_binary: bytes,
*args, encoding: str = SYS_ENCODING) -> str:
"""
Returns text output of a command, passing binary data in via stdin.
"""
p = subprocess.Popen(arg... |
Converts a PDF file to text.
Pass either a filename or a binary object.
def convert_pdf_to_txt(filename: str = None, blob: bytes = None,
config: TextProcessingConfig = _DEFAULT_CONFIG) -> str:
"""
Converts a PDF file to text.
Pass either a filename or a binary object.
"""
... |
Is a PDF-to-text tool available?
def availability_pdf() -> bool:
"""
Is a PDF-to-text tool available?
"""
pdftotext = tools['pdftotext']
if pdftotext:
return True
elif pdfminer:
log.warning("PDF conversion: pdftotext missing; "
"using pdfminer (less efficient... |
Generate XML files (as strings) from a DOCX file.
Args:
fp: :class:`BinaryIO` object for reading the ``.DOCX`` file
Yields:
the string contents of each individual XML file within the ``.DOCX``
file
Raises:
zipfile.BadZipFile: if the zip is unreadable (encrypted?)
def gen_... |
Converts an XML tree of a DOCX file to string contents.
Args:
xml: raw XML text
config: :class:`TextProcessingConfig` control object
Returns:
contents as a string
def docx_text_from_xml(xml: str, config: TextProcessingConfig) -> str:
"""
Converts an XML tree of a DOCX file to ... |
Returns text from an XML node within a DOCX file.
Args:
node: an XML node
level: current level in XML hierarchy (used for recursion; start level
is 0)
config: :class:`TextProcessingConfig` control object
Returns:
contents as a string
def docx_text_from_xml_node(nod... |
Converts an XML node representing a DOCX table into a textual
representation.
Args:
table_node: XML node
level: current level in XML hierarchy (used for recursion; start level
is 0)
config: :class:`TextProcessingConfig` control object
Returns:
string representat... |
Word-wraps text.
Args:
text: text to process
width: width to word-wrap to (or 0 to skip word wrapping)
Returns:
wrapped text
def docx_process_simple_text(text: str, width: int) -> str:
"""
Word-wraps text.
Args:
text: text to process
width: width to word-w... |
Converts a DOCX table to text.
Structure representing a DOCX table:
.. code-block:: none
table
.rows[]
.cells[]
.paragraphs[]
.text
That's the structure of a :class:`docx.table.Table` object, but also of our
homebrew cre... |
Iterate through items of a DOCX file.
See https://github.com/python-openxml/python-docx/issues/40.
Yield each paragraph and table child within ``parent``, in document order.
Each returned value is an instance of either :class:`Table` or
:class:`Paragraph`. ``parent`` would most commonly be a reference... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.