code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def get(self, sid):
"""
Constructs a CallContext
:param sid: The unique string that identifies this resource
:returns: twilio.rest.api.v2010.account.call.CallContext
:rtype: twilio.rest.api.v2010.account.call.CallContext
"""
return CallContext(self._version, acc... | Constructs a CallContext
:param sid: The unique string that identifies this resource
:returns: twilio.rest.api.v2010.account.call.CallContext
:rtype: twilio.rest.api.v2010.account.call.CallContext |
def get_public_dsn(self, scheme=None):
"""
Returns a public DSN which is consumable by raven-js
>>> # Return scheme-less DSN
>>> print client.get_public_dsn()
>>> # Specify a scheme to use (http or https)
>>> print client.get_public_dsn('https')
"""
if s... | Returns a public DSN which is consumable by raven-js
>>> # Return scheme-less DSN
>>> print client.get_public_dsn()
>>> # Specify a scheme to use (http or https)
>>> print client.get_public_dsn('https') |
def triangle_area(p0, p1, p2):
if p2.ndim < 2:
p2 = p2[np.newaxis, :]
'''p2 can be a vector'''
area = 0.5 * np.abs(p0[0] * p1[1] - p0[0] * p2[:,1] +
p1[0] * p2[:,1] - p1[0] * p0[1] +
p2[:,0] * p0[1] - p2[:,0] * p1[1])
return area | p2 can be a vector |
def read_data(self, offsets):
# type: (Descriptor, Offsets) -> Tuple[bytes, Offsets]
"""Read data from file
:param Descriptor self: this
:param Offsets offsets: offsets
:rtype: tuple
:return: (file data bytes, new Offsets if stdin)
"""
newoffset = None
... | Read data from file
:param Descriptor self: this
:param Offsets offsets: offsets
:rtype: tuple
:return: (file data bytes, new Offsets if stdin) |
def create_pgroup_snapshot(self, source, **kwargs):
"""Create snapshot of pgroup from specified source.
:param source: Name of pgroup of which to take snapshot.
:type source: str
:param \*\*kwargs: See the REST API Guide on your array for the
documentation on ... | Create snapshot of pgroup from specified source.
:param source: Name of pgroup of which to take snapshot.
:type source: str
:param \*\*kwargs: See the REST API Guide on your array for the
documentation on the request:
**POST pgroup**
... |
def email(self, email):
""" Set email and generate confirmation """
if email == self.email:
return
email = email.lower()
if self._email is None:
self._email = email
self.require_email_confirmation()
else:
self.email_new = email
... | Set email and generate confirmation |
def has_edge_citation(self, u: BaseEntity, v: BaseEntity, key: str) -> bool:
"""Check if the given edge has a citation."""
return self._has_edge_attr(u, v, key, CITATION) | Check if the given edge has a citation. |
def links(self):
"""
returns {attr1: href, attr2: href2}
"""
dlinks = {}
for key, value in self.__dict__.items():
if isinstance(value, dict) and value['link']:
dlinks[key] = value['link']
return dlinks | returns {attr1: href, attr2: href2} |
def impute(self, M_c, X_L, X_D, Y, Q, seed, n):
"""Impute values from predictive distribution of the given latent state.
:param Y: A list of constraints to apply when sampling. Each constraint
is a triplet of (r,d,v): r is the row index, d is the column
index and v is the value... | Impute values from predictive distribution of the given latent state.
:param Y: A list of constraints to apply when sampling. Each constraint
is a triplet of (r,d,v): r is the row index, d is the column
index and v is the value of the constraint
:type Y: list of lists
:... |
def remove(self, vehID, reason=tc.REMOVE_VAPORIZED):
'''Remove vehicle with the given ID for the give reason.
Reasons are defined in module constants and start with REMOVE_'''
self._connection._sendByteCmd(
tc.CMD_SET_VEHICLE_VARIABLE, tc.REMOVE, vehID, reason) | Remove vehicle with the given ID for the give reason.
Reasons are defined in module constants and start with REMOVE_ |
def surface_deriv(self, param):
"""Return the surface derivative at ``param``.
This is a constant function evaluating to `axis` everywhere.
Parameters
----------
param : float or `array-like`
Parameter value(s) at which to evaluate.
Returns
-------
... | Return the surface derivative at ``param``.
This is a constant function evaluating to `axis` everywhere.
Parameters
----------
param : float or `array-like`
Parameter value(s) at which to evaluate.
Returns
-------
deriv : `numpy.ndarray`
... |
def transform_multidim_to_1d_ref(aref, dimension_dict):
"""
Transform ast of multidimensional reference to a single dimension reference.
In-place operation!
"""
dims = []
name = aref
while type(name) is c_ast.ArrayRef:
dims.append(name.subscript)
name = name.name
subscr... | Transform ast of multidimensional reference to a single dimension reference.
In-place operation! |
def btc_make_p2sh_address( script_hex ):
"""
Make a P2SH address from a hex script
"""
h = hashing.bin_hash160(binascii.unhexlify(script_hex))
addr = bin_hash160_to_address(h, version_byte=multisig_version_byte)
return addr | Make a P2SH address from a hex script |
def mel(sr, n_dft, n_mels=128, fmin=0.0, fmax=None, htk=False, norm=1):
"""[np] create a filterbank matrix to combine stft bins into mel-frequency bins
use Slaney (said Librosa)
n_mels: numbre of mel bands
fmin : lowest frequency [Hz]
fmax : highest frequency [Hz]
If `None`, use `sr / 2.0`
... | [np] create a filterbank matrix to combine stft bins into mel-frequency bins
use Slaney (said Librosa)
n_mels: numbre of mel bands
fmin : lowest frequency [Hz]
fmax : highest frequency [Hz]
If `None`, use `sr / 2.0` |
def load(obj, env=None, silent=None, key=None):
"""Reads and loads in to "settings" a single key or all keys from vault
:param obj: the settings instance
:param env: settings env default='DYNACONF'
:param silent: if errors should raise
:param key: if defined load a single key, else load all in env
... | Reads and loads in to "settings" a single key or all keys from vault
:param obj: the settings instance
:param env: settings env default='DYNACONF'
:param silent: if errors should raise
:param key: if defined load a single key, else load all in env
:return: None |
def to_offset(freq):
"""
Return DateOffset object from string or tuple representation
or datetime.timedelta object
Parameters
----------
freq : str, tuple, datetime.timedelta, DateOffset or None
Returns
-------
DateOffset
None if freq is None.
Raises
------
Val... | Return DateOffset object from string or tuple representation
or datetime.timedelta object
Parameters
----------
freq : str, tuple, datetime.timedelta, DateOffset or None
Returns
-------
DateOffset
None if freq is None.
Raises
------
ValueError
If freq is an inv... |
def items(self, match="*", count=1000):
""" :see::meth:RedisMap.items """
for field, value in self._client.hscan_iter(
self.key_prefix, match=match, count=count):
yield self._decode(field), self._loads(value) | :see::meth:RedisMap.items |
def execute(self, env, args):
""" Removes a task.
`env`
Runtime ``Environment`` instance.
`args`
Arguments object from arg parser.
"""
# extract args
task_name = args.task_name
force = args.force
if env.task.a... | Removes a task.
`env`
Runtime ``Environment`` instance.
`args`
Arguments object from arg parser. |
def _reset_lazymodule(module, cls_attrs):
"""Resets a module's lazy state from cached data.
"""
modclass = type(module)
del modclass.__getattribute__
del modclass.__setattr__
try:
del modclass._LOADING
except AttributeError:
pass
for cls_attr in _CLS_ATTRS:
try:
... | Resets a module's lazy state from cached data. |
def repeat(coro, times=1, step=1, limit=1, loop=None):
"""
Executes the coroutine function ``x`` number of times,
and accumulates results in order as you would use with ``map``.
Execution concurrency is configurable using ``limit`` param.
This function is a coroutine.
Arguments:
coro... | Executes the coroutine function ``x`` number of times,
and accumulates results in order as you would use with ``map``.
Execution concurrency is configurable using ``limit`` param.
This function is a coroutine.
Arguments:
coro (coroutinefunction): coroutine function to schedule.
times... |
def create_figure(width=20, height=10):
"""Create a figure instance.
:params width: figure width
:params height: figure height
"""
figure = plt.figure(figsize=(width, height))
axis = figure.add_subplot(1, 1, 1)
return figure, axis | Create a figure instance.
:params width: figure width
:params height: figure height |
def extract(self, table: dict) -> List[Extraction]:
"""
:param table: a table extracted by table extractor, as a json object
:return: list of all extractions from the input table
"""
if table['features']['max_cols_in_a_row'] != 2 and table['features']['no_of_rows'] < 2:
... | :param table: a table extracted by table extractor, as a json object
:return: list of all extractions from the input table |
def extra_hosts(self, value):
"""
:param value:
:return None:
"""
if value is None:
self._extra_hosts = value
elif isinstance(value, list):
# TODO: better validation
self._extra_hosts = value
elif isinstance(value, dict):
... | :param value:
:return None: |
def seedRandom(self, seed):
"""
C_SeedRandom
:param seed: seed material
:type seed: iterable
"""
low_seed = ckbytelist(seed)
rv = self.lib.C_SeedRandom(self.session, low_seed)
if rv != CKR_OK:
raise PyKCS11Error(rv) | C_SeedRandom
:param seed: seed material
:type seed: iterable |
def check_dataset_format(ds_format):
"""
Ensure dataset format is XML or CSV
:param str ds_format: Format of the Dataset (expected to be one of `csv` or `xml`)
"""
if ds_format.lower() not in DATASET_FORMATS.keys():
raise ValueError(
"dataset_format is expected to be one of %s. ... | Ensure dataset format is XML or CSV
:param str ds_format: Format of the Dataset (expected to be one of `csv` or `xml`) |
def get(self, item):
"""Helper method to avoid calling getattr
"""
if item in self: # noqa
item = getattr(self, item)
return item() | Helper method to avoid calling getattr |
def _add(self):
"""
Add function logic, override to implement different logic
returns add widget or None
"""
is_valid_form = True
get_filter_args(self._filters)
exclude_cols = self._filters.get_relation_cols()
form = self.add_form.refresh()
... | Add function logic, override to implement different logic
returns add widget or None |
def did_parse(did):
"""
Parse a DID into it's parts.
:param did: Asset did, str.
:return: Python dictionary with the method and the id.
"""
if not isinstance(did, str):
raise TypeError(f'Expecting DID of string type, got {did} of {type(did)} type')
match = re.match('^did:([a-z0-9]+... | Parse a DID into it's parts.
:param did: Asset did, str.
:return: Python dictionary with the method and the id. |
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=con... | .. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of ... |
def norm(value, dims, order=None):
"""Compute the norm of the given (possibly batched) value.
Args:
value: A `Tensor` of real dtype.
dims: An Python integer with the number of non-batching dimensions in the
value, i.e. `dims=0` (scalars), `dims=1` (vectors), `dims=2` (matrices).
order: Order of t... | Compute the norm of the given (possibly batched) value.
Args:
value: A `Tensor` of real dtype.
dims: An Python integer with the number of non-batching dimensions in the
value, i.e. `dims=0` (scalars), `dims=1` (vectors), `dims=2` (matrices).
order: Order of the norm, defaults to `np.inf`. |
def register_logging_factories(loader):
"""
Registers default factories for logging standard package.
:param loader: Loader where you want register default logging factories
"""
loader.register_factory(logging.Logger, LoggerFactory)
loader.register_factory(logging.Handler, LoggingHandlerFactory... | Registers default factories for logging standard package.
:param loader: Loader where you want register default logging factories |
def op(name,
data,
display_name=None,
description=None,
collections=None):
"""Create a legacy scalar summary op.
Arguments:
name: A unique name for the generated summary node.
data: A real numeric rank-0 `Tensor`. Must have `dtype` castable
to `float32`.
display_name: ... | Create a legacy scalar summary op.
Arguments:
name: A unique name for the generated summary node.
data: A real numeric rank-0 `Tensor`. Must have `dtype` castable
to `float32`.
display_name: Optional name for this summary in TensorBoard, as a
constant `str`. Defaults to `name`.
descriptio... |
def _connect_nntp (self, nntpserver):
"""
This is done only once per checking task. Also, the newly
introduced error codes 504 and 505 (both inclining "Too busy, retry
later", are caught.
"""
tries = 0
nntp = None
while tries < 2:
tries += 1
... | This is done only once per checking task. Also, the newly
introduced error codes 504 and 505 (both inclining "Too busy, retry
later", are caught. |
async def dnsbl_request(self, addr, provider):
"""
Make lookup to dnsbl provider
Parameters:
* addr (string) - ip address to check
* provider (string) - dnsbl provider
Returns:
* DNSBLResponse object
Raises:
* ValueError
"... | Make lookup to dnsbl provider
Parameters:
* addr (string) - ip address to check
* provider (string) - dnsbl provider
Returns:
* DNSBLResponse object
Raises:
* ValueError |
def _get_request(self, request_url, request_method, **params):
"""
Return a Request object that has the GET parameters
attached to the url or the POST data attached to the object.
"""
if request_method == 'GET':
if params:
request_url += '&%s' % urlenc... | Return a Request object that has the GET parameters
attached to the url or the POST data attached to the object. |
def index(self, val, start=None, stop=None):
"""
Return the smallest *k* such that L[k] == val and i <= k < j`. Raises
ValueError if *val* is not present. *stop* defaults to the end of the
list. *start* defaults to the beginning. Negative indices are supported,
as for slice ind... | Return the smallest *k* such that L[k] == val and i <= k < j`. Raises
ValueError if *val* is not present. *stop* defaults to the end of the
list. *start* defaults to the beginning. Negative indices are supported,
as for slice indices. |
def draw(args):
"""
%prog draw --input newicktrees [options]
Draw phylogenetic trees into single or combined plots.
Input trees should be one of the following:
1. single Newick format tree file
2. a dir containing *ONLY* the tree files to be drawn
Newick format:
http://evolution.gene... | %prog draw --input newicktrees [options]
Draw phylogenetic trees into single or combined plots.
Input trees should be one of the following:
1. single Newick format tree file
2. a dir containing *ONLY* the tree files to be drawn
Newick format:
http://evolution.genetics.washington.edu/phylip/n... |
def write(self, data):
"""
Write the given data to the file.
"""
# Do the write
self.backingStream.write(data)
for listener in self.writeListeners:
# Send out notifications
listener(len(data)) | Write the given data to the file. |
def option_registrations_iter(self):
"""Returns an iterator over the normalized registration arguments of each option in this parser.
Useful for generating help and other documentation.
Each yielded item is an (args, kwargs) pair, as passed to register(), except that kwargs
will be normalized in the f... | Returns an iterator over the normalized registration arguments of each option in this parser.
Useful for generating help and other documentation.
Each yielded item is an (args, kwargs) pair, as passed to register(), except that kwargs
will be normalized in the following ways:
- It will always have '... |
def get_authenticated_user(self, callback):
"""Fetches the authenticated user data upon redirect."""
# Look to see if we are doing combined OpenID/OAuth
oauth_ns = ""
for name, values in self.request.arguments.iteritems():
if name.startswith("openid.ns.") and \
... | Fetches the authenticated user data upon redirect. |
def elementwise_cdf(self, p):
r"""Convert a sample to random variates uniform on :math:`[0, 1]`.
For a univariate distribution, this is simply evaluating the CDF. To
facilitate efficient sampling, this function returns a *vector* of CDF
values, one value for each variable. Basic... | r"""Convert a sample to random variates uniform on :math:`[0, 1]`.
For a univariate distribution, this is simply evaluating the CDF. To
facilitate efficient sampling, this function returns a *vector* of CDF
values, one value for each variable. Basically, the idea is that, given
... |
def delete_group_entitlement(self, group_id, rule_option=None, remove_group_membership=None):
"""DeleteGroupEntitlement.
[Preview API] Delete a group entitlement.
:param str group_id: ID of the group to delete.
:param str rule_option: RuleOption [ApplyGroupRule/TestApplyGroupRule] - spec... | DeleteGroupEntitlement.
[Preview API] Delete a group entitlement.
:param str group_id: ID of the group to delete.
:param str rule_option: RuleOption [ApplyGroupRule/TestApplyGroupRule] - specifies if the rules defined in group entitlement should be deleted and the changes are applied to it’s mem... |
def nav_filter_bias_send(self, usec, accel_0, accel_1, accel_2, gyro_0, gyro_1, gyro_2, force_mavlink1=False):
'''
Accelerometer and Gyro biases from the navigation filter
usec : Timestamp (microseconds) (uint64_t)
accel_0 ... | Accelerometer and Gyro biases from the navigation filter
usec : Timestamp (microseconds) (uint64_t)
accel_0 : b_f[0] (float)
accel_1 : b_f[1] (float)
accel_2 : b_f[2] (float)
... |
def derive(self, input):
'''
Compute the Brzozowski derivative of this FSM with respect to the input
string of symbols. <https://en.wikipedia.org/wiki/Brzozowski_derivative>
If any of the symbols are not members of the alphabet, that's a KeyError.
If you fall into oblivion, then the derivative is an FSM a... | Compute the Brzozowski derivative of this FSM with respect to the input
string of symbols. <https://en.wikipedia.org/wiki/Brzozowski_derivative>
If any of the symbols are not members of the alphabet, that's a KeyError.
If you fall into oblivion, then the derivative is an FSM accepting no
strings. |
def MakeNewConfig(self):
"""Creates a new configuration option based on this one.
Note that it is not normally possible to just instantiate the
config object because it will have an empty set of type
descriptors (i.e. no config options will be defined). Config
options are normally defined at import... | Creates a new configuration option based on this one.
Note that it is not normally possible to just instantiate the
config object because it will have an empty set of type
descriptors (i.e. no config options will be defined). Config
options are normally defined at import time, and then they get
add... |
def kms_decrypt_value(self, lookup):
"""
Args:
lookup: the encrypted value to be decrypted by KMS; base64 encoded
Returns:
The decrypted lookup value
"""
decrypted_lookup = ef_utils.kms_decrypt(EFAwsResolver.__CLIENTS["kms"], lookup)
return decrypted_lookup | Args:
lookup: the encrypted value to be decrypted by KMS; base64 encoded
Returns:
The decrypted lookup value |
def do_min(environment, value, case_sensitive=False, attribute=None):
"""Return the smallest item from the sequence.
.. sourcecode:: jinja
{{ [1, 2, 3]|min }}
-> 1
:param case_sensitive: Treat upper and lower case strings as distinct.
:param attribute: Get the object with the max ... | Return the smallest item from the sequence.
.. sourcecode:: jinja
{{ [1, 2, 3]|min }}
-> 1
:param case_sensitive: Treat upper and lower case strings as distinct.
:param attribute: Get the object with the max value of this attribute. |
def list(cls, rc_file='~/.odoorpcrc'):
"""Return a list of all stored sessions available in the
`rc_file` file:
.. doctest::
:options: +SKIP
>>> import odoorpc
>>> odoorpc.ODOO.list()
['foo', 'bar']
Use the :func:`save <odoorpc.ODOO.save... | Return a list of all stored sessions available in the
`rc_file` file:
.. doctest::
:options: +SKIP
>>> import odoorpc
>>> odoorpc.ODOO.list()
['foo', 'bar']
Use the :func:`save <odoorpc.ODOO.save>` and
:func:`load <odoorpc.ODOO.load>` me... |
def parse_kwargs(kwargs):
"""
Convert a list of kwargs into a dictionary. Duplicates of the same keyword
get added to an list within the dictionary.
>>> parse_kwargs(['--var1=1', '--var2=2', '--var1=3']
{'var1': [1, 3], 'var2': 2}
"""
d = defaultdict(list)
for k, v in ((k.lstrip('-... | Convert a list of kwargs into a dictionary. Duplicates of the same keyword
get added to an list within the dictionary.
>>> parse_kwargs(['--var1=1', '--var2=2', '--var1=3']
{'var1': [1, 3], 'var2': 2} |
def iter_endpoints(graph, match_func):
"""
Iterate through matching endpoints.
The `match_func` is expected to have a signature of:
def matches(operation, ns, rule):
return True
:returns: a generator over (`Operation`, `Namespace`, rule, func) tuples.
"""
for rule in grap... | Iterate through matching endpoints.
The `match_func` is expected to have a signature of:
def matches(operation, ns, rule):
return True
:returns: a generator over (`Operation`, `Namespace`, rule, func) tuples. |
def get_fast_scanner(self):
r"""Return :class:`glimix_core.lmm.FastScanner` for the current
delta."""
from numpy_sugar.linalg import ddot, economic_qs, sum2diag
y = self.eta / self.tau
if self._QS is None:
K = eye(y.shape[0]) / self.tau
else:
Q0 ... | r"""Return :class:`glimix_core.lmm.FastScanner` for the current
delta. |
def _change_logging_kwargs(kwargs):
""" Helper function to turn the simple logging kwargs into a `log_config`."""
log_levels = kwargs.pop('log_level', None)
log_folder = kwargs.pop('log_folder', 'logs')
logger_names = kwargs.pop('logger_names', '')
if log_levels is None:
log_levels = kwargs.... | Helper function to turn the simple logging kwargs into a `log_config`. |
def read(self):
"""Return a single byte from the output buffer
"""
if self._output_buffer:
b, self._output_buffer = (self._output_buffer[0:1],
self._output_buffer[1:])
return b
return b'' | Return a single byte from the output buffer |
def _write_named_sockets(self, socket_map):
"""Write multiple named sockets using a socket mapping."""
for socket_name, socket_info in socket_map.items():
self.write_named_socket(socket_name, socket_info) | Write multiple named sockets using a socket mapping. |
def add_state_view_for_model(self, state_m, parent_v=None, rel_pos=(0, 0), size=(100, 100), hierarchy_level=1):
"""Creates a `StateView` (recursively) and adds it to the canvas
The method uses the `StateModel` `state_m` to create the according `StateView`. For all content within
`state_m`, suc... | Creates a `StateView` (recursively) and adds it to the canvas
The method uses the `StateModel` `state_m` to create the according `StateView`. For all content within
`state_m`, such as connections, states and ports, the views are also created. All views are added to the canvas.
:param rafcon.g... |
def cancel(
self,
identifier: typing.Any,
exc_type: typing.Optional[type]=None,
) -> bool:
"""Cancel an active coroutine and remove it from the schedule.
Args:
identifier (typing.Any): The identifier returned from add.
exc_type (typing.Opt... | Cancel an active coroutine and remove it from the schedule.
Args:
identifier (typing.Any): The identifier returned from add.
exc_type (typing.Optional[type]): The exception type to throw into
the coroutine on cancel. No exception is thrown if nothing is
g... |
def from_config(config_file, use_admin=False):
"""
Initialize a QueryEngine from a JSON config file generated using mgdb
init.
Args:
config_file:
Filename of config file.
use_admin:
If True, the admin user and password in the confi... | Initialize a QueryEngine from a JSON config file generated using mgdb
init.
Args:
config_file:
Filename of config file.
use_admin:
If True, the admin user and password in the config file is
used. Otherwise, the readonly_user and pa... |
def _initialize_archive(self):
"""Initialize archive based on the parsed parameters"""
if 'archive_path' not in self.parsed_args:
manager = None
elif self.parsed_args.no_archive:
manager = None
else:
if not self.parsed_args.archive_path:
... | Initialize archive based on the parsed parameters |
def autoencoder_discrete_cifar():
"""Discrete autoencoder model for compressing cifar."""
hparams = autoencoder_ordered_discrete()
hparams.bottleneck_noise = 0.0
hparams.bottleneck_bits = 90
hparams.num_hidden_layers = 2
hparams.hidden_size = 256
hparams.num_residual_layers = 4
hparams.batch_size = 32
... | Discrete autoencoder model for compressing cifar. |
def post(self, request, hook_id):
"""
Process Kik webhook:
1. Get an enabled Kik bot
2. Verify Kik signature
3. Serialize each message
4. For each message create :class:`KikMessage <permabots.models.kik_api.KikMessage>` and :class:`KikUser <permabots.model... | Process Kik webhook:
1. Get an enabled Kik bot
2. Verify Kik signature
3. Serialize each message
4. For each message create :class:`KikMessage <permabots.models.kik_api.KikMessage>` and :class:`KikUser <permabots.models.kik_api.KikUser>`
5. Delay each message ... |
def subdomain(self, hostname):
"""
Determine of which known domain the given hostname is a subdomain.
@return: A two-tuple giving the subdomain part and the domain part or
C{None} if the domain is not a subdomain of any known domain.
"""
hostname = hostname.split(":"... | Determine of which known domain the given hostname is a subdomain.
@return: A two-tuple giving the subdomain part and the domain part or
C{None} if the domain is not a subdomain of any known domain. |
def handle(client_message, handle_event_entry=None, to_object=None):
""" Event handler """
message_type = client_message.get_message_type()
if message_type == EVENT_ENTRY and handle_event_entry is not None:
key = None
if not client_message.read_bool():
key = client_message.read_d... | Event handler |
def hybrid_forward(self, F, inputs, mask=None): # pylint: disable=arguments-differ
# pylint: disable=unused-argument
"""Transformer Encoder Attention Cell.
Parameters
----------
inputs : Symbol or NDArray
Input sequence. Shape (batch_size, length, C_in)
mask... | Transformer Encoder Attention Cell.
Parameters
----------
inputs : Symbol or NDArray
Input sequence. Shape (batch_size, length, C_in)
mask : Symbol or NDArray or None
Mask for inputs. Shape (batch_size, length, length)
Returns
-------
enc... |
def tasks(self, path, postmap=None, **params):
"""
Return the task status. This delves into the operating structures
and picks out information about tasks that is useful for status
monitoring.
For each task, the response includes:
control - The active task control ... | Return the task status. This delves into the operating structures
and picks out information about tasks that is useful for status
monitoring.
For each task, the response includes:
control - The active task control value, whoich may have been
changed via the manag... |
def copy(string, cmd=copy_cmd, stdin=PIPE):
"""Copy given string into system clipboard.
"""
Popen(cmd, stdin=stdin).communicate(string.encode('utf-8')) | Copy given string into system clipboard. |
def default_view_method(pid, record, template=None):
"""Default view method.
Sends ``record_viewed`` signal and renders template.
"""
record_viewed.send(
current_app._get_current_object(),
pid=pid,
record=record,
)
deposit_type = request.values.get('type')
return r... | Default view method.
Sends ``record_viewed`` signal and renders template. |
def load_related_model(self, name, load_only=None, dont_load=None):
'''Load a the :class:`ForeignKey` field ``name`` if this is part of the
fields of this model and if the related object is not already loaded.
It is used by the lazy loading mechanism of :ref:`one-to-many <one-to-many>`
relationships.
:paramete... | Load a the :class:`ForeignKey` field ``name`` if this is part of the
fields of this model and if the related object is not already loaded.
It is used by the lazy loading mechanism of :ref:`one-to-many <one-to-many>`
relationships.
:parameter name: the :attr:`Field.name` of the :class:`ForeignKey` to load.
:parameter l... |
def window(self, window):
"""
This method does the following:
1. Switches to the given window (it can be located by window instance/lambda/string).
2. Executes the given block (within window located at previous step).
3. Switches back (this step will be invoked even if exception... | This method does the following:
1. Switches to the given window (it can be located by window instance/lambda/string).
2. Executes the given block (within window located at previous step).
3. Switches back (this step will be invoked even if exception happens at second step).
Args:
... |
def get_serializer_class(self):
"""gets the class type of the serializer
:return: `rest_framework.Serializer`
"""
klass = None
lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field
if lookup_url_kwarg in self.kwargs:
# Looks like this is a detail...
... | gets the class type of the serializer
:return: `rest_framework.Serializer` |
def _to_enos_networks(networks):
"""Transform the networks returned by deploy5k.
Args:
networks (dict): networks returned by
:py:func:`enoslib.infra.provider.Provider.init`
"""
nets = []
for roles, network in networks:
nets.append(network.to_enos(roles))
logger.debug... | Transform the networks returned by deploy5k.
Args:
networks (dict): networks returned by
:py:func:`enoslib.infra.provider.Provider.init` |
def get_sky_coords(self):
""" Get the sky coordinates of all the pixels in this pixelization """
if self._ipix is None:
theta, phi = hp.pix2ang(
self._nside, list(range(self._npix)), self._nest)
else:
theta, phi = hp.pix2ang(self._nside, self._ipix, self._... | Get the sky coordinates of all the pixels in this pixelization |
def create(cls, name, enabled=True, superuser=True):
"""
Create a new API Client. Once client is created,
you can create a new password by::
>>> client = ApiClient.create('myclient')
>>> print(client)
ApiClient(name=myclient)
>>> client.change_pas... | Create a new API Client. Once client is created,
you can create a new password by::
>>> client = ApiClient.create('myclient')
>>> print(client)
ApiClient(name=myclient)
>>> client.change_password('mynewpassword')
:param str name: name of client
:... |
def get_shark_field(self, fields):
"""get parameters via wireshark syntax.
out = x.get_shark_field('wlan.fc.type')
out = x.get_shark_field(['wlan.fc.type', 'wlan.seq'])
:fields: str or str[]
:return: dict
out[fields[0]] = val[0] or None
out[fields[1]] = va... | get parameters via wireshark syntax.
out = x.get_shark_field('wlan.fc.type')
out = x.get_shark_field(['wlan.fc.type', 'wlan.seq'])
:fields: str or str[]
:return: dict
out[fields[0]] = val[0] or None
out[fields[1]] = val[1] or None ... |
def prepare_request(settings):
""" Prepare SAML request """
# Set the ACS url and binding method
settings["sp"]["assertionConsumerService"] = {
"url": web.ctx.homedomain + web.ctx.homepath + "/auth/callback/" + settings["id"],
"binding": "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"
... | Prepare SAML request |
def slicer(self):
"""
Array slicer object for this tile
>>> Tile((2,3)).slicer
(slice(0, 2, None), slice(0, 3, None))
>>> np.arange(10)[Tile((4,)).slicer]
array([0, 1, 2, 3])
"""
return tuple(np.s_[l:r] for l,r in zip(*self.bounds)) | Array slicer object for this tile
>>> Tile((2,3)).slicer
(slice(0, 2, None), slice(0, 3, None))
>>> np.arange(10)[Tile((4,)).slicer]
array([0, 1, 2, 3]) |
def tasks(self):
"""
Returns a list of all tasks known to the engine.
:return: A list of task names.
"""
task_input = {'taskName': 'QueryTaskCatalog'}
output = taskengine.execute(task_input, self._engine_name, cwd=self._cwd)
return output['outputParameters']['TAS... | Returns a list of all tasks known to the engine.
:return: A list of task names. |
def requestExec(self, commandLine):
"""Request execution of :commandLine: and return a deferred reply.
"""
data = common.NS(commandLine)
return self.sendRequest('exec', data, wantReply=True) | Request execution of :commandLine: and return a deferred reply. |
def save_config(
self,
cmd="copy running-configuration startup-configuration",
confirm=False,
confirm_response="",
):
"""Saves Config"""
return super(DellDNOS6Base, self).save_config(
cmd=cmd, confirm=confirm, confirm_response=confirm_response
) | Saves Config |
def matchRecordAttrs(mapobj, attrs):
"""attempt to match given attributes against a single map object's attributes"""
for k,v in iteritems(attrs):
try: val = getattr(mapobj, k)
except AttributeError: # k isn't an attr of record
if bool(v): return False # if k doesn't exist i... | attempt to match given attributes against a single map object's attributes |
def adjust(self, to):
'''
Adjusts the time from kwargs to timedelta
**Will change this object**
return new copy of self
'''
if self.date == 'infinity':
return
new = copy(self)
if type(to) in (str, unicode):
to = to.lower()
... | Adjusts the time from kwargs to timedelta
**Will change this object**
return new copy of self |
def _expectation(p, kern, none1, none2, none3, nghp=None):
r"""
Compute the expectation:
<\HadamardProd_i diag(Ki_{X[:, active_dims_i], X[:, active_dims_i]})>_p(X)
- \HadamardProd_i Ki_{.,.} :: Product kernel
- p :: DiagonalGaussian distribution (p.cov NxD)
:retur... | r"""
Compute the expectation:
<\HadamardProd_i diag(Ki_{X[:, active_dims_i], X[:, active_dims_i]})>_p(X)
- \HadamardProd_i Ki_{.,.} :: Product kernel
- p :: DiagonalGaussian distribution (p.cov NxD)
:return: N |
def bins_range(self, axis=0, overflow=False):
"""
Return a range of bin indices for iterating along an axis
Parameters
----------
axis : int, optional (default=1)
The axis (0, 1 or 2).
overflow : bool, optional (default=False)
If True then inclu... | Return a range of bin indices for iterating along an axis
Parameters
----------
axis : int, optional (default=1)
The axis (0, 1 or 2).
overflow : bool, optional (default=False)
If True then include the underflow and overflow bins
otherwise only incl... |
def _ConvertRowToUnicode(self, parser_mediator, row):
"""Converts all strings in a DSV row dict to Unicode.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
row (dict[str, bytes]): a row from a DSV file, where t... | Converts all strings in a DSV row dict to Unicode.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
row (dict[str, bytes]): a row from a DSV file, where the dictionary
key contains the column name and the ... |
def get_parameter_diff(awsclient, config):
"""get differences between local config and currently active config
"""
client_cf = awsclient.get_client('cloudformation')
try:
stack_name = config['stack']['StackName']
if stack_name:
response = client_cf.describe_stacks(StackName=s... | get differences between local config and currently active config |
def __getJoinerState(self):
""" get joiner state """
maxDuration = 150 # seconds
t_end = time.time() + maxDuration
while time.time() < t_end:
joinerState = self.__stripValue(self.__sendCommand('sudo wpanctl getprop -v NCP:State')[0])
if joinerState == 'offline:co... | get joiner state |
def toxml(self):
"""
Exports this object into a LEMS XML object
"""
return '<With ' + \
(' instance="{0}"'.format(self.instance) if self.instance else '') +\
(' list="{0}"'.format(self.list) if self.list else '') + \
(' index="{0}"'.format(self.index) if se... | Exports this object into a LEMS XML object |
def _print_command(self, cmd):
"""Wrapper to avoid adding unnecessary blank lines."""
text = helpers.repr_bytes(cmd)
self.outf.write(text)
if not text.endswith(b'\n'):
self.outf.write(b'\n') | Wrapper to avoid adding unnecessary blank lines. |
def get_sleepstage(self, stage_idx=None):
"""Score the sleep stage, using shortcuts or combobox."""
if self.annot is None: # remove if buttons are disabled
error_dialog = QErrorMessage()
error_dialog.setWindowTitle('Error getting sleep stage')
error_dialog.showMessag... | Score the sleep stage, using shortcuts or combobox. |
def unmasked_sparse_to_sparse_from_mask_and_pixel_centres(mask, unmasked_sparse_grid_pixel_centres,
total_sparse_pixels):
"""Determine the mapping between every pixelization-grid pixel and masked pixelization-grid pixel. This is
performed by checking whe... | Determine the mapping between every pixelization-grid pixel and masked pixelization-grid pixel. This is
performed by checking whether each pixelization-grid pixel is within the regular-masks, and mapping the indexes.
Pixelization pixels are paired with the next masked pixel index. This may mean that a pixel is... |
def sort_dependencies(app_list):
"""Sort a list of (app_config, models) pairs into a single list of models.
The single list of models is sorted so that any model with a natural key
is serialized before a normal model, and any model with a natural key
dependency has it's dependencies serialized first.
... | Sort a list of (app_config, models) pairs into a single list of models.
The single list of models is sorted so that any model with a natural key
is serialized before a normal model, and any model with a natural key
dependency has it's dependencies serialized first. |
def add_vertex(self, v):
"""
Add a vertex to the graph. The vertex must implement __hash__ and __eq__ as it will be stored in a set.
:param v: vertex
:return: graph owned vertex
"""
if v not in self.adjacency:
self.adjacency[v] = Vertex(v)
return self.... | Add a vertex to the graph. The vertex must implement __hash__ and __eq__ as it will be stored in a set.
:param v: vertex
:return: graph owned vertex |
def render_template(self, template, **kwargs):
'''
Enforce the states in a template
'''
high = compile_template(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
... | Enforce the states in a template |
async def sync_recent_conversations(
self, sync_recent_conversations_request
):
"""Return info on recent conversations and their events."""
response = hangouts_pb2.SyncRecentConversationsResponse()
await self._pb_request('conversations/syncrecentconversations',
... | Return info on recent conversations and their events. |
def fromTerm(cls, term):
"""Create a functor from a Term or term handle."""
if isinstance(term, Term):
term = term.handle
elif not isinstance(term, (c_void_p, int)):
raise ArgumentTypeError((str(Term), str(int)), str(type(term)))
f = functor_t()
if PL_ge... | Create a functor from a Term or term handle. |
def read_task_from_index(task_family, index_file=None):
"""
Returns module id, task family and space-separated parameters in a tuple for a task given by
*task_family* from the *index_file*. When *None*, the *index_file* refers to the default as
defined in :py:mod:`law.config`. Returns *None* when the ta... | Returns module id, task family and space-separated parameters in a tuple for a task given by
*task_family* from the *index_file*. When *None*, the *index_file* refers to the default as
defined in :py:mod:`law.config`. Returns *None* when the task could not be found. |
def simulate(self, time,
feedforwardInputI,
feedforwardInputE,
v,
recurrent=True,
dt=None,
envelope=False,
inputNoise=None):
"""
:param time: Amount of time to simulate.
Divided into chunks of len... | :param time: Amount of time to simulate.
Divided into chunks of len dt.
:param feedforwardInputI: feedforward input to inhibitory cells. Must have
shape (numInhibitory,). Should be total input over period time.
:param feedforwardInputE: feedforward input to excitatory cells. Must have
... |
def addFailure(self, test: unittest.case.TestCase, exc_info: tuple) -> None:
"""
Transforms the test in a serializable version of it and sends it to a queue for further analysis
:param test: the test to save
:param exc_info: tuple of the form (Exception class, Exception instance, traceb... | Transforms the test in a serializable version of it and sends it to a queue for further analysis
:param test: the test to save
:param exc_info: tuple of the form (Exception class, Exception instance, traceback) |
def get_dev_asset_details(ipaddress, auth, url):
"""Takes in ipaddress as input to fetch device assett details from HP IMC RESTFUL API
:param ipaddress: IP address of the device you wish to gather the asset details
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:p... | Takes in ipaddress as input to fetch device assett details from HP IMC RESTFUL API
:param ipaddress: IP address of the device you wish to gather the asset details
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:param url: base url of IMC RS interface #usually auth.url... |
def group_associations_types(
self,
main_type,
sub_type,
unique_id,
target,
api_branch=None,
api_entity=None,
owner=None,
params=None,
):
"""
Args:
owner:
main_type:
... | Args:
owner:
main_type:
sub_type:
unique_id:
target:
api_branch:
api_entity:
params:
Return: |
def back_make(dev, cache_mode='writeback', force=False, attach=True, bucket_size=None):
'''
Create a backing device for attachment to a set.
Because the block size must be the same, a cache set already needs to exist.
CLI example:
.. code-block:: bash
salt '*' bcache.back_make sdc cache_m... | Create a backing device for attachment to a set.
Because the block size must be the same, a cache set already needs to exist.
CLI example:
.. code-block:: bash
salt '*' bcache.back_make sdc cache_mode=writeback attach=True
:param cache_mode: writethrough, writeback, writearound or none.
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.