text stringlengths 81 112k |
|---|
r"""
Retrieves a textual representation of the call stack.
Args:
start_back: number of calls back in the frame stack (starting
from the frame stack as seen by :func:`get_caller_stack_info`)
to begin with
Returns:
list of descriptions
Example:
.. code-block... |
Sends details about a Python to the log, specifically its ``repr()``
representation, and all of its attributes with their name, value, and type.
Args:
obj: object to debug
log_level: log level to use; default is ``logging.DEBUG``
def debug_object(obj, log_level: int = logging.DEBUG) -> None:
... |
"Called in all circumstances when the data is loaded from the
database, including in aggregates and values() calls."
def from_db_value(self, value, expression, connection, context):
"""
"Called in all circumstances when the data is loaded from the
database, including in aggregates and v... |
"Called during deserialization and during the clean() method used
from forms.... [s]hould deal gracefully with... (*) an instance of
the correct type; (*) a string; (*) None (if the field allows
null=True)."
"For ``to_python()``, if anything goes wrong during value conversion,
y... |
Parse the given XML input and convert it into a dictionary.
`xml_input` can either be a `string` or a file-like object.
If `xml_attribs` is `True`, element attributes are put in the dictionary
among regular child elements, using `@` as a prefix to avoid collisions. If
set to `False`, they are just ign... |
Matches C++ class declarations.
>>> from glud import *
>>> config = '''
... class W;
... template<typename T> class X {};
... struct Y {};
... union Z {};
... '''
>>> m = cxxRecordDecl()
>>> for c in walk(m, parse_string(config).cursor):
... print(c.spelling)
W
X... |
Matches class, struct, and union declarations.
>>> from glud import *
>>> config = '''
... class W;
... template<typename T> class X {};
... struct Y {};
... union Z {};
... '''
>>> m = recordDecl()
>>> for c in walk(m, parse_string(config).cursor):
... print(c.spelling)... |
Transforms its input to a ``bool`` (or returns ``default`` if ``x`` is
falsy but not itself a boolean). Accepts various common string versions.
def convert_to_bool(x: Any, default: bool = None) -> bool:
"""
Transforms its input to a ``bool`` (or returns ``default`` if ``x`` is
falsy but not itself a bo... |
Transforms its input into an integer, or returns ``default``.
def convert_to_int(x: Any, default: int = None) -> int:
"""
Transforms its input into an integer, or returns ``default``.
"""
try:
return int(x)
except (TypeError, ValueError):
return default |
Applies :func:`convert_to_bool` to the specified attributes of an object,
modifying it in place.
def convert_attrs_to_bool(obj: Any,
attrs: Iterable[str],
default: bool = None) -> None:
"""
Applies :func:`convert_to_bool` to the specified attributes of an... |
Converts the specified attributes of an object to upper case, modifying
the object in place.
def convert_attrs_to_uppercase(obj: Any, attrs: Iterable[str]) -> None:
"""
Converts the specified attributes of an object to upper case, modifying
the object in place.
"""
for a in attrs:
value... |
Converts the specified attributes of an object to lower case, modifying
the object in place.
def convert_attrs_to_lowercase(obj: Any, attrs: Iterable[str]) -> None:
"""
Converts the specified attributes of an object to lower case, modifying
the object in place.
"""
for a in attrs:
value... |
Applies :func:`convert_to_int` to the specified attributes of an object,
modifying it in place.
def convert_attrs_to_int(obj: Any,
attrs: Iterable[str],
default: int = None) -> None:
"""
Applies :func:`convert_to_int` to the specified attributes of an objec... |
Reverse :func:`hex_xformat_encode`.
The parameter is a hex-encoded BLOB like
.. code-block:: none
"X'CDE7A24B1A9DBA3148BCB7A0B9DA5BB6A424486C'"
Original purpose and notes:
- SPECIAL HANDLING for BLOBs: a string like ``X'01FF'`` means a hex-encoded
BLOB. Titanium is rubbish at BLOBs, s... |
Reverse :func:`base64_64format_encode`.
Original purpose and notes:
- THIS IS ANOTHER WAY OF DOING BLOBS: base64 encoding, e.g. a string like
``64'cGxlYXN1cmUu'`` is a base-64-encoded BLOB (the ``64'...'`` bit is my
representation).
- regex from http://stackoverflow.com/questions/475074
- ... |
Fetch setting from the environment. The bahavior of the setting if it
is not in environment is as follows:
1. If it is required and the default is None, raise Exception
2. If it is requried and a default exists, return default
3. If it is not required and default is None, return None
... |
Insantiates the configuration by attempting to load the
configuration from YAML files specified by the CONF_PATH module
variable. This should be the main entry point for configuration.
def load(klass):
"""
Insantiates the configuration by attempting to load the
configuration fro... |
Allows updating of the configuration via a dictionary of
configuration terms or a configuration object. Generally speaking,
this method is utilized to configure the object from a JSON or
YAML parsing.
def configure(self, conf={}):
"""
Allows updating of the configuration via a d... |
Returns an iterable of sorted option names in order to loop
through all the configuration directives specified in the class.
def options(self):
"""
Returns an iterable of sorted option names in order to loop
through all the configuration directives specified in the class.
"""
... |
Formats a ``datetime.date`` to ISO-8601 basic format, to minute accuracy
with no timezone (or, if ``include_time`` is ``False``, omit the time).
def formatdt(date: datetime.date, include_time: bool = True) -> str:
"""
Formats a ``datetime.date`` to ISO-8601 basic format, to minute accuracy
with no time... |
Convert a ``datetime.timedelta`` object -- a duration -- into other
units. Possible units:
``s``, ``sec``, ``seconds``
``m``, ``min``, ``minutes``
``h``, ``hr``, ``hours``
``d``, ``days``
``w``, ``weeks``
``y``, ``years``
def convert_duration(duration: datetime.time... |
Does this interval overlap the other?
Overlap:
.. code-block:: none
S--------S S---S S---S
O---O O---O O---O
Simpler method of testing is for non-overlap!
.. code-block:: none
S---S S---S
... |
Does this interval overlap or touch the other?
def contiguous(self, other: "Interval") -> bool:
"""
Does this interval overlap or touch the other?
"""
return not(self.end < other.start or self.start > other.end) |
Does the interval contain a momentary time?
Args:
time: the ``datetime.datetime`` to check
inclusive: use inclusive rather than exclusive range checks?
def contains(self, time: datetime.datetime,
inclusive: bool = True) -> bool:
"""
Does the interval co... |
Is this interval contained within the other?
Args:
other: the :class:`Interval` to check
inclusive: use inclusive rather than exclusive range checks?
def within(self, other: "Interval", inclusive: bool = True) -> bool:
"""
Is this interval contained within the other?
... |
Returns an :class:`Interval` representing the intersection of this and
the ``other``, or ``None`` if they don't overlap.
def intersection(self, other: "Interval") -> Optional["Interval"]:
"""
Returns an :class:`Interval` representing the intersection of this and
the ``other``, or ``None... |
Returns a list of intervals produced by using times (a list of
``datetime.datetime`` objects, or a single such object) as a set of
knives to slice this interval.
def cut(self, times: Union[datetime.datetime,
List[datetime.datetime]]) -> List["Interval"]:
"""
... |
Returns an :class:`Interval` covering the date given (midnight at the
start of that day to midnight at the start of the next day).
def wholeday(date: datetime.date) -> "Interval":
"""
Returns an :class:`Interval` covering the date given (midnight at the
start of that day to midnight at ... |
Returns an :class:`Interval` representing daytime on the date given.
def daytime(date: datetime.date,
daybreak: datetime.time = datetime.time(NORMAL_DAY_START_H),
nightfall: datetime.time = datetime.time(NORMAL_DAY_END_H)) \
-> "Interval":
"""
Returns an :cla... |
Returns an :class:`Interval` representing the date range given, from
midnight at the start of the first day to midnight at the end of the
last (i.e. at the start of the next day after the last), or if
include_end is False, 24h before that.
If the parameters are invalid, returns ``None``... |
Returns the part of this interval that falls on the date given, or
``None`` if the interval doesn't have any part during that date.
def component_on_date(self, date: datetime.date) -> Optional["Interval"]:
"""
Returns the part of this interval that falls on the date given, or
``None`` i... |
Returns a ``(day, night)`` tuple of ``datetime.timedelta`` objects
giving the duration of this interval that falls into day and night
respectively.
def day_night_duration(
self,
daybreak: datetime.time = datetime.time(NORMAL_DAY_START_H),
nightfall: datetime.time = d... |
Returns a duration (a ``datetime.timedelta`` object) representing the
number of hours outside normal working hours.
This is not simply a subset of :meth:`day_night_duration`, because
weekends are treated differently (they are always out of hours).
The options allow the calculation of c... |
Returns the number of weekends that this interval covers. Includes
partial weekends.
def n_weekends(self) -> int:
"""
Returns the number of weekends that this interval covers. Includes
partial weekends.
"""
startdate = self.start.date()
enddate = self.end.date()
... |
Returns the dates of all Saturdays that are part of weekends that this
interval covers (each Saturday representing a unique identifier for
that weekend). The Saturday itself isn't necessarily the part of the
weekend that the interval covers!
def saturdays_of_weekends(self) -> Set[datetime.date]... |
Makes and returns a copy of the :class:`IntervalList`. The
``no_overlap``/``no_contiguous`` parameters can be changed.
Args:
no_overlap: merge intervals that overlap (now and on subsequent
addition)?
no_contiguous: if ``no_overlap`` is set, merge intervals that a... |
Adds an interval to the list. If ``self.no_overlap`` is True, as is the
default, it will merge any overlapping intervals thus created.
def add(self, interval: Interval) -> None:
"""
Adds an interval to the list. If ``self.no_overlap`` is True, as is the
default, it will merge any overla... |
Removes overlaps, etc., and sorts.
def _tidy(self) -> None:
"""
Removes overlaps, etc., and sorts.
"""
if self.no_overlap:
self.remove_overlap(self.no_contiguous) # will sort
else:
self._sort() |
Called by :meth:`remove_overlap`. Removes the first overlap found.
Args:
also_remove_contiguous: treat contiguous (as well as overlapping)
intervals as worthy of merging?
Returns:
bool: ``True`` if an overlap was removed; ``False`` otherwise
def _remove_overlap... |
Merges any overlapping intervals.
Args:
also_remove_contiguous: treat contiguous (as well as overlapping)
intervals as worthy of merging?
def remove_overlap(self, also_remove_contiguous: bool = False) -> None:
"""
Merges any overlapping intervals.
Args:
... |
Do any of the intervals overlap?
Args:
test_overlap: if ``True``, test for overlapping intervals; if
``False``, test for contiguous intervals.
def _any_overlap_or_contiguous(self, test_overlap: bool) -> bool:
"""
Do any of the intervals overlap?
Args:
... |
Returns the start date of the set of intervals, or ``None`` if empty.
def start_datetime(self) -> Optional[datetime.datetime]:
"""
Returns the start date of the set of intervals, or ``None`` if empty.
"""
if not self.intervals:
return None
return self.intervals[0].st... |
Returns the end date of the set of intervals, or ``None`` if empty.
def end_datetime(self) -> Optional[datetime.datetime]:
"""
Returns the end date of the set of intervals, or ``None`` if empty.
"""
if not self.intervals:
return None
return max([x.end for x in self.i... |
Returns the start date of the set of intervals, or ``None`` if empty.
def start_date(self) -> Optional[datetime.date]:
"""
Returns the start date of the set of intervals, or ``None`` if empty.
"""
if not self.intervals:
return None
return self.start_datetime().date() |
Returns the end date of the set of intervals, or ``None`` if empty.
def end_date(self) -> Optional[datetime.date]:
"""
Returns the end date of the set of intervals, or ``None`` if empty.
"""
if not self.intervals:
return None
return self.end_datetime().date() |
Returns an :class:`Interval` running from the earliest start of an
interval in this list to the latest end. Returns ``None`` if we are
empty.
def extent(self) -> Optional[Interval]:
"""
Returns an :class:`Interval` running from the earliest start of an
interval in this list to t... |
Returns a ``datetime.timedelta`` object with the total sum of
durations. If there is overlap, time will be double-counted, so beware!
def total_duration(self) -> datetime.timedelta:
"""
Returns a ``datetime.timedelta`` object with the total sum of
durations. If there is overlap, time wi... |
Returns an :class:`IntervalList` containing intervals representing
periods of overlap between intervals in this one.
def get_overlaps(self) -> "IntervalList":
"""
Returns an :class:`IntervalList` containing intervals representing
periods of overlap between intervals in this one.
... |
Returns a list of ``datetime.timedelta`` objects representing the
durations of each interval in our list.
def durations(self) -> List[datetime.timedelta]:
"""
Returns a list of ``datetime.timedelta`` objects representing the
durations of each interval in our list.
"""
re... |
Returns the duration of the longest interval, or None if none.
def longest_duration(self) -> Optional[datetime.timedelta]:
"""
Returns the duration of the longest interval, or None if none.
"""
if not self.intervals:
return None
return max(self.durations()) |
Returns the longest interval, or ``None`` if none.
def longest_interval(self) -> Optional[Interval]:
"""
Returns the longest interval, or ``None`` if none.
"""
longest_duration = self.longest_duration()
for i in self.intervals:
if i.duration() == longest_duration:
... |
Returns our first interval that starts with the ``start`` parameter, or
``None``.
def first_interval_starting(self, start: datetime.datetime) -> \
Optional[Interval]:
"""
Returns our first interval that starts with the ``start`` parameter, or
``None``.
"""
fo... |
Returns our first interval that ends with the ``end`` parameter, or
``None``.
def first_interval_ending(self, end: datetime.datetime) \
-> Optional[Interval]:
"""
Returns our first interval that ends with the ``end`` parameter, or
``None``.
"""
for i in self.... |
Returns all the gaps between intervals, as an :class:`IntervalList`.
def gaps(self) -> "IntervalList":
"""
Returns all the gaps between intervals, as an :class:`IntervalList`.
"""
if len(self.intervals) < 2:
return IntervalList(None)
gaps = []
for i in range(... |
Returns an IntervalList that's a subset of this one, only containing
intervals that meet the "interval" parameter criterion. What "meet"
means is defined by the ``flexibility`` parameter.
``flexibility == 0``: permits only wholly contained intervals:
.. code-block:: none
i... |
Returns an IntervalList that's a subset of this one, only containing
*gaps* between intervals that meet the interval criterion.
See :meth:`subset` for the meaning of parameters.
def gap_subset(self, interval: Interval,
flexibility: int = 2) -> "IntervalList":
"""
Ret... |
Returns the number of weekends that the intervals collectively touch
(where "touching a weekend" means "including time on a Saturday or a
Sunday").
def n_weekends(self) -> int:
"""
Returns the number of weekends that the intervals collectively touch
(where "touching a weekend" m... |
Returns the total duration outside normal working hours, i.e.
evenings/nights, weekends (and Bank Holidays).
def duration_outside_nwh(
self,
starttime: datetime.time = datetime.time(NORMAL_DAY_START_H),
endtime: datetime.time = datetime.time(NORMAL_DAY_END_H)) \
... |
The length of the longest sequence of days in which all days include
an interval.
Returns:
tuple:
``(longest_length, longest_interval)`` where
``longest_interval`` is a :class:`Interval` containing the
start and end date of the longest span -... |
Are there sufficient gaps (specified by ``requiredgaps``) in the date
range specified? This is a worker function for :meth:`sufficient_gaps`.
def _sufficient_gaps(self,
startdate: datetime.date,
enddate: datetime.date,
requiredgaps: Lis... |
Are gaps present sufficiently often?
For example:
.. code-block:: python
every_n_days=21
requiredgaps=[
datetime.timedelta(hours=62),
datetime.timedelta(hours=48),
]
... means "is there at least one 62-hour gap and one (separ... |
Returns the cumulative time contained in our intervals up to the
specified time point.
def cumulative_time_to(self,
when: datetime.datetime) -> datetime.timedelta:
"""
Returns the cumulative time contained in our intervals up to the
specified time point.
... |
Return the cumulative time within our gaps, up to ``when``.
def cumulative_gaps_to(self,
when: datetime.datetime) -> datetime.timedelta:
"""
Return the cumulative time within our gaps, up to ``when``.
"""
gaps = self.gaps()
return gaps.cumulative_time_... |
Returns the time after our last interval, but before ``when``.
If ``self`` is an empty list, returns ``None``.
def time_afterwards_preceding(
self, when: datetime.datetime) -> Optional[datetime.timedelta]:
"""
Returns the time after our last interval, but before ``when``.
If... |
For a given time, ``when``, returns the cumulative time
- after ``start`` but before ``self`` begins, prior to ``when``;
- after ``start`` and during intervals represented by ``self``, prior
to ``when``;
- after ``start`` and after at least one interval represented by
... |
Provides a ``repr``-style representation of a function parameter.
def repr_parameter(param: inspect.Parameter) -> str:
"""
Provides a ``repr``-style representation of a function parameter.
"""
return (
"Parameter(name={name}, annotation={annotation}, kind={kind}, "
"default={default}".f... |
Returns a representation of a function's name (perhaps within a namespace),
like
.. code-block:: none
mymodule:MyClass.myclassfunc # with no namespace
mymodule:MyClass.myclassfunc|somenamespace # with a namespace
Args:
fn: a function
namespace: an optional namespace, whi... |
Replacement for :func:`dogpile.cache.util.function_key_generator` that
handles type-hinted functions like
.. code-block:: python
def testfunc(param: str) -> str:
return param + "hello"
... at which :func:`inspect.getargspec` balks; plus
:func:`inspect.getargspec` is deprecated in ... |
As for :func:`fkg_allowing_type_hints`, but allowing keyword arguments.
For ``kwargs`` passed in, we will build a ``dict`` of all argname (key) to
argvalue (values) pairs, including default args from the argspec, and then
alphabetize the list before generating the key.
NOTE ALSO that once we have keyw... |
Returns the GPG version
def gpg_version():
"""Returns the GPG version"""
cmd = flatten([gnupg_bin(), "--version"])
output = stderr_output(cmd)
output = output \
.split('\n')[0] \
.split(" ")[2] \
.split('.')
return tuple([int(x) for x in output]) |
Returns a "proper" string that should work in both Py3/Py2
def polite_string(a_string):
"""Returns a "proper" string that should work in both Py3/Py2"""
if is_py3() and hasattr(a_string, 'decode'):
try:
return a_string.decode('utf-8')
except UnicodeDecodeError:
return a_... |
It's probably not a string, in the sense
that Python2/3 get confused about these things
def not_a_string(obj):
"""It's probably not a string, in the sense
that Python2/3 get confused about these things"""
my_type = str(type(obj))
if is_py3():
is_str = my_type.find('bytes') < 0 and my_type.f... |
Flatten iterables
This is super ugly. There must be a cleaner py2/3 way
of handling this.
def actually_flatten(iterable):
"""Flatten iterables
This is super ugly. There must be a cleaner py2/3 way
of handling this."""
remainder = iter(iterable)
while True:
first = next(remainder) #... |
Read passphrase from a file. This should only ever be
used by our built in integration tests. At this time,
during normal operation, only pinentry is supported for
entry of passwords.
def passphrase_file(passphrase=None):
"""Read passphrase from a file. This should only ever be
used by our built in... |
Returns appropriate arguments if GNUPGHOME is set
def gnupg_home():
"""Returns appropriate arguments if GNUPGHOME is set"""
if 'GNUPGHOME' in os.environ:
gnupghome = os.environ['GNUPGHOME']
if not os.path.isdir(gnupghome):
raise CryptoritoError("Invalid GNUPGHOME directory")
... |
Extracts a key matching a specific fingerprint from a
Keybase API response
def fingerprint_from_keybase(fingerprint, kb_obj):
"""Extracts a key matching a specific fingerprint from a
Keybase API response"""
if 'public_keys' in kb_obj and \
'pgp_public_keys' in kb_obj['public_keys']:
for ... |
Look up a public key from a username
def key_from_keybase(username, fingerprint=None):
"""Look up a public key from a username"""
url = keybase_lookup_url(username)
resp = requests.get(url)
if resp.status_code == 200:
j_resp = json.loads(polite_string(resp.content))
if 'them' in j_resp ... |
Checks to see if we have this gpg fingerprint
def has_gpg_key(fingerprint):
"""Checks to see if we have this gpg fingerprint"""
if len(fingerprint) > 8:
fingerprint = fingerprint[-8:]
fingerprint = fingerprint.upper()
cmd = flatten([gnupg_bin(), gnupg_home(), "--list-public-keys"])
lines =... |
Extract a fingerprint from a GPG public key
def fingerprint_from_var(var):
"""Extract a fingerprint from a GPG public key"""
vsn = gpg_version()
cmd = flatten([gnupg_bin(), gnupg_home()])
if vsn[0] >= 2 and vsn[1] < 1:
cmd.append("--with-fingerprint")
output = polite_string(stderr_with_inp... |
Extract a fingerprint from a GPG public key file
def fingerprint_from_file(filename):
"""Extract a fingerprint from a GPG public key file"""
cmd = flatten([gnupg_bin(), gnupg_home(), filename])
outp = stderr_output(cmd).split('\n')
if not outp[0].startswith('pub'):
raise CryptoritoError('probab... |
Generate debug-level appropriate stderr context for
executing things through subprocess. Normally stderr gets
sent to dev/null but when debugging it is sent to stdout.
def stderr_handle():
"""Generate debug-level appropriate stderr context for
executing things through subprocess. Normally stderr gets
... |
Wraps the execution of check_output in a way that
ignores stderr when not in debug mode
def stderr_output(cmd):
"""Wraps the execution of check_output in a way that
ignores stderr when not in debug mode"""
handle, gpg_stderr = stderr_handle()
try:
output = subprocess.check_output(cmd, stde... |
Runs a command, passing something in stdin, and returning
whatever came out from stdout
def stderr_with_input(cmd, stdin):
"""Runs a command, passing something in stdin, and returning
whatever came out from stdout"""
handle, gpg_stderr = stderr_handle()
LOGGER.debug("GPG command %s", ' '.join(cmd))... |
Imports a GPG key
def import_gpg_key(key):
"""Imports a GPG key"""
if not key:
raise CryptoritoError('Invalid GPG Key')
key_fd, key_filename = mkstemp("cryptorito-gpg-import")
key_handle = os.fdopen(key_fd, 'w')
key_handle.write(polite_string(key))
key_handle.close()
cmd = flatten... |
Exports a GPG key and returns it
def export_gpg_key(key):
"""Exports a GPG key and returns it"""
cmd = flatten([gnupg_bin(), gnupg_verbose(), gnupg_home(),
"--export", key])
handle, gpg_stderr = stderr_handle()
try:
gpg_proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, # ... |
Encrypts a file using the given keys
def encrypt(source, dest, keys):
"""Encrypts a file using the given keys"""
cmd = flatten([gnupg_bin(), "--armor", "--output", dest, gnupg_verbose(),
gnupg_home(), recipients_args(keys),
"--encrypt", source])
stderr_output(cmd)
... |
Attempts to encrypt a variable
def encrypt_var(source, keys):
"""Attempts to encrypt a variable"""
cmd = flatten([gnupg_bin(), "--armor", "--encrypt", gnupg_verbose(),
recipients_args(keys)])
output = stderr_with_input(cmd, source)
return output |
Handles the output of subprocess errors
in a way that is compatible with the log level
def gpg_error(exception, message):
"""Handles the output of subprocess errors
in a way that is compatible with the log level"""
LOGGER.debug("GPG Command %s", ' '.join([str(x) for x in exception.cmd]))
LOGGER.deb... |
Attempts to decrypt a variable
def decrypt_var(source, passphrase=None):
"""Attempts to decrypt a variable"""
cmd = [gnupg_bin(), "--decrypt", gnupg_home(), gnupg_verbose(),
passphrase_file(passphrase)]
return stderr_with_input(flatten(cmd), source) |
Attempts to decrypt a file
def decrypt(source, dest=None, passphrase=None):
"""Attempts to decrypt a file"""
if not os.path.exists(source):
raise CryptoritoError("Encrypted file %s not found" % source)
cmd = [gnupg_bin(), gnupg_verbose(), "--decrypt", gnupg_home(),
passphrase_file(passp... |
Determines whether or not a string is likely to
be base64 encoded binary nonsense
def is_base64(string):
"""Determines whether or not a string is likely to
be base64 encoded binary nonsense"""
return (not re.match('^[0-9]+$', string)) and \
(len(string) % 4 == 0) and \
re.match('^[A-Za-... |
Wrap b64encode for Python 2 & 3
def portable_b64encode(thing):
"""Wrap b64encode for Python 2 & 3"""
if is_py3():
try:
some_bits = bytes(thing, 'utf-8')
except TypeError:
some_bits = thing
return polite_string(b64encode(some_bits).decode('utf-8'))
return po... |
From the *Encyclopedia of Paleomagnetism*
From Onstott, 1980:
Vector resultant: R is analogous to eigenvectors
of T.
Eigenvalues are analogous to |R|/N.
def bingham_pdf(fit):
"""
From the *Encyclopedia of Paleomagnetism*
From Onstott, 1980:
Vector resultant: R is analogous to eigenvec... |
Downloads a URL to a file, unless the file already exists.
def download_if_not_exists(url: str, filename: str,
skip_cert_verify: bool = True,
mkdir: bool = True) -> None:
"""
Downloads a URL to a file, unless the file already exists.
"""
if os.path.... |
Fetches a Git repository, unless we have it already.
Args:
prettyname: name to display to user
url: URL
directory: destination directory
branch: repository branch
commit: repository commit tag
clone_options: additional options to pass to ``git clone``
run_fun... |
Unpacks a TAR file into a specified directory.
Args:
tarfile: filename of the ``.tar`` file
directory: destination directory
verbose: be verbose?
gzipped: is the ``.tar`` also gzipped, e.g. a ``.tar.gz`` file?
skip_if_dir_exists: don't do anything if the destrination directo... |
Convert an environment into a set of commands that can be copied/pasted, on
the build platform, to recreate that environment.
def make_copy_paste_env(env: Dict[str, str]) -> str:
"""
Convert an environment into a set of commands that can be copied/pasted, on
the build platform, to recreate that environ... |
Runs an external process, announcing it.
Optionally, retrieves its ``stdout`` and/or ``stderr`` output (if not
retrieved, the output will be visible to the user).
Args:
args: list of command-line arguments (the first being the executable)
env: operating system environment to use (if ``Non... |
Run a command and returns its stdout.
Args:
args: the command-line arguments
env: the operating system environment to use
encoding: the encoding to use for ``stdout``
Returns:
the command's ``stdout`` output
def fetch(args: List[str], env: Dict[str, str] = None,
enco... |
Dumps some connection info, as an SQL comment. Obscures passwords.
Args:
engine: the SQLAlchemy :class:`Engine` to dump metadata information
from
fileobj: the file-like object (default ``sys.stdout``) to write
information to
def dump_connection_info(engine: Engine, fileobj:... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.