code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def get_query_arguments(self, name: str, strip: bool = True) -> List[str]:
"""Returns a list of the query arguments with the given name.
If the argument is not present, returns an empty list.
.. versionadded:: 3.2
"""
return self._get_arguments(name, self.request.query_argument... | Returns a list of the query arguments with the given name.
If the argument is not present, returns an empty list.
.. versionadded:: 3.2 |
def __create_rec(*args, **kwargs):
'''
Create the record.
'''
uid = args[0]
kind = args[1]
post_data = kwargs['post_data']
try:
TabWiki.create(
uid=uid,
title=post_data['title'].strip(),
date=datetime.da... | Create the record. |
def add_annotation(self, description, **attrs):
"""Add an annotation to span.
:type description: str
:param description: A user-supplied message describing the event.
The maximum length for the description is 256 bytes.
:type attrs: kwargs
:param attrs: ... | Add an annotation to span.
:type description: str
:param description: A user-supplied message describing the event.
The maximum length for the description is 256 bytes.
:type attrs: kwargs
:param attrs: keyworded arguments e.g. failed=True, name='Caching' |
def set_writer(self, writer):
"""
Changes the writer function to handle writing to the text edit.
A writer function must have the following prototype:
.. code-block:: python
def write(text_edit, text, color)
:param writer: write function as described above.
... | Changes the writer function to handle writing to the text edit.
A writer function must have the following prototype:
.. code-block:: python
def write(text_edit, text, color)
:param writer: write function as described above. |
def add_plugin(self, plugin, tabs, data, icon):
"""Add a plugin to display its files."""
self.plugins_tabs.append((tabs, plugin))
self.plugins_data.append((data, icon))
self.plugins_instances.append(plugin) | Add a plugin to display its files. |
def _processCheckAuthResponse(self, response, server_url):
"""Process the response message from a check_authentication
request, invalidating associations if requested.
"""
is_valid = response.getArg(OPENID_NS, 'is_valid', 'false')
invalidate_handle = response.getArg(OPENID_NS, '... | Process the response message from a check_authentication
request, invalidating associations if requested. |
def parse_url(track_url):
"""
Detects if a URL is a track or a playlist, and parses the track(s)
to the track downloader
"""
global arguments
item = get_item(track_url)
logger.debug(item)
if not item:
return
elif item['kind'] == 'track':
logger.info('Found a track')
... | Detects if a URL is a track or a playlist, and parses the track(s)
to the track downloader |
def cbpdn_relax(k):
"""Do relaxation for the cbpdn stage. The only parameter is the slice
index `k` and there are no return values; all inputs and outputs are
from and to global variables.
"""
mp_Z_X[k] = mp_xrlx * mp_Z_X[k] + (1 - mp_xrlx) * mp_Z_Y[k] | Do relaxation for the cbpdn stage. The only parameter is the slice
index `k` and there are no return values; all inputs and outputs are
from and to global variables. |
def shot_chart(x, y, kind="scatter", title="", color="b", cmap=None,
xlim=(-250, 250), ylim=(422.5, -47.5),
court_color="gray", court_lw=1, outer_lines=False,
flip_court=False, kde_shade=True, gridsize=None, ax=None,
despine=False, **kwargs):
"""
Retur... | Returns an Axes object with player shots plotted.
Parameters
----------
x, y : strings or vector
The x and y coordinates of the shots taken. They can be passed in as
vectors (such as a pandas Series) or as columns from the pandas
DataFrame passed into ``data``.
data : DataFrame... |
def linkify_h_by_h(self):
"""Link hosts with their parents
:return: None
"""
for host in self:
# The new member list
new_parents = []
for parent in getattr(host, 'parents', []):
parent = parent.strip()
o_parent = self.f... | Link hosts with their parents
:return: None |
def set_value(dct, key, value):
"""Set a value in a dict. If `key` contains a '.', it is assumed
be a path (i.e. dot-delimited string) to the value's location.
::
>>> d = {}
>>> set_value(d, 'foo.bar', 42)
>>> d
{'foo': {'bar': 42}}
"""
if '.' in key:
head, ... | Set a value in a dict. If `key` contains a '.', it is assumed
be a path (i.e. dot-delimited string) to the value's location.
::
>>> d = {}
>>> set_value(d, 'foo.bar', 42)
>>> d
{'foo': {'bar': 42}} |
def shortcut_update(self, shortcut_id, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/chat/shortcuts#update-shortcut"
api_path = "/api/v2/shortcuts/{shortcut_id}"
api_path = api_path.format(shortcut_id=shortcut_id)
return self.call(api_path, method="PUT", data=data, **kwar... | https://developer.zendesk.com/rest_api/docs/chat/shortcuts#update-shortcut |
def _get_qgen_var(self, generators, base_mva):
""" Returns the generator reactive power variable set.
"""
Qg = array([g.q / base_mva for g in generators])
Qmin = array([g.q_min / base_mva for g in generators])
Qmax = array([g.q_max / base_mva for g in generators])
retur... | Returns the generator reactive power variable set. |
def detect_builtin_shadowing_definitions(self, contract):
""" Detects if functions, access modifiers, events, state variables, or local variables are named after built-in
symbols. Any such definitions are returned in a list.
Returns:
list of tuple: (type, definition, [local vari... | Detects if functions, access modifiers, events, state variables, or local variables are named after built-in
symbols. Any such definitions are returned in a list.
Returns:
list of tuple: (type, definition, [local variable parent]) |
def update(self, project, params={}, **options):
"""A specific, existing project can be updated by making a PUT request on the
URL for that project. Only the fields provided in the `data` block will be
updated; any unspecified fields will remain unchanged.
When using this metho... | A specific, existing project can be updated by making a PUT request on the
URL for that project. Only the fields provided in the `data` block will be
updated; any unspecified fields will remain unchanged.
When using this method, it is best to specify only those fields you wish
t... |
def new_stats_exporter(option):
""" new_stats_exporter returns an exporter
that exports stats to Prometheus.
"""
if option.namespace == "":
raise ValueError("Namespace can not be empty string.")
collector = new_collector(option)
exporter = PrometheusStatsExporter(options=option,
... | new_stats_exporter returns an exporter
that exports stats to Prometheus. |
def gfit(X, sigma, p=5, nbin=200, unif_fraction=0.1):
"""
Fit empirical Bayes prior in the hierarchical model [Efron2014]_.
.. math::
mu ~ G, X ~ N(mu, sigma^2)
Parameters
----------
X: ndarray
A 1D array of observations.
sigma: float
Noise estimate on X.
p: in... | Fit empirical Bayes prior in the hierarchical model [Efron2014]_.
.. math::
mu ~ G, X ~ N(mu, sigma^2)
Parameters
----------
X: ndarray
A 1D array of observations.
sigma: float
Noise estimate on X.
p: int
Number of parameters used to fit G. Default: 5
nbin:... |
def get_from_package(package_name, path):
"""
Get the absolute path to a file in a package.
Parameters
----------
package_name : str
e.g. 'mpu'
path : str
Path within a package
Returns
-------
filepath : str
"""
filepath = pkg_resources.resource_filename(pac... | Get the absolute path to a file in a package.
Parameters
----------
package_name : str
e.g. 'mpu'
path : str
Path within a package
Returns
-------
filepath : str |
def save_catalog(self):
"""
Saves the catalog data to given key
Cancels if the cmd is cancel
Notifies user with the process.
"""
if self.input["cmd"] == 'save_catalog':
try:
edited_object = dict()
for i in self.input["form"]["Ca... | Saves the catalog data to given key
Cancels if the cmd is cancel
Notifies user with the process. |
def deserialize(cls, raw_bytes):
"""
Deserializes the given raw bytes into an instance.
Since this is a subclass of ``Part`` but a top-level one (i.e. no other
subclass of ``Part`` would have a ``Response`` as a part) this merely
has to parse the raw bytes and discard the result... | Deserializes the given raw bytes into an instance.
Since this is a subclass of ``Part`` but a top-level one (i.e. no other
subclass of ``Part`` would have a ``Response`` as a part) this merely
has to parse the raw bytes and discard the resulting offset. |
def _in_range_inclusive(cls, val, **kwargs):
'''
checks that a value is in an inclusive range
The value for 0 used by Max Password Age is actually 0xffffffff
'''
minimum = kwargs.get('min', 0)
maximum = kwargs.get('max', 1)
zero_value = kwargs.get('zero_value', 0)... | checks that a value is in an inclusive range
The value for 0 used by Max Password Age is actually 0xffffffff |
def generate_prediction_data(self):
"""
Create data that caches intermediate results used for predicting
the label of new/unseen points. This data is only useful if
you are intending to use functions from ``hdbscan.prediction``.
"""
if self.metric in FAST_METRICS:
... | Create data that caches intermediate results used for predicting
the label of new/unseen points. This data is only useful if
you are intending to use functions from ``hdbscan.prediction``. |
def _buildTemplates(self):
"""
OVERRIDING THIS METHOD from Factory
"""
jsontree_classes = build_D3treeStandard(
0, 99, 1, self.ontospy_graph.toplayer_classes)
c_total = len(self.ontospy_graph.all_classes)
JSON_DATA_CLASSES = json.dumps({
'childre... | OVERRIDING THIS METHOD from Factory |
def get_parser():
""" Return argument parser. """
parser = argparse.ArgumentParser(
formatter_class=argparse.RawTextHelpFormatter,
description=__doc__,
)
# connection to redis server
parser.add_argument('--host', default='localhost')
parser.add_argument('--port', default=6379, t... | Return argument parser. |
def read(self):
'''Execute the expression and capture its output, similar to backticks
or $() in the shell. This is a wrapper around run() which captures
stdout, decodes it, trims it, and returns it directly.'''
result = self.stdout_capture().run()
stdout_str = decode_with_univer... | Execute the expression and capture its output, similar to backticks
or $() in the shell. This is a wrapper around run() which captures
stdout, decodes it, trims it, and returns it directly. |
def inflect(self, filename):
"""Inflect a filename to indicate its type.
If the file is a directory, the suffix "/" is appended, otherwise
a space is appended.
:param filename: the name of the file to inflect
"""
suffix = ("/" if os.path.isdir(filename) else " ")
... | Inflect a filename to indicate its type.
If the file is a directory, the suffix "/" is appended, otherwise
a space is appended.
:param filename: the name of the file to inflect |
def make_heap_initializer(dist, dist_args):
"""Create a numba accelerated version of heap initialization for the
alternative k-neighbor graph algorithm. This approach builds two heaps
of neighbors simultaneously, one is a heap used to construct a very
approximate k-neighbor graph for searching; the othe... | Create a numba accelerated version of heap initialization for the
alternative k-neighbor graph algorithm. This approach builds two heaps
of neighbors simultaneously, one is a heap used to construct a very
approximate k-neighbor graph for searching; the other is the
initialization for searching.
Par... |
def _hook_syscall(self, uc, data):
"""
Unicorn hook that transfers control to Manticore so it can execute the syscall
"""
logger.debug(f"Stopping emulation at {hex(uc.reg_read(self._to_unicorn_id('RIP')))} to perform syscall")
self.sync_unicorn_to_manticore()
from ..nativ... | Unicorn hook that transfers control to Manticore so it can execute the syscall |
def load_savefile(input_file, layers=0, verbose=False, lazy=False):
"""
Parse a savefile as a pcap_savefile instance. Returns the savefile
on success and None on failure. Verbose mode prints additional information
about the file's processing. layers defines how many layers to descend and
decode the ... | Parse a savefile as a pcap_savefile instance. Returns the savefile
on success and None on failure. Verbose mode prints additional information
about the file's processing. layers defines how many layers to descend and
decode the packet. input_file should be a Python file object. |
def base_concrete_model(abstract, model):
"""
Used in methods of abstract models to find the super-most concrete
(non abstract) model in the inheritance chain that inherits from the
given abstract model. This is so the methods in the abstract model can
query data consistently across the correct conc... | Used in methods of abstract models to find the super-most concrete
(non abstract) model in the inheritance chain that inherits from the
given abstract model. This is so the methods in the abstract model can
query data consistently across the correct concrete model.
Consider the following::
cla... |
def delete(self, key):
"""
Removes the specified key from the database.
"""
obj = self._get_content()
obj.pop(key, None)
self.write_data(self.path, obj) | Removes the specified key from the database. |
def _check_mapper(self, mapper):
""" Check that the mapper has valid signature. """
if not hasattr(mapper, 'parse') or not callable(mapper.parse):
raise ValueError('mapper must implement parse()')
if not hasattr(mapper, 'format') or not callable(mapper.format):
raise Valu... | Check that the mapper has valid signature. |
def props(self, element=None, mode='all', deep=False):
r"""
Returns a list containing the names of all defined pore or throat
properties.
Parameters
----------
element : string, optional
Can be either 'pore' or 'throat' to specify what properties are
... | r"""
Returns a list containing the names of all defined pore or throat
properties.
Parameters
----------
element : string, optional
Can be either 'pore' or 'throat' to specify what properties are
returned. If no element is given, both are returned
... |
def element_set_to_node_set(self, tag):
"""
Makes a node set from an element set.
"""
nodes, elements = self.nodes, self.elements
loc = (elements.conn[elements[("sets", tag, "")]]
.stack().stack().unique())
loc = loc[loc != 0]
nodes[("sets", tag)] = False
nodes.loc[loc, ("sets... | Makes a node set from an element set. |
def bubbletext(text, font='cybermedium'):
r"""
Uses pyfiglet to create bubble text.
Args:
font (str): default=cybermedium, other fonts include: cybersmall and
cyberlarge.
References:
http://www.figlet.org/
Example:
>>> # ENABLE_DOCTEST
>>> import utool ... | r"""
Uses pyfiglet to create bubble text.
Args:
font (str): default=cybermedium, other fonts include: cybersmall and
cyberlarge.
References:
http://www.figlet.org/
Example:
>>> # ENABLE_DOCTEST
>>> import utool as ut
>>> bubble_text = ut.bubbletext(... |
def _MergeEntities(self, a, b):
"""Merges two stops.
For the stops to be merged, they must have:
- the same stop_id
- the same stop_name (case insensitive)
- the same zone_id
- locations less than largest_stop_distance apart
The other attributes can have arbitary changes. The merged... | Merges two stops.
For the stops to be merged, they must have:
- the same stop_id
- the same stop_name (case insensitive)
- the same zone_id
- locations less than largest_stop_distance apart
The other attributes can have arbitary changes. The merged attributes are
taken from the new ... |
def update(self, friendly_name=values.unset, log_queries=values.unset,
unique_name=values.unset, callback_url=values.unset,
callback_events=values.unset, fallback_actions=values.unset,
initiation_actions=values.unset, style_sheet=values.unset):
"""
Update the... | Update the AssistantInstance
:param unicode friendly_name: A text description for the Assistant. It is non-unique and can up to 255 characters long.
:param bool log_queries: A boolean that specifies whether queries should be logged for 30 days further training. If false, no queries will be stored, if t... |
def get_formatter_by_name(_alias, **options):
"""Lookup and instantiate a formatter by alias.
Raises ClassNotFound if not found.
"""
cls = find_formatter_class(_alias)
if cls is None:
raise ClassNotFound("no formatter found for name %r" % _alias)
return cls(**options) | Lookup and instantiate a formatter by alias.
Raises ClassNotFound if not found. |
def get_assessment_id(self):
"""Gets the assessment ``Id`` associated with this learning objective.
return: (osid.id.Id) - the assessment ``Id``
raise: IllegalState - ``has_assessment()`` is ``false``
*compliance: mandatory -- This method must be implemented.*
"""
# Im... | Gets the assessment ``Id`` associated with this learning objective.
return: (osid.id.Id) - the assessment ``Id``
raise: IllegalState - ``has_assessment()`` is ``false``
*compliance: mandatory -- This method must be implemented.* |
def delete(name,
purge=False,
force=False):
'''
Remove a user from the minion
Args:
name (str): The name of the user to delete
purge (bool, optional): Boolean value indicating that the user profile
should also be removed when the user account is deleted. I... | Remove a user from the minion
Args:
name (str): The name of the user to delete
purge (bool, optional): Boolean value indicating that the user profile
should also be removed when the user account is deleted. If set to
True the profile will be removed. Default is False.
... |
def create_file(self, file_path, st_mode=S_IFREG | PERM_DEF_FILE,
contents='', st_size=None, create_missing_dirs=True,
apply_umask=False, encoding=None, errors=None,
side_effect=None):
"""Create `file_path`, including all the parent directories along
... | Create `file_path`, including all the parent directories along
the way.
This helper method can be used to set up tests more easily.
Args:
file_path: The path to the file to create.
st_mode: The stat constant representing the file type.
contents: the contents... |
def reconstruct_anc(self, method='probabilistic', infer_gtr=False,
marginal=False, **kwargs):
"""Reconstruct ancestral sequences
Parameters
----------
method : str
Method to use. Supported values are "fitch" and "ml"
infer_gtr : bool
... | Reconstruct ancestral sequences
Parameters
----------
method : str
Method to use. Supported values are "fitch" and "ml"
infer_gtr : bool
Infer a GTR model before reconstructing the sequences
marginal : bool
Assign sequences that are most likely... |
def signal_children(children):
"""Relay interupt/term signals to children, for more solid process cleanup."""
def terminate_children(sig, frame):
log = Application.instance().log
log.critical("Got signal %i, terminating children..."%sig)
for child in children:
child.terminate... | Relay interupt/term signals to children, for more solid process cleanup. |
def fixed_gaussian_prior_builder(
getter, name, dtype=None, *args, **kwargs):
"""A pre-canned builder for fixed gaussian prior distributions.
Given a true `getter` function and arguments forwarded from `tf.get_variable`,
return a distribution object for a scalar-valued fixed gaussian prior which
will be br... | A pre-canned builder for fixed gaussian prior distributions.
Given a true `getter` function and arguments forwarded from `tf.get_variable`,
return a distribution object for a scalar-valued fixed gaussian prior which
will be broadcast over a variable of the requisite shape.
Args:
getter: The `getter` passe... |
async def from_client(cls, client, *, shard_id=None, session=None, sequence=None, resume=False):
"""Creates a main websocket for Discord from a :class:`Client`.
This is for internal use only.
"""
gateway = await client.http.get_gateway()
ws = await websockets.connect(gateway, lo... | Creates a main websocket for Discord from a :class:`Client`.
This is for internal use only. |
def write(self, value):
"""
Output a voltage from the pin
:arg value: Uses value as a boolean if the pin is in output mode, or
expects a float from 0 to 1 if the pin is in PWM mode. If the pin
is in SERVO the value should be in degrees.
"""
if self.mode ... | Output a voltage from the pin
:arg value: Uses value as a boolean if the pin is in output mode, or
expects a float from 0 to 1 if the pin is in PWM mode. If the pin
is in SERVO the value should be in degrees. |
def _set_get_port_profile_status(self, v, load=False):
"""
Setter method for get_port_profile_status, mapped from YANG variable /brocade_port_profile_ext_rpc/get_port_profile_status (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_get_port_profile_status is consider... | Setter method for get_port_profile_status, mapped from YANG variable /brocade_port_profile_ext_rpc/get_port_profile_status (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_get_port_profile_status is considered as a private
method. Backends looking to populate this varia... |
def remove_user(self, name):
"""Remove a user from kubeconfig.
"""
user = self.get_user(name)
users = self.get_users()
users.remove(user) | Remove a user from kubeconfig. |
def _remove_docstring_indent(self, docstring):
"""Remove indenting.
We follow Python's convention and remove the minimum indent of the lines
after the first, see:
https://www.python.org/dev/peps/pep-0257/#handling-docstring-indentation
preserving relative indentation.
Args:
docstring: A ... | Remove indenting.
We follow Python's convention and remove the minimum indent of the lines
after the first, see:
https://www.python.org/dev/peps/pep-0257/#handling-docstring-indentation
preserving relative indentation.
Args:
docstring: A docstring.
Returns:
A list of strings, one ... |
def _mutual_info_score(reference_indices, estimated_indices, contingency=None):
"""Compute the mutual information between two sequence labelings.
Parameters
----------
reference_indices : np.ndarray
Array of reference indices
estimated_indices : np.ndarray
Array of estimated indices... | Compute the mutual information between two sequence labelings.
Parameters
----------
reference_indices : np.ndarray
Array of reference indices
estimated_indices : np.ndarray
Array of estimated indices
contingency : np.ndarray
Pre-computed contingency matrix. If None, one wi... |
def pcwd(func):
"""A decorator to provide the functionality of the
PreserveWorkingDirectory context manager for functions and methods."""
@wraps(func)
def inner(*args, **kw):
with PreserveWorkingDirectory():
return func(*args, **kw)
return inner | A decorator to provide the functionality of the
PreserveWorkingDirectory context manager for functions and methods. |
def xisabs(filename):
""" Cross-platform version of `os.path.isabs()`
Returns True if `filename` is absolute on
Linux, OS X or Windows.
"""
if filename.startswith(b'/'): # Linux/Unix
return True
elif filename.startswith(b'\\'): # Windows
return True
elif re.match(b'\\w:[\\\\/]', filen... | Cross-platform version of `os.path.isabs()`
Returns True if `filename` is absolute on
Linux, OS X or Windows. |
def move_next_to(self, body_a, body_b, offset_a, offset_b):
'''Move one body to be near another one.
After moving, the location described by ``offset_a`` on ``body_a`` will
be coincident with the location described by ``offset_b`` on ``body_b``.
Parameters
----------
bo... | Move one body to be near another one.
After moving, the location described by ``offset_a`` on ``body_a`` will
be coincident with the location described by ``offset_b`` on ``body_b``.
Parameters
----------
body_a : str or :class:`Body`
The body to use as a reference ... |
def cidr_broadcast(cidr):
'''
Get the broadcast address associated with a CIDR address.
CLI example::
salt myminion netaddress.cidr_netmask 192.168.0.0/20
'''
ips = netaddr.IPNetwork(cidr)
return six.text_type(ips.broadcast) | Get the broadcast address associated with a CIDR address.
CLI example::
salt myminion netaddress.cidr_netmask 192.168.0.0/20 |
def get_fragment_generator(self, gp, **kwargs):
"""
Return a fragment generator for a given gp.
:param gp:
:param kwargs:
:return:
"""
collector = FragmentCollector(self.__host, gp)
return collector.get_fragment_generator(**kwargs) | Return a fragment generator for a given gp.
:param gp:
:param kwargs:
:return: |
def GenQuotedState(self):
"""Generate string matching state rules."""
for i, q in enumerate(self.quot):
label = "%s_STRING" % i
escaped = re.escape(q)
self._AddToken(label, escaped, "PopState", None)
self._AddToken(label, q, "PopState", None)
if self.ml_quote:
self._AddToke... | Generate string matching state rules. |
def parse(cls, dom):
"""Converts DOM into paragraphs."""
handler = cls()
saxify(dom, handler)
return handler.content | Converts DOM into paragraphs. |
def get_agenda(self,
conservative: bool = False):
"""
Returns an agenda that can be used guide search.
Parameters
----------
conservative : ``bool``
Setting this flag will return a subset of the agenda items that correspond to high
conf... | Returns an agenda that can be used guide search.
Parameters
----------
conservative : ``bool``
Setting this flag will return a subset of the agenda items that correspond to high
confidence lexical matches. You'll need this if you are going to use this agenda to
... |
def crab_gateway_request(client, method, *args):
'''
Utility function that helps making requests to the CRAB service.
This is a specialised version of :func:`crabpy.client.crab_request` that
allows adding extra functionality for the calls made by the gateway.
:param client: A :class:`suds.client.C... | Utility function that helps making requests to the CRAB service.
This is a specialised version of :func:`crabpy.client.crab_request` that
allows adding extra functionality for the calls made by the gateway.
:param client: A :class:`suds.client.Client` for the CRAB service.
:param string action: Which ... |
def print_computation_log(self, aggregate = False):
"""
Print the computation log of a simulation.
If ``aggregate`` is ``False`` (default), print the value of each computed vector.
If ``aggregate`` is ``True``, only print the minimum, maximum, and average value of each comp... | Print the computation log of a simulation.
If ``aggregate`` is ``False`` (default), print the value of each computed vector.
If ``aggregate`` is ``True``, only print the minimum, maximum, and average value of each computed vector.
This mode is more suited for simulations on a large... |
def respond(text=None, ssml=None, attributes=None, reprompt_text=None,
reprompt_ssml=None, end_session=True):
""" Build a dict containing a valid response to an Alexa request.
If speech output is desired, either of `text` or `ssml` should
be specified.
:param text: Plain text speech output... | Build a dict containing a valid response to an Alexa request.
If speech output is desired, either of `text` or `ssml` should
be specified.
:param text: Plain text speech output to be said by Alexa device.
:param ssml: Speech output in SSML form.
:param attributes: Dictionary of attributes to store... |
def bpf_select(fds_list, timeout=None):
"""A call to recv() can return several frames. This functions hides the fact
that some frames are read from the internal buffer."""
# Check file descriptors types
bpf_scks_buffered = list()
select_fds = list()
for tmp_fd in fds_list:
# Specif... | A call to recv() can return several frames. This functions hides the fact
that some frames are read from the internal buffer. |
def _q_to_dcm(self, q):
"""
Create DCM from q
:param q: array q which represents a quaternion [w, x, y, z]
:returns: 3x3 dcm array
"""
assert(len(q) == 4)
assert(np.allclose(QuaternionBase.norm_array(q), 1))
dcm = np.zeros([3, 3])
a = q[0]
... | Create DCM from q
:param q: array q which represents a quaternion [w, x, y, z]
:returns: 3x3 dcm array |
def valid_function_signature(input_type, func):
"""Check that the declared number of inputs (the length of `input_type`)
and the number of inputs to `func` are equal.
Parameters
----------
input_type : List[DataType]
func : callable
Returns
-------
inspect.Signature
"""
fun... | Check that the declared number of inputs (the length of `input_type`)
and the number of inputs to `func` are equal.
Parameters
----------
input_type : List[DataType]
func : callable
Returns
-------
inspect.Signature |
def execute(self, eopatch, title=None, colorbar=False):
"""Shows data and scrolls through. Currently not working from Jupyter notebooks.
:param eopatch: Image sequence to display. Can be single channel, RGB or multi-channel. If multi-channel,
indices must be specified.
... | Shows data and scrolls through. Currently not working from Jupyter notebooks.
:param eopatch: Image sequence to display. Can be single channel, RGB or multi-channel. If multi-channel,
indices must be specified.
:type eopatch: numpy array
:param title: String to be d... |
def start(cmd, port=None, numRetries=10, label="default"):
"""
Start a sumo server using cmd, establish a connection to it and
store it under the given label. This method is not thread-safe.
"""
if port is None:
port = sumolib.miscutils.getFreeSocketPort()
sumoProcess = subprocess.Popen(... | Start a sumo server using cmd, establish a connection to it and
store it under the given label. This method is not thread-safe. |
def read_igor_VJ_palindrome_parameters(self, params_file_name):
"""Read V and J palindrome parameters from file.
Sets the attributes max_delV_palindrome and max_delJ_palindrome.
Parameters
----------
params_file_name : str
File name for an IGoR parameter... | Read V and J palindrome parameters from file.
Sets the attributes max_delV_palindrome and max_delJ_palindrome.
Parameters
----------
params_file_name : str
File name for an IGoR parameter file of a VJ generative model. |
def _raise_document_too_large(operation, doc_size, max_size):
"""Internal helper for raising DocumentTooLarge."""
if operation == "insert":
raise DocumentTooLarge("BSON document too large (%d bytes)"
" - the connected server supports"
" BSON ... | Internal helper for raising DocumentTooLarge. |
def add_user(self, name, password=None, read_only=None, **kwargs):
"""Create user `name` with password `password`.
Add a new user with permissions for this :class:`Database`.
.. note:: Will change the password if user `name` already exists.
:Parameters:
- `name`: the name of... | Create user `name` with password `password`.
Add a new user with permissions for this :class:`Database`.
.. note:: Will change the password if user `name` already exists.
:Parameters:
- `name`: the name of the user to create
- `password` (optional): the password of the use... |
def main(*argv,
filesystem=None,
do_exit=True,
stdout=None,
stderr=None):
"""Main method for the cli.
We allow the filesystem to be overridden for test purposes."""
try:
mdcli = MdCLI()
mdcli.filesystem = filesystem
mdcli.stdout = stdout or ... | Main method for the cli.
We allow the filesystem to be overridden for test purposes. |
def fingerprint(self, word):
"""Return the omission key.
Parameters
----------
word : str
The word to transform into its omission key
Returns
-------
str
The omission key
Examples
--------
>>> ok = OmissionKey()
... | Return the omission key.
Parameters
----------
word : str
The word to transform into its omission key
Returns
-------
str
The omission key
Examples
--------
>>> ok = OmissionKey()
>>> ok.fingerprint('The quick bro... |
def _add_image_part(self, image):
"""
Return an |ImagePart| instance newly created from image and appended
to the collection.
"""
partname = self._next_image_partname(image.ext)
image_part = ImagePart.from_image(image, partname)
self.append(image_part)
ret... | Return an |ImagePart| instance newly created from image and appended
to the collection. |
def download(self, dirpath):
""" Download artifact from S3 and store in dirpath directory.
If the artifact is already downloaded nothing is done. """
if os.path.isfile(self.lpath) and os.path.getsize(self.lpath) > 0:
return
print('Downloading %s -> %s' % (self.path, self.... | Download artifact from S3 and store in dirpath directory.
If the artifact is already downloaded nothing is done. |
def get_poolmember_state(self, id_pools, checkstatus=0):
"""
Enable/Disable pool member by list
"""
uri = "api/v3/pool/real/%s/member/status/?checkstatus=%s" % (';'.join(id_pools), checkstatus)
return self.get(uri) | Enable/Disable pool member by list |
def _get_request_representer(self):
"""
Returns a representer for the content type specified in the request.
:raises HTTPUnsupportedMediaType: If the specified content type is
not supported.
"""
try:
mime_type = \
get_registered_mime_type_for_... | Returns a representer for the content type specified in the request.
:raises HTTPUnsupportedMediaType: If the specified content type is
not supported. |
def remove(self, class_name, name):
"""
Removes a single component from the network.
Removes it from component DataFrames.
Parameters
----------
class_name : string
Component class name
name : string
Component name
Examples
... | Removes a single component from the network.
Removes it from component DataFrames.
Parameters
----------
class_name : string
Component class name
name : string
Component name
Examples
--------
>>> network.remove("Line","my_line 1... |
def _insert(self, element, new_element, before):
"""
Insert a element before or after other element.
:param element: The reference element.
:type element: hatemile.util.html.htmldomelement.HTMLDOMElement
:param new_element: The element that be inserted.
:type new_element... | Insert a element before or after other element.
:param element: The reference element.
:type element: hatemile.util.html.htmldomelement.HTMLDOMElement
:param new_element: The element that be inserted.
:type new_element: hatemile.util.html.htmldomelement.HTMLDOMElement
:param bef... |
def parse_domain_users(domain_users_file, domain_groups_file):
"""
Parses the domain users and groups files.
"""
with open(domain_users_file) as f:
users = json.loads(f.read())
domain_groups = {}
if domain_groups_file:
with open(domain_groups_file) as f:
groups =... | Parses the domain users and groups files. |
def consolidate(self, key):
"""
Collapses a 'continuous' acquisition into a single dataset.
This must be performed before calling *get* function for *key* in these
modes.
:param key: name of the dataset to consolidate.
:type key: str
"""
if self.meta[key... | Collapses a 'continuous' acquisition into a single dataset.
This must be performed before calling *get* function for *key* in these
modes.
:param key: name of the dataset to consolidate.
:type key: str |
def AltTab(self, n=1, delay=0):
"""Press down Alt, then press n times Tab, then release Alt.
"""
self._delay(delay)
self.add(Command("KeyDown", 'KeyDown "%s", %s' % (BoardKey.Alt, 1)))
for i in range(n):
self.add(Command("KeyPress", 'KeyPress "%s", %s' % (BoardKey.Tab... | Press down Alt, then press n times Tab, then release Alt. |
def send_email(name, ctx_dict, send_to=None, subject=u'Subject', **kwargs):
"""
Shortcut function for EmailFromTemplate class
@return: None
"""
eft = EmailFromTemplate(name=name)
eft.subject = subject
eft.context = ctx_dict
eft.get_object()
eft.render_message()
eft.send_email(s... | Shortcut function for EmailFromTemplate class
@return: None |
def auto_init_default(column):
"""
Set the default value for a column when it's first accessed rather than
first committed to the database.
"""
if isinstance(column, ColumnProperty):
default = column.columns[0].default
else:
default = column.default
@event.listens_for(column... | Set the default value for a column when it's first accessed rather than
first committed to the database. |
def _get_piece(string, index):
"""
Returns Piece subclass given index of piece.
:type: index: int
:type: loc Location
:raise: KeyError
"""
piece = string[index].strip()
piece = piece.upper()
piece_dict = {'R': Rook,
'P': Pawn,
'B': Bishop,
... | Returns Piece subclass given index of piece.
:type: index: int
:type: loc Location
:raise: KeyError |
def update_client(self, client_id, client_dict):
"""
Updates a client
:param client_id: the client id
:param client_dict: dict
:return: dict
"""
return self._create_put_request(
resource=CLIENTS,
billomat_id=client_id,
send_dat... | Updates a client
:param client_id: the client id
:param client_dict: dict
:return: dict |
def data_names(self):
"""A list of names for data required by this module."""
if self.binded:
return self._curr_module.data_names
else:
_, data_names, _ = self._call_sym_gen(self._default_bucket_key)
return data_names | A list of names for data required by this module. |
def magic_help(self, line):
"""
Print out the help for magics
Usage:
Call help with no arguments to list all magics,
or call it with a magic to print out it's help info.
`%help`
or
`%help run
"""
line = line.strip()
if not line:
... | Print out the help for magics
Usage:
Call help with no arguments to list all magics,
or call it with a magic to print out it's help info.
`%help`
or
`%help run |
def get_query_columns(engine, query):
""" Extract columns names and python typos from query
Args:
engine: SQLAlchemy connection engine
query: SQL query
Returns:
dict with columns names and python types
"""
con = engine.connect()
result = con.execute(query).fetchone()
... | Extract columns names and python typos from query
Args:
engine: SQLAlchemy connection engine
query: SQL query
Returns:
dict with columns names and python types |
def state(self, container_id=None, sudo=None, sync_socket=None):
''' get the state of an OciImage, if it exists. The optional states that
can be returned are created, running, stopped or (not existing).
Equivalent command line example:
singularity oci state <container_ID>
... | get the state of an OciImage, if it exists. The optional states that
can be returned are created, running, stopped or (not existing).
Equivalent command line example:
singularity oci state <container_ID>
Parameters
==========
container_id: the id to g... |
def get_allocations(self, prefix=None):
""" Lists all the allocations.
https://www.nomadproject.io/docs/http/allocs.html
arguments:
- prefix :(str) optional, specifies a string to filter allocations on based on an prefix.
This is specified as a query... | Lists all the allocations.
https://www.nomadproject.io/docs/http/allocs.html
arguments:
- prefix :(str) optional, specifies a string to filter allocations on based on an prefix.
This is specified as a querystring parameter.
returns: list
... |
def singleOrPair(obj):
'''Chech an object is single or pair or neither.
Of course,, all pairs are single, so what the function is really detecting is whether an object is only single or at the same time a pair.
Args:
obj (object): Literally anything.
Returns:
str: 'Single', or 'Pair',... | Chech an object is single or pair or neither.
Of course,, all pairs are single, so what the function is really detecting is whether an object is only single or at the same time a pair.
Args:
obj (object): Literally anything.
Returns:
str: 'Single', or 'Pair', or 'Neither' |
def _get_indicators_for_report_page_generator(self, report_id, start_page=0, page_size=None):
"""
Creates a generator from the |get_indicators_for_report_page| method that returns each successive page.
:param str report_id: The ID of the report to get indicators for.
:param int start_pa... | Creates a generator from the |get_indicators_for_report_page| method that returns each successive page.
:param str report_id: The ID of the report to get indicators for.
:param int start_page: The page to start on.
:param int page_size: The size of each page.
:return: The generator. |
def cmd(self, command, args, prefix=None):
"""
Sends a command to the server.
:param command: IRC code to send.
:type command: unicode
:param args: arguments to pass with the command.
:type args: basestring
:param prefix: optional prefix to prepend to the command... | Sends a command to the server.
:param command: IRC code to send.
:type command: unicode
:param args: arguments to pass with the command.
:type args: basestring
:param prefix: optional prefix to prepend to the command.
:type prefix: str or None |
def set_data(self, source_data):
"""
:source_data": Data from data.get('SearchResults:searchresults', None)['response']['results']['result']['localRealEstate']
:return:
"""
self.region_name = source_data['region']['@name']
self.region_id = source_data['region']['@id']
... | :source_data": Data from data.get('SearchResults:searchresults', None)['response']['results']['result']['localRealEstate']
:return: |
def funTransQuadF(k, s):
""" Focusing quad in X, defocusing in Y
:param k: k1, in [T/m]
:param s: width, in [m]
:return: 2x2 numpy array
"""
sqrtk = np.sqrt(complex(k))
a = np.cos(sqrtk * s)
b = np.sin(sqrtk * s) / sqrtk
c = -sqrtk * np.sin(sqrtk * s)
d = np.cos(sqrtk * s)
r... | Focusing quad in X, defocusing in Y
:param k: k1, in [T/m]
:param s: width, in [m]
:return: 2x2 numpy array |
def run_bwakit(job, config, sort=True, trim=False, mark_secondary=False):
"""
Runs BWA-Kit to align single or paired-end fastq files or realign SAM/BAM files.
:param JobFunctionWrappingJob job: Passed by Toil automatically
:param Namespace config: A configuration object that holds strings as attributes... | Runs BWA-Kit to align single or paired-end fastq files or realign SAM/BAM files.
:param JobFunctionWrappingJob job: Passed by Toil automatically
:param Namespace config: A configuration object that holds strings as attributes.
The attributes must be accessible via the dot operator.
The config m... |
def setHtml(self, html, baseUrl=QUrl()):
"""
Reimplement Qt method to prevent WebEngine to steal focus
when setting html on the page
Solution taken from
https://bugreports.qt.io/browse/QTBUG-52999
"""
if WEBENGINE:
self.setEnabled(False)
... | Reimplement Qt method to prevent WebEngine to steal focus
when setting html on the page
Solution taken from
https://bugreports.qt.io/browse/QTBUG-52999 |
def _store_parameters(self):
"""Store startup params and config in datadir/.mlaunch_startup."""
datapath = self.dir
out_dict = {
'protocol_version': 2,
'mtools_version': __version__,
'parsed_args': self.args,
'unknown_args': self.unknown_args,
... | Store startup params and config in datadir/.mlaunch_startup. |
def fetchUnseen(self):
"""
Get the unseen (new) thread list
:return: List of unseen thread ids
:rtype: list
:raises: FBchatException if request failed
"""
j = self._post(
self.req_url.UNSEEN_THREADS, None, fix_request=True, as_json=True
)
... | Get the unseen (new) thread list
:return: List of unseen thread ids
:rtype: list
:raises: FBchatException if request failed |
def write_byte(self, value):
"""
Write a single byte to the stream.
Args:
value (bytes, str or int): value to write to the stream.
"""
if isinstance(value, bytes):
self.stream.write(value)
elif isinstance(value, str):
self.stream.write... | Write a single byte to the stream.
Args:
value (bytes, str or int): value to write to the stream. |
def set_workflow_by_name(self, workflow_name):
"""Configure the workflow to run by the name of this one.
Allows the modification of the workflow that the engine will run
by looking in the registry the name passed in parameter.
:param workflow_name: name of the workflow.
:type w... | Configure the workflow to run by the name of this one.
Allows the modification of the workflow that the engine will run
by looking in the registry the name passed in parameter.
:param workflow_name: name of the workflow.
:type workflow_name: str |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.