code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def package_and_copy(package_root_dir, setup_py, output_tar_path):
"""Repackage an CloudML package and copy it to a staging dir.
Args:
package_root_dir: the root dir to install package from. Usually you can get the path
from inside your module using a relative path to __file__.
setup_py: the path t... | Repackage an CloudML package and copy it to a staging dir.
Args:
package_root_dir: the root dir to install package from. Usually you can get the path
from inside your module using a relative path to __file__.
setup_py: the path to setup.py.
output_tar_path: the GCS path of the output tarball pack... |
def smallStepsPerLargeStep(self, smallStepsPerLargeStep):
""" Sets the number of small steps that go in a large one.
"""
self._smallStepsPerLargeStep = smallStepsPerLargeStep
self._smallStepFactor = np.power(self.largeStepFactor, 1.0 / smallStepsPerLargeStep) | Sets the number of small steps that go in a large one. |
def runcp(
pfpickle,
outdir,
lcbasedir,
lcfname=None,
cprenorm=False,
lclistpkl=None,
nbrradiusarcsec=60.0,
maxnumneighbors=5,
makeneighborlcs=True,
fast_mode=False,
gaia_max_timeout=60.0,
gaia_mirror=None,
xmatchinf... | This makes a checkplot pickle for the given period-finding result pickle
produced by `lcproc.periodfinding.runpf`.
Parameters
----------
pfpickle : str or None
This is the filename of the period-finding result pickle file created by
`lcproc.periodfinding.runpf`. If this is None, the ch... |
def menu(self, choices, prompt='Please choose from the provided options:',
error='Invalid choice', intro=None, strict=True, default=None,
numerator=lambda x: [i + 1 for i in range(x)],
formatter=lambda x, y: '{0:>3}) {1}'.format(x, y),
clean=utils.safeint):
""... | Print a menu
The choices must be an iterable of two-tuples where the first value is
the value of the menu item, and the second is the label for that
matches the value.
The menu will be printed with numeric choices. For example::
1) foo
2) bar
Formattin... |
def clip_out_of_image(self, image):
"""
Clip off all parts of the bounding box that are outside of the image.
Parameters
----------
image : (H,W,...) ndarray or tuple of int
Image dimensions to use for the clipping of the bounding box.
If an ndarray, its ... | Clip off all parts of the bounding box that are outside of the image.
Parameters
----------
image : (H,W,...) ndarray or tuple of int
Image dimensions to use for the clipping of the bounding box.
If an ndarray, its shape will be used.
If a tuple, it is assume... |
async def settings(dev: Device):
"""Print out all possible settings."""
settings_tree = await dev.get_settings()
for module in settings_tree:
await traverse_settings(dev, module.usage, module.settings) | Print out all possible settings. |
def diff_dir(dir_cmp, left_path=True):
"""
A generator that, given a ``filecmp.dircmp`` object, yields the paths to all files that are different. Works
recursively.
:param dir_cmp: A ``filecmp.dircmp`` object representing the comparison.
:param left_path: If ``True``, paths will be relative to dirc... | A generator that, given a ``filecmp.dircmp`` object, yields the paths to all files that are different. Works
recursively.
:param dir_cmp: A ``filecmp.dircmp`` object representing the comparison.
:param left_path: If ``True``, paths will be relative to dircmp.left. Else paths will be relative to dircmp.righ... |
def numeric_task_id(task_id):
"""Converts a task-id to the numeric task-id.
Args:
task_id: task-id in either task-n or n format
Returns:
n
"""
# This function exists to support the legacy "task-id" format in the "google"
# provider. Google labels originally could not be numeric. When the google
... | Converts a task-id to the numeric task-id.
Args:
task_id: task-id in either task-n or n format
Returns:
n |
def sample_rwalk(args):
"""
Return a new live point proposed by random walking away from an
existing live point.
Parameters
----------
u : `~numpy.ndarray` with shape (npdim,)
Position of the initial sample. **This is a copy of an existing live
point.**
loglstar : float
... | Return a new live point proposed by random walking away from an
existing live point.
Parameters
----------
u : `~numpy.ndarray` with shape (npdim,)
Position of the initial sample. **This is a copy of an existing live
point.**
loglstar : float
Ln(likelihood) bound.
axes... |
def global_iterator_to_indices(self, git=None):
"""
Return sympy expressions translating global_iterator to loop indices.
If global_iterator is given, an integer is returned
"""
# unwind global iteration count into loop counters:
base_loop_counters = {}
global_it... | Return sympy expressions translating global_iterator to loop indices.
If global_iterator is given, an integer is returned |
def _handle_received_k_element(self, k_element: BeautifulSoup):
"""
The 'k' element appears to be kik's connection-related stanza.
It lets us know if a connection or a login was successful or not.
:param k_element: The XML element we just received from kik.
"""
if k_elem... | The 'k' element appears to be kik's connection-related stanza.
It lets us know if a connection or a login was successful or not.
:param k_element: The XML element we just received from kik. |
def query(self, value):
"""
Serialize an ORM query, Base-64 encode it and set it to
the b64_query field
"""
if not isinstance(value, Q):
raise Exception('Must only be passed a Django (Q)uery object')
s = QSerializer(base64=True)
self.b64_query = s.dump... | Serialize an ORM query, Base-64 encode it and set it to
the b64_query field |
async def nextset(self):
"""Get the next query set"""
conn = self._get_db()
current_result = self._result
if current_result is None or current_result is not conn._result:
return
if not current_result.has_next:
return
self._result = None
sel... | Get the next query set |
def _method_scope(input_layer, name):
"""Creates a nested set of name and id scopes and avoids repeats."""
global _in_method_scope
# pylint: disable=protected-access
with input_layer.g.as_default(), \
scopes.var_and_name_scope(
None if _in_method_scope else input_layer._scope), \
scope... | Creates a nested set of name and id scopes and avoids repeats. |
def as_call(self):
"""
Return this call as it is called in its source.
"""
default = self._default()
default = ', ' + default if default else ''
return "pyconfig.%s(%r%s)" % (self.method, self.get_key(), default) | Return this call as it is called in its source. |
def run(self, timeout = 0):
"""
Run a proactor loop and return new socket events. Timeout is a timedelta
object, 0 if active coros or None.
epoll timeout param is a integer number of miliseconds (seconds/1000).
"""
ptimeout = int(timeout.microseconds/1000+timeout.... | Run a proactor loop and return new socket events. Timeout is a timedelta
object, 0 if active coros or None.
epoll timeout param is a integer number of miliseconds (seconds/1000). |
def generate_chunks(data, chunk_size=DEFAULT_CHUNK_SIZE):
"""Yield 'chunk_size' items from 'data' at a time."""
iterator = iter(repeated.getvalues(data))
while True:
chunk = list(itertools.islice(iterator, chunk_size))
if not chunk:
return
yield chunk | Yield 'chunk_size' items from 'data' at a time. |
def disconnect(self):
"""
Disconnect the client from IBM Watson IoT Platform
"""
# self.logger.info("Closing connection to the IBM Watson IoT Platform")
self.client.disconnect()
# If we don't call loop_stop() it appears we end up with a zombie thread which continues to pr... | Disconnect the client from IBM Watson IoT Platform |
def serialize(self, dt):
"""
Converts the date to a string using the :py:attr:`~_DateParameterBase.date_format`.
"""
if dt is None:
return str(dt)
return dt.strftime(self.date_format) | Converts the date to a string using the :py:attr:`~_DateParameterBase.date_format`. |
def _raisePermanenceToThreshold(self, perm, mask):
"""
This method ensures that each column has enough connections to input bits
to allow it to become active. Since a column must have at least
'self._stimulusThreshold' overlaps in order to be considered during the
inhibition phase, columns without s... | This method ensures that each column has enough connections to input bits
to allow it to become active. Since a column must have at least
'self._stimulusThreshold' overlaps in order to be considered during the
inhibition phase, columns without such minimal number of connections, even
if all the input bi... |
def _clean_up_columns(
self):
"""clean up columns of the NED table
.. todo ::
- update key arguments values and definitions with defaults
- update return values and definitions
- update usage examples and text
- update docstring text
... | clean up columns of the NED table
.. todo ::
- update key arguments values and definitions with defaults
- update return values and definitions
- update usage examples and text
- update docstring text
- check sublime snippet exists
- clip... |
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
if self.body:
return '\n'.join(stmt.pretty_str(indent) for stmt in self.body)
else:
... | Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation. |
def calc_avgstrlen_pathstextnodes(pars_tnodes, dbg=False):
"""In the effort of not using external libraries (like scipy, numpy, etc),
I've written some harmless code for basic statistical calculations
"""
ttl = 0
for _, tnodes in pars_tnodes:
ttl += tnodes[3] # index #3 holds th... | In the effort of not using external libraries (like scipy, numpy, etc),
I've written some harmless code for basic statistical calculations |
def _database(self, writable=False):
"""
Private method that returns a xapian.Database for use.
Optional arguments:
``writable`` -- Open the database in read/write mode (default=False)
Returns an instance of a xapian.Database or xapian.WritableDatabase
"""
i... | Private method that returns a xapian.Database for use.
Optional arguments:
``writable`` -- Open the database in read/write mode (default=False)
Returns an instance of a xapian.Database or xapian.WritableDatabase |
def update_partition_static_route(self, org_name, part_name,
static_ip_list, vrf_prof=None,
service_node_ip=None):
"""Send static route update requests to DCNM.
:param org_name: name of organization
:param part_name: na... | Send static route update requests to DCNM.
:param org_name: name of organization
:param part_name: name of partition
:static_ip_list: List of static IP addresses
:vrf_prof: VRF Profile
:service_node_ip: Service Node IP address |
def quick_doc(request_data):
"""
Worker that returns the documentation of the symbol under cursor.
"""
code = request_data['code']
line = request_data['line'] + 1
column = request_data['column']
path = request_data['path']
# encoding = 'utf-8'
encoding = 'utf-8'
script = jedi.Scr... | Worker that returns the documentation of the symbol under cursor. |
def normalised_autocorrelation_function(chain, index=0, burn=None,
limit=None, fig=None, figsize=None):
"""
Plot the autocorrelation function for each parameter of a sampler chain.
:param chain:
The sampled parameter values.
:type chain:
:class:`numpy.ndarray`
:param index: [... | Plot the autocorrelation function for each parameter of a sampler chain.
:param chain:
The sampled parameter values.
:type chain:
:class:`numpy.ndarray`
:param index: [optional]
Index to calculate the autocorrelation from.
:type index:
int
:param limit: [optional... |
def update_assembly(data):
"""
Create a new Assembly() and convert as many of our old params to the new
version as we can. Also report out any parameters that are removed
and what their values are.
"""
print("##############################################################")
print("Updating... | Create a new Assembly() and convert as many of our old params to the new
version as we can. Also report out any parameters that are removed
and what their values are. |
def bsrch(self, domain):
"""
This function uses the Bloomberg API to retrieve 'bsrch' (Bloomberg
SRCH Data) queries. Returns list of tickers.
Parameters
----------
domain: string
A character string with the name of the domain to execute.
It can be... | This function uses the Bloomberg API to retrieve 'bsrch' (Bloomberg
SRCH Data) queries. Returns list of tickers.
Parameters
----------
domain: string
A character string with the name of the domain to execute.
It can be a user defined SRCH screen, commodity screen... |
def send_msg(self, message):
"""Send a SLIP-encoded message over the stream.
:param bytes message: The message to encode and send
"""
packet = self.driver.send(message)
self.send_bytes(packet) | Send a SLIP-encoded message over the stream.
:param bytes message: The message to encode and send |
def get_order_columns_list(self, list_columns=None):
"""
Returns the columns that can be ordered
:param list_columns: optional list of columns name, if provided will
use this list only.
"""
ret_lst = list()
list_columns = list_columns or self.get_... | Returns the columns that can be ordered
:param list_columns: optional list of columns name, if provided will
use this list only. |
def _start_slave(src_id, cmdline, router):
"""
This runs in the target context, it is invoked by _fakessh_main running in
the fakessh context immediately after startup. It starts the slave process
(the the point where it has a stdin_handle to target but not stdout_chan to
write to), and waits for ma... | This runs in the target context, it is invoked by _fakessh_main running in
the fakessh context immediately after startup. It starts the slave process
(the the point where it has a stdin_handle to target but not stdout_chan to
write to), and waits for main to. |
def list_privileges(name, **client_args):
'''
List privileges from a user.
name
Name of the user from whom privileges will be listed.
CLI Example:
.. code-block:: bash
salt '*' influxdb.list_privileges <name>
'''
client = _client(**client_args)
res = {}
for item ... | List privileges from a user.
name
Name of the user from whom privileges will be listed.
CLI Example:
.. code-block:: bash
salt '*' influxdb.list_privileges <name> |
def save_lastnode_id():
"""Save the id of the last node created."""
init_counter()
with FileLock(_COUNTER_FILE):
with AtomicFile(_COUNTER_FILE, mode="w") as fh:
fh.write("%d\n" % _COUNTER) | Save the id of the last node created. |
def finish (self, keyset, mask=True):
"""Returns (weights, means, variances), where:
weights
ndarray of number of samples per key
means
computed mean value for each key
variances
computed variance for each key
"""
n_us = len (self._keymap)
... | Returns (weights, means, variances), where:
weights
ndarray of number of samples per key
means
computed mean value for each key
variances
computed variance for each key |
def from_dict(cls, d):
"""
Makes XcFunc obey the general json interface used in pymatgen for easier serialization.
"""
return cls(xc=d.get("xc"), x=d.get("x"), c=d.get("c")) | Makes XcFunc obey the general json interface used in pymatgen for easier serialization. |
def parse_function_params(params):
""" parse function params to args and kwargs.
Args:
params (str): function param in string
Returns:
dict: function meta dict
{
"args": [],
"kwargs": {}
}
Examples:
>>> parse_function_pa... | parse function params to args and kwargs.
Args:
params (str): function param in string
Returns:
dict: function meta dict
{
"args": [],
"kwargs": {}
}
Examples:
>>> parse_function_params("")
{'args': [], 'kwargs': {}}... |
def load_config_module():
"""
If the config.py file exists, import it as a module. If it does not exist,
call sys.exit() with a request to run oaepub configure.
"""
import imp
config_path = config_location()
try:
config = imp.load_source('config', config_path)
except IOError:
... | If the config.py file exists, import it as a module. If it does not exist,
call sys.exit() with a request to run oaepub configure. |
def _sim_colour(r1, r2):
"""
calculate the sum of histogram intersection of colour
"""
return sum([min(a, b) for a, b in zip(r1["hist_c"], r2["hist_c"])]) | calculate the sum of histogram intersection of colour |
def v1_tag_associate(request, tags, tag):
'''Associate an HTML element with a tag.
The association should be a JSON serialized object on the
request body. Here is an example association that should
make the object's structure clear:
.. code-block:: python
{
"url": "http://exam... | Associate an HTML element with a tag.
The association should be a JSON serialized object on the
request body. Here is an example association that should
make the object's structure clear:
.. code-block:: python
{
"url": "http://example.com/abc/xyz?foo=bar",
"text": "Th... |
def perform_preflight_check(self):
"""Performs checks to see if we have everything needed to mount
sshfs filesystems.
:return: two-tuple (boolean checks_pass, list failure messages)
"""
failures = []
if not os.access(self.mount_path_base, os.W_OK):
msg = ("Mou... | Performs checks to see if we have everything needed to mount
sshfs filesystems.
:return: two-tuple (boolean checks_pass, list failure messages) |
def get_tuids_from_revision(self, revision):
"""
Gets the TUIDs for the files modified by a revision.
:param revision: revision to get files from
:return: list of (file, list(tuids)) tuples
"""
result = []
URL_TO_FILES = self.hg_url / self.config.hg.branch / 'jso... | Gets the TUIDs for the files modified by a revision.
:param revision: revision to get files from
:return: list of (file, list(tuids)) tuples |
def valid_daily_max_min_temperature(comp, units='K'):
r"""Decorator to check that a computation runs on valid min and max temperature datasets."""
@wraps(comp)
def func(tasmax, tasmin, **kwds):
valid_daily_max_temperature(tasmax, units)
valid_daily_min_temperature(tasmin, units)
re... | r"""Decorator to check that a computation runs on valid min and max temperature datasets. |
def prompt_file(prompt, default=None):
"""Prompt a file name with autocompletion"""
def complete(text: str, state):
text = text.replace('~', HOME)
sugg = (glob.glob(text + '*') + [None])[state]
if sugg is None:
return
sugg = sugg.replace(HOME, '~')
sugg = ... | Prompt a file name with autocompletion |
def get_package(name, version, paths=None):
"""Get an exact version of a package.
Args:
name (str): Name of the package, eg 'maya'.
version (Version or str): Version of the package, eg '1.0.0'
paths (list of str, optional): paths to search for package, defaults
to `config.pa... | Get an exact version of a package.
Args:
name (str): Name of the package, eg 'maya'.
version (Version or str): Version of the package, eg '1.0.0'
paths (list of str, optional): paths to search for package, defaults
to `config.packages_path`.
Returns:
`Package` objec... |
def static_url(context, static_file_path):
"""Filter for generating urls for static files.
NOTE: you'll need
to set app['static_root_url'] to be used as the root for the urls returned.
Usage: {{ static('styles.css') }} might become
"/static/styles.css" or "http://mycdn.example.com/styles.css"
... | Filter for generating urls for static files.
NOTE: you'll need
to set app['static_root_url'] to be used as the root for the urls returned.
Usage: {{ static('styles.css') }} might become
"/static/styles.css" or "http://mycdn.example.com/styles.css" |
def supports(self, config, context):
"""
Check whether we are in a Flask request context.
:param config: honeybadger configuration.
:param context: current honeybadger configuration.
:return: True if this is a django request, False else.
"""
try:
from ... | Check whether we are in a Flask request context.
:param config: honeybadger configuration.
:param context: current honeybadger configuration.
:return: True if this is a django request, False else. |
def analyze(self, scratch, **kwargs):
"""Run and return the results form the DeadCode plugin.
The variable_event indicates that the Scratch file contains at least
one instance of a broadcast event based on a variable. When
variable_event is True, dead code scripts reported by this plugi... | Run and return the results form the DeadCode plugin.
The variable_event indicates that the Scratch file contains at least
one instance of a broadcast event based on a variable. When
variable_event is True, dead code scripts reported by this plugin that
begin with a "when I receive" bloc... |
def cbuuid_to_uuid(cbuuid):
"""Convert Objective-C CBUUID type to native Python UUID type."""
data = cbuuid.data().bytes()
template = '{:0>8}-0000-1000-8000-00805f9b34fb' if len(data) <= 4 else '{:0>32}'
value = template.format(hexlify(data.tobytes()[:16]).decode('ascii'))
return uuid.UUID(hex=valu... | Convert Objective-C CBUUID type to native Python UUID type. |
def enter(self):
"""Send a LineConfirmation to the controller.
When this state is entered, a
:class:`AYABInterface.communication.host_messages.LineConfirmation`
is sent to the controller.
Also, the :attr:`last line requested
<AYABInterface.communication.Communication.las... | Send a LineConfirmation to the controller.
When this state is entered, a
:class:`AYABInterface.communication.host_messages.LineConfirmation`
is sent to the controller.
Also, the :attr:`last line requested
<AYABInterface.communication.Communication.last_requested_line_number>`
... |
def linreg_ols_pinv(y, X, rcond=1e-15):
"""Linear Regression, OLS, by multiplying with Pseudoinverse"""
import numpy as np
try: # multiply with inverse to compute coefficients
return np.dot(np.linalg.pinv(
np.dot(X.T, X), rcond=rcond), np.dot(X.T, y))
except np.linalg.LinAlgError:
... | Linear Regression, OLS, by multiplying with Pseudoinverse |
def save(self, inplace=True):
"""
Saves modification to the api server.
"""
data = self._modified_data()
data = data['permissions']
if bool(data):
url = six.text_type(self.href) + self._URL['permissions']
extra = {'resource': self.__class__.__name_... | Saves modification to the api server. |
def last_written_time(self):
"""dfdatetime.DateTimeValues: last written time."""
timestamp = self._pyregf_key.get_last_written_time_as_integer()
if timestamp == 0:
return dfdatetime_semantic_time.SemanticTime('Not set')
return dfdatetime_filetime.Filetime(timestamp=timestamp) | dfdatetime.DateTimeValues: last written time. |
def minimal_export(self, target_analytes=None, path=None):
"""
Exports a analysis parameters, standard info and a minimal dataset,
which can be imported by another user.
Parameters
----------
target_analytes : str or iterable
Which analytes to include in the ... | Exports a analysis parameters, standard info and a minimal dataset,
which can be imported by another user.
Parameters
----------
target_analytes : str or iterable
Which analytes to include in the export. If specified, the export
will contain these analytes, and a... |
def import_path(path):
"""
Imports any valid python module or attribute path as though it were a
module
:Example:
>>> from yamlconf import import_path
>>> from my_package.my_module.my_submodule import attribute
>>> attribute.sub_attribute == \
... import_path("y_pack... | Imports any valid python module or attribute path as though it were a
module
:Example:
>>> from yamlconf import import_path
>>> from my_package.my_module.my_submodule import attribute
>>> attribute.sub_attribute == \
... import_path("y_package.my_module.my_submodule.attribut... |
def update_image_2(self, container_name, image_name):
"""
update a container's image,
:param container_name: `class`:`str`, container name
:param image_name: `class`:`str`, the full image name, like alpine:3.3
:return: `class`:`bool`, True if success, otherwise False.
... | update a container's image,
:param container_name: `class`:`str`, container name
:param image_name: `class`:`str`, the full image name, like alpine:3.3
:return: `class`:`bool`, True if success, otherwise False. |
def load(self, source: Source) -> None:
"""
Attempts to load all resources (i.e., bugs, tools, and blueprints)
provided by a given source. If the given source has already been
loaded, then that resources for that source are unloaded and
reloaded.
"""
logger.info('... | Attempts to load all resources (i.e., bugs, tools, and blueprints)
provided by a given source. If the given source has already been
loaded, then that resources for that source are unloaded and
reloaded. |
def map_resource_to_distribution(resource, portal_url):
"""Mapea un diccionario con metadatos de cierto 'resource' CKAN a dicts
con metadatos de una 'distribution' según el estándar data.json."""
distribution = dict()
distribution_mapping = {
'url': 'downloadURL',
'name': 'title',
... | Mapea un diccionario con metadatos de cierto 'resource' CKAN a dicts
con metadatos de una 'distribution' según el estándar data.json. |
def in_transaction(self):
"""Check if this database is in a transactional context."""
if not hasattr(self.local, 'tx'):
return False
return len(self.local.tx) > 0 | Check if this database is in a transactional context. |
def passive_mode(self) -> Tuple[str, int]:
'''Enable passive mode.
Returns:
The address (IP address, port) of the passive port.
Coroutine.
'''
yield from self._control_stream.write_command(Command('PASV'))
reply = yield from self._control_stream.read_reply(... | Enable passive mode.
Returns:
The address (IP address, port) of the passive port.
Coroutine. |
async def get_raw(self, champion_name: str) -> Tuple[dict]:
"""A method to retrieve **raw** optimal runes for a given champion.
Parameters
----------
champion_name : str
Case insensitive name of the champion to get runes for.
Returns
-------
Tuple[di... | A method to retrieve **raw** optimal runes for a given champion.
Parameters
----------
champion_name : str
Case insensitive name of the champion to get runes for.
Returns
-------
Tuple[dict]
A tuple of dicts which contain the rune information.
... |
def get_asset_content_form_for_update(self, asset_content_id=None):
"""Gets the asset form for updating content for an existing asset.
A new asset content form should be requested for each update
transaction.
:param asset_content_id: the ``Id`` of the ``AssetContent``
:type ass... | Gets the asset form for updating content for an existing asset.
A new asset content form should be requested for each update
transaction.
:param asset_content_id: the ``Id`` of the ``AssetContent``
:type asset_content_id: ``osid.id.Id``
:return: the asset content form
:... |
def do_file_update_metadata(client, args):
"""Update file metadata"""
client.update_file_metadata(args.uri, filename=args.filename,
description=args.description, mtime=args.mtime,
privacy=args.privacy)
return True | Update file metadata |
def _parse_PREFIX(value):
"channel user prefixes"
channel_modes, channel_chars = value.split(')')
channel_modes = channel_modes[1:]
return collections.OrderedDict(zip(channel_chars, channel_modes)) | channel user prefixes |
def precedes(self, other):
"""Returns a boolean indicating whether this element precedes the other element"""
try:
ancestor = next(commonancestors(AbstractElement, self, other))
except StopIteration:
raise Exception("Elements share no common ancestor")
#now we jus... | Returns a boolean indicating whether this element precedes the other element |
def focusOutEvent(self, event):
"""
Processes when this widget loses focus.
:param event | <QFocusEvent>
"""
if not self.signalsBlocked():
self.focusChanged.emit(False)
self.focusExited.emit()
return super(XTextEdit... | Processes when this widget loses focus.
:param event | <QFocusEvent> |
def launch(self, args, unknown):
"""Launch something according to the provided arguments
:param args: arguments from the launch parser
:type args: Namespace
:param unknown: list of unknown arguments
:type unknown: list
:returns: None
:rtype: None
:raises:... | Launch something according to the provided arguments
:param args: arguments from the launch parser
:type args: Namespace
:param unknown: list of unknown arguments
:type unknown: list
:returns: None
:rtype: None
:raises: SystemExit |
def template_name_from_class_name(class_name):
""" Remove the last 'Template' in the name. """
suffix = 'Template'
output = class_name
if (class_name.endswith(suffix)):
output = class_name[:-len(suffix)]
return output | Remove the last 'Template' in the name. |
def update_device(self, device_obj):
""" Implements the Update device Portals API.
http://docs.exosite.com/portals/#update-device
"""
rid = device_obj['rid']
device_obj['info']['description']['meta'] = \
json.dumps(device_obj['info']['description'... | Implements the Update device Portals API.
http://docs.exosite.com/portals/#update-device |
def parse_member(
cls,
obj: dict,
collection: "HttpResolverDtsCollection",
direction: str,
**additional_parameters):
""" Parse the member value of a Collection response
and returns the list of object while setting the graph
relationshi... | Parse the member value of a Collection response
and returns the list of object while setting the graph
relationship based on `direction`
:param obj: PyLD parsed JSON+LD
:param collection: Collection attached to the member property
:param direction: Direction of the member (child... |
def macaroon(self, version, expiry, caveats, ops):
''' Takes a macaroon with the given version from the oven,
associates it with the given operations and attaches the given caveats.
There must be at least one operation specified.
The macaroon will expire at the given time - a time_before... | Takes a macaroon with the given version from the oven,
associates it with the given operations and attaches the given caveats.
There must be at least one operation specified.
The macaroon will expire at the given time - a time_before first party
caveat will be added with that time.
... |
def setdefault(self, name: str, default: Any=None) -> Any:
"""Set an attribute with a default value."""
return self.__dict__.setdefault(name, default) | Set an attribute with a default value. |
def put_design(self, design_name, design, verbose=False):
"""
Updates a design document for the loaded databases
design_name <str> name of the design
design <str> json string of the design document
"""
try:
try:
# check if there is a previous revision of the
# specified ... | Updates a design document for the loaded databases
design_name <str> name of the design
design <str> json string of the design document |
def delete_currency_by_id(cls, currency_id, **kwargs):
"""Delete Currency
Delete an instance of Currency by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.delete_currency_by_id(curren... | Delete Currency
Delete an instance of Currency by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.delete_currency_by_id(currency_id, async=True)
>>> result = thread.get()
:par... |
def nvmlDeviceSetDefaultAutoBoostedClocksEnabled(handle, enabled, flags):
r"""
/**
* Try to set the default state of Auto Boosted clocks on a device. This is the default state that Auto Boosted clocks will
* return to when no compute running processes (e.g. CUDA application which have an active contex... | r"""
/**
* Try to set the default state of Auto Boosted clocks on a device. This is the default state that Auto Boosted clocks will
* return to when no compute running processes (e.g. CUDA application which have an active context) are running
*
* For Kepler &tm; or newer non-GeForce fully suppor... |
def transition_local(n_states, width, window='triangle', wrap=False):
'''Construct a localized transition matrix.
The transition matrix will have the following properties:
- `transition[i, j] = 0` if `|i - j| > width`
- `transition[i, i]` is maximal
- `transition[i, i - width//2 : i + ... | Construct a localized transition matrix.
The transition matrix will have the following properties:
- `transition[i, j] = 0` if `|i - j| > width`
- `transition[i, i]` is maximal
- `transition[i, i - width//2 : i + width//2]` has shape `window`
This type of transition matrix is appropri... |
def get_cohp_by_label(self, label):
"""
Get specific COHP object.
Args:
label: string (for newer Lobster versions: a number)
Returns:
Returns the COHP object to simplify plotting
"""
if label.lower() == "average":
return Cohp(efermi=s... | Get specific COHP object.
Args:
label: string (for newer Lobster versions: a number)
Returns:
Returns the COHP object to simplify plotting |
def set_grid_site(self,site):
"""
Set the grid site to run on. If not specified,
will not give hint to Pegasus
"""
self.__grid_site=str(site)
if site != 'local':
self.set_executable_installed(False) | Set the grid site to run on. If not specified,
will not give hint to Pegasus |
def json_parse(self, response):
"""
Wraps and abstracts response validation and JSON parsing
to make sure the user gets the correct response.
:param response: The response returned to us from the request
:returns: a dict of the json response
"""
try:
... | Wraps and abstracts response validation and JSON parsing
to make sure the user gets the correct response.
:param response: The response returned to us from the request
:returns: a dict of the json response |
def check_relations(self, relations):
"""Recursive function which checks if a relation is valid."""
for rel in relations:
if not rel:
continue
fields = rel.split('.', 1)
local_field = fields[0]
if local_field not in self.fields:
... | Recursive function which checks if a relation is valid. |
def distance_df(df, xyz=(0.00, 0.00, 0.00)):
"""Computes Euclidean distance between atoms and a 3D point.
Parameters
----------
df : DataFrame
DataFrame containing entries similar to the PandasMol2.df
format for the
the distance computation to the `xy... | Computes Euclidean distance between atoms and a 3D point.
Parameters
----------
df : DataFrame
DataFrame containing entries similar to the PandasMol2.df
format for the
the distance computation to the `xyz` reference coordinates.
xyz : tuple (0.00, 0.0... |
def parse_catalytic(insertion, gff):
"""
parse catalytic RNAs to gff format
"""
offset = insertion['offset']
GeneStrand = insertion['strand']
if type(insertion['intron']) is not str:
return gff
for intron in parse_fasta(insertion['intron'].split('|')):
ID, annot, strand, pos ... | parse catalytic RNAs to gff format |
def update(self, account_sid=values.unset, api_version=values.unset,
friendly_name=values.unset, sms_application_sid=values.unset,
sms_fallback_method=values.unset, sms_fallback_url=values.unset,
sms_method=values.unset, sms_url=values.unset,
status_callback=v... | Update the IncomingPhoneNumberInstance
:param unicode account_sid: The SID of the Account that created the resource to update
:param unicode api_version: The API version to use for incoming calls made to the phone number
:param unicode friendly_name: A string to describe the resource
:p... |
def _tab_changed(self):
"""Triggered when the current tab is changed."""
current = self.tab_widget.currentWidget()
if current == self.analysisTab:
self.btn_back.setEnabled(False)
self.btn_next.setEnabled(True)
elif current == self.reportingTab:
if self... | Triggered when the current tab is changed. |
def default_privileges_list(
name,
object_type,
prepend='public',
maintenance_db=None,
user=None,
host=None,
port=None,
password=None,
runas=None):
'''
.. versionadded:: 2019.0.0
Return a list of default privileges for the specified ob... | .. versionadded:: 2019.0.0
Return a list of default privileges for the specified object.
CLI Example:
.. code-block:: bash
salt '*' postgres.default_privileges_list table_name table maintenance_db=db_name
name
Name of the object for which the permissions should be returned
objec... |
def setKWARGS(self, **kwargs):
"""
Used to set all attributes given in a **kwargs parameter.
Might throw an Exception if attribute was not found.
#TODO: check if we should fix this using "setAttribute"
"""
for key in list(kwargs.keys()):
#try:
f =... | Used to set all attributes given in a **kwargs parameter.
Might throw an Exception if attribute was not found.
#TODO: check if we should fix this using "setAttribute" |
def callback_result(self):
"""Block the main thead until future finish, return the future.callback_result."""
if self._state in [PENDING, RUNNING]:
self.x
if self._user_callbacks:
return self._callback_result
else:
return self.x | Block the main thead until future finish, return the future.callback_result. |
def ssh_init_sec_context(
self, target, desired_mech=None, username=None, recv_token=None
):
"""
Initialize a SSPI context.
:param str username: The name of the user who attempts to login
:param str target: The FQDN of the target to connect to
:param str desired_mech... | Initialize a SSPI context.
:param str username: The name of the user who attempts to login
:param str target: The FQDN of the target to connect to
:param str desired_mech: The negotiated SSPI mechanism
("pseudo negotiated" mechanism, because we
... |
def get_comments(self):
"""
:calls: `GET /repos/:owner/:repo/comments <http://developer.github.com/v3/repos/comments>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.CommitComment.CommitComment`
"""
return github.PaginatedList.PaginatedList(
gi... | :calls: `GET /repos/:owner/:repo/comments <http://developer.github.com/v3/repos/comments>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.CommitComment.CommitComment` |
def createrawtransaction(self, inputs, outputs):
"""[{"txid":input_txid,"vout":0}, ...], {recv_addr: amount, change: amount, ...}"""
if not isinstance(outputs, dict):
raise TypeError("outputs variable must be a dictionary")
if not isinstance(inputs, list):
raise TypeError... | [{"txid":input_txid,"vout":0}, ...], {recv_addr: amount, change: amount, ...} |
def create_field_from_definition(field_definition, name=None, sub_name=None):
"""Helper to create a field from definition.
:param field_definition: The definition of the field (see:
safe.definitions.fields).
:type field_definition: dict
:param name: The name is required if the field name is dy... | Helper to create a field from definition.
:param field_definition: The definition of the field (see:
safe.definitions.fields).
:type field_definition: dict
:param name: The name is required if the field name is dynamic and need a
string formatting.
:type name: basestring
:param su... |
def _fetch(self):
""" Receive at least one message from the server, if available.
:return: 2-tuple of number of detail messages and number of summary messages fetched
"""
if self.closed():
raise self.Error("Failed to read from closed connection {!r}".format(self.server.addre... | Receive at least one message from the server, if available.
:return: 2-tuple of number of detail messages and number of summary messages fetched |
def add_droplets(self, droplet_ids):
"""
Assign a LoadBalancer to a Droplet.
Args:
droplet_ids (obj:`list` of `int`): A list of Droplet IDs
"""
return self.get_data(
"load_balancers/%s/droplets/" % self.id,
type=POST,
params={"drop... | Assign a LoadBalancer to a Droplet.
Args:
droplet_ids (obj:`list` of `int`): A list of Droplet IDs |
def zeros(dur=None):
"""
Zeros/zeroes stream generator.
You may sum your endless stream by this to enforce an end to it.
Parameters
----------
dur :
Duration, in number of samples; endless if not given.
Returns
-------
Stream that repeats "0.0" during a given time duration (if any) or
endlessl... | Zeros/zeroes stream generator.
You may sum your endless stream by this to enforce an end to it.
Parameters
----------
dur :
Duration, in number of samples; endless if not given.
Returns
-------
Stream that repeats "0.0" during a given time duration (if any) or
endlessly. |
def tag_to_version(tag, config=None):
"""
take a tag that might be prefixed with a keyword and return only the version part
:param config: optional configuration object
"""
trace("tag", tag)
if not config:
config = Configuration()
tagdict = _parse_version_tag(tag, config)
if no... | take a tag that might be prefixed with a keyword and return only the version part
:param config: optional configuration object |
def load_trajectory(name, skip=1, format=None):
'''Load a trajectory file into chemlab. You should call this
command after you load a `~chemlab.core.System` through
load_system or load_remote_system.
'''
df = datafile(name, format=format)
dt, coords = df.read('trajectory', skip=skip)
boxes ... | Load a trajectory file into chemlab. You should call this
command after you load a `~chemlab.core.System` through
load_system or load_remote_system. |
def run_hook(name, workspace, hooks):
"""Runs all hooks added under the give name.
Parameters
----------
name - str
Name of the hook to invoke
workspace - dict
Workspace that the hook functions operate on
hooks - dict of lists
Mapping with hook names and callback funct... | Runs all hooks added under the give name.
Parameters
----------
name - str
Name of the hook to invoke
workspace - dict
Workspace that the hook functions operate on
hooks - dict of lists
Mapping with hook names and callback functions |
def get_form(self, form_class):
"""Returns an instance of the form to be used in this view."""
if not hasattr(self, '_form'):
kwargs = self.get_form_kwargs()
self._form = form_class(instance=self.object, **kwargs)
return self._form | Returns an instance of the form to be used in this view. |
def perform_get_or_create(self, request, *args, **kwargs):
"""Perform "get_or_create" - return existing object if found."""
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
process = serializer.validated_data.get('process')
process_inp... | Perform "get_or_create" - return existing object if found. |
def start(self, timeout=None):
"""Install the server on its IOLoop, optionally starting the IOLoop.
Parameters
----------
timeout : float or None, optional
Time in seconds to wait for server thread to start.
"""
if self._running.isSet():
raise Ru... | Install the server on its IOLoop, optionally starting the IOLoop.
Parameters
----------
timeout : float or None, optional
Time in seconds to wait for server thread to start. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.