code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def vms(nictag):
'''
List all vms connect to nictag
nictag : string
name of nictag
CLI Example:
.. code-block:: bash
salt '*' nictagadm.vms admin
'''
ret = {}
cmd = 'nictagadm vms {0}'.format(nictag)
res = __salt__['cmd.run_all'](cmd)
retcode = res['retcode']
... | List all vms connect to nictag
nictag : string
name of nictag
CLI Example:
.. code-block:: bash
salt '*' nictagadm.vms admin |
def getShocks(self):
'''
Gets permanent and transitory shocks (combining idiosyncratic and aggregate shocks), but
only consumers who update their macroeconomic beliefs this period incorporate all pre-
viously unnoticed aggregate permanent shocks. Agents correctly observe the level of al... | Gets permanent and transitory shocks (combining idiosyncratic and aggregate shocks), but
only consumers who update their macroeconomic beliefs this period incorporate all pre-
viously unnoticed aggregate permanent shocks. Agents correctly observe the level of all
real variables (market resource... |
def verify_checksum(file_id, pessimistic=False, chunk_size=None, throws=True,
checksum_kwargs=None):
"""Verify checksum of a file instance.
:param file_id: The file ID.
"""
f = FileInstance.query.get(uuid.UUID(file_id))
# Anything might happen during the task, so being pessimis... | Verify checksum of a file instance.
:param file_id: The file ID. |
def save_file(self, filename = 'StockChart'):
""" save htmlcontent as .html file """
filename = filename + '.html'
with open(filename, 'w') as f:
#self.buildhtml()
f.write(self.htmlcontent)
f.closed | save htmlcontent as .html file |
def trades(self, cursor=None, order='asc', limit=10, sse=False):
"""Retrieve the trades JSON from this instance's Horizon server.
Retrieve the trades JSON response for the account associated with
this :class:`Address`.
:param cursor: A paging token, specifying where to start returning ... | Retrieve the trades JSON from this instance's Horizon server.
Retrieve the trades JSON response for the account associated with
this :class:`Address`.
:param cursor: A paging token, specifying where to start returning records from.
When streaming this can be set to "now" to stream ... |
def min_or(a, b, c, d, w):
"""
Lower bound of result of ORing 2-intervals.
:param a: Lower bound of first interval
:param b: Upper bound of first interval
:param c: Lower bound of second interval
:param d: Upper bound of second interval
:param w: bit width
... | Lower bound of result of ORing 2-intervals.
:param a: Lower bound of first interval
:param b: Upper bound of first interval
:param c: Lower bound of second interval
:param d: Upper bound of second interval
:param w: bit width
:return: Lower bound of ORing 2-intervals |
def expand(self, basedir, config, sourcedir, targetdir, cwd):
"""
Validate that given paths are not the same.
Args:
basedir (string): Project base directory used to prepend relative
paths. If empty or equal to '.', it will be filled with current
direc... | Validate that given paths are not the same.
Args:
basedir (string): Project base directory used to prepend relative
paths. If empty or equal to '.', it will be filled with current
directory path.
config (string): Settings file path.
sourcedir ... |
def set_alias(self, alias_hosted_zone_id, alias_dns_name):
"""Make this an alias resource record set"""
self.alias_hosted_zone_id = alias_hosted_zone_id
self.alias_dns_name = alias_dns_name | Make this an alias resource record set |
def get_trackrs(self):
"""
Extract each Trackr device from the trackrApiInterface state.
return a list of all Trackr objects from account.
"""
trackrs = []
for trackr in self.state:
trackrs.append(trackrDevice(trackr, self))
return trackrs | Extract each Trackr device from the trackrApiInterface state.
return a list of all Trackr objects from account. |
def run(self, mod):
"""Find all assert statements in *mod* and rewrite them."""
if not mod.body:
# Nothing to do.
return
# Insert some special imports at the top of the module but after any
# docstrings and __future__ imports.
aliases = [ast.alias(py.built... | Find all assert statements in *mod* and rewrite them. |
def translate_doc(self, d, field_mapping=None, map_identifiers=None, **kwargs):
"""
Translate a solr document (i.e. a single result row)
"""
if field_mapping is not None:
self.map_doc(d, field_mapping)
subject = self.translate_obj(d, M.SUBJECT)
obj = self.tran... | Translate a solr document (i.e. a single result row) |
def mod_watch(name, url='http://localhost:8080/manager', timeout=180):
'''
The tomcat watcher, called to invoke the watch command.
When called, it will reload the webapp in question
.. note::
This state exists to support special handling of the ``watch``
:ref:`requisite <requisites>`. I... | The tomcat watcher, called to invoke the watch command.
When called, it will reload the webapp in question
.. note::
This state exists to support special handling of the ``watch``
:ref:`requisite <requisites>`. It should not be called directly.
Parameters for this function should be se... |
def pathIndex(self, path):
'''Return index of item with *path*.'''
if path == self.root.path:
return QModelIndex()
if not path.startswith(self.root.path):
return QModelIndex()
parts = []
while True:
if path == self.root.path:
... | Return index of item with *path*. |
def list_asgs(access_token, subscription_id, resource_group):
'''Get details about the application security groups for a resource group.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
resource_group (str): Azure resource group... | Get details about the application security groups for a resource group.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
resource_group (str): Azure resource group name.
Returns:
HTTP response. ASG JSON body. |
def _bind_parameters(operation, parameters):
""" Helper method that binds parameters to a SQL query. """
# inspired by MySQL Python Connector (conversion.py)
string_parameters = {}
for (name, value) in iteritems(parameters):
if value is None:
string_parameters[name] = 'NULL'
... | Helper method that binds parameters to a SQL query. |
def ets(self):
"""Equitable Threat Score, Gilbert Skill Score, v, (a - R)/(a + b + c - R), R=(a+b)(a+c)/N"""
r = (self.table[0, 0] + self.table[0, 1]) * (self.table[0, 0] + self.table[1, 0]) / self.N
return (self.table[0, 0] - r) / (self.table[0, 0] + self.table[0, 1] + self.table[1, 0] - r) | Equitable Threat Score, Gilbert Skill Score, v, (a - R)/(a + b + c - R), R=(a+b)(a+c)/N |
def json_2_text(inp, out, verbose = False):
"""Convert a Wikipedia article to Text object.
Concatenates the sections in wikipedia file and rearranges other information so it
can be interpreted as a Text object.
Links and other elements with start and end positions are annotated
as layers.
Para... | Convert a Wikipedia article to Text object.
Concatenates the sections in wikipedia file and rearranges other information so it
can be interpreted as a Text object.
Links and other elements with start and end positions are annotated
as layers.
Parameters
----------
inp: directory of parsed ... |
def raise_error(error_type: str) -> None:
"""Raise the appropriate error based on error message."""
try:
error = next((v for k, v in ERROR_CODES.items() if k in error_type))
except StopIteration:
error = AirVisualError
raise error(error_type) | Raise the appropriate error based on error message. |
def remove_scene(self, scene_id):
"""remove a scene by Scene ID"""
if self.state.activeSceneId == scene_id:
err_msg = "Requested to delete scene {sceneNum}, which is currently active. Cannot delete active scene.".format(sceneNum=scene_id)
logging.info(err_msg)
return(... | remove a scene by Scene ID |
def __set_title(self, value):
"""
Sets title of this axis.
"""
# OpenOffice on Debian "squeeze" ignore value of target.XAxis.String
# unless target.HasXAxisTitle is set to True first. (Despite the
# fact that target.HasXAxisTitle is reported to be False until
# ta... | Sets title of this axis. |
def check_process_counts(self):
"""Check for the minimum consumer process levels and start up new
processes needed.
"""
LOGGER.debug('Checking minimum consumer process levels')
for name in self.consumers:
processes_needed = self.process_spawn_qty(name)
if... | Check for the minimum consumer process levels and start up new
processes needed. |
def check_for_errors(self):
"""Check Connection for errors.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:return:
"""
if not self.exceptions:
if not self.is_closed:
return
... | Check Connection for errors.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:return: |
def key_exists(hive, key, use_32bit_registry=False):
'''
Check that the key is found in the registry. This refers to keys and not
value/data pairs. To check value/data pairs, use ``value_exists``
Args:
hive (str): The hive to connect to
key (str): The key to check
use_32bit_r... | Check that the key is found in the registry. This refers to keys and not
value/data pairs. To check value/data pairs, use ``value_exists``
Args:
hive (str): The hive to connect to
key (str): The key to check
use_32bit_registry (bool): Look in the 32bit portion of the registry
Re... |
def reset(self, indices=None):
"""Reset the environment and convert the resulting observation.
Args:
indices: The batch indices of environments to reset; defaults to all.
Returns:
Batch of observations.
"""
if indices is None:
indices = np.arange(len(self._envs))
if self._blo... | Reset the environment and convert the resulting observation.
Args:
indices: The batch indices of environments to reset; defaults to all.
Returns:
Batch of observations. |
def args(parsed_args, name=None):
"""Interpret parsed args to streams"""
strings = parsed_args.arg_strings(name)
files = [s for s in strings if os.path.isfile(s)]
if files:
streams = [open(f) for f in files]
else:
streams = []
if getattr(parsed_args, 'paste', not files):
... | Interpret parsed args to streams |
def molmz(df, noise=10000):
"""
The mz of the molecular ion.
"""
d = ((df.values > noise) * df.columns).max(axis=1)
return Trace(d, df.index, name='molmz') | The mz of the molecular ion. |
def get_current_user(self):
"""Get data from the current user endpoint"""
url = self.current_user_url
result = self.get(url)
return result | Get data from the current user endpoint |
def write(gctoo, out_fname, data_null="NaN", metadata_null="-666", filler_null="-666", data_float_format="%.4f"):
"""Write a gctoo object to a gct file.
Args:
gctoo (gctoo object)
out_fname (string): filename for output gct file
data_null (string): how to represent missing values in the... | Write a gctoo object to a gct file.
Args:
gctoo (gctoo object)
out_fname (string): filename for output gct file
data_null (string): how to represent missing values in the data (default = "NaN")
metadata_null (string): how to represent missing values in the metadata (default = "-666"... |
def compile_insert(self, query, values):
"""
Compile insert statement into SQL
:param query: A QueryBuilder instance
:type query: QueryBuilder
:param values: The insert values
:type values: dict or list
:return: The compiled insert
:rtype: str
"... | Compile insert statement into SQL
:param query: A QueryBuilder instance
:type query: QueryBuilder
:param values: The insert values
:type values: dict or list
:return: The compiled insert
:rtype: str |
def to_fmt(self):
"""
Return an Fmt representation for pretty-printing
"""
params = ""
txt = fmt.sep(" ", ['fun'])
name = self.show_name()
if name != "":
txt.lsdata.append(name)
tparams = []
if self.tparams is not None:
tparams = list(self.tparams)
if self.variadi... | Return an Fmt representation for pretty-printing |
def get_phenotype(self, individual_id):
"""
Return the phenotype of an individual
If individual does not exist return 0
Arguments:
individual_id (str): Represents the individual id
Returns:
int : Integer that represents the pheno... | Return the phenotype of an individual
If individual does not exist return 0
Arguments:
individual_id (str): Represents the individual id
Returns:
int : Integer that represents the phenotype |
def read(database, table, key):
"""Does a single read operation."""
with database.snapshot() as snapshot:
result = snapshot.execute_sql('SELECT u.* FROM %s u WHERE u.id="%s"' %
(table, key))
for row in result:
key = row[0]
for i in range(... | Does a single read operation. |
def parse_yaml(self, y):
'''Parse a YAML specification of a service port connector into this
object.
'''
self.connector_id = y['connectorId']
self.name = y['name']
if 'transMethod' in y:
self.trans_method = y['transMethod']
else:
self.tran... | Parse a YAML specification of a service port connector into this
object. |
def trigger(self, id, **kwargs):
"""
Triggers a build of a specific Build Configuration
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>... | Triggers a build of a specific Build Configuration
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> p... |
def lock_file(path, maxdelay=.1, lock_cls=LockFile, timeout=10.0):
"""Cooperative file lock. Uses `lockfile.LockFile` polling under the hood.
`maxdelay` defines the interval between individual polls.
"""
lock = lock_cls(path)
max_t = time.time() + timeout
while True:
if time.time() >= ... | Cooperative file lock. Uses `lockfile.LockFile` polling under the hood.
`maxdelay` defines the interval between individual polls. |
def write_markdown_to_file(self, f):
"""Prints this library to file `f`.
Args:
f: File to write to.
Returns:
Dictionary of documented members.
"""
print("---", file=f)
print("---", file=f)
print("<!-- This file is machine generated: DO NOT EDIT! -->", file=f)
print("", file... | Prints this library to file `f`.
Args:
f: File to write to.
Returns:
Dictionary of documented members. |
def show_replace(self):
"""Show replace widgets"""
self.show(hide_replace=False)
for widget in self.replace_widgets:
widget.show() | Show replace widgets |
def extension (network, session, version, scn_extension, start_snapshot,
end_snapshot, **kwargs):
"""
Function that adds an additional network to the existing network container.
The new network can include every PyPSA-component (e.g. buses, lines, links).
To connect it to the existing ... | Function that adds an additional network to the existing network container.
The new network can include every PyPSA-component (e.g. buses, lines, links).
To connect it to the existing network, transformers are needed.
All components and its timeseries of the additional scenario need to be insert... |
def get_document_models():
"""Return dict of index.doc_type: model."""
mappings = {}
for i in get_index_names():
for m in get_index_models(i):
key = "%s.%s" % (i, m._meta.model_name)
mappings[key] = m
return mappings | Return dict of index.doc_type: model. |
def parse_seconds(value):
'''
Parse string into Seconds instances.
Handled formats:
HH:MM:SS
HH:MM
SS
'''
svalue = str(value)
colons = svalue.count(':')
if colons == 2:
hours, minutes, seconds = [int(v) for v in svalue.split(':... | Parse string into Seconds instances.
Handled formats:
HH:MM:SS
HH:MM
SS |
def get_resource_uri(self, obj):
"""
Return the uri of the given object.
"""
url = 'api:%s:%s-detail' % (
self.api_version,
getattr(
self, 'resource_view_name',
self.Meta.model._meta.model_name
)
)
retur... | Return the uri of the given object. |
def get_orderbook(self):
"""Get orderbook for the instrument
:Retruns:
orderbook : dict
orderbook dict for the instrument
"""
if self in self.parent.books.keys():
return self.parent.books[self]
return {
"bid": [0], "bidsize": ... | Get orderbook for the instrument
:Retruns:
orderbook : dict
orderbook dict for the instrument |
def _match_data_to_parameter(cls, data):
""" find the appropriate parameter for a parameter field """
in_value = data["in"]
for cls in [QueryParameter, HeaderParameter, FormDataParameter,
PathParameter, BodyParameter]:
if in_value == cls.IN:
return cls
return None | find the appropriate parameter for a parameter field |
def absent(email, profile="splunk", **kwargs):
'''
Ensure a splunk user is absent
.. code-block:: yaml
ensure example test user 1:
splunk.absent:
- email: 'example@domain.com'
- name: 'exampleuser'
The following parameters are required:
email
... | Ensure a splunk user is absent
.. code-block:: yaml
ensure example test user 1:
splunk.absent:
- email: 'example@domain.com'
- name: 'exampleuser'
The following parameters are required:
email
This is the email of the user in splunk
name
... |
def save_new_environment(name, datadir, srcdir, ckan_version,
deploy_target=None, always_prod=False):
"""
Save an environment's configuration to the source dir and data dir
"""
with open(datadir + '/.version', 'w') as f:
f.write('2')
cp = ConfigParser.SafeConfigParser()
cp.read... | Save an environment's configuration to the source dir and data dir |
def count_curves(self, keys=None, alias=None):
"""
Counts the number of curves in the well that will be selected with the
given key list and the given alias dict. Used by Project's curve table.
"""
if keys is None:
keys = [k for k, v in self.data.items() if isinstance... | Counts the number of curves in the well that will be selected with the
given key list and the given alias dict. Used by Project's curve table. |
def save_as(self, new_filename):
"""
Save our file with the name provided.
Args:
new_filename: New name for the workbook file. String.
Returns:
Nothing.
"""
xfile._save_file(self._filename, self._datasourceTree, new_filename) | Save our file with the name provided.
Args:
new_filename: New name for the workbook file. String.
Returns:
Nothing. |
def wipe_cfg_vals_from_git_cfg(*cfg_opts):
"""Remove a set of options from Git config."""
for cfg_key_suffix in cfg_opts:
cfg_key = f'cherry-picker.{cfg_key_suffix.replace("_", "-")}'
cmd = "git", "config", "--local", "--unset-all", cfg_key
subprocess.check_call(cmd, stderr=subprocess.ST... | Remove a set of options from Git config. |
def hkeys(self, name, key_start, key_end, limit=10):
"""
Return a list of the top ``limit`` keys between ``key_start`` and
``key_end`` in hash ``name``
Similiar with **Redis.HKEYS**
.. note:: The range is (``key_start``, ``key_end``]. The ``key_start``
isn't ... | Return a list of the top ``limit`` keys between ``key_start`` and
``key_end`` in hash ``name``
Similiar with **Redis.HKEYS**
.. note:: The range is (``key_start``, ``key_end``]. The ``key_start``
isn't in the range, but ``key_end`` is.
:param string name: the hash n... |
def get_string_from_data(self, offset, data):
"""Get an ASCII string from data."""
s = self.get_bytes_from_data(offset, data)
end = s.find(b'\0')
if end >= 0:
s = s[:end]
return s | Get an ASCII string from data. |
def _add_encoded(self, encoded):
"""Returns E(a + b), given self=E(a) and b.
Args:
encoded (EncodedNumber): an :class:`EncodedNumber` to be added
to `self`.
Returns:
EncryptedNumber: E(a + b), calculated by encrypting b and
taking the product of E(a)... | Returns E(a + b), given self=E(a) and b.
Args:
encoded (EncodedNumber): an :class:`EncodedNumber` to be added
to `self`.
Returns:
EncryptedNumber: E(a + b), calculated by encrypting b and
taking the product of E(a) and E(b) modulo
:attr:`~Paillie... |
def msg_curse(self, args=None, max_width=None):
"""Return the dict to display in the curse interface."""
# Init the return message
ret = []
# Only process if stats exist and display plugin enable...
if args.disable_process:
msg = "PROCESSES DISABLED (press 'z' to dis... | Return the dict to display in the curse interface. |
def _release_info():
"""Check latest fastfood release info from PyPI."""
pypi_url = 'http://pypi.python.org/pypi/fastfood/json'
headers = {
'Accept': 'application/json',
}
request = urllib.Request(pypi_url, headers=headers)
response = urllib.urlopen(request).read().decode('utf_8')
da... | Check latest fastfood release info from PyPI. |
def sync_matchers(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2019.2.0
Sync engine modules from ``salt://_matchers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a... | .. versionadded:: 2019.2.0
Sync engine modules from ``salt://_matchers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
... |
def pvariance(data, mu=None):
"""Return the population variance of ``data``.
data should be an iterable of Real-valued numbers, with at least one
value. The optional argument mu, if given, should be the mean of
the data. If it is missing or None, the mean is automatically calculated.
Use this func... | Return the population variance of ``data``.
data should be an iterable of Real-valued numbers, with at least one
value. The optional argument mu, if given, should be the mean of
the data. If it is missing or None, the mean is automatically calculated.
Use this function to calculate the variance from t... |
def _create_update_tracking_related_event(instance):
"""
Create a TrackingEvent and TrackedFieldModification for an UPDATE event
for each related model.
"""
events = {}
# Create a dict mapping related model field to modified fields
for field, related_fields in instance._tracked_related_field... | Create a TrackingEvent and TrackedFieldModification for an UPDATE event
for each related model. |
def transformer_base_v1():
"""Set of hyperparameters."""
hparams = common_hparams.basic_params1()
hparams.norm_type = "layer"
hparams.hidden_size = 512
hparams.batch_size = 4096
hparams.max_length = 256
hparams.clip_grad_norm = 0. # i.e. no gradient clipping
hparams.optimizer_adam_epsilon = 1e-9
hpar... | Set of hyperparameters. |
def str_is_well_formed(xml_str):
"""
Args:
xml_str : str
DataONE API XML doc.
Returns:
bool: **True** if XML doc is well formed.
"""
try:
str_to_etree(xml_str)
except xml.etree.ElementTree.ParseError:
return False
else:
return True | Args:
xml_str : str
DataONE API XML doc.
Returns:
bool: **True** if XML doc is well formed. |
def resolve_addresses(self, node):
"""
Resolve addresses of children of Addrmap and Regfile components
"""
# Get alignment based on 'alignment' property
# This remains constant for all children
prop_alignment = self.alignment_stack[-1]
if prop_alignment is None:
... | Resolve addresses of children of Addrmap and Regfile components |
def GetTSKFileByPathSpec(self, path_spec):
"""Retrieves the SleuthKit file object for a path specification.
Args:
path_spec (PathSpec): path specification.
Returns:
pytsk3.File: TSK file.
Raises:
PathSpecError: if the path specification is missing inode and location.
"""
# O... | Retrieves the SleuthKit file object for a path specification.
Args:
path_spec (PathSpec): path specification.
Returns:
pytsk3.File: TSK file.
Raises:
PathSpecError: if the path specification is missing inode and location. |
def get_rdataset(self, rdclass, rdtype, covers=dns.rdatatype.NONE,
create=False):
"""Get an rdataset matching the specified properties in the
current node.
None is returned if an rdataset of the specified type and
class does not exist and I{create} is not True.
... | Get an rdataset matching the specified properties in the
current node.
None is returned if an rdataset of the specified type and
class does not exist and I{create} is not True.
@param rdclass: The class of the rdataset
@type rdclass: int
@param rdtype: The type of the r... |
def info(torrent_path):
"""Print out information from .torrent file."""
my_torrent = Torrent.from_file(torrent_path)
size = my_torrent.total_size
click.secho('Name: %s' % my_torrent.name, fg='blue')
click.secho('Files:')
for file_tuple in my_torrent.files:
click.secho(file_tuple.name)... | Print out information from .torrent file. |
def fromutc(self, dt):
'''See datetime.tzinfo.fromutc'''
if dt.tzinfo is not None and dt.tzinfo is not self:
raise ValueError('fromutc: dt.tzinfo is not self')
return (dt + self._utcoffset).replace(tzinfo=self) | See datetime.tzinfo.fromutc |
def get_rate_limits():
"""Retrieve status (and optionally) version from the API."""
client = get_rates_api()
with catch_raise_api_exception():
data, _, headers = client.rates_limits_list_with_http_info()
ratelimits.maybe_rate_limit(client, headers)
return {
k: RateLimitsInfo.from_... | Retrieve status (and optionally) version from the API. |
def monitoring_problems(self):
"""Get Alignak scheduler monitoring status
Returns an object with the scheduler livesynthesis
and the known problems
:return: scheduler live synthesis
:rtype: dict
"""
if self.app.type != 'scheduler':
return {'_status':... | Get Alignak scheduler monitoring status
Returns an object with the scheduler livesynthesis
and the known problems
:return: scheduler live synthesis
:rtype: dict |
def cublasZhpmv(handle, uplo, n, alpha, AP, x, incx, beta, y, incy):
"""
Matrix-vector product for Hermitian-packed matrix.
"""
status = _libcublas.cublasZhpmv_v2(handle,
_CUBLAS_FILL_MODE[uplo],
n, ctypes.byref(cuda.cu... | Matrix-vector product for Hermitian-packed matrix. |
def run_compute(self, compute=None, model=None, detach=False,
times=None, **kwargs):
"""
Run a forward model of the system on the enabled dataset using
a specified set of compute options.
To attach and set custom values for compute options, including choosing
... | Run a forward model of the system on the enabled dataset using
a specified set of compute options.
To attach and set custom values for compute options, including choosing
which backend to use, see:
* :meth:`add_compute`
To define the dataset types and times at which the mod... |
def get(key, default=-1):
"""Backport support for original codes."""
if isinstance(key, int):
return OptionNumber(key)
if key not in OptionNumber._member_map_:
extend_enum(OptionNumber, key, default)
return OptionNumber[key] | Backport support for original codes. |
def can_see_members(self, user):
"""Determine if given user can see other group members.
:param user: User to be checked.
:returns: True or False.
"""
if self.privacy_policy == PrivacyPolicy.PUBLIC:
return True
elif self.privacy_policy == PrivacyPolicy.MEMBER... | Determine if given user can see other group members.
:param user: User to be checked.
:returns: True or False. |
def assemble_oligos(dna_list, reference=None):
'''Given a list of DNA sequences, assemble into a single construct.
:param dna_list: List of DNA sequences - they must be single-stranded.
:type dna_list: coral.DNA list
:param reference: Expected sequence - once assembly completed, this will
be used to... | Given a list of DNA sequences, assemble into a single construct.
:param dna_list: List of DNA sequences - they must be single-stranded.
:type dna_list: coral.DNA list
:param reference: Expected sequence - once assembly completed, this will
be used to reorient the DNA (assembly could potentially occur fr... |
def bar(self, width, **_):
"""Returns the completed progress bar. Every time this is called the animation moves.
Positional arguments:
width -- the width of the entire bar (including borders).
"""
width -= self._width_offset
self._position += self._direction
# C... | Returns the completed progress bar. Every time this is called the animation moves.
Positional arguments:
width -- the width of the entire bar (including borders). |
def taskfile_user_data(file_, role):
"""Return the data for user
:param file_: the file that holds the data
:type file_: :class:`jukeboxcore.djadapter.models.File`
:param role: item data role
:type role: QtCore.Qt.ItemDataRole
:returns: data for the user
:rtype: depending on role
:raise... | Return the data for user
:param file_: the file that holds the data
:type file_: :class:`jukeboxcore.djadapter.models.File`
:param role: item data role
:type role: QtCore.Qt.ItemDataRole
:returns: data for the user
:rtype: depending on role
:raises: None |
def _get_requirement_attr(self, attr, path):
"""
Gets the attribute for a given requirement file in path
:param attr: string, attribute
:param path: string, path
:return: The attribute for the requirement, or the global default
"""
for req_file in self.requirement... | Gets the attribute for a given requirement file in path
:param attr: string, attribute
:param path: string, path
:return: The attribute for the requirement, or the global default |
def update(self, environments):
"""
Method to update environments vip
:param environments vip: List containing environments vip desired
to updated
:return: None
"""
data = {'environments_vip': environments}
environments_ids = [st... | Method to update environments vip
:param environments vip: List containing environments vip desired
to updated
:return: None |
def dropKey(self, key):
'''Drop an attribute/element/key-value pair from all the dictionaries.
If the dictionary key does not exist in a particular dictionary, then
that dictionary is left unchanged.
Side effect: if the key is a number and it matches a list (interpreted
as a di... | Drop an attribute/element/key-value pair from all the dictionaries.
If the dictionary key does not exist in a particular dictionary, then
that dictionary is left unchanged.
Side effect: if the key is a number and it matches a list (interpreted
as a dictionary), it will cause the "keys"... |
def fit(self, X, y=None, init=None):
"""
Computes the position of the points in the embedding space
Parameters
----------
X : array, shape=[n_samples, n_features], or [n_samples, n_samples] \
if dissimilarity='precomputed'
Input data.
... | Computes the position of the points in the embedding space
Parameters
----------
X : array, shape=[n_samples, n_features], or [n_samples, n_samples] \
if dissimilarity='precomputed'
Input data.
init : {None or ndarray, shape (n_samples,)}, optional
... |
def owned_expansions(self):
"""List of expansions owned by the player."""
owned = {}
for el in self.expansion_locations:
def is_near_to_expansion(t):
return t.position.distance_to(el) < self.EXPANSION_GAP_THRESHOLD
th = next((x for x in self.townhalls if... | List of expansions owned by the player. |
def annihilate(predicate: tuple, stack: tuple) -> tuple:
'''Squash and reduce the input stack.
Removes the elements of input that match predicate and only keeps the last
match at the end of the stack.
'''
extra = tuple(filter(lambda x: x not in predicate, stack))
head = reduce(lambda x, y: y if ... | Squash and reduce the input stack.
Removes the elements of input that match predicate and only keeps the last
match at the end of the stack. |
def followingPrefix(prefix):
"""Returns a String that sorts just after all Strings beginning with a prefix"""
prefixBytes = array('B', prefix)
changeIndex = len(prefixBytes) - 1
while (changeIndex >= 0 and prefixBytes[changeIndex] == 0xff ):
changeIndex = changeIndex - 1;
... | Returns a String that sorts just after all Strings beginning with a prefix |
def set_circuit_breakers(mv_grid, mode='load', debug=False):
""" Calculates the optimal position of a circuit breaker on all routes of mv_grid, adds and connects them to graph.
Args
----
mv_grid: MVGridDing0
Description#TODO
debug: bool, defaults to False
If True, information is p... | Calculates the optimal position of a circuit breaker on all routes of mv_grid, adds and connects them to graph.
Args
----
mv_grid: MVGridDing0
Description#TODO
debug: bool, defaults to False
If True, information is printed during process
Notes
-----
According to plan... |
def extract_run_id(key):
"""Extract date part from run id
Arguments:
key - full key name, such as shredded-archive/run=2012-12-11-01-31-33/
(trailing slash is required)
>>> extract_run_id('shredded-archive/run=2012-12-11-01-11-33/')
'shredded-archive/run=2012-12-11-01-11-33/'
>>> ext... | Extract date part from run id
Arguments:
key - full key name, such as shredded-archive/run=2012-12-11-01-31-33/
(trailing slash is required)
>>> extract_run_id('shredded-archive/run=2012-12-11-01-11-33/')
'shredded-archive/run=2012-12-11-01-11-33/'
>>> extract_run_id('shredded-archive/ru... |
def set_activate_user_form(self, card_id, **kwargs):
"""
设置开卡字段接口
详情请参考
https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1451025283
"6 激活会员卡" -> "6.2 一键激活" -> "步骤二:设置开卡字段接口"
参数示例:
{
"card_id": "pbLatjnrwUUdZI641gKdTMJzHGfc",
"service... | 设置开卡字段接口
详情请参考
https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1451025283
"6 激活会员卡" -> "6.2 一键激活" -> "步骤二:设置开卡字段接口"
参数示例:
{
"card_id": "pbLatjnrwUUdZI641gKdTMJzHGfc",
"service_statement": {
"name": "会员守则",
"url": "ht... |
def fcat(*fs):
"""Concatenate a sequence of farrays.
The variadic *fs* input is a homogeneous sequence of functions or arrays.
"""
items = list()
for f in fs:
if isinstance(f, boolfunc.Function):
items.append(f)
elif isinstance(f, farray):
items.extend(f.flat... | Concatenate a sequence of farrays.
The variadic *fs* input is a homogeneous sequence of functions or arrays. |
def artifact_filename(self):
"""Returns the canonical maven-style filename for an artifact pointed at by this coordinate.
:API: public
:rtype: string
"""
def maybe_compenent(component):
return '-{}'.format(component) if component else ''
return '{org}-{name}{rev}{classifier}.{ext}'.form... | Returns the canonical maven-style filename for an artifact pointed at by this coordinate.
:API: public
:rtype: string |
def set_presence(self, state, status={}, priority=0):
"""
Change the presence broadcast by the client.
:param state: New presence state to broadcast
:type state: :class:`aioxmpp.PresenceState`
:param status: New status information to broadcast
:type status: :class:`dict`... | Change the presence broadcast by the client.
:param state: New presence state to broadcast
:type state: :class:`aioxmpp.PresenceState`
:param status: New status information to broadcast
:type status: :class:`dict` or :class:`str`
:param priority: New priority for the resource
... |
def is_ancestor_of_bank(self, id_, bank_id):
"""Tests if an ``Id`` is an ancestor of a bank.
arg: id (osid.id.Id): an ``Id``
arg: bank_id (osid.id.Id): the ``Id`` of a bank
return: (boolean) - ``true`` if this ``id`` is an ancestor of
``bank_id,`` ``false`` otherw... | Tests if an ``Id`` is an ancestor of a bank.
arg: id (osid.id.Id): an ``Id``
arg: bank_id (osid.id.Id): the ``Id`` of a bank
return: (boolean) - ``true`` if this ``id`` is an ancestor of
``bank_id,`` ``false`` otherwise
raise: NotFound - ``bank_id`` is not found
... |
def get_clusters_representation(chromosome, count_clusters=None):
""" Convert chromosome to cluster representation:
chromosome : [0, 1, 1, 0, 2, 3, 3]
clusters: [[0, 3], [1, 2], [4], [5, 6]]
"""
if count_clusters is None:
count_clusters = ga_math.calc... | Convert chromosome to cluster representation:
chromosome : [0, 1, 1, 0, 2, 3, 3]
clusters: [[0, 3], [1, 2], [4], [5, 6]] |
def get_sections_2d_nts(self, sortby=None):
"""Get high GO IDs that are actually used to group current set of GO IDs."""
sections_2d_nts = []
for section_name, hdrgos_actual in self.get_sections_2d():
hdrgo_nts = self.gosubdag.get_nts(hdrgos_actual, sortby=sortby)
section... | Get high GO IDs that are actually used to group current set of GO IDs. |
def check_key(data_object, key, cardinal=False):
"""
Update the value of an index key by matching values or getting positionals.
"""
itype = (int, np.int32, np.int64)
if not isinstance(key, itype + (slice, tuple, list, np.ndarray)):
raise KeyError("Unknown key type {} for key {}".format(type... | Update the value of an index key by matching values or getting positionals. |
def text(self, path, wholetext=False, lineSep=None):
"""
Loads a text file stream and returns a :class:`DataFrame` whose schema starts with a
string column named "value", and followed by partitioned columns if there
are any.
The text files must be encoded as UTF-8.
By de... | Loads a text file stream and returns a :class:`DataFrame` whose schema starts with a
string column named "value", and followed by partitioned columns if there
are any.
The text files must be encoded as UTF-8.
By default, each line in the text file is a new row in the resulting DataFrame... |
def field_function(self, type_code, func_name):
"""Return the field function."""
assert func_name in ('to_json', 'from_json')
name = "field_%s_%s" % (type_code.lower(), func_name)
return getattr(self, name) | Return the field function. |
def script(name,
source,
saltenv='base',
args=None,
template=None,
exec_driver=None,
stdin=None,
python_shell=True,
output_loglevel='debug',
ignore_retcode=False,
use_vt=False,
keep_env=None):
''... | Run :py:func:`cmd.script <salt.modules.cmdmod.script>` within a container
.. note::
While the command is run within the container, it is initiated from the
host. Therefore, the PID in the return dict is from the host, not from
the container.
name
Container name or ID
sour... |
def _extract_models(cls, apis):
'''An helper function to extract all used models from the apis.'''
# TODO: This would probably be much better if the info would be
# extracted from the classes, rather than from the swagger
# representation...
models = set()
for api in apis... | An helper function to extract all used models from the apis. |
async def disconnect(self, requested=True):
"""
Disconnects this player from it's voice channel.
"""
if self.state == PlayerState.DISCONNECTING:
return
await self.update_state(PlayerState.DISCONNECTING)
if not requested:
log.debug(
... | Disconnects this player from it's voice channel. |
def download(self,age=None,metallicity=None,outdir=None,force=False):
"""
Check valid parameter range and download isochrones from:
http://stev.oapd.inaf.it/cgi-bin/cmd
"""
try:
from urllib.error import URLError
except ImportError:
from urllib2 imp... | Check valid parameter range and download isochrones from:
http://stev.oapd.inaf.it/cgi-bin/cmd |
def to_copy(self, column_names=None, selection=None, strings=True, virtual=False, selections=True):
"""Return a copy of the DataFrame, if selection is None, it does not copy the data, it just has a reference
:param column_names: list of column names, to copy, when None DataFrame.get_column_names(string... | Return a copy of the DataFrame, if selection is None, it does not copy the data, it just has a reference
:param column_names: list of column names, to copy, when None DataFrame.get_column_names(strings=strings, virtual=virtual) is used
:param selection: {selection}
:param strings: argument pass... |
def _get_button_label(self):
"""Gets Button label from user and returns string"""
dlg = wx.TextEntryDialog(self, _('Button label:'))
if dlg.ShowModal() == wx.ID_OK:
label = dlg.GetValue()
else:
label = ""
dlg.Destroy()
return label | Gets Button label from user and returns string |
def set_outputs(self, *outputs):
""" Set the outputs of the view
"""
self._outputs = OrderedDict()
for output in outputs:
out_name = None
type_or_serialize = None
if isinstance((list, tuple), output):
if len(output) == 1:
... | Set the outputs of the view |
def _PrintEventLabelsCounter(
self, event_labels_counter, session_identifier=None):
"""Prints the event labels counter.
Args:
event_labels_counter (collections.Counter): number of event tags per
label.
session_identifier (Optional[str]): session identifier.
"""
if not event_... | Prints the event labels counter.
Args:
event_labels_counter (collections.Counter): number of event tags per
label.
session_identifier (Optional[str]): session identifier. |
def create_contract(self, price=0, address=None, caller=None, balance=0, init=None, gas=None):
"""
Create a contract account. Sends a transaction to initialize the contract
:param address: the address of the new account, if known. If omitted, a new address will be generated as closely to the Ye... | Create a contract account. Sends a transaction to initialize the contract
:param address: the address of the new account, if known. If omitted, a new address will be generated as closely to the Yellow Paper as possible.
:param balance: the initial balance of the account in Wei
:param init: the ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.