text stringlengths 81 112k |
|---|
Serialize an orientation object to a dict suitable
for JSON
def serialize(pca, **kwargs):
"""
Serialize an orientation object to a dict suitable
for JSON
"""
strike, dip, rake = pca.strike_dip_rake()
hyp_axes = sampling_axes(pca)
return dict(
**kwargs,
principal_axes = ... |
Under UNIX: is a keystroke available?
def _kbhit_unix() -> bool:
"""
Under UNIX: is a keystroke available?
"""
dr, dw, de = select.select([sys.stdin], [], [], 0)
return dr != [] |
Command to produce an :class:`InsertOnDuplicate` object.
Args:
tablename: name of the table
values: values to ``INSERT``
inline: as per
http://docs.sqlalchemy.org/en/latest/core/dml.html#sqlalchemy.sql.expression.insert
kwargs: additional parameters
Returns:
... |
Hooks into the use of the :class:`InsertOnDuplicate` class
for the MySQL dialect. Compiles the relevant SQL for an ``INSERT...
ON DUPLICATE KEY UPDATE`` statement.
Notes:
- We can't get the fieldnames directly from ``insert`` or ``compiler``.
- We could rewrite the innards of the visit_insert sta... |
Create groups of an orientation measurement dataset
def create_groups(orientations, *groups, **kwargs):
"""
Create groups of an orientation measurement dataset
"""
grouped = []
# Copy all datasets to be safe (this could be bad for
# memory usage, so can be disabled).
if kwargs.pop('copy', T... |
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``
deb... |
Command-line processor. See ``--help`` for details.
def main():
"""
Command-line processor. See ``--help`` for details.
"""
main_only_quicksetup_rootlogger()
parser = argparse.ArgumentParser()
parser.add_argument(
"filenames",
nargs="+",
help="Names of CSV/TSV files to ... |
r"""
Standard softmax function:
.. math::
P_i = \frac {e ^ {\beta \cdot x_i}} { \sum_{i}{\beta \cdot x_i} }
Args:
x: vector (``numpy.array``) of values
b: exploration parameter :math:`\beta`, or inverse temperature
[Daw2009], or :math:`1/t`; see below
Returns:
... |
r"""
Standard logistic function.
.. math::
y = \frac {1} {1 + e^{-k (x - \theta)}}
Args:
x: :math:`x`
k: :math:`k`
theta: :math:`\theta`
Returns:
:math:`y`
def logistic(x: Union[float, np.ndarray],
k: float,
theta: float) -> Optional... |
r"""
Inverse standard logistic function:
.. math::
x = ( log( \frac {1} {y} - 1) / -k ) + \theta
Args:
y: :math:`y`
k: :math:`k`
theta: :math:`\theta`
Returns:
:math:`x`
def inv_logistic(y: Union[float, np.ndarray],
k: float,
... |
lookup object based on point as [longitude, latitude]
def get_object(self, point, buffer_size=0, multiple=False):
""" lookup object based on point as [longitude, latitude] """
# first search bounding boxes
# idx.intersection method modifies input if it is a list
try:
tmp = t... |
Build a RTree index to disk using bounding box of each feature
def _build_from_geojson(self, src):
""" Build a RTree index to disk using bounding box of each feature """
geojson = json.loads(self.read(src))
idx = index.Index()
data_store = {}
for i, feature in enumerate(geojson[... |
lookup state and county based on geohash of coordinates from tweet
def get(self, point, buffer_size=0, multiple=False):
""" lookup state and county based on geohash of coordinates from tweet """
lon, lat = point
geohash = Geohash.encode(lat, lon, precision=self.precision)
key = (geohash... |
Convert nose-style test reports to UnitTH-style test reports by splitting modules into separate XML files
Args:
in_file_nose (:obj:`str`): path to nose-style test report
out_file_unitth (:obj:`str`): path to save UnitTH-style test reports
def run(in_file_nose, out_dir_unitth):
... |
Parse nose-style test reports into a `dict`
Args:
in_file (:obj:`str`): path to nose-style test report
Returns:
:obj:`dict`: dictionary of test suites
def read_nose(in_file):
""" Parse nose-style test reports into a `dict`
Args:
in_file (:obj:`str`... |
Write UnitTH-style test reports
Args:
suites (:obj:`dict`): dictionary of test suites
out_dir (:obj:`str`): path to save UnitTH-style test reports
def write_unitth(suites, out_dir):
""" Write UnitTH-style test reports
Args:
suites (:obj:`dict`): dictionar... |
Plots asymptotic error bounds for
hyperbola on a stereonet.
def error_asymptotes(pca,**kwargs):
"""
Plots asymptotic error bounds for
hyperbola on a stereonet.
"""
ax = kwargs.pop("ax",current_axes())
lon,lat = pca.plane_errors('upper', n=1000)
ax.plot(lon,lat,'-')
lon,lat = pca.p... |
Returns results and column names from a query.
Args:
session: SQLAlchemy :class:`Session`, :class:`Engine`, or
:class:`Connection` object
sql: raw SQL to execure
Returns:
``(rows, fieldnames)`` where ``rows`` is the usual set of results and
``fieldnames`` are the na... |
Returns the result of ``COUNT(*)`` from the specified table (with
additional ``WHERE`` criteria if desired).
Args:
session: SQLAlchemy :class:`Session`, :class:`Engine`, or
:class:`Connection` object
tablename: name of the table
criteria: optional SQLAlchemy "where" criteria... |
Implements an efficient way of detecting if a record or records exist;
should be faster than ``COUNT(*)`` in some circumstances.
Args:
session: SQLAlchemy :class:`Session`, :class:`Engine`, or
:class:`Connection` object
table_: SQLAlchemy :class:`Table` object
criteria: opti... |
Implements an efficient way of detecting if a record or records exist;
should be faster than COUNT(*) in some circumstances.
Args:
session: SQLAlchemy :class:`Session`, :class:`Engine`, or
:class:`Connection` object
tablename: name of the table
criteria: optional SQLAlchemy ... |
Returns a list of the first values in each row returned by a ``SELECT``
query.
A Core version of this sort of thing:
http://xion.io/post/code/sqlalchemy-query-values.html
Args:
session: SQLAlchemy :class:`Session` object
select_statement: SQLAlchemy :class:`Select` object
Returns:... |
Plots a hyperbola that opens along y axis
def hyperbola(axes, **kwargs):
"""
Plots a hyperbola that opens along y axis
"""
opens_up = kwargs.pop('opens_up', True)
center = kwargs.pop('center', defaults['center'])
th = N.linspace(0,2*N.pi,kwargs.pop('n', 500))
vals = [N.tan(th),1/N.cos(th)]... |
This method doesn't work as well
def __reverse_ellipse(axes, scalar=1):
"""
This method doesn't work as well
"""
ax1 = axes.copy()[::-1]*scalar
center = ax1[1]*N.sqrt(2)*scalar
return ax1, center |
If we're running under SQL Server, disable constraint checking for the
specified table while the resource is held.
Args:
session: SQLAlchemy :class:`Session`
tablename: table name
See
https://stackoverflow.com/questions/123558/sql-server-2005-t-sql-to-temporarily-disable-a-trigger
def... |
If we're running under SQL Server, disable triggers AND constraints for the
specified table while the resource is held.
Args:
session: SQLAlchemy :class:`Session`
tablename: table name
def if_sqlserver_disable_constraints_triggers(session: SqlASession,
... |
From one document or action definition passed in by the user extract the
action/data lines needed for elasticsearch's
:meth:`~elasticsearch.Elasticsearch.bulk` api.
:return es format to bulk doc
def expand_action(data):
"""
From one document or action definition passed in by the... |
Helper for the :meth:`~elasticsearch.Elasticsearch.bulk` api that provides
a more human friendly interface - it consumes an iterator of actions and
sends them to elasticsearch in chunks. It returns a tuple with summary
information - number of successfully executed actions and either list of
... |
Streaming bulk consumes actions from the iterable passed in and return the results of all bulk data
:func:`~elasticsearch.helpers.bulk` which is a wrapper around streaming
bulk that returns summary information about the bulk operation once the
entire input is consumed and sent.
:arg acti... |
Send a bulk request to elasticsearch and process the output.
def _process_bulk_chunk(self, bulk_actions, raise_on_exception=True, raise_on_error=True, **kwargs):
"""
Send a bulk request to elasticsearch and process the output.
"""
# if raise on error is set, we need to collect errors pe... |
Gets the HTML to display for reCAPTCHA
site_key -- The site key
language -- The language code for the widget.
theme -- The color theme of the widget. `light` or `dark`
fallback -- Old version recaptcha.
d_type -- The type of CAPTCHA to serve. `image` or `audio`
size -- The size of the dispalyed... |
Submits a reCAPTCHA request for verification. Returns RecaptchaResponse
for the request
recaptcha_response_field -- The value from the form
secret_key -- your reCAPTCHA secret key
remoteip -- the user's ip address
def submit(recaptcha_response_field,
secret_key,
remoteip,
... |
Ask Alembic what its head revision is (i.e. where the Python code would
like the database to be at).
Arguments:
alembic_config_filename: config filename
alembic_base_dir: directory to start in, so relative paths in the
config file work.
version_table: table name for Alembic ... |
Ask the database what its current revision is.
Arguments:
database_url: SQLAlchemy URL for the database
version_table: table name for Alembic versions
def get_current_revision(
database_url: str,
version_table: str = DEFAULT_ALEMBIC_VERSION_TABLE) -> str:
"""
Ask the databa... |
Returns a tuple of ``(current_revision, head_revision)``; see
:func:`get_current_revision` and :func:`get_head_revision_from_alembic`.
Arguments:
database_url: SQLAlchemy URL for the database
alembic_config_filename: config filename
alembic_base_dir: directory to start in, so relative p... |
Use Alembic to upgrade our database.
See http://alembic.readthedocs.org/en/latest/api/runtime.html
but also, in particular, ``site-packages/alembic/command.py``
Arguments:
alembic_config_filename:
config filename
alembic_base_dir:
directory to start in, so relative... |
Create a new Alembic migration script.
Alembic compares the **state of the database** to the **state of the
metadata**, and generates a migration that brings the former up to the
latter. (It does **not** compare the most recent revision to the current
metadata, so make sure your database is up to d... |
Stamps the Alembic version table with the given revision; don't run any
migrations.
This function is a clone of ``alembic.command.stamp()``, but allowing
``version_table`` to change. See
http://alembic.zzzcomputing.com/en/latest/api/commands.html#alembic.command.stamp
def stamp_allowing_unusual_versio... |
Parameters:
+------+--------+
| key | value |
+======+========+
| key1 | value1 |
+------+--------+
| key2 | value2 |
+------+--------+
def set_url_path_with_params(context, url_path_str_format):
"""
Parameters:
+------+--------+
| key... |
Parameters:
+--------------+---------------+
| header_name | header_value |
+==============+===============+
| header1 | value1 |
+--------------+---------------+
| header2 | value2 |
+--------------+---------------+
def set_headers(con... |
Parameters:
+-------------+--------------+
| param_name | param_value |
+=============+==============+
| param1 | value1 |
+-------------+--------------+
| param2 | value2 |
+-------------+--------------+
def set_form_parameters(context):... |
Parameters:
+-------------+--------------+
| param_name | path_to_file |
+=============+==============+
| param1 | value1 |
+-------------+--------------+
| param2 | value2 |
+-------------+--------------+
def set_body_files(context):
... |
Parameters:
+-------------+--------------+
| param_name | param_value |
+=============+==============+
| param1 | value1 |
+-------------+--------------+
| param2 | value2 |
+-------------+--------------+
def send_http_request_with_query_... |
Parameters:
+-------------+--------------+
| param_name | param_value |
+=============+==============+
| param1 | value1 |
+-------------+--------------+
| param2 | value2 |
+-------------+--------------+
def send_http_request_with_body_p... |
Parameters:
+-------------+--------------+
| param_name | param_value |
+=============+==============+
| param1 | value1 |
+-------------+--------------+
| param2 | value2 |
+-------------+--------------+
def send_http_request_with_form_p... |
Parameters:
.. code-block:: json
{
"param1": "value1",
"param2": "value2",
"param3": {
"param31": "value31"
}
}
def send_http_request_with_json(context, method):
"""
Parameters:
.. cod... |
Takes a command-line command, executes it, and returns its ``stdout``
output.
Args:
command: command string
Returns:
output from the command as ``bytes``
def get_external_command_output(command: str) -> bytes:
"""
Takes a command-line command, executes it, and returns its ``stdout... |
Get the output from a piped series of commands.
Args:
commands: sequence of command strings
stdinput: optional ``stdin`` data to feed into the start of the pipe
Returns:
``stdout`` from the end of the pipe
def get_pipe_series_output(commands: Sequence[str],
... |
Launches a file using the operating system's standard launcher.
Args:
filename: file to launch
raise_if_fails: raise any exceptions from
``subprocess.call(["xdg-open", filename])`` (Linux)
or ``os.startfile(filename)`` (otherwise)? If not, exceptions
are suppress... |
Kills a tree of processes, starting with the parent. Slightly modified from
https://stackoverflow.com/questions/1230669/subprocess-deleting-child-processes-in-windows.
Args:
pid: process ID of the parent
including_parent: kill the parent too?
timeout_s: timeout to wait for processes... |
Makes an SQLAlchemy URL for a MySQL database.
def make_mysql_url(username: str, password: str, dbname: str,
driver: str = "mysqldb", host: str = "localhost",
port: int = 3306, charset: str = "utf8") -> str:
"""
Makes an SQLAlchemy URL for a MySQL database.
"""
retu... |
Makes an SQLAlchemy URL for a SQLite database.
def make_sqlite_url(filename: str) -> str:
"""
Makes an SQLAlchemy URL for a SQLite database.
"""
absfile = os.path.abspath(filename)
return "sqlite://{host}/{path}".format(host="", path=absfile) |
Gets the SQLAlchemy :class:`Engine` from a SQLAlchemy :class:`Session`.
def get_engine_from_session(dbsession: Session) -> Engine:
"""
Gets the SQLAlchemy :class:`Engine` from a SQLAlchemy :class:`Session`.
"""
engine = dbsession.bind
assert isinstance(engine, Engine)
return engine |
Gets a URL from an :class:`Engine`, obscuring the password.
def get_safe_url_from_engine(engine: Engine) -> str:
"""
Gets a URL from an :class:`Engine`, obscuring the password.
"""
raw_url = engine.url # type: str
url_obj = make_url(raw_url) # type: URL
return repr(url_obj) |
Converts strings to integers if they're composed of digits; otherwise
returns the strings unchanged. One way of sorting strings with numbers;
it will mean that ``"11"`` is more than ``"2"``.
def atoi(text: str) -> Union[int, str]:
"""
Converts strings to integers if they're composed of digits; otherwis... |
Sort key function.
Returns text split into string/number parts, for natural sorting; as per
http://stackoverflow.com/questions/5967500/how-to-correctly-sort-a-string-with-a-number-inside
Example (as per the source above):
.. code-block:: python
>>> from cardinal_pythonlib.sort... |
Return a pretty printed body using the Content-Type header information.
:param headers: Headers for the request/response (dict)
:param body: Body to pretty print (string)
:return: Body pretty printed (string)
def _get_pretty_body(headers, body):
"""
Return a pretty printed body using the Content-T... |
Log an HTTP request data in a user-friendly representation.
:param method: HTTP method
:param url: URL
:param query_params: Query parameters in the URL
:param headers: Headers (dict)
:param body: Body (raw body, string)
:return: None
def log_print_request(method, url, query_params=None, header... |
Log an HTTP response data in a user-friendly representation.
:param status_code: HTTP Status Code
:param response: Raw response content (string)
:param headers: Headers in the response (dict)
:return: None
def log_print_response(status_code, response, headers=None):
"""
Log an HTTP response da... |
Converts a set of ``args`` and ``kwargs`` to an ``InitDict``.
def args_kwargs_to_initdict(args: ArgsList, kwargs: KwargsDict) -> InitDict:
"""
Converts a set of ``args`` and ``kwargs`` to an ``InitDict``.
"""
return {ARGS_LABEL: args,
KWARGS_LABEL: kwargs} |
Clones a dictionary, removing leading underscores from key names.
Raises ``ValueError`` if this causes an attribute conflict.
def strip_leading_underscores_from_keys(d: Dict) -> Dict:
"""
Clones a dictionary, removing leading underscores from key names.
Raises ``ValueError`` if this causes an attribute... |
Ensures that its parameter is a proper ``InitDict``, or raises
``ValueError``.
def verify_initdict(initdict: InitDict) -> None:
"""
Ensures that its parameter is a proper ``InitDict``, or raises
``ValueError``.
"""
if (not isinstance(initdict, dict) or
ARGS_LABEL not in initdict or
... |
Converse of simple_to_dict().
Given that JSON dictionary, we will end up re-instantiating the class with
.. code-block:: python
d = {'a': 1, 'b': 2, 'c': 3}
new_x = SimpleClass(**d)
We'll also support arbitrary creation, by using both ``*args`` and
``**kwargs``.
def initdict_to_insta... |
Wraps a function producing a ``KwargsDict``, making it into a function
producing an ``InitDict``.
def wrap_kwargs_to_initdict(init_kwargs_fn: InitKwargsFnType,
typename: str,
check_result: bool = True) \
-> InstanceToInitDictFnType:
"""
Wraps ... |
Wraps a function producing a ``KwargsDict``, making it into a function
producing an ``InitDict``.
def wrap_args_kwargs_to_initdict(init_args_kwargs_fn: InitArgsKwargsFnType,
typename: str,
check_result: bool = True) \
-> InstanceToInitDictFn... |
Returns a function that takes an object (instance) and produces an
``InitDict`` enabling its re-creation.
def make_instance_to_initdict(attributes: List[str]) -> InstanceToDictFnType:
"""
Returns a function that takes an object (instance) and produces an
``InitDict`` enabling its re-creation.
"""
... |
Registers the class cls for JSON serialization.
- If both ``obj_to_dict_fn`` and dict_to_obj_fn are registered, the
framework uses these to convert instances of the class to/from Python
dictionaries, which are in turn serialized to JSON.
- Otherwise:
.. code-block:: python
if metho... |
Class decorator to register classes with our JSON system.
- If method is ``'provides_init_args_kwargs'``, the class provides a
function
.. code-block:: python
def init_args_kwargs(self) -> Tuple[List[Any], Dict[str, Any]]
that returns an ``(args, kwargs)`` tuple, suitable for passing t... |
Prints the JSON "registered types" map to the specified file.
def dump_map(file: TextIO = sys.stdout) -> None:
"""
Prints the JSON "registered types" map to the specified file.
"""
pp = pprint.PrettyPrinter(indent=4, stream=file)
print("Type map: ", file=file)
pp.pprint(TYPE_MAP) |
Provides a JSON decoder that converts dictionaries to Python objects if
suitable methods are found in our ``TYPE_MAP``.
def json_class_decoder_hook(d: Dict) -> Any:
"""
Provides a JSON decoder that converts dictionaries to Python objects if
suitable methods are found in our ``TYPE_MAP``.
"""
if... |
Encodes an object to JSON using our custom encoder.
The ``**kwargs`` can be used to pass things like ``'indent'``, for
formatting.
def json_encode(obj: Instance, **kwargs) -> str:
"""
Encodes an object to JSON using our custom encoder.
The ``**kwargs`` can be used to pass things like ``'indent'``... |
Decodes an object from JSON using our custom decoder.
def json_decode(s: str) -> Any:
"""
Decodes an object from JSON using our custom decoder.
"""
try:
return json.JSONDecoder(object_hook=json_class_decoder_hook).decode(s)
except json.JSONDecodeError:
log.warning("Failed to decode ... |
Converts an ``dict`` to a ``Enum``.
def dict_to_enum_fn(d: Dict[str, Any], enum_class: Type[Enum]) -> Enum:
"""
Converts an ``dict`` to a ``Enum``.
"""
return enum_class[d['name']] |
Class decorator to register ``Enum``-derived classes with our JSON system.
See comments/help for ``@register_for_json``, above.
def register_enum_for_json(*args, **kwargs) -> Any:
"""
Class decorator to register ``Enum``-derived classes with our JSON system.
See comments/help for ``@register_for_json``... |
Converts a ``dict`` object back to a ``Pendulum``.
def dict_to_pendulum(d: Dict[str, Any],
pendulum_class: ClassType) -> DateTime:
"""
Converts a ``dict`` object back to a ``Pendulum``.
"""
return pendulum.parse(d['iso']) |
Converts a ``dict`` object back to a ``pendulum.Date``.
def dict_to_pendulumdate(d: Dict[str, Any],
pendulumdate_class: ClassType) -> Date:
"""
Converts a ``dict`` object back to a ``pendulum.Date``.
"""
# noinspection PyTypeChecker
return pendulum.parse(d['iso']).date() |
Test if two objects are equal, based on a comparison of the specified
attributes ``attrs``.
def simple_eq(one: Instance, two: Instance, attrs: List[str]) -> bool:
"""
Test if two objects are equal, based on a comparison of the specified
attributes ``attrs``.
"""
return all(getattr(one, a) == ge... |
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.
def smart_open(filename: str, mode: str = 'Ur', buffering: int = -1,
encoding: str ... |
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)
def writelines_nl(fileobj: TextIO, lines: Iterable[str]) -> None:
"""
Write... |
Writes text to a file.
def write_text(filename: str, text: str) -> None:
"""
Writes text to a file.
"""
with open(filename, 'w') as f: # type: TextIO
print(text, file=f) |
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:
- http... |
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!
def get_lines_without_comments(filename: str) -> List[str]:
"""
Reads a file, and returns all lines as a list, ... |
Generates file-like objects from a list of filenames.
Args:
filenames: iterable of filenames
Yields:
each file as a :class:`TextIO` object
def gen_textfiles_from_filenames(
filenames: Iterable[str]) -> Generator[TextIO, None, None]:
"""
Generates file-like objects from a list ... |
Generates lines from file-like objects.
Args:
files: iterable of :class:`TextIO` objects
Yields:
each line of all the files
def gen_lines_from_textfiles(
files: Iterable[TextIO]) -> Generator[str, None, None]:
"""
Generates lines from file-like objects.
Args:
file... |
Args:
x: iterable of strings
Yields:
each string in lower case
def gen_lower(x: Iterable[str]) -> Generator[str, None, None]:
"""
Args:
x: iterable of strings
Yields:
each string in lower case
"""
for string in x:
yield string.lower() |
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
def gen_lines_from_binary_files(
files: Iterable[BinaryIO],
encoding: str = UTF8) -> Ge... |
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
def gen_part_from_line(lines: Iterable[str],
... |
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``
def gen_part_from_iterables(iterables: Iterable[Any],
part_index: int) -> Generat... |
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 :f... |
Rewrites a file from ``srcfilename`` to ``destfilename``, HTML-escaping it
in the process.
def webify_file(srcfilename: str, destfilename: str) -> None:
"""
Rewrites a file from ``srcfilename`` to ``destfilename``, HTML-escaping it
in the process.
"""
with open(srcfilename) as infile, open(dest... |
Uses external ``gunzip``/``gzip`` tools to remove a ``gzip`` timestamp.
Necessary for Lintian.
def remove_gzip_timestamp(filename: str,
gunzip_executable: str = "gunzip",
gzip_executable: str = "gzip",
gzip_args: List[str] = None) -> Non... |
Replaces text in a file.
Args:
filename: filename to process (modifying it in place)
text_from: original text to replace
text_to: replacement text
def replace_in_file(filename: str, text_from: str, text_to: str) -> None:
"""
Replaces text in a file.
Args:
filename: fil... |
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
def replace_multiple_in_file(filename: str,
replacements: List[Tuple[str, str]]) -> None:
... |
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)
def convert_line_endings(filename: str, to_unix: bool = False,
... |
Detects whether a line is present within a file.
Args:
filename: file to check
line: line to search for (as an exact match)
def is_line_in_file(filename: str, line: str) -> bool:
"""
Detects whether a line is present within a file.
Args:
filename: file to check
line: l... |
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)
def add_line_if_absent(filename: str, line: str) -> None:
"""
Adds a line (at the end) if it's not already in the file s... |
:param results: the response from Elasticsearch
:return: true if the get query returned a result, false otherwise
def is_get_query_with_results(results):
"""
:param results: the response from Elasticsearch
:return: true if the get query returned a result, false otherwise
"""
... |
Check if there's a failed shard in the scan query
def validate_scan_result(results):
""" Check if there's a failed shard in the scan query"""
if results[EsConst.SHARDS][EsConst.FAILED] and results[EsConst.SHARDS][EsConst.FAILED] > 0:
raise ScanError(
'Scroll request has fail... |
Take an object and test to see if it can be represented as a
dictionary. If it can be, return a list of tuples, e.g.,
::
>>> to_key_val_list([('key', 'val')])
[('key', 'val')]
>>> to_key_val_list({'key': 'val'})
[('key', 'val')]
>>> to_key_val_list({'key': 'val'}, sort=Tr... |
Take an object and test to see if it can be represented as a
dictionary. If it can be, return a list of tuples, e.g.,
::
>>> to_key_val_dict([('key', 'val')])
{'key': 'val'}
>>> to_key_val_dict({'key': 'val'})
{'key': 'val'}
>>> to_key_val_dict('string')
ValueErro... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.