Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
387,300 | def vms(nictag):
*
ret = {}
cmd = .format(nictag)
res = __salt__[](cmd)
retcode = res[]
if retcode != 0:
ret[] = res[] if in res else
else:
ret = res[].splitlines()
return ret | List all vms connect to nictag
nictag : string
name of nictag
CLI Example:
.. code-block:: bash
salt '*' nictagadm.vms admin |
387,301 | def getShocks(self):
super(self.__class__,self).getShocks()
newborns = self.t_age == 0
self.TranShkNow[newborns] = self.TranShkAggNow*self.wRteNow
self.PermShkNow[newborns] = self.PermShkAggNow
self.getUpdaters()
pLvlErrNew... | 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... |
387,302 | def verify_checksum(file_id, pessimistic=False, chunk_size=None, throws=True,
checksum_kwargs=None):
f = FileInstance.query.get(uuid.UUID(file_id))
if pessimistic:
f.clear_last_check()
db.session.commit()
f.verify_checksum(
progress_callback=progre... | Verify checksum of a file instance.
:param file_id: The file ID. |
387,303 | def save_file(self, filename = ):
filename = filename +
with open(filename, ) as f:
f.write(self.htmlcontent)
f.closed | save htmlcontent as .html file |
387,304 | def trades(self, cursor=None, order=, limit=10, sse=False):
return self.horizon.account_trades(
self.address, cursor=cursor, order=order, limit=limit, sse=sse) | 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 ... |
387,305 | def min_or(a, b, c, d, w):
m = (1 << (w - 1))
while m != 0:
if ((~a) & c & m) != 0:
temp = (a | m) & -m
if temp <= b:
a = temp
break
elif (a & (~c) & m) != 0:
temp = (c | m) & -m
... | 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 |
387,306 | def expand(self, basedir, config, sourcedir, targetdir, cwd):
expanded_basedir = os.path.expanduser(basedir)
expanded_config = os.path.expanduser(config)
expanded_sourcedir = os.path.expanduser(sourcedir)
expanded_targetdir = os.path.expanduser(targetdir)
... | 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 ... |
387,307 | def set_alias(self, alias_hosted_zone_id, alias_dns_name):
self.alias_hosted_zone_id = alias_hosted_zone_id
self.alias_dns_name = alias_dns_name | Make this an alias resource record set |
387,308 | def get_trackrs(self):
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. |
387,309 | def run(self, mod):
if not mod.body:
return
aliases = [ast.alias(py.builtin.builtins.__name__, "@py_builtins"),
ast.alias("dessert.rewrite", "@dessert_ar")]
expect_docstring = True
pos = 0
lineno = 0
f... | Find all assert statements in *mod* and rewrite them. |
387,310 | def translate_doc(self, d, field_mapping=None, map_identifiers=None, **kwargs):
if field_mapping is not None:
self.map_doc(d, field_mapping)
subject = self.translate_obj(d, M.SUBJECT)
obj = self.translate_obj(d, M.OBJECT)
if map_identifiers is not None:
... | Translate a solr document (i.e. a single result row) |
387,311 | def mod_watch(name, url=, timeout=180):
msg = __salt__[](name, url, timeout)
result = msg.startswith()
ret = {: name,
: result,
: {name: result},
: msg
}
return ret | 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... |
387,312 | def pathIndex(self, 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:
break
head, tail = os.path... | Return index of item with *path*. |
387,313 | def list_asgs(access_token, subscription_id, resource_group):
endpoint = .join([get_rm_endpoint(),
, subscription_id,
, resource_group,
,
, NETWORK_API])
return do_get(endpoint, access_token) | 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. |
387,314 | def _bind_parameters(operation, parameters):
string_parameters = {}
for (name, value) in iteritems(parameters):
if value is None:
string_parameters[name] =
elif isinstance(value, basestring):
string_parameters[name] = ""
else:
string_paramet... | Helper method that binds parameters to a SQL query. |
387,315 | def ets(self):
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 |
387,316 | def json_2_text(inp, out, verbose = False):
for root, dirs, filenames in os.walk(inp):
for f in filenames:
log = codecs.open(os.path.join(root, f), )
j_obj = json.load(log)
j_obj = json_format(j_obj)
textWriter(j_obj, out, ver... | 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 ... |
387,317 | def raise_error(error_type: str) -> None:
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. |
387,318 | def remove_scene(self, 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(False, 0, err_msg)
try:
... | remove a scene by Scene ID |
387,319 | def __set_title(self, value):
self._target.setPropertyValue(self._has_axis_title_property, True)
target = self._get_title_target()
target.setPropertyValue(, text_type(value)) | Sets title of this axis. |
387,320 | def check_process_counts(self):
LOGGER.debug()
for name in self.consumers:
processes_needed = self.process_spawn_qty(name)
if processes_needed:
LOGGER.info(,
processes_needed, name)
self.start_processes(name, pr... | Check for the minimum consumer process levels and start up new
processes needed. |
387,321 | def check_for_errors(self):
if not self.exceptions:
if not self.is_closed:
return
why = AMQPConnectionError()
self.exceptions.append(why)
self.set_state(self.CLOSED)
self.close()
raise self.exceptions[0] | Check Connection for errors.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:return: |
387,322 | def key_exists(hive, key, use_32bit_registry=False):
HKLMSOFTWARE\\Microsoft
local_hive = _to_unicode(hive)
local_key = _to_unicode(key)
registry = Registry()
try:
hkey = registry.hkeys[local_hive]
except KeyError:
raise CommandExecutionError(.format(local_hive))
access_mask... | 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... |
387,323 | def reset(self, indices=None):
if indices is None:
indices = np.arange(len(self._envs))
if self._blocking:
observs = [self._envs[index].reset() for index in indices]
else:
observs = [self._envs[index].reset(blocking=False) for index in indices]
observs = [observ() for observ in ... | Reset the environment and convert the resulting observation.
Args:
indices: The batch indices of environments to reset; defaults to all.
Returns:
Batch of observations. |
387,324 | def args(parsed_args, name=None):
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, , not files):
streams.append(clipboard_stream())
if get... | Interpret parsed args to streams |
387,325 | def molmz(df, noise=10000):
d = ((df.values > noise) * df.columns).max(axis=1)
return Trace(d, df.index, name=) | The mz of the molecular ion. |
387,326 | def get_current_user(self):
url = self.current_user_url
result = self.get(url)
return result | Get data from the current user endpoint |
387,327 | def write(gctoo, out_fname, data_null="NaN", metadata_null="-666", filler_null="-666", data_float_format="%.4f"):
if not out_fname.endswith(".gct"):
out_fname += ".gct"
f = open(out_fname, "w")
dims = [str(gctoo.data_df.shape[0]), str(gctoo.data_df.shape[1]),
str(gctoo.ro... | 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"... |
387,328 | def compile_insert(self, query, values):
table = self.wrap_table(query.from__)
if not isinstance(values, list):
values = [values]
if len(values) == 1:
return super(SQLiteQueryGrammar, self).compile_insert(query, values)
names = self.columnize(... | 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 |
387,329 | def to_fmt(self):
params = ""
txt = fmt.sep(" ", [])
name = self.show_name()
if name != "":
txt.lsdata.append(name)
tparams = []
if self.tparams is not None:
tparams = list(self.tparams)
if self.variadic:
tparams.append()
params = + ", ".join(tparams) +
... | Return an Fmt representation for pretty-printing |
387,330 | def get_phenotype(self, individual_id):
phenotype = 0
if individual_id in self.individuals:
phenotype = self.individuals[individual_id].phenotype
return phenotype | 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 |
387,331 | def read(database, table, key):
with database.snapshot() as snapshot:
result = snapshot.execute_sql( %
(table, key))
for row in result:
key = row[0]
for i in range(NUM_FIELD):
field = row[i + 1] | Does a single read operation. |
387,332 | def parse_yaml(self, y):
self.connector_id = y[]
self.name = y[]
if in y:
self.trans_method = y[]
else:
self.trans_method =
if RTS_EXT_NS_YAML + in y:
self.comment = y[RTS_EXT_NS_YAML + ]
else:
self.comment =
... | Parse a YAML specification of a service port connector into this
object. |
387,333 | def trigger(self, id, **kwargs):
kwargs[] = True
if kwargs.get():
return self.trigger_with_http_info(id, **kwargs)
else:
(data) = self.trigger_with_http_info(id, **kwargs)
return data | 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... |
387,334 | def lock_file(path, maxdelay=.1, lock_cls=LockFile, timeout=10.0):
lock = lock_cls(path)
max_t = time.time() + timeout
while True:
if time.time() >= max_t:
raise LockTimeout("Timeout waiting to acquire lock for %s" % (path,))
try:
lock.acquire(timeout=0)
... | Cooperative file lock. Uses `lockfile.LockFile` polling under the hood.
`maxdelay` defines the interval between individual polls. |
387,335 | def write_markdown_to_file(self, f):
print("---", file=f)
print("---", file=f)
print("<!-- This file is machine generated: DO NOT EDIT! -->", file=f)
print("", file=f)
print("
if self._prefix:
print(self._prefix, file=f)
print("[TOC]", file=f)
print("", file=f)
i... | Prints this library to file `f`.
Args:
f: File to write to.
Returns:
Dictionary of documented members. |
387,336 | def show_replace(self):
self.show(hide_replace=False)
for widget in self.replace_widgets:
widget.show() | Show replace widgets |
387,337 | def extension (network, session, version, scn_extension, start_snapshot,
end_snapshot, **kwargs):
if version is None:
ormcls_prefix =
else:
ormcls_prefix =
scenario = NetworkScenario(session,
version = version,
... | 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... |
387,338 | def get_document_models():
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. |
387,339 | def parse_seconds(value):
svalue = str(value)
colons = svalue.count()
if colons == 2:
hours, minutes, seconds = [int(v) for v in svalue.split()]
elif colons == 1:
hours, minutes = [int(v) for v in svalue.split()]
seconds = 0
elif colon... | Parse string into Seconds instances.
Handled formats:
HH:MM:SS
HH:MM
SS |
387,340 | def get_resource_uri(self, obj):
url = % (
self.api_version,
getattr(
self, ,
self.Meta.model._meta.model_name
)
)
return reverse(url, request=self.context.get(, None), kwargs={
self.lookup_field: getattr(... | Return the uri of the given object. |
387,341 | def get_orderbook(self):
if self in self.parent.books.keys():
return self.parent.books[self]
return {
"bid": [0], "bidsize": [0],
"ask": [0], "asksize": [0]
} | Get orderbook for the instrument
:Retruns:
orderbook : dict
orderbook dict for the instrument |
387,342 | def _match_data_to_parameter(cls, data):
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 |
387,343 | def absent(email, profile="splunk", **kwargs):
example@domain.comexampleuser
user_identity = kwargs.get()
ret = {
: user_identity,
: {},
: None,
: .format(user_identity)
}
target = __salt__[](email, profile=profile)
if not target:
ret[] = .format(user_i... | 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
... |
387,344 | def save_new_environment(name, datadir, srcdir, ckan_version,
deploy_target=None, always_prod=False):
with open(datadir + , ) as f:
f.write()
cp = ConfigParser.SafeConfigParser()
cp.read(srcdir + )
if not cp.has_section():
cp.add_section()
cp.set(, , name)
cp.set(... | Save an environment's configuration to the source dir and data dir |
387,345 | def count_curves(self, keys=None, alias=None):
if keys is None:
keys = [k for k, v in self.data.items() if isinstance(v, Curve)]
else:
keys = utils.flatten_list(keys)
return len(list(filter(None, [self.get_mnemonic(k, alias=alias) for k in keys]))) | 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. |
387,346 | def save_as(self, new_filename):
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. |
387,347 | def wipe_cfg_vals_from_git_cfg(*cfg_opts):
for cfg_key_suffix in cfg_opts:
cfg_key = f
cmd = "git", "config", "--local", "--unset-all", cfg_key
subprocess.check_call(cmd, stderr=subprocess.STDOUT) | Remove a set of options from Git config. |
387,348 | def hkeys(self, name, key_start, key_end, limit=10):
limit = get_positive_integer(, limit)
return self.execute_command(, name, key_start, key_end, limit) | 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... |
387,349 | def get_string_from_data(self, offset, data):
s = self.get_bytes_from_data(offset, data)
end = s.find(b)
if end >= 0:
s = s[:end]
return s | Get an ASCII string from data. |
387,350 | def _add_encoded(self, encoded):
if self.public_key != encoded.public_key:
raise ValueError("Attempted to add numbers encoded against "
"different public keys!")
a, b = self, encoded
if a.exponent > b.exponent:
a = self.decr... | 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... |
387,351 | def msg_curse(self, args=None, max_width=None):
ret = []
if args.disable_process:
msg = "PROCESSES DISABLED (press to display)"
ret.append(self.curse_add_line(msg))
return ret
if not self.stats:
return ret
... | Return the dict to display in the curse interface. |
387,352 | def _release_info():
pypi_url =
headers = {
: ,
}
request = urllib.Request(pypi_url, headers=headers)
response = urllib.urlopen(request).read().decode()
data = json.loads(response)
return data | Check latest fastfood release info from PyPI. |
387,353 | def sync_matchers(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
**
ret = _sync(, saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret | .. 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
... |
387,354 | def pvariance(data, mu=None):
if iter(data) is data:
data = list(data)
n = len(data)
if n < 1:
raise StatisticsError()
ss = _ss(data, mu)
return ss / n | 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... |
387,355 | def _create_update_tracking_related_event(instance):
events = {}
for field, related_fields in instance._tracked_related_fields.items():
if not isinstance(instance._meta.get_field(field), ManyToManyField):
if isinstance(instance._meta.get_field(field), ForeignKey):
... | Create a TrackingEvent and TrackedFieldModification for an UPDATE event
for each related model. |
387,356 | def transformer_base_v1():
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.
hparams.optimizer_adam_epsilon = 1e-9
hparams.learning_rate_schedule = "legacy"
hparams.learning... | Set of hyperparameters. |
387,357 | def str_is_well_formed(xml_str):
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. |
387,358 | def resolve_addresses(self, node):
prop_alignment = self.alignment_stack[-1]
if prop_alignment is None:
prop_alignment = 1
prev_node = None
for child_node in node.children(skip_not_present=False):
if not isinstance(child_n... | Resolve addresses of children of Addrmap and Regfile components |
387,359 | def GetTSKFileByPathSpec(self, path_spec):
inode = getattr(path_spec, , None)
location = getattr(path_spec, , None)
if inode is not None:
tsk_file = self._tsk_file_system.open_meta(inode=inode)
elif location is not None:
tsk_file = self._tsk_file_system.open(location)
els... | 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. |
387,360 | def get_rdataset(self, rdclass, rdtype, covers=dns.rdatatype.NONE,
create=False):
try:
rds = self.find_rdataset(rdclass, rdtype, covers, create)
except KeyError:
rds = None
return rds | 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... |
387,361 | def info(torrent_path):
my_torrent = Torrent.from_file(torrent_path)
size = my_torrent.total_size
click.secho( % my_torrent.name, fg=)
click.secho()
for file_tuple in my_torrent.files:
click.secho(file_tuple.name)
click.secho( % my_torrent.info_hash, fg=)
click.secho( % (hum... | Print out information from .torrent file. |
387,362 | def fromutc(self, dt):
if dt.tzinfo is not None and dt.tzinfo is not self:
raise ValueError()
return (dt + self._utcoffset).replace(tzinfo=self) | See datetime.tzinfo.fromutc |
387,363 | def get_rate_limits():
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_dict(v)
for k, v in six.iteritems(data.to_dict().get... | Retrieve status (and optionally) version from the API. |
387,364 | def monitoring_problems(self):
if self.app.type != :
return {: u,
: u"This service is only available for a scheduler daemon"}
res = self.identity()
res.update(self.app.get_monitoring_problems())
return res | Get Alignak scheduler monitoring status
Returns an object with the scheduler livesynthesis
and the known problems
:return: scheduler live synthesis
:rtype: dict |
387,365 | def cublasZhpmv(handle, uplo, n, alpha, AP, x, incx, beta, y, incy):
status = _libcublas.cublasZhpmv_v2(handle,
_CUBLAS_FILL_MODE[uplo],
n, ctypes.byref(cuda.cuDoubleComplex(alpha.real,
... | Matrix-vector product for Hermitian-packed matrix. |
387,366 | def run_compute(self, compute=None, model=None, detach=False,
times=None, **kwargs):
if isinstance(detach, str):
self.as_client(server=detach)
self.run_compute(compute=compute, model=model, time=time, **kwargs)
self.as_client(False)
... | 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... |
387,367 | def get(key, default=-1):
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. |
387,368 | def can_see_members(self, user):
if self.privacy_policy == PrivacyPolicy.PUBLIC:
return True
elif self.privacy_policy == PrivacyPolicy.MEMBERS:
return self.is_member(user) or self.is_admin(user)
elif self.privacy_policy == PrivacyPolicy.ADMINS:
return... | Determine if given user can see other group members.
:param user: User to be checked.
:returns: True or False. |
387,369 | def assemble_oligos(dna_list, reference=None):
t assemble for any reason.
:returns: A single assembled DNA sequence
:rtype: coral.DNA
ends on the assembly
match_3 = [bind_unique(seq, dna_list, right=True) for i, seq in
enumerate(dna_list)]
flip = Fals... | 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... |
387,370 | def bar(self, width, **_):
width -= self._width_offset
self._position += self._direction
if self._position <= 0 and self._direction < 0:
self._position = 0
self._direction = 1
elif self._position > width:
self._position = width - 1
... | Returns the completed progress bar. Every time this is called the animation moves.
Positional arguments:
width -- the width of the entire bar (including borders). |
387,371 | def taskfile_user_data(file_, role):
if role == QtCore.Qt.DisplayRole or role == QtCore.Qt.EditRole:
return file_.user.username | 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 |
387,372 | def _get_requirement_attr(self, attr, path):
for req_file in self.requirements:
if path.strip("/") == req_file.path.strip("/"):
return getattr(req_file, attr)
return getattr(self, attr) | 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 |
387,373 | def update(self, environments):
data = {: environments}
environments_ids = [str(env.get()) for env in environments]
uri = % .join(environments_ids)
return super(ApiEnvironmentVip, self).put(uri, data) | Method to update environments vip
:param environments vip: List containing environments vip desired
to updated
:return: None |
387,374 | def dropKey(self, key):
JimLarryJoeJimzam99Bill
result = []
for row in self.table:
result.append(internal.remove_member(row, key))
self.table = result
return self | 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"... |
387,375 | def fit(self, X, y=None, init=None):
self.fit_transform(X, init=init)
return self | 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
... |
387,376 | def owned_expansions(self):
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 is_near_to_expansion(x)), None)
... | List of expansions owned by the player. |
387,377 | def annihilate(predicate: tuple, stack: tuple) -> tuple:
extra = tuple(filter(lambda x: x not in predicate, stack))
head = reduce(lambda x, y: y if y in predicate else x, stack, None)
return extra + (head,) if head else extra | 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. |
387,378 | def followingPrefix(prefix):
prefixBytes = array(, prefix)
changeIndex = len(prefixBytes) - 1
while (changeIndex >= 0 and prefixBytes[changeIndex] == 0xff ):
changeIndex = changeIndex - 1;
if(changeIndex < 0):
return None
newBytes = array(, prefi... | Returns a String that sorts just after all Strings beginning with a prefix |
387,379 | def set_circuit_breakers(mv_grid, mode=, debug=False):
cos_phi_load = cfg_ding0.get(, )
cos_phi_feedin = cfg_ding0.get(, )
for ring, circ_breaker in zip(mv_grid.rings_nodes(include_root_node=False), mv_grid.circuit_breakers()):
nodes_peak_load = []
nodes_peak_generation = [... | 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... |
387,380 | def extract_run_id(key):
filename = key.split()[-2]
run_id = filename.lstrip()
try:
datetime.strptime(run_id, )
return key
except ValueError:
return None | 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... |
387,381 | def set_activate_user_form(self, card_id, **kwargs):
kwargs[] = card_id
return self._post(
,
data=kwargs
) | 设置开卡字段接口
详情请参考
https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1451025283
"6 激活会员卡" -> "6.2 一键激活" -> "步骤二:设置开卡字段接口"
参数示例:
{
"card_id": "pbLatjnrwUUdZI641gKdTMJzHGfc",
"service_statement": {
"name": "会员守则",
"url": "ht... |
387,382 | def fcat(*fs):
items = list()
for f in fs:
if isinstance(f, boolfunc.Function):
items.append(f)
elif isinstance(f, farray):
items.extend(f.flat)
else:
raise TypeError("expected Function or farray")
return farray(items) | Concatenate a sequence of farrays.
The variadic *fs* input is a homogeneous sequence of functions or arrays. |
387,383 | def artifact_filename(self):
def maybe_compenent(component):
return .format(component) if component else
return .format(org=self.org,
name=self.name,
rev=maybe_compenent(self.rev),
... | Returns the canonical maven-style filename for an artifact pointed at by this coordinate.
:API: public
:rtype: string |
387,384 | def set_presence(self, state, status={}, priority=0):
if not isinstance(priority, numbers.Integral):
raise TypeError(
"invalid priority: got {}, expected integer".format(
type(priority)
)
)
if not isinstance(state, ai... | 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
... |
387,385 | def is_ancestor_of_bank(self, id_, bank_id):
if self._catalog_session is not None:
return self._catalog_session.is_ancestor_of_catalog(id_=id_, catalog_id=bank_id)
return self._hierarchy_session.is_ancestor(id_=id_, ancestor_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`` otherwise
raise: NotFound - ``bank_id`` is not found
... |
387,386 | def get_clusters_representation(chromosome, count_clusters=None):
if count_clusters is None:
count_clusters = ga_math.calc_count_centers(chromosome)
clusters = [[] for _ in range(count_clusters)]
for _idx_data in range(len(chromosome)):
clust... | Convert chromosome to cluster representation:
chromosome : [0, 1, 1, 0, 2, 3, 3]
clusters: [[0, 3], [1, 2], [4], [5, 6]] |
387,387 | def get_sections_2d_nts(self, sortby=None):
sections_2d_nts = []
for section_name, hdrgos_actual in self.get_sections_2d():
hdrgo_nts = self.gosubdag.get_nts(hdrgos_actual, sortby=sortby)
sections_2d_nts.append((section_name, hdrgo_nts))
return sections_2d_nts | Get high GO IDs that are actually used to group current set of GO IDs. |
387,388 | def check_key(data_object, key, cardinal=False):
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(key), key))
keys = data_object.index.values
if cardinal and data_object._cardinal ... | Update the value of an index key by matching values or getting positionals. |
387,389 | def text(self, path, wholetext=False, lineSep=None):
self._set_opts(wholetext=wholetext, lineSep=lineSep)
if isinstance(path, basestring):
return self._df(self._jreader.text(path))
else:
raise TypeError("path can be only a single string") | 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... |
387,390 | def field_function(self, type_code, func_name):
assert func_name in (, )
name = "field_%s_%s" % (type_code.lower(), func_name)
return getattr(self, name) | Return the field function. |
387,391 | def script(name,
source,
saltenv=,
args=None,
template=None,
exec_driver=None,
stdin=None,
python_shell=True,
output_loglevel=,
ignore_retcode=False,
use_vt=False,
keep_env=None):
s utils.vt to s... | 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... |
387,392 | def _extract_models(cls, apis):
models = set()
for api in apis:
for op in api.get(, []):
models.add(op[])
for param in op.get(, []):
models.add(param.get(, ))
for msg in op[]:
... | An helper function to extract all used models from the apis. |
387,393 | async def disconnect(self, requested=True):
if self.state == PlayerState.DISCONNECTING:
return
await self.update_state(PlayerState.DISCONNECTING)
if not requested:
log.debug(
f"Forcing player disconnect for guild {self.channel.guild.id}"
... | Disconnects this player from it's voice channel. |
387,394 | def download(self,age=None,metallicity=None,outdir=None,force=False):
try:
from urllib.error import URLError
except ImportError:
from urllib2 import URLError
if age is None: age = float(self.age)
if metallicity is None: metallicity = float(self.metallici... | Check valid parameter range and download isochrones from:
http://stev.oapd.inaf.it/cgi-bin/cmd |
387,395 | def to_copy(self, column_names=None, selection=None, strings=True, virtual=False, selections=True):
if column_names:
column_names = _ensure_strings_from_expressions(column_names)
df = vaex.from_items(*self.to_items(column_names=column_names, selection=selection, strings=strings, vir... | 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... |
387,396 | def _get_button_label(self):
dlg = wx.TextEntryDialog(self, _())
if dlg.ShowModal() == wx.ID_OK:
label = dlg.GetValue()
else:
label = ""
dlg.Destroy()
return label | Gets Button label from user and returns string |
387,397 | def set_outputs(self, *outputs):
self._outputs = OrderedDict()
for output in outputs:
out_name = None
type_or_serialize = None
if isinstance((list, tuple), output):
if len(output) == 1:
out_name = output[0]
... | Set the outputs of the view |
387,398 | def _PrintEventLabelsCounter(
self, event_labels_counter, session_identifier=None):
if not event_labels_counter:
return
title =
if session_identifier:
title = .format(title, session_identifier)
table_view = views.ViewsFactory.GetTableView(
self._views_format_type,
... | Prints the event labels counter.
Args:
event_labels_counter (collections.Counter): number of event tags per
label.
session_identifier (Optional[str]): session identifier. |
387,399 | def create_contract(self, price=0, address=None, caller=None, balance=0, init=None, gas=None):
expected_address = self.create_account(self.new_address(sender=caller))
if address is None:
address = expected_address
elif caller is not None and address != expected_address:
... | 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.