code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def section(node):
"""
A section in reStructuredText, which needs a title (the first child)
This is a custom type
"""
title = '' # All sections need an id
if node.first_child is not None:
if node.first_child.t == u'heading':
title = node.first_child.first_child.literal
o... | A section in reStructuredText, which needs a title (the first child)
This is a custom type |
def data(self, column, role):
"""Return the data for the specified column and role
The column addresses one attribute of the data.
:param column: the data column
:type column: int
:param role: the data role
:type role: QtCore.Qt.ItemDataRole
:returns: data depen... | Return the data for the specified column and role
The column addresses one attribute of the data.
:param column: the data column
:type column: int
:param role: the data role
:type role: QtCore.Qt.ItemDataRole
:returns: data depending on the role
:rtype:
... |
def cookies(self, url):
"""
Return cookies that are matching the path and are still valid
:param url:
:return:
"""
part = urlparse(url)
#if part.port:
# _domain = "%s:%s" % (part.hostname, part.port)
#else:
_domain = part.hostname
... | Return cookies that are matching the path and are still valid
:param url:
:return: |
def get_or_create_stream(self, stream_id, try_create=True):
"""
Helper function to get a stream or create one if it's not already defined
:param stream_id: The stream id
:param try_create: Whether to try to create the stream if not found
:return: The stream object
"""
... | Helper function to get a stream or create one if it's not already defined
:param stream_id: The stream id
:param try_create: Whether to try to create the stream if not found
:return: The stream object |
def _fill_role_cache(self, principal, overwrite=False):
"""Fill role cache for `principal` (User or Group), in order to avoid
too many queries when checking role access with 'has_role'.
Return role_cache of `principal`
"""
if not self.app_state.use_cache:
return None... | Fill role cache for `principal` (User or Group), in order to avoid
too many queries when checking role access with 'has_role'.
Return role_cache of `principal` |
def authenticate_client_id(self, client_id, request, *args, **kwargs):
"""Authenticate a non-confidential client.
:param client_id: Client ID of the non-confidential client
:param request: The Request object passed by oauthlib
"""
if client_id is None:
client_id, _ =... | Authenticate a non-confidential client.
:param client_id: Client ID of the non-confidential client
:param request: The Request object passed by oauthlib |
def select_template_from_string(arg):
"""
Select a template from a string, which can include multiple
template paths separated by commas.
"""
if ',' in arg:
tpl = loader.select_template(
[tn.strip() for tn in arg.split(',')])
else:
tpl = loader.get_template(arg)
... | Select a template from a string, which can include multiple
template paths separated by commas. |
def unshare_me(self, keys=None, auto_update=False, draw=None,
update_other=True):
"""
Close the sharing connection of this plotter with others
This method undoes the sharing connections made by the :meth:`share`
method and release this plotter again.
Paramete... | Close the sharing connection of this plotter with others
This method undoes the sharing connections made by the :meth:`share`
method and release this plotter again.
Parameters
----------
keys: string or iterable of strings
The formatoptions to unshare, or group name... |
def load_plugins(self):
"""Load plugins from `dyndnsc.plugins.builtin`."""
from dyndnsc.plugins.builtin import PLUGINS
for plugin in PLUGINS:
self.add_plugin(plugin())
super(BuiltinPluginManager, self).load_plugins() | Load plugins from `dyndnsc.plugins.builtin`. |
def get_authenticated_user(self, callback):
"""Fetches the authenticated user data upon redirect.
This method should be called by the handler that receives the
redirect from the authenticate_redirect() or authorize_redirect()
methods.
"""
# Verify the OpenID response via... | Fetches the authenticated user data upon redirect.
This method should be called by the handler that receives the
redirect from the authenticate_redirect() or authorize_redirect()
methods. |
def visit_literal_block(self, node):
"""Check syntax of code block."""
# For "..code-block:: language"
language = node.get('language', None)
is_code_node = False
if not language:
# For "..code:: language"
is_code_node = True
classes = node.get(... | Check syntax of code block. |
def check_model_permission(self, app, model):
""" Checks if model is listed in apps_dict
Since apps_dict is derived from the app_list
given by django admin, it lists only the apps
and models the user can view
"""
if self.apps_dict.get(app, False) and model in ... | Checks if model is listed in apps_dict
Since apps_dict is derived from the app_list
given by django admin, it lists only the apps
and models the user can view |
def mergeAllLayers(self):
"""
Merge all the layers together.
:rtype: The result :py:class:`Layer` object.
"""
start = time.time()
while(len(self.layers)>1):
self.mergeBottomLayers()
print('merge time:'+str(time.time()-start))
return self.layers[0] | Merge all the layers together.
:rtype: The result :py:class:`Layer` object. |
def addObject(self, object, name=None):
"""
Adds an object to the Machine.
Objects should be PhysicalObjects.
"""
if name is None:
name = len(self.objects)
self.objects[name] = object | Adds an object to the Machine.
Objects should be PhysicalObjects. |
def eval_in_new(cls, expr, *args, **kwargs):
""":meth:`eval` an expression in a new, temporary :class:`Context`.
This should be safe to use directly on user input.
Args:
expr (LispVal): The expression to evaluate.
*args: Args for the :class:`Context` constructor.
... | :meth:`eval` an expression in a new, temporary :class:`Context`.
This should be safe to use directly on user input.
Args:
expr (LispVal): The expression to evaluate.
*args: Args for the :class:`Context` constructor.
**kwargs: Kwargs for the :class:`Context` construc... |
def _on_merge(self, other):
"""
After merging statements update IO, sensitivity and context
:attention: rank is not updated
"""
self._inputs.extend(other._inputs)
self._outputs.extend(other._outputs)
if self._sensitivity is not None:
self._sensitivit... | After merging statements update IO, sensitivity and context
:attention: rank is not updated |
def systematic_resample(weights):
""" Performs the systemic resampling algorithm used by particle filters.
This algorithm separates the sample space into N divisions. A single random
offset is used to to choose where to sample from for all divisions. This
guarantees that every sample is exactly 1/N apa... | Performs the systemic resampling algorithm used by particle filters.
This algorithm separates the sample space into N divisions. A single random
offset is used to to choose where to sample from for all divisions. This
guarantees that every sample is exactly 1/N apart.
Parameters
----------
wei... |
def mass_enclosed_3d(self, r, kwargs_profile):
"""
computes the mass enclosed within a sphere of radius r
:param r: radius (arcsec)
:param kwargs_profile: keyword argument list with lens model parameters
:return: 3d mass enclosed of r
"""
kwargs = copy.deepcopy(kw... | computes the mass enclosed within a sphere of radius r
:param r: radius (arcsec)
:param kwargs_profile: keyword argument list with lens model parameters
:return: 3d mass enclosed of r |
async def try_sending(self,msg,timeout_secs, max_attempts):
"""Coroutine used to send message to the device when a response or ack is needed.
This coroutine will try to send up to max_attempts time the message, waiting timeout_secs
for an answer. If no answer is received, it will consider that ... | Coroutine used to send message to the device when a response or ack is needed.
This coroutine will try to send up to max_attempts time the message, waiting timeout_secs
for an answer. If no answer is received, it will consider that the device is no longer
accessible and will unregister it.
... |
def case(*, to, **kwargs):
"""Converts an identifier from one case type to another.
An identifier is an ASCII string consisting of letters, digits and underscores, not starting with a digit.
The supported case types are camelCase, PascalCase, snake_case, and CONSTANT_CASE,
identified as camel, pascal, s... | Converts an identifier from one case type to another.
An identifier is an ASCII string consisting of letters, digits and underscores, not starting with a digit.
The supported case types are camelCase, PascalCase, snake_case, and CONSTANT_CASE,
identified as camel, pascal, snake, and constant.
The input ... |
def next_listing(self, limit=None):
"""GETs next :class:`Listing` directed to by this :class:`Listing`. Returns :class:`Listing` object.
:param limit: max number of entries to get
:raise UnsupportedError: raised when trying to load more comments
"""
if self.after:
... | GETs next :class:`Listing` directed to by this :class:`Listing`. Returns :class:`Listing` object.
:param limit: max number of entries to get
:raise UnsupportedError: raised when trying to load more comments |
def set_element(self, index, e):
r""" Replaces a pipeline stage.
Replace an element in chain and return replaced element.
"""
if index > len(self._chain):
raise IndexError("tried to access element %i, but chain has only %i"
" elements" % (index, ... | r""" Replaces a pipeline stage.
Replace an element in chain and return replaced element. |
def exec_args(args, in_data='', chdir=None, shell=None, emulate_tty=False):
"""
Run a command in a subprocess, emulating the argument handling behaviour of
SSH.
:param list[str]:
Argument vector.
:param bytes in_data:
Optional standard input for the command.
:param bool emulate_... | Run a command in a subprocess, emulating the argument handling behaviour of
SSH.
:param list[str]:
Argument vector.
:param bytes in_data:
Optional standard input for the command.
:param bool emulate_tty:
If :data:`True`, arrange for stdout and stderr to be merged into the
... |
def model_ids(self, protocol=None, groups=None):
"""Returns a list of model ids for the specific query by the user.
Models correspond to Clients for the XM2VTS database (At most one model per identity).
Keyword Parameters:
protocol
Ignored.
groups
The groups to which the subjects a... | Returns a list of model ids for the specific query by the user.
Models correspond to Clients for the XM2VTS database (At most one model per identity).
Keyword Parameters:
protocol
Ignored.
groups
The groups to which the subjects attached to the models belong ('dev', 'eval', 'world')
... |
def melt(expr, id_vars=None, value_vars=None, var_name='variable', value_name='value', ignore_nan=False):
"""
“Unpivots” a DataFrame from wide format to long format, optionally leaving identifier variables set.
This function is useful to massage a DataFrame into a format where one or more columns are ident... | “Unpivots” a DataFrame from wide format to long format, optionally leaving identifier variables set.
This function is useful to massage a DataFrame into a format where one or more columns are identifier
variables (id_vars), while all other columns, considered measured variables (value_vars), are “unpivoted”
... |
def _convert_agg_to_wx_image(agg, bbox):
"""
Convert the region of the agg buffer bounded by bbox to a wx.Image. If
bbox is None, the entire buffer is converted.
Note: agg must be a backend_agg.RendererAgg instance.
"""
if bbox is None:
# agg => rgb -> image
image = wx.EmptyIma... | Convert the region of the agg buffer bounded by bbox to a wx.Image. If
bbox is None, the entire buffer is converted.
Note: agg must be a backend_agg.RendererAgg instance. |
def one(self):
"""Return exactly one record or raise an exception.
:return:
- Dictionary containing the only item in the response content
:raise:
- MultipleResults: If more than one records are present in the content
- NoResults: If the result is empty
... | Return exactly one record or raise an exception.
:return:
- Dictionary containing the only item in the response content
:raise:
- MultipleResults: If more than one records are present in the content
- NoResults: If the result is empty |
def on_ok(self):
""" Add the repository """
def popup(thr, add_type, title):
"""
Start the thread and display a popup of the plugin being cloned
until the thread is finished
"""
thr.start()
tool_str = 'Cloning repository...'
... | Add the repository |
def quantiles(self, k=5):
"""Returns an ndarray of quantile breaks."""
arr = self.array()
q = list(np.linspace(0, 100, k))
return np.percentile(arr.compressed(), q) | Returns an ndarray of quantile breaks. |
def getattr(self, key):
""" This method gets the attribute value of external method object. """
if key in _MethodFactoryMeta[self.classId]:
""" property exists """
return self.__dict__[key]
else:
""" property does not exist """
return None | This method gets the attribute value of external method object. |
def cfn_viz(template, parameters={}, outputs={}, out=sys.stdout):
"""Render dot output for cloudformation.template in json format.
"""
known_sg, open_sg = _analyze_sg(template['Resources'])
(graph, edges) = _extract_graph(template.get('Description', ''),
template['Res... | Render dot output for cloudformation.template in json format. |
def users(store):
"""Display a list of all users and which institutes they belong to."""
user_objs = list(store.users())
total_events = store.user_events().count()
for user_obj in user_objs:
if user_obj.get('institutes'):
user_obj['institutes'] = [store.institute(inst_id) for inst_id... | Display a list of all users and which institutes they belong to. |
def _inner_join(left, right, left_key_fn, right_key_fn, join_fn=union_join):
""" Inner join using left and right key functions
:param left: left iterable to be joined
:param right: right iterable to be joined
:param function left_key_fn: function that produces hashable value from left objects
:para... | Inner join using left and right key functions
:param left: left iterable to be joined
:param right: right iterable to be joined
:param function left_key_fn: function that produces hashable value from left objects
:param function right_key_fn: function that produces hashable value from right objects
... |
def absent(name, force=False):
'''
Ensure that a container is absent
name
Name of the container
force : False
Set to ``True`` to remove the container even if it is running
Usage Examples:
.. code-block:: yaml
mycontainer:
docker_container.absent
mu... | Ensure that a container is absent
name
Name of the container
force : False
Set to ``True`` to remove the container even if it is running
Usage Examples:
.. code-block:: yaml
mycontainer:
docker_container.absent
multiple_containers:
docker_contain... |
def is_all_field_none(self):
"""
:rtype: bool
"""
if self._id_ is not None:
return False
if self._created is not None:
return False
if self._updated is not None:
return False
if self._name is not None:
return Fal... | :rtype: bool |
def fromSearch(text):
"""
Generates a regular expression from 'simple' search terms.
:param text | <str>
:usage |>>> import projex.regex
|>>> projex.regex.fromSearch('*cool*')
|'^.*cool.*$'
|>>> projex.projex.fromSearch('*cool*,*test*')... | Generates a regular expression from 'simple' search terms.
:param text | <str>
:usage |>>> import projex.regex
|>>> projex.regex.fromSearch('*cool*')
|'^.*cool.*$'
|>>> projex.projex.fromSearch('*cool*,*test*')
|'^.*cool.*$|^.*t... |
def delete(gandi, resource, force, background):
""" Delete a vhost. """
output_keys = ['name', 'paas_id', 'state', 'date_creation']
if not force:
proceed = click.confirm('Are you sure to delete vhost %s?' %
resource)
if not proceed:
return
op... | Delete a vhost. |
def dedicate(rh):
"""
Dedicate device.
Input:
Request Handle with the following properties:
function - 'CHANGEVM'
subfunction - 'DEDICATEDM'
userid - userid of the virtual machine
parms['vaddr'] - Virtual address
parms['raddr'] - Re... | Dedicate device.
Input:
Request Handle with the following properties:
function - 'CHANGEVM'
subfunction - 'DEDICATEDM'
userid - userid of the virtual machine
parms['vaddr'] - Virtual address
parms['raddr'] - Real address
parms['mo... |
def describe_file_extensions(self):
"""Returns two arrays describing the supported file extensions.
The first array contains the supported extensions and the seconds one
the type each extension supports. Both have the same size.
Note that some backends do not work on fi... | Returns two arrays describing the supported file extensions.
The first array contains the supported extensions and the seconds one
the type each extension supports. Both have the same size.
Note that some backends do not work on files, so this array may be
empty.
... |
def _config(key, mandatory=True, opts=None):
'''
Return a value for 'name' from master config file options or defaults.
'''
try:
if opts:
value = opts['auth.ldap.{0}'.format(key)]
else:
value = __opts__['auth.ldap.{0}'.format(key)]
except KeyError:
try... | Return a value for 'name' from master config file options or defaults. |
def get_proficiency_search_session_for_objective_bank(self, objective_bank_id, proxy):
"""Gets the ``OsidSession`` associated with the proficiency search service for the given objective bank.
:param objective_bank_id: the ``Id`` of the ``ObjectiveBank``
:type objective_bank_id: ``osid.id.Id``
... | Gets the ``OsidSession`` associated with the proficiency search service for the given objective bank.
:param objective_bank_id: the ``Id`` of the ``ObjectiveBank``
:type objective_bank_id: ``osid.id.Id``
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: a ``Profic... |
def create(cls, card_id, type_=None, custom_headers=None):
"""
Generate a new CVC2 code for a card.
:type user_id: int
:type card_id: int
:param type_: The type of generated cvc2. Can be STATIC or GENERATED.
:type type_: str
:type custom_headers: dict[str, str]|N... | Generate a new CVC2 code for a card.
:type user_id: int
:type card_id: int
:param type_: The type of generated cvc2. Can be STATIC or GENERATED.
:type type_: str
:type custom_headers: dict[str, str]|None
:rtype: BunqResponseInt |
def _op_generic_StoU_saturation(self, value, min_value, max_value): #pylint:disable=no-self-use
"""
Return unsigned saturated BV from signed BV.
Min and max value should be unsigned.
"""
return claripy.If(
claripy.SGT(value, max_value),
max_value,
... | Return unsigned saturated BV from signed BV.
Min and max value should be unsigned. |
def error(self, session=None):
"""
Forces the task instance's state to FAILED in the database.
"""
self.log.error("Recording the task instance as FAILED")
self.state = State.FAILED
session.merge(self)
session.commit() | Forces the task instance's state to FAILED in the database. |
def mute(self):
"""get/set the current mute state"""
response = self.rendering_control.GetMute(InstanceID=1, Channel=1)
return response.CurrentMute == 1 | get/set the current mute state |
def greenlet_admin(self):
""" This greenlet is used to get status information about the worker
when --admin_port was given
"""
if self.config["processes"] > 1:
self.log.debug(
"Admin server disabled because of multiple processes.")
return
... | This greenlet is used to get status information about the worker
when --admin_port was given |
def seed_aws_data(ctx, data):
"""Seeds SWAG from a list of known AWS accounts."""
swag = create_swag_from_ctx(ctx)
for k, v in json.loads(data.read()).items():
for account in v['accounts']:
data = {
'description': 'This is an AWS owned account used for {}'.format(k),
... | Seeds SWAG from a list of known AWS accounts. |
def plot_raster(self, ax, xlim, x, y, pop_names=False,
markersize=20., alpha=1., legend=True,
marker='o', rasterized=True):
"""
Plot network raster plot in subplot object.
Parameters
----------
ax : `matplotlib.axes.AxesSu... | Plot network raster plot in subplot object.
Parameters
----------
ax : `matplotlib.axes.AxesSubplot` object
plot axes
xlim : list
List of floats. Spike time interval, e.g., [0., 1000.].
x : dict
Key-value entries are populatio... |
def remove_my_api_key_from_groups(self, body, **kwargs): # noqa: E501
"""Remove API key from groups. # noqa: E501
An endpoint for removing API key from groups. **Example usage:** `curl -X DELETE https://api.us-east-1.mbedcloud.com/v3/api-keys/me/groups -d '[0162056a9a1586f30242590700000000,0117056a... | Remove API key from groups. # noqa: E501
An endpoint for removing API key from groups. **Example usage:** `curl -X DELETE https://api.us-east-1.mbedcloud.com/v3/api-keys/me/groups -d '[0162056a9a1586f30242590700000000,0117056a9a1586f30242590700000000]' -H 'content-type: application/json' -H 'Authorization: ... |
def enable(self, identifier, exclude_children=False):
"""
Enable a previously disabled include type
:param identifier: module or name of the include type
:param exclude_children: disable the include type only for child processes, not the current process
The ``identifier`` can b... | Enable a previously disabled include type
:param identifier: module or name of the include type
:param exclude_children: disable the include type only for child processes, not the current process
The ``identifier`` can be specified in multiple ways to disable an include type.
See :py:m... |
def _make_single_run(self):
""" Modifies the trajectory for single runs executed by the environment """
self._is_run = False # to be able to use f_set_crun
self._new_nodes = OrderedDict()
self._new_links = OrderedDict()
self._is_run = True
return self | Modifies the trajectory for single runs executed by the environment |
def load_collection_from_url(resource, url, content_type=None):
"""
Creates a new collection for the registered resource and calls
`load_into_collection_from_url` with it.
"""
coll = create_staging_collection(resource)
load_into_collection_from_url(coll, url, content_type=content_type)
retur... | Creates a new collection for the registered resource and calls
`load_into_collection_from_url` with it. |
def close(self, force=True):
'''This closes the connection with the child application. Note that
calling close() more than once is valid. This emulates standard Python
behavior with files. Set force to True if you want to make sure that
the child is terminated (SIGKILL is sent if the chi... | This closes the connection with the child application. Note that
calling close() more than once is valid. This emulates standard Python
behavior with files. Set force to True if you want to make sure that
the child is terminated (SIGKILL is sent if the child ignores SIGHUP
and SIGINT). |
def shutdown_host(kwargs=None, call=None):
'''
Shut down the specified host system in this VMware environment
.. note::
If the host system is not in maintenance mode, it will not be shut down. If you
want to shut down the host system regardless of whether it is in maintenance mode,
... | Shut down the specified host system in this VMware environment
.. note::
If the host system is not in maintenance mode, it will not be shut down. If you
want to shut down the host system regardless of whether it is in maintenance mode,
set ``force=True``. Default is ``force=False``.
C... |
def update_counter(self, key, value, **kwargs):
"""
Updates the value of a counter stored in this bucket. Positive
values increment the counter, negative values decrement. See
:meth:`RiakClient.update_counter()
<riak.client.RiakClient.update_counter>` for options.
.. dep... | Updates the value of a counter stored in this bucket. Positive
values increment the counter, negative values decrement. See
:meth:`RiakClient.update_counter()
<riak.client.RiakClient.update_counter>` for options.
.. deprecated:: 2.1.0 (Riak 2.0) Riak 1.4-style counters are
de... |
def CopyFromDateTimeString(self, time_string):
"""Copies a POSIX timestamp from a date and time string.
Args:
time_string (str): date and time value formatted as:
YYYY-MM-DD hh:mm:ss.######[+-]##:##
Where # are numeric digits ranging from 0 to 9 and the seconds
fraction can... | Copies a POSIX timestamp from a date and time string.
Args:
time_string (str): date and time value formatted as:
YYYY-MM-DD hh:mm:ss.######[+-]##:##
Where # are numeric digits ranging from 0 to 9 and the seconds
fraction can be either 3 or 6 digits. The time of day, seconds
... |
def parse(self):
"""
Parse a Pipfile (as seen in pipenv)
:return:
"""
try:
data = toml.loads(self.obj.content, _dict=OrderedDict)
if data:
for package_type in ['packages', 'dev-packages']:
if package_type in data:
... | Parse a Pipfile (as seen in pipenv)
:return: |
def competition_submit(self, file_name, message, competition, quiet=False):
""" submit a competition!
Parameters
==========
file_name: the competition metadata file
message: the submission description
competition: the competition name
quie... | submit a competition!
Parameters
==========
file_name: the competition metadata file
message: the submission description
competition: the competition name
quiet: suppress verbose output (default is False) |
def _compute_asset_ids(cls, inputs, marker_output_index, outputs, asset_quantities):
"""
Computes the asset IDs of every output in a transaction.
:param list[TransactionOutput] inputs: The outputs referenced by the inputs of the transaction.
:param int marker_output_index: The position ... | Computes the asset IDs of every output in a transaction.
:param list[TransactionOutput] inputs: The outputs referenced by the inputs of the transaction.
:param int marker_output_index: The position of the marker output in the transaction.
:param list[CTxOut] outputs: The outputs of the transact... |
async def connect(self):
"""
Create a TURN allocation.
"""
request = stun.Message(message_method=stun.Method.ALLOCATE,
message_class=stun.Class.REQUEST)
request.attributes['LIFETIME'] = self.lifetime
request.attributes['REQUESTED-TRANSPORT']... | Create a TURN allocation. |
def set(self, r, g, b, intensity=None):
"""Set the R/G/B and optionally intensity in one call"""
self.r = r
self.g = g
self.b = b
if intensity:
self.intensity = intensity | Set the R/G/B and optionally intensity in one call |
def json_worker(self, mask, cache_id=None, cache_method="string",
cache_section="www"):
"""A function annotation that adds a worker request. A worker request
is a POST request that is computed asynchronously. That is, the
actual task is performed in a different thread a... | A function annotation that adds a worker request. A worker request
is a POST request that is computed asynchronously. That is, the
actual task is performed in a different thread and the network
request returns immediately. The client side uses polling to fetch
the result and ... |
def get_bits_from_int(val_int, val_size=16):
"""Get the list of bits of val_int integer (default size is 16 bits)
Return bits list, least significant bit first. Use list.reverse() if
need.
:param val_int: integer value
:type val_int: int
:param val_size: bit size of integer... | Get the list of bits of val_int integer (default size is 16 bits)
Return bits list, least significant bit first. Use list.reverse() if
need.
:param val_int: integer value
:type val_int: int
:param val_size: bit size of integer (word = 16, long = 32) (optional)
:type val... |
def generate_session_key(hmac_secret=b''):
"""
:param hmac_secret: optional HMAC
:type hmac_secret: :class:`bytes`
:return: (session_key, encrypted_session_key) tuple
:rtype: :class:`tuple`
"""
session_key = random_bytes(32)
encrypted_session_key = PKCS1_OAEP.new(UniverseKey.Public, SHA1... | :param hmac_secret: optional HMAC
:type hmac_secret: :class:`bytes`
:return: (session_key, encrypted_session_key) tuple
:rtype: :class:`tuple` |
def reconcile_extend(self, high):
'''
Pull the extend data and add it to the respective high data
'''
errors = []
if '__extend__' not in high:
return high, errors
ext = high.pop('__extend__')
for ext_chunk in ext:
for name, body in six.iter... | Pull the extend data and add it to the respective high data |
async def container_size(
self, container_len=None, container_type=None, params=None
):
"""
Container size
:param container_len:
:param container_type:
:param params:
:return:
"""
if hasattr(container_type, "serialize_archive"):
... | Container size
:param container_len:
:param container_type:
:param params:
:return: |
def get_flair_choices(self, subreddit, link=None):
"""Return available flair choices and current flair.
:param link: If link is given, return the flair options for this
submission. Not normally given directly, but instead set by calling
the flair_choices method for Submission ob... | Return available flair choices and current flair.
:param link: If link is given, return the flair options for this
submission. Not normally given directly, but instead set by calling
the flair_choices method for Submission objects.
Use the default for the session's user.
... |
def reorientate(self, override_exif=True):
"""
Rotates the image in the buffer so that it is oriented correctly.
If override_exif is True (default) then the metadata
orientation is adjusted as well.
:param override_exif: If the metadata should be adjusted as well.
:type o... | Rotates the image in the buffer so that it is oriented correctly.
If override_exif is True (default) then the metadata
orientation is adjusted as well.
:param override_exif: If the metadata should be adjusted as well.
:type override_exif: Boolean |
def get_pool_context(self):
# TODO: Add in-process caching
"""
Builds context for the WF pool.
Returns:
Context dict.
"""
context = {self.current.lane_id: self.current.role, 'self': self.current.role}
for lane_id, role_id in self.current.pool.items():... | Builds context for the WF pool.
Returns:
Context dict. |
def zpopmax(self, name, count=None):
"""
Remove and return up to ``count`` members with the highest scores
from the sorted set ``name``.
"""
args = (count is not None) and [count] or []
options = {
'withscores': True
}
return self.execute_comma... | Remove and return up to ``count`` members with the highest scores
from the sorted set ``name``. |
def perceptual_weighting(S, frequencies, **kwargs):
'''Perceptual weighting of a power spectrogram:
`S_p[f] = A_weighting(f) + 10*log(S[f] / ref)`
Parameters
----------
S : np.ndarray [shape=(d, t)]
Power spectrogram
frequencies : np.ndarray [shape=(d,)]
Center frequency for e... | Perceptual weighting of a power spectrogram:
`S_p[f] = A_weighting(f) + 10*log(S[f] / ref)`
Parameters
----------
S : np.ndarray [shape=(d, t)]
Power spectrogram
frequencies : np.ndarray [shape=(d,)]
Center frequency for each row of `S`
kwargs : additional keyword arguments
... |
def visit_Assign(self, node):
"""
Replace list calls by static_list calls when possible
>>> import gast as ast
>>> from pythran import passmanager, backend
>>> node = ast.parse("def foo(n): x = __builtin__.list(n); x[0] = 0; return __builtin__.tuple(x)")
>>> pm = passman... | Replace list calls by static_list calls when possible
>>> import gast as ast
>>> from pythran import passmanager, backend
>>> node = ast.parse("def foo(n): x = __builtin__.list(n); x[0] = 0; return __builtin__.tuple(x)")
>>> pm = passmanager.PassManager("test")
>>> _, node = pm.... |
def start(self, priority_queue, resource_queue):
self._kill_event = threading.Event()
self._priority_queue_pull_thread = threading.Thread(target=self._migrate_logs_to_internal,
args=(
... | maintain a set to track the tasks that are already INSERTED into database
to prevent race condition that the first resource message (indicate 'running' state)
arrives before the first task message.
If race condition happens, add to left_messages and operate them later |
def params_size(event_size, num_components, name=None):
"""The number of `params` needed to create a single distribution."""
with tf.compat.v1.name_scope(
name, 'CategoricalMixtureOfOneHotCategorical_params_size',
[event_size, num_components]):
return MixtureSameFamily.params_size(
... | The number of `params` needed to create a single distribution. |
def create_table(self, names=None):
"""Create an astropy Table object with the contents of the ROI model.
"""
scan_shape = (1,)
for src in self._srcs:
scan_shape = max(scan_shape, src['dloglike_scan'].shape)
tab = create_source_table(scan_shape)
for s in sel... | Create an astropy Table object with the contents of the ROI model. |
def get_preferred_path(self):
"""Return preferred mapping for a resource mapping.
Different URLs may map to the same resource, e.g.:
'/a/b' == '/A/b' == '/a/b/'
get_preferred_path() returns the same value for all these variants, e.g.:
'/a/b/' (assuming resource names c... | Return preferred mapping for a resource mapping.
Different URLs may map to the same resource, e.g.:
'/a/b' == '/A/b' == '/a/b/'
get_preferred_path() returns the same value for all these variants, e.g.:
'/a/b/' (assuming resource names considered case insensitive)
@par... |
def _prepare_facet_field_spies(self, facets):
"""
Returns a list of spies based on the facets
used to count frequencies.
"""
spies = []
for facet in facets:
slot = self.column[facet]
spy = xapian.ValueCountMatchSpy(slot)
# add attribute... | Returns a list of spies based on the facets
used to count frequencies. |
def java_potential_term(mesh, instructions):
'''
java_potential_term(mesh, instructions) yields a Java object that implements the potential field
described in the given list of instructions. Generally, this should not be invoked directly
and should only be called by mesh_register. Note: this expects... | java_potential_term(mesh, instructions) yields a Java object that implements the potential field
described in the given list of instructions. Generally, this should not be invoked directly
and should only be called by mesh_register. Note: this expects a single term's description,
not a series of descr... |
def scan(self, pattern):
"""
Scan the text for the given pattern and update pos/match
and related fields. The return value is a boolen that
indicates if the pattern matched. The matched value is
stored on the instance as ``match``, the last value is
stored as ``last``. ``... | Scan the text for the given pattern and update pos/match
and related fields. The return value is a boolen that
indicates if the pattern matched. The matched value is
stored on the instance as ``match``, the last value is
stored as ``last``. ``start_pos`` is the position of the
po... |
def use_dev_config_dir(use_dev_config_dir=USE_DEV_CONFIG_DIR):
"""Return whether the dev configuration directory should used."""
if use_dev_config_dir is not None:
if use_dev_config_dir.lower() in {'false', '0'}:
use_dev_config_dir = False
else:
use_dev_config_dir = DEV or ... | Return whether the dev configuration directory should used. |
def get_sequence_rules_for_assessment(self, assessment_id):
"""Gets a ``SequenceRuleList`` for an entire assessment.
arg: assessment_id (osid.id.Id): an assessment ``Id``
return: (osid.assessment.authoring.SequenceRuleList) - the
returned ``SequenceRule`` list
raise: ... | Gets a ``SequenceRuleList`` for an entire assessment.
arg: assessment_id (osid.id.Id): an assessment ``Id``
return: (osid.assessment.authoring.SequenceRuleList) - the
returned ``SequenceRule`` list
raise: NullArgument - ``assessment_id`` is ``null``
raise: Operation... |
def configure(self, user_dn, group_dn, url='ldap://127.0.0.1', case_sensitive_names=False, starttls=False,
tls_min_version='tls12', tls_max_version='tls12', insecure_tls=False, certificate=None, bind_dn=None,
bind_pass=None, user_attr='cn', discover_dn=False, deny_null_bind=True, upn... | Configure the LDAP auth method.
Supported methods:
POST: /auth/{mount_point}/config. Produces: 204 (empty body)
:param user_dn: Base DN under which to perform user search. Example: ou=Users,dc=example,dc=com
:type user_dn: str | unicode
:param group_dn: LDAP search base to ... |
def allowed_domains(self):
"""
This property lists the allowed domains for a load balancer.
The allowed domains are restrictions set for the allowed domain names
used for adding load balancer nodes. In order to submit a domain name
as an address for the load balancer node to add... | This property lists the allowed domains for a load balancer.
The allowed domains are restrictions set for the allowed domain names
used for adding load balancer nodes. In order to submit a domain name
as an address for the load balancer node to add, the user must verify
that the domain ... |
def rate_limit(self, name, limit=5, per=60, debug=False):
"""
Rate limit implementation. Allows up to `limit` of events every `per`
seconds.
See :ref:`rate-limit` for more information.
"""
return RateLimit(self, name, limit, per, debug) | Rate limit implementation. Allows up to `limit` of events every `per`
seconds.
See :ref:`rate-limit` for more information. |
def Issue(self, state, results):
"""Collect anomalous findings into a CheckResult.
Comparisons with anomalous conditions collect anomalies into a single
CheckResult message. The contents of the result varies depending on whether
the method making the comparison is a Check, Method or Probe.
- Probes... | Collect anomalous findings into a CheckResult.
Comparisons with anomalous conditions collect anomalies into a single
CheckResult message. The contents of the result varies depending on whether
the method making the comparison is a Check, Method or Probe.
- Probes evaluate raw host data and generate Ano... |
def print_runs(query):
""" Print all rows in this result query. """
if query is None:
return
for tup in query:
print(("{0} @ {1} - {2} id: {3} group: {4}".format(
tup.end, tup.experiment_name, tup.project_name,
tup.experiment_group, tup.run_group))) | Print all rows in this result query. |
def render_source(self):
"""Render the sourcecode."""
return SOURCE_TABLE_HTML % u'\n'.join(line.render() for line in
self.get_annotated_lines()) | Render the sourcecode. |
def get_accessible_time(self, plugin_override=True):
""" Get the accessible time of this task """
vals = self._hook_manager.call_hook('task_accessibility', course=self.get_course(), task=self, default=self._accessible)
return vals[0] if len(vals) and plugin_override else self._accessible | Get the accessible time of this task |
def _try_get_state_scope(name, mark_name_scope_used=True):
"""Returns a fresh variable/name scope for a module's state.
In order to import a module into a given scope without major complications
we require the scope to be empty. This function deals with deciding an unused
scope where to define the module state... | Returns a fresh variable/name scope for a module's state.
In order to import a module into a given scope without major complications
we require the scope to be empty. This function deals with deciding an unused
scope where to define the module state. This is non trivial in cases where
name_scope and variable_s... |
def tmp_configuration_copy(chmod=0o600):
"""
Returns a path for a temporary file including a full copy of the configuration
settings.
:return: a path to a temporary file
"""
cfg_dict = conf.as_dict(display_sensitive=True, raw=True)
temp_fd, cfg_path = mkstemp()
with os.fdopen(temp_fd, '... | Returns a path for a temporary file including a full copy of the configuration
settings.
:return: a path to a temporary file |
def add_advisor(self, name, ids=None, degree_type=None, record=None, curated=False):
"""Add an advisor.
Args:
:param name: full name of the advisor.
:type name: string
:param ids: list with the IDs of the advisor.
:type ids: list
:param degr... | Add an advisor.
Args:
:param name: full name of the advisor.
:type name: string
:param ids: list with the IDs of the advisor.
:type ids: list
:param degree_type: one of the allowed types of degree the advisor helped with.
:type degree_ty... |
def parse_metadata(section):
"""Given the first part of a slide, returns metadata associated with it."""
metadata = {}
metadata_lines = section.split('\n')
for line in metadata_lines:
colon_index = line.find(':')
if colon_index != -1:
key = line[:colon_index].strip()
val = line[colon_index +... | Given the first part of a slide, returns metadata associated with it. |
def take_while(self, predicate):
'''Returns elements from the start while the predicate is True.
Note: This method uses deferred execution.
Args:
predicate: A function returning True or False with which elements
will be tested.
Returns:
A Querya... | Returns elements from the start while the predicate is True.
Note: This method uses deferred execution.
Args:
predicate: A function returning True or False with which elements
will be tested.
Returns:
A Queryable over the elements from the beginning of ... |
def _ignore_path(cls, path, ignore_list=None, white_list=None):
"""Returns a whether a path should be ignored or not."""
ignore_list = ignore_list or []
white_list = white_list or []
return (cls._matches_patterns(path, ignore_list) and
not cls._matches_patterns(path, whit... | Returns a whether a path should be ignored or not. |
def split_cl_function(cl_str):
"""Split an CL function into a return type, function name, parameters list and the body.
Args:
cl_str (str): the CL code to parse and plit into components
Returns:
tuple: string elements for the return type, function name, parameter list and the body
"""
... | Split an CL function into a return type, function name, parameters list and the body.
Args:
cl_str (str): the CL code to parse and plit into components
Returns:
tuple: string elements for the return type, function name, parameter list and the body |
def ListField(field):
"""
This wraps a field so that when get_from_instance is called, the field's
values are iterated over
"""
# alter the original field's get_from_instance so it iterates over the
# values that the field's get_from_instance() method returns
original_get_from_instance = fie... | This wraps a field so that when get_from_instance is called, the field's
values are iterated over |
def _get_from_c_api():
"""dictproxy does exist in previous versions, but the Python constructor
refuses to create new objects, so we must be underhanded and sneaky with
ctypes.
"""
from ctypes import pythonapi, py_object
PyDictProxy_New = pythonapi.PyDictProxy_New
PyDictProxy_New.argtypes =... | dictproxy does exist in previous versions, but the Python constructor
refuses to create new objects, so we must be underhanded and sneaky with
ctypes. |
def group_variant(self):
"""Current group variant (get-only).
:getter: Returns current group variant
:type: str
"""
v_mapping = {symdata.index: symdata.variant for symdata in self._symboldata_list}
return v_mapping[self.group_num] or "" | Current group variant (get-only).
:getter: Returns current group variant
:type: str |
def savetofile(self, filelike, sortkey = True):
"""
Save configurations to a file-like object which supports `writelines`
"""
filelike.writelines(k + '=' + repr(v) + '\n' for k,v in self.config_items(sortkey)) | Save configurations to a file-like object which supports `writelines` |
def _prep_vcf(in_file, region_bed, sample, new_sample, stats, work_dir, data):
"""Prepare VCF for SV validation:
- Subset to passing variants
- Subset to genotyped variants -- removes reference and no calls
- Selects and names samples
- Subset to callable regions
- Remove larger annotations whi... | Prepare VCF for SV validation:
- Subset to passing variants
- Subset to genotyped variants -- removes reference and no calls
- Selects and names samples
- Subset to callable regions
- Remove larger annotations which slow down VCF processing |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.