code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def execute_pubsub(self, command, *channels):
"""Executes Redis (p)subscribe/(p)unsubscribe commands.
ConnectionsPool picks separate connection for pub/sub
and uses it until explicitly closed or disconnected
(unsubscribing from all channels/patterns will leave connection
locked... | Executes Redis (p)subscribe/(p)unsubscribe commands.
ConnectionsPool picks separate connection for pub/sub
and uses it until explicitly closed or disconnected
(unsubscribing from all channels/patterns will leave connection
locked for pub/sub use).
There is no auto-reconnect fo... |
def projects_from_cli(args):
"""Take arguments through the CLI can create a list of specified projects."""
description = ('Determine if a set of project dependencies will work with '
'Python 3')
parser = argparse.ArgumentParser(description=description)
req_help = 'path(s) to a pip req... | Take arguments through the CLI can create a list of specified projects. |
def mod_aggregate(low, chunks, running):
'''
The mod_aggregate function which looks up all rules in the available
low chunks and merges them into a single rules ref in the present low data
'''
rules = []
agg_enabled = [
'append',
'insert',
]
if low.get('fun') not ... | The mod_aggregate function which looks up all rules in the available
low chunks and merges them into a single rules ref in the present low data |
def archive(cwd,
output,
rev='HEAD',
prefix=None,
git_opts='',
user=None,
password=None,
ignore_retcode=False,
output_encoding=None,
**kwargs):
'''
.. versionchanged:: 2015.8.0
Returns ``True`` if... | .. versionchanged:: 2015.8.0
Returns ``True`` if successful, raises an error if not.
Interface to `git-archive(1)`_, exports a tarball/zip file of the
repository
cwd
The path to be archived
.. note::
``git archive`` permits a partial archive to be created. Thus, this
... |
def fso_rmtree(self, path, ignore_errors=False, onerror=None):
'overlays shutil.rmtree()'
if ignore_errors:
def onerror(*args):
pass
elif onerror is None:
def onerror(*args):
raise
try:
if self.fso_islink(path):
# symlinks to directories are forbidden, see shuti... | overlays shutil.rmtree() |
def destroy_vm_vdis(name=None, session=None, call=None):
'''
Get virtual block devices on VM
.. code-block:: bash
salt-cloud -a destroy_vm_vdis xenvm01
'''
if session is None:
session = _get_session()
ret = {}
# get vm object
vms = session.xenapi.VM.get_by_name_label(... | Get virtual block devices on VM
.. code-block:: bash
salt-cloud -a destroy_vm_vdis xenvm01 |
def process_exception(self, request, exception):
"""
When we get a CasTicketException, that is probably caused by the ticket timing out.
So logout/login and get the same page again.
"""
if isinstance(exception, CasTicketException):
do_logout(request)
# Th... | When we get a CasTicketException, that is probably caused by the ticket timing out.
So logout/login and get the same page again. |
def find_uncommitted_filefields(sender, instance, **kwargs):
"""
A pre_save signal handler which attaches an attribute to the model instance
containing all uncommitted ``FileField``s, which can then be used by the
:func:`signal_committed_filefields` post_save handler.
"""
uncommitted = instance.... | A pre_save signal handler which attaches an attribute to the model instance
containing all uncommitted ``FileField``s, which can then be used by the
:func:`signal_committed_filefields` post_save handler. |
def numpy_binning(data, bins=10, range=None, *args, **kwargs) -> NumpyBinning:
"""Construct binning schema compatible with numpy.histogram
Parameters
----------
data: array_like, optional
This is optional if both bins and range are set
bins: int or array_like
range: Optional[tuple]
... | Construct binning schema compatible with numpy.histogram
Parameters
----------
data: array_like, optional
This is optional if both bins and range are set
bins: int or array_like
range: Optional[tuple]
(min, max)
includes_right_edge: Optional[bool]
default: True
See ... |
def dead_letter(self, description=None):
"""Move the message to the Dead Letter queue.
The Dead Letter queue is a sub-queue that can be
used to store messages that failed to process correctly, or otherwise require further inspection
or processing. The queue can also be configured to sen... | Move the message to the Dead Letter queue.
The Dead Letter queue is a sub-queue that can be
used to store messages that failed to process correctly, or otherwise require further inspection
or processing. The queue can also be configured to send expired messages to the Dead Letter queue.
... |
def add_record(self, is_sslv2=None, is_tls13=None):
"""
Add a new TLS or SSLv2 or TLS 1.3 record to the packets buffered out.
"""
if is_sslv2 is None and is_tls13 is None:
v = (self.cur_session.tls_version or
self.cur_session.advertised_tls_version)
... | Add a new TLS or SSLv2 or TLS 1.3 record to the packets buffered out. |
def factorset_divide(factorset1, factorset2):
r"""
Base method for dividing two factor sets.
Division of two factor sets :math:`\frac{\vec\phi_1}{\vec\phi_2}` basically translates to union of all the factors
present in :math:`\vec\phi_2` and :math:`\frac{1}{\phi_i}` of all the factors present in :math:... | r"""
Base method for dividing two factor sets.
Division of two factor sets :math:`\frac{\vec\phi_1}{\vec\phi_2}` basically translates to union of all the factors
present in :math:`\vec\phi_2` and :math:`\frac{1}{\phi_i}` of all the factors present in :math:`\vec\phi_2`.
Parameters
----------
f... |
def encode(self, x):
"""
Given an input array `x` it returns its associated encoding `y(x)`.
Please cf. the paper for more details.
Note that NO learning takes place.
"""
n = self._outputSize
y = np.zeros(n)
Q = self._Q
W = self._W
t = sel... | Given an input array `x` it returns its associated encoding `y(x)`.
Please cf. the paper for more details.
Note that NO learning takes place. |
def query_disease():
"""
Returns list of diseases by query parameters
---
tags:
- Query functions
parameters:
- name: identifier
in: query
type: string
required: false
description: Disease identifier
default: DI-03832
- name: ref_id
... | Returns list of diseases by query parameters
---
tags:
- Query functions
parameters:
- name: identifier
in: query
type: string
required: false
description: Disease identifier
default: DI-03832
- name: ref_id
in: query
type: strin... |
def hash_from_stream(n, hash_stream):
"""
Not standard hashing algorithm!
Install NumPy for better hashing service.
>>> from Redy.Tools._py_hash import hash_from_stream
>>> s = iter((1, 2, 3))
>>> assert hash_from_stream(3, map(hash, s)) == hash((1, 2, 3))
"""
_to_int64 = to_int64
x... | Not standard hashing algorithm!
Install NumPy for better hashing service.
>>> from Redy.Tools._py_hash import hash_from_stream
>>> s = iter((1, 2, 3))
>>> assert hash_from_stream(3, map(hash, s)) == hash((1, 2, 3)) |
def join(self, *args):
"""Returns the arguments in the list joined by STR.
FIRST,JOIN_BY,ARG_1,...,ARG_N
%{JOIN: ,A,...,F} -> 'A B C ... F'
"""
call_args = list(args)
joiner = call_args.pop(0)
self.random.shuffle(call_args)
return joiner.join(call_arg... | Returns the arguments in the list joined by STR.
FIRST,JOIN_BY,ARG_1,...,ARG_N
%{JOIN: ,A,...,F} -> 'A B C ... F' |
def get_strategy_types():
"""Get a list of all :class:`Strategy` subclasses."""
def get_subtypes(type_):
subtypes = type_.__subclasses__()
for subtype in subtypes:
subtypes.extend(get_subtypes(subtype))
return subtypes
return get_subtypes(Strategy) | Get a list of all :class:`Strategy` subclasses. |
def get_deployments(self, project, definition_id=None, definition_environment_id=None, created_by=None, min_modified_time=None, max_modified_time=None, deployment_status=None, operation_status=None, latest_attempts_only=None, query_order=None, top=None, continuation_token=None, created_for=None, min_started_time=None, ... | GetDeployments.
:param str project: Project ID or project name
:param int definition_id:
:param int definition_environment_id:
:param str created_by:
:param datetime min_modified_time:
:param datetime max_modified_time:
:param str deployment_status:
:param... |
def reload_plugin(self, name, *args):
"""
Reloads a given plugin
:param name: The name of the plugin
:param args: The args to pass to the plugin
"""
self._logger.debug("Reloading {}.".format(name))
self._logger.debug("Disabling {}.".format(name))
self.ge... | Reloads a given plugin
:param name: The name of the plugin
:param args: The args to pass to the plugin |
def set_org_disclaimer(self):
"""Auto-connect slot activated when org disclaimer checkbox is toggled.
"""
is_checked = self.custom_org_disclaimer_checkbox.isChecked()
if is_checked:
# Show previous organisation disclaimer
org_disclaimer = setting(
... | Auto-connect slot activated when org disclaimer checkbox is toggled. |
def ingest(self, text, logMessage=None):
"""Ingest a new object into Fedora. Returns the pid of the new object on success.
Return response should have a status of 201 Created on success, and
the content of the response will be the newly created pid.
Wrapper function for `Fedora REST API... | Ingest a new object into Fedora. Returns the pid of the new object on success.
Return response should have a status of 201 Created on success, and
the content of the response will be the newly created pid.
Wrapper function for `Fedora REST API ingest <http://fedora-commons.org/confluence/displa... |
def learn_transportation_mode(track, clf):
""" Inserts transportation modes of a track into a classifier
Args:
track (:obj:`Track`)
clf (:obj:`Classifier`)
"""
for segment in track.segments:
tmodes = segment.transportation_modes
points = segment.points
features =... | Inserts transportation modes of a track into a classifier
Args:
track (:obj:`Track`)
clf (:obj:`Classifier`) |
def parse_instance_count(instance_count, speaker_total_count):
"""This parses the instance count dictionary
(that may contain floats from 0.0 to 1.0 representing a percentage)
and converts it to actual instance count.
"""
# Use all the instances of a speaker unless specified
result = copy.copy(... | This parses the instance count dictionary
(that may contain floats from 0.0 to 1.0 representing a percentage)
and converts it to actual instance count. |
def getScreenshotPropertyType(self, screenshotHandle):
"""
When your application receives a
VREvent_RequestScreenshot event, call these functions to get
the details of the screenshot request.
"""
fn = self.function_table.getScreenshotPropertyType
pError = EVRSc... | When your application receives a
VREvent_RequestScreenshot event, call these functions to get
the details of the screenshot request. |
def ndiff(a, b, linejunk=None, charjunk=IS_CHARACTER_JUNK):
r"""
Compare `a` and `b` (lists of strings); return a `Differ`-style delta.
Optional keyword parameters `linejunk` and `charjunk` are for filter
functions (or None):
- linejunk: A function that should accept a single string argument, and
... | r"""
Compare `a` and `b` (lists of strings); return a `Differ`-style delta.
Optional keyword parameters `linejunk` and `charjunk` are for filter
functions (or None):
- linejunk: A function that should accept a single string argument, and
return true iff the string is junk. The default is None, ... |
def nonwhitelisted_allowed_principals(self, whitelist=None):
"""Find non whitelisted allowed principals."""
if not whitelist:
return []
nonwhitelisted = []
for statement in self.statements:
if statement.non_whitelisted_principals(whitelist) and statement.effect ... | Find non whitelisted allowed principals. |
def network_from_df(self, df):
"""
Defines a network from an array.
Parameters
----------
array : array
Pandas dataframe. Should have columns: \'i\', \'j\', \'t\' where i and j are node indicies and t is the temporal index.
If weighted, should also includ... | Defines a network from an array.
Parameters
----------
array : array
Pandas dataframe. Should have columns: \'i\', \'j\', \'t\' where i and j are node indicies and t is the temporal index.
If weighted, should also include \'weight\'. Each row is an edge. |
def get_action_side_effects(self):
"""Returns all side effects for all batches of this
Executor used by the underlying Action.
"""
result = SCons.Util.UniqueList([])
for target in self.get_action_targets():
result.extend(target.side_effects)
return result | Returns all side effects for all batches of this
Executor used by the underlying Action. |
def query(conn_type, option, post_data=None):
'''
Execute the HTTP request to the API
'''
if ticket is None or csrf is None or url is None:
log.debug('Not authenticated yet, doing that now..')
_authenticate()
full_url = 'https://{0}:{1}/api2/json/{2}'.format(url, port, option)
... | Execute the HTTP request to the API |
def list_items(cls, repo, *args, **kwargs):
"""
Find all items of this type - subclasses can specify args and kwargs differently.
If no args are given, subclasses are obliged to return all items if no additional
arguments arg given.
:note: Favor the iter_items method as it will
... | Find all items of this type - subclasses can specify args and kwargs differently.
If no args are given, subclasses are obliged to return all items if no additional
arguments arg given.
:note: Favor the iter_items method as it will
:return:list(Item,...) list of item instances |
def mem_extend(self, start: int, size: int) -> None:
"""Extends the memory of this machine state.
:param start: Start of memory extension
:param size: Size of memory extension
"""
m_extend = self.calculate_extension_size(start, size)
if m_extend:
extend_gas =... | Extends the memory of this machine state.
:param start: Start of memory extension
:param size: Size of memory extension |
def cmyk(self):
"""CMYK: all returned in range 0.0 - 1.0"""
c, m, y = self.cmy
k = min(c, m, y)
# Handle division by zero in case of black = 1
if k != 1:
c = (c - k) / (1 - k)
m = (m - k) / (1 - k)
y = (y - k) / (1 - k)
else:
... | CMYK: all returned in range 0.0 - 1.0 |
def indices(this, that, axis=semantics.axis_default, missing='raise'):
"""Find indices such that this[indices] == that
If multiple indices satisfy this condition, the first index found is returned
Parameters
----------
this : indexable object
items to search in
that : indexable object
... | Find indices such that this[indices] == that
If multiple indices satisfy this condition, the first index found is returned
Parameters
----------
this : indexable object
items to search in
that : indexable object
items to search for
axis : int, optional
axis to operate on... |
def get(self, entry):
"""Gets an entry by key. Will return None if there is no
matching entry."""
try:
list = self.cache[entry.key]
return list[list.index(entry)]
except:
return None | Gets an entry by key. Will return None if there is no
matching entry. |
def to_unicode(s):
"""Return the object as unicode (only matters for Python 2.x).
If s is already Unicode, return s as is.
Otherwise, assume that s is UTF-8 encoded, and convert to Unicode.
:param (basestring) s: a str, unicode or other basestring object
:return (unicode): the object as unicode
... | Return the object as unicode (only matters for Python 2.x).
If s is already Unicode, return s as is.
Otherwise, assume that s is UTF-8 encoded, and convert to Unicode.
:param (basestring) s: a str, unicode or other basestring object
:return (unicode): the object as unicode |
def enable_caching(self):
"Enable the cache of this object."
self.caching_enabled = True
for c in self.values():
c.enable_cacher() | Enable the cache of this object. |
def handle_profile_delete(self, sender, instance, **kwargs):
""" Custom handler for user profile delete """
try:
self.handle_save(instance.user.__class__, instance.user) # we call save just as well
except (get_profile_model().DoesNotExist):
pass | Custom handler for user profile delete |
def add(repo_path, dest_path):
'''
Registers a git repository with homely so that it will run its `HOMELY.py`
script on each invocation of `homely update`. `homely add` also immediately
executes a `homely update` so that the dotfiles are installed straight
away. If the git repository is hosted onlin... | Registers a git repository with homely so that it will run its `HOMELY.py`
script on each invocation of `homely update`. `homely add` also immediately
executes a `homely update` so that the dotfiles are installed straight
away. If the git repository is hosted online, a local clone will be created
first.... |
def _generate_autoscaling_metadata(self, cls, args):
""" Provides special handling for the autoscaling.Metadata object """
assert isinstance(args, Mapping)
init_config = self._create_instance(
cloudformation.InitConfig,
args['AWS::CloudFormation::Init']['config'])
... | Provides special handling for the autoscaling.Metadata object |
def steal_docstring_from(obj):
"""Decorator that lets you steal a docstring from another object
Example
-------
::
@steal_docstring_from(superclass.meth)
def meth(self, arg):
"Extra subclass documentation"
pass
In this case the docstring of the new 'meth' will be copied f... | Decorator that lets you steal a docstring from another object
Example
-------
::
@steal_docstring_from(superclass.meth)
def meth(self, arg):
"Extra subclass documentation"
pass
In this case the docstring of the new 'meth' will be copied from superclass.meth, and
if an add... |
def add_entity(self, rdf_type, superclass, label, definition=None):
''' Adds entity as long as it doesn't exist and has a usable
superclass ILX ID and rdf:type
'''
# Checks if you inputed the right type
rdf_type = rdf_type.lower().strip().replace('owl:Class', 'term')
... | Adds entity as long as it doesn't exist and has a usable
superclass ILX ID and rdf:type |
def ensure_directory(directory):
"""
Create the directories along the provided directory path that do not exist.
"""
directory = os.path.expanduser(directory)
try:
os.makedirs(directory)
except OSError as e:
if e.errno != errno.EEXIST:
raise e | Create the directories along the provided directory path that do not exist. |
def write_options_to_JSON(self, filename):
"""Writes the options in JSON format to a file.
:param str filename: Target file to write the options.
"""
fd = open(filename, "w")
fd.write(json.dumps(_options_to_dict(self.gc), indent=2,
separators=(',', ':... | Writes the options in JSON format to a file.
:param str filename: Target file to write the options. |
def size(self, destination):
"""
Size of the queue for specified destination.
@param destination: The queue destination (e.g. /queue/foo)
@type destination: C{str}
@return: The number of frames in specified queue.
@rtype: C{int}
"""
if not destination in... | Size of the queue for specified destination.
@param destination: The queue destination (e.g. /queue/foo)
@type destination: C{str}
@return: The number of frames in specified queue.
@rtype: C{int} |
def json_serializer(pid, data, *args):
"""Build a JSON Flask response using the given data.
:param pid: The `invenio_pidstore.models.PersistentIdentifier` of the
record.
:param data: The record metadata.
:returns: A Flask response with JSON data.
:rtype: :py:class:`flask.Response`.
"""
... | Build a JSON Flask response using the given data.
:param pid: The `invenio_pidstore.models.PersistentIdentifier` of the
record.
:param data: The record metadata.
:returns: A Flask response with JSON data.
:rtype: :py:class:`flask.Response`. |
def as_proto(self):
"""Returns this shape as a `TensorShapeProto`."""
if self._dims is None:
return tensor_shape_pb2.TensorShapeProto(unknown_rank=True)
else:
return tensor_shape_pb2.TensorShapeProto(
dim=[
tensor_shape_pb2.TensorShapeP... | Returns this shape as a `TensorShapeProto`. |
def normalize(x:TensorImage, mean:FloatTensor,std:FloatTensor)->TensorImage:
"Normalize `x` with `mean` and `std`."
return (x-mean[...,None,None]) / std[...,None,None] | Normalize `x` with `mean` and `std`. |
def sim(self, args):
"""
Simulate I/O points by setting the Out_Of_Service property, then doing a
WriteProperty to the point's Present_Value.
:param args: String with <addr> <type> <inst> <prop> <value> [ <indx> ] [ <priority> ]
"""
if not self._started:
... | Simulate I/O points by setting the Out_Of_Service property, then doing a
WriteProperty to the point's Present_Value.
:param args: String with <addr> <type> <inst> <prop> <value> [ <indx> ] [ <priority> ] |
def Hk(self, k, m_pred, P_pred): # returns state iteration matrix
"""
function (k, m, P) return Jacobian of measurement function, it is
passed into p_h.
k (iteration number), starts at 0
m: point where Jacobian is evaluated
P: parameter for Jacobian, usua... | function (k, m, P) return Jacobian of measurement function, it is
passed into p_h.
k (iteration number), starts at 0
m: point where Jacobian is evaluated
P: parameter for Jacobian, usually covariance matrix. |
def wald_wolfowitz(sequence):
"""
implements the wald-wolfowitz runs test:
http://en.wikipedia.org/wiki/Wald-Wolfowitz_runs_test
http://support.sas.com/kb/33/092.html
:param sequence: any iterable with at most 2 values. e.g.
'1001001'
[1, 0, 1, 0, 1]
... | implements the wald-wolfowitz runs test:
http://en.wikipedia.org/wiki/Wald-Wolfowitz_runs_test
http://support.sas.com/kb/33/092.html
:param sequence: any iterable with at most 2 values. e.g.
'1001001'
[1, 0, 1, 0, 1]
'abaaabbba'
:rtype: a ... |
def getSizeFromPage(rh, page):
"""
Convert a size value from page to a number with a magnitude appended.
Input:
Request Handle
Size in page
Output:
Converted value with a magnitude
"""
rh.printSysLog("Enter generalUtils.getSizeFromPage")
bSize = float(page) * 4096
... | Convert a size value from page to a number with a magnitude appended.
Input:
Request Handle
Size in page
Output:
Converted value with a magnitude |
def key56_to_key64(key):
"""
This takes in an a bytes string of 7 bytes and converts it to a bytes
string of 8 bytes with the odd parity bit being set to every 8 bits,
For example
b"\x01\x02\x03\x04\x05\x06\x07"
00000001 00000010 00000011 00000100 00000101 00000110 0000... | This takes in an a bytes string of 7 bytes and converts it to a bytes
string of 8 bytes with the odd parity bit being set to every 8 bits,
For example
b"\x01\x02\x03\x04\x05\x06\x07"
00000001 00000010 00000011 00000100 00000101 00000110 00000111
is converted to
b"\x01... |
def getContactUIDForUser(self):
"""Get the UID of the user associated with the authenticated user
"""
membership_tool = api.get_tool("portal_membership")
member = membership_tool.getAuthenticatedMember()
username = member.getUserName()
r = self.portal_catalog(
... | Get the UID of the user associated with the authenticated user |
def get_value_tuple(self):
"""
Returns a tuple of the color's values (in order). For example,
an LabColor object will return (lab_l, lab_a, lab_b), where each
member of the tuple is the float value for said variable.
"""
retval = tuple()
for val in self.VALUES:
... | Returns a tuple of the color's values (in order). For example,
an LabColor object will return (lab_l, lab_a, lab_b), where each
member of the tuple is the float value for said variable. |
def blk_1d(blk, shape):
"""Iterate through the slices that recover a line.
This function is used by :func:`blk_nd` as a base 1d case.
The last slice is returned even if is lesser than blk.
:param blk: the size of the block
:param shape: the size of the array
:return: a generator that yields ... | Iterate through the slices that recover a line.
This function is used by :func:`blk_nd` as a base 1d case.
The last slice is returned even if is lesser than blk.
:param blk: the size of the block
:param shape: the size of the array
:return: a generator that yields the slices |
def unpack(self, buff, offset=0):
"""Unpack a binary struct into this object's attributes.
Return the values instead of the lib's basic types.
Args:
buff (bytes): Binary buffer.
offset (int): Where to begin unpacking.
Raises:
:exc:`~.exceptions.Unpa... | Unpack a binary struct into this object's attributes.
Return the values instead of the lib's basic types.
Args:
buff (bytes): Binary buffer.
offset (int): Where to begin unpacking.
Raises:
:exc:`~.exceptions.UnpackException`: If unpack fails. |
def time2slurm(timeval, unit="s"):
"""
Convert a number representing a time value in the given unit (Default: seconds)
to a string following the slurm convention: "days-hours:minutes:seconds".
>>> assert time2slurm(61) == '0-0:1:1' and time2slurm(60*60+1) == '0-1:0:1'
>>> assert time2slurm(0.5, uni... | Convert a number representing a time value in the given unit (Default: seconds)
to a string following the slurm convention: "days-hours:minutes:seconds".
>>> assert time2slurm(61) == '0-0:1:1' and time2slurm(60*60+1) == '0-1:0:1'
>>> assert time2slurm(0.5, unit="h") == '0-0:30:0' |
def visit_RETURN(self, node):
""" Visits only children[1], since children[0] points to
the current function being returned from (if any), and
might cause infinite recursion.
"""
if len(node.children) == 2:
node.children[1] = (yield ToVisit(node.children[1]))
y... | Visits only children[1], since children[0] points to
the current function being returned from (if any), and
might cause infinite recursion. |
def add(self, opener):
"""Adds an opener to the registry
:param opener: Opener object
:type opener: Opener inherited object
"""
index = len(self.openers)
self.openers[index] = opener
for name in opener.names:
self.registry[name] = index | Adds an opener to the registry
:param opener: Opener object
:type opener: Opener inherited object |
def copy(self):
"""Return a copy of this _TimeAnchor."""
return _TimeAnchor(self.reading_id, self.uptime, self.utc, self.is_break, self.exact) | Return a copy of this _TimeAnchor. |
def mask_unphysical(self, data):
"""Mask data array where values are outside physically valid range."""
if not self.valid_range:
return data
else:
return np.ma.masked_outside(data, np.min(self.valid_range),
np.max(self.valid_range)) | Mask data array where values are outside physically valid range. |
def make_defaults_and_annotations(make_function_instr, builders):
"""
Get the AST expressions corresponding to the defaults, kwonly defaults, and
annotations for a function created by `make_function_instr`.
"""
# Integer counts.
n_defaults, n_kwonlydefaults, n_annotations = unpack_make_function_... | Get the AST expressions corresponding to the defaults, kwonly defaults, and
annotations for a function created by `make_function_instr`. |
def show_top(queue=False, **kwargs):
'''
Return the top data that the minion will use for a highstate
CLI Example:
.. code-block:: bash
salt '*' state.show_top
'''
if 'env' in kwargs:
# "env" is not supported; Use "saltenv".
kwargs.pop('env')
conflict = _check_que... | Return the top data that the minion will use for a highstate
CLI Example:
.. code-block:: bash
salt '*' state.show_top |
def getHTML(self):
'''
getHTML - Get the full HTML as contained within this tree.
If parsed from a document, this will contain the original whitespacing.
@returns - <str> of html
@see getFormattedHTML
@see getMiniHTML
... | getHTML - Get the full HTML as contained within this tree.
If parsed from a document, this will contain the original whitespacing.
@returns - <str> of html
@see getFormattedHTML
@see getMiniHTML |
def getMaximinScores(profile):
"""
Returns a dictionary that associates integer representations of each candidate with their
Copeland score.
:ivar Profile profile: A Profile object that represents an election profile.
"""
# Currently, we expect the profile to contain complete ordering over can... | Returns a dictionary that associates integer representations of each candidate with their
Copeland score.
:ivar Profile profile: A Profile object that represents an election profile. |
def postprocess(x, n_bits_x=8):
"""Converts x from [-0.5, 0.5], to [0, 255].
Args:
x: 3-D or 4-D Tensor normalized between [-0.5, 0.5]
n_bits_x: Number of bits representing each pixel of the output.
Defaults to 8, to default to 256 possible values.
Returns:
x: 3-D or 4-D Tensor represen... | Converts x from [-0.5, 0.5], to [0, 255].
Args:
x: 3-D or 4-D Tensor normalized between [-0.5, 0.5]
n_bits_x: Number of bits representing each pixel of the output.
Defaults to 8, to default to 256 possible values.
Returns:
x: 3-D or 4-D Tensor representing images or videos. |
def seek(self, offset, whence=os.SEEK_SET):
"""Seeks to an offset within the file-like object.
Args:
offset (int): offset to seek.
whence (Optional[int]): value that indicates whether offset is an
absolute or relative position within the file.
Raises:
IOError: if the seek faile... | Seeks to an offset within the file-like object.
Args:
offset (int): offset to seek.
whence (Optional[int]): value that indicates whether offset is an
absolute or relative position within the file.
Raises:
IOError: if the seek failed.
OSError: if the seek failed. |
def commit_analyzer(commits, label_pattern, label_position="footer"):
"""Analyzes a list of :class:`~braulio.git.Commit` objects searching for
messages that match a given message convention and extract metadata from
them.
A message convention is determined by ``label_pattern``, which is not a
regul... | Analyzes a list of :class:`~braulio.git.Commit` objects searching for
messages that match a given message convention and extract metadata from
them.
A message convention is determined by ``label_pattern``, which is not a
regular expression pattern. Instead it must be a string literals with
placehol... |
def create_database(self, name):
"""Create a new database."""
statement = "CREATE DATABASE {0} DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci".format(wrap(name))
return self.execute(statement) | Create a new database. |
def update_task(self, differences):
"""
Updates a task as done if we have a new value for this alternative language
:param differences:
:return:
"""
self.log('differences UPDATING: {}'.format(differences))
object_name = '{} - {}'.format(self.app_label, self.ins... | Updates a task as done if we have a new value for this alternative language
:param differences:
:return: |
def add_default_plugins(self, except_global=[], except_local=[]):
"""
Add the ginga-distributed default set of plugins to the
reference viewer.
"""
# add default global plugins
for spec in plugins:
ptype = spec.get('ptype', 'local')
if ptype == 'gl... | Add the ginga-distributed default set of plugins to the
reference viewer. |
def locked_get(self):
"""Retrieves the current credentials from the store.
Returns:
An instance of :class:`oauth2client.client.Credentials` or `None`.
"""
credential = self._backend.locked_get(self._key)
if credential is not None:
credential.set_store(se... | Retrieves the current credentials from the store.
Returns:
An instance of :class:`oauth2client.client.Credentials` or `None`. |
def get_value_for_expr(self, expr, target):
"""I have no idea."""
if expr in LOGICAL_OPERATORS.values():
return None
rvalue = expr['value']
if rvalue == HISTORICAL:
history = self.history[target]
if len(history) < self.history_size:
ret... | I have no idea. |
def get_message_handler(self, message_handlers):
"""
Create a MessageHandler for the configured Encoder
:param message_handlers: a dictionart of MessageHandler keyed by encoder
:return: a MessageHandler
"""
encoder = self.options.encoder
try:
return me... | Create a MessageHandler for the configured Encoder
:param message_handlers: a dictionart of MessageHandler keyed by encoder
:return: a MessageHandler |
def jam_pack(jam, **kwargs):
'''Pack data into a jams sandbox.
If not already present, this creates a `muda` field within `jam.sandbox`,
along with `history`, `state`, and version arrays which are populated by
deformation objects.
Any additional fields can be added to the `muda` sandbox by supplyi... | Pack data into a jams sandbox.
If not already present, this creates a `muda` field within `jam.sandbox`,
along with `history`, `state`, and version arrays which are populated by
deformation objects.
Any additional fields can be added to the `muda` sandbox by supplying
keyword arguments.
Param... |
def get_observation_fields(search_query: str="", page: int=1) -> List[Dict[str, Any]]:
"""
Search the (globally available) observation
:param search_query:
:param page:
:return:
"""
payload = {
'q': search_query,
'page': page
} # type: Dict[str, Union[int, str]]
res... | Search the (globally available) observation
:param search_query:
:param page:
:return: |
def _learn_init_params(self, n_calib_beats=8):
"""
Find a number of consecutive beats and use them to initialize:
- recent qrs amplitude
- recent noise amplitude
- recent rr interval
- qrs detection threshold
The learning works as follows:
- Find all loca... | Find a number of consecutive beats and use them to initialize:
- recent qrs amplitude
- recent noise amplitude
- recent rr interval
- qrs detection threshold
The learning works as follows:
- Find all local maxima (largest sample within `qrs_radius`
samples) of ... |
def _convert_default_value(self, default):
"""Convert the passed default value to binary.
The default value (if passed) may be specified as either a `bytes`
object or a python int or list of ints. If an int or list of ints is
passed, it is converted to binary. Otherwise, the raw binar... | Convert the passed default value to binary.
The default value (if passed) may be specified as either a `bytes`
object or a python int or list of ints. If an int or list of ints is
passed, it is converted to binary. Otherwise, the raw binary data is
used.
If you pass a bytes o... |
def panels(self):
"""
Add 2 panels to the figure, top for signal and bottom for gene models
"""
ax1 = self.fig.add_subplot(211)
ax2 = self.fig.add_subplot(212, sharex=ax1)
return (ax2, self.gene_panel), (ax1, self.signal_panel) | Add 2 panels to the figure, top for signal and bottom for gene models |
def add_document(self, question, answer):
"""Add question answer set to DB.
:param question: A question to an answer
:type question: :class:`str`
:param answer: An answer to a question
:type answer: :class:`str`
"""
question = question.strip()
answer = ... | Add question answer set to DB.
:param question: A question to an answer
:type question: :class:`str`
:param answer: An answer to a question
:type answer: :class:`str` |
def should_execute(self, workload):
"""
If we have been suspended by i3bar, only execute those modules that set the keep_alive flag to a truthy
value. See the docs on the suspend_signal_handler method of the io module for more information.
"""
if not self._suspended.is_set():
... | If we have been suspended by i3bar, only execute those modules that set the keep_alive flag to a truthy
value. See the docs on the suspend_signal_handler method of the io module for more information. |
def _GetMemberDataTypeMaps(self, data_type_definition, data_type_map_cache):
"""Retrieves the member data type maps.
Args:
data_type_definition (DataTypeDefinition): data type definition.
data_type_map_cache (dict[str, DataTypeMap]): cached data type maps.
Returns:
list[DataTypeMap]: mem... | Retrieves the member data type maps.
Args:
data_type_definition (DataTypeDefinition): data type definition.
data_type_map_cache (dict[str, DataTypeMap]): cached data type maps.
Returns:
list[DataTypeMap]: member data type maps.
Raises:
FormatError: if the data type maps cannot be ... |
def make_rw(obj: Any):
"""
Copy a RO object into a RW structure made with standard Python classes.
WARNING there is no protection against recursion.
"""
if isinstance(obj, RoDict):
return {k: make_rw(v) for k, v in obj.items()}
elif isinstance(obj, RoList):
return [make_rw(x) f... | Copy a RO object into a RW structure made with standard Python classes.
WARNING there is no protection against recursion. |
def get_policy_config(platform,
filters=None,
prepend=True,
pillar_key='acl',
pillarenv=None,
saltenv=None,
merge_pillar=True,
only_lower_merge=False,
... | Return the configuration of the whole policy.
platform
The name of the Capirca platform.
filters
List of filters for this policy.
If not specified or empty, will try to load the configuration from the pillar,
unless ``merge_pillar`` is set as ``False``.
prepend: ``True``
... |
def td_sp(points, speed_threshold):
""" Top-Down Speed-Based Trajectory Compression Algorithm
Detailed in https://www.itc.nl/library/Papers_2003/peer_ref_conf/meratnia_new.pdf
Args:
points (:obj:`list` of :obj:`Point`): trajectory or part of it
speed_threshold (float): max speed error, in ... | Top-Down Speed-Based Trajectory Compression Algorithm
Detailed in https://www.itc.nl/library/Papers_2003/peer_ref_conf/meratnia_new.pdf
Args:
points (:obj:`list` of :obj:`Point`): trajectory or part of it
speed_threshold (float): max speed error, in km/h
Returns:
:obj:`list` of :ob... |
def delete_bucket():
"""
Delete S3 Bucket
"""
args = parser.parse_args
s3_bucket(args.aws_access_key_id, args.aws_secret_access_key, args.bucket_name)().delete() | Delete S3 Bucket |
def construct(cls, name: str, declared_fields: typing.List[tuple]):
"""
Utility method packaged along with the factory to be able to construct Request Object
classes on the fly.
Example:
.. code-block:: python
UserShowRequestObject = Factory.create_request_object(
... | Utility method packaged along with the factory to be able to construct Request Object
classes on the fly.
Example:
.. code-block:: python
UserShowRequestObject = Factory.create_request_object(
'CreateRequestObject',
[('identifier', int, {'required':... |
def get_type_properties(self, property_obj, name, additional_prop=False):
"""
Extend parents 'Get internal properties of property'-method
"""
property_type, property_format, property_dict = \
super(Schema, self).get_type_properties(property_obj, name, additional_prop=addition... | Extend parents 'Get internal properties of property'-method |
def schemaValidateOneElement(self, elem):
"""Validate a branch of a tree, starting with the given @elem. """
if elem is None: elem__o = None
else: elem__o = elem._o
ret = libxml2mod.xmlSchemaValidateOneElement(self._o, elem__o)
return ret | Validate a branch of a tree, starting with the given @elem. |
def _create_emitter(self, event):
"""Create a method that emits an event of the same name."""
if not hasattr(self, event):
setattr(self, event,
lambda *args, **kwargs: self.emit(event, *args, **kwargs)) | Create a method that emits an event of the same name. |
def call(self, op, args):
"""
Calls operation `op` on args `args` with this backend.
:return: A backend object representing the result.
"""
converted = self.convert_list(args)
return self._call(op, converted) | Calls operation `op` on args `args` with this backend.
:return: A backend object representing the result. |
def vinet_v(p, v0, k0, k0p, min_strain=0.01):
"""
find volume at given pressure
:param p: pressure in GPa
:param v0: unit-cell volume in A^3 at 1 bar
:param k0: bulk modulus at reference conditions
:param k0p: pressure derivative of bulk modulus at reference conditions
:param min_strain: de... | find volume at given pressure
:param p: pressure in GPa
:param v0: unit-cell volume in A^3 at 1 bar
:param k0: bulk modulus at reference conditions
:param k0p: pressure derivative of bulk modulus at reference conditions
:param min_strain: defining minimum v/v0 value to search volume for
:return... |
def popup(self, title, callfn, initialdir=None, filename=None):
"""Let user select and load file."""
self.cb = callfn
self.filew.set_title(title)
if initialdir:
self.filew.set_current_folder(initialdir)
if filename:
#self.filew.set_filename(filename)
... | Let user select and load file. |
def web_services_from_str(
list_splitter_fn=ujson.loads,
):
"""
parameters:
list_splitter_fn - a function that will take the json compatible string
rerpesenting a list of mappings.
"""
# -------------------------------------------------------------------------
def class_list... | parameters:
list_splitter_fn - a function that will take the json compatible string
rerpesenting a list of mappings. |
def args_ok(self, options, args):
"""Check for conflicts and problems in the options.
Returns True if everything is ok, or False if not.
"""
for i in ['erase', 'execute']:
for j in ['annotate', 'html', 'report', 'combine']:
if (i in options.actions) and (j i... | Check for conflicts and problems in the options.
Returns True if everything is ok, or False if not. |
def from_config(self, k, v):
"""
Hook method that allows converting values from the dictionary.
:param k: the key in the dictionary
:type k: str
:param v: the value
:type v: object
:return: the potentially parsed value
:rtype: object
"""
i... | Hook method that allows converting values from the dictionary.
:param k: the key in the dictionary
:type k: str
:param v: the value
:type v: object
:return: the potentially parsed value
:rtype: object |
def run_check200(_):
'''
Running the script.
'''
tstr = ''
idx = 1
for kind in config.router_post.keys():
posts = MPost.query_all(kind=kind, limit=20000)
for post in posts:
the_url0 = '{site_url}/{kind_url}/{uid}'.format(
site_url=config.SITE_CFG['sit... | Running the script. |
def pool_full(self, session):
"""
Returns a boolean as to whether the slot pool has room for this
task to run
"""
if not self.task.pool:
return False
pool = (
session
.query(Pool)
.filter(Pool.pool == self.task.pool)
... | Returns a boolean as to whether the slot pool has room for this
task to run |
def _instantiate_layers(self):
"""Instantiates all the convolutional modules used in the network."""
# Here we are entering the module's variable scope to name our submodules
# correctly (not to create variables). As such it's safe to not check
# whether we're in the same graph. This is important if we... | Instantiates all the convolutional modules used in the network. |
def find_global(self, pattern):
"""
Searches for the pattern in the whole process memory space and returns the first occurrence.
This is exhaustive!
"""
pos_s = self.reader.search(pattern)
if len(pos_s) == 0:
return -1
return pos_s[0] | Searches for the pattern in the whole process memory space and returns the first occurrence.
This is exhaustive! |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.