code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def import_fasst(self, checked=False, test_fasst=None, test_annot=None):
"""Action: import from FASST .mat file"""
if self.parent.info.filename is not None:
fasst_file = splitext(self.parent.info.filename)[0] + '.mat'
annot_file = splitext(self.parent.info.filename)[0] + '_score... | Action: import from FASST .mat file |
def assert_title(self, title, **kwargs):
"""
Asserts that the page has the given title.
Args:
title (str | RegexObject): The string or regex that the title should match.
**kwargs: Arbitrary keyword arguments for :class:`TitleQuery`.
Returns:
True
... | Asserts that the page has the given title.
Args:
title (str | RegexObject): The string or regex that the title should match.
**kwargs: Arbitrary keyword arguments for :class:`TitleQuery`.
Returns:
True
Raises:
ExpectationNotMet: If the assertion... |
def create_module_page(mod, dest_path, force=False):
"Create the documentation notebook for module `mod_name` in path `dest_path`"
nb = get_empty_notebook()
mod_name = mod.__name__
strip_name = strip_fastai(mod_name)
init_cell = [get_md_cell(f'## Title for {strip_name} (use plain english, not module... | Create the documentation notebook for module `mod_name` in path `dest_path` |
def save(self):
"""Save this entry.
If the entry does not have an :attr:`id`, a new id will be assigned,
and the :attr:`id` attribute set accordingly.
Pre-save processing of the fields saved can be done by
overriding the :meth:`prepare_save` method.
Additional actions ... | Save this entry.
If the entry does not have an :attr:`id`, a new id will be assigned,
and the :attr:`id` attribute set accordingly.
Pre-save processing of the fields saved can be done by
overriding the :meth:`prepare_save` method.
Additional actions to be done after the save o... |
def hgnc_genes(self, hgnc_symbol, build='37', search=False):
"""Fetch all hgnc genes that match a hgnc symbol
Check both hgnc_symbol and aliases
Args:
hgnc_symbol(str)
build(str): The build in which to search
search(bool): if partial sear... | Fetch all hgnc genes that match a hgnc symbol
Check both hgnc_symbol and aliases
Args:
hgnc_symbol(str)
build(str): The build in which to search
search(bool): if partial searching should be used
Returns:
result() |
def stop(self, container, instances=None, map_name=None, **kwargs):
"""
Stops instances for a container configuration.
:param container: Container name.
:type container: unicode | str
:param instances: Instance names to stop. If not specified, will stop all instances as specifie... | Stops instances for a container configuration.
:param container: Container name.
:type container: unicode | str
:param instances: Instance names to stop. If not specified, will stop all instances as specified in the
configuration (or just one default instance).
:type instances:... |
def standardizeMapName(mapName):
"""pretty-fy the name for pysc2 map lookup"""
#print("foreignName: %s (%s)"%(mapName, mapName in c.mapNameTranslations))
#if mapName in c.mapNameTranslations:
# return c.mapNameTranslations[mapName]
newName = os.path.basename(mapName)
newName = newName.split(... | pretty-fy the name for pysc2 map lookup |
def _convert_from_thrift_binary_annotations(self, thrift_binary_annotations):
"""Accepts a thrift decoded binary annotation and converts it
to a v1 binary annotation.
"""
tags = {}
local_endpoint = None
remote_endpoint = None
for binary_annotation in thrift_binar... | Accepts a thrift decoded binary annotation and converts it
to a v1 binary annotation. |
def network_interfaces_list_all(**kwargs):
'''
.. versionadded:: 2019.2.0
List all network interfaces within a subscription.
CLI Example:
.. code-block:: bash
salt-call azurearm_network.network_interfaces_list_all
'''
result = {}
netconn = __utils__['azurearm.get_client']('n... | .. versionadded:: 2019.2.0
List all network interfaces within a subscription.
CLI Example:
.. code-block:: bash
salt-call azurearm_network.network_interfaces_list_all |
def dispatch_request(self, *args, **kwargs):
"""Dispatch the request.
Its the actual ``view`` flask will use.
"""
if request.method in ('POST', 'PUT'):
return_url, context = self.post(*args, **kwargs)
if return_url is not None:
return redirect(retu... | Dispatch the request.
Its the actual ``view`` flask will use. |
def write_into(self, block, level=0):
"""Append this block to another one, passing all dependencies"""
for line, l in self._lines:
block.write_line(line, level + l)
for name, obj in _compat.iteritems(self._deps):
block.add_dependency(name, obj) | Append this block to another one, passing all dependencies |
def create(self, template=None, flags=0, args=()):
"""
Create a new rootfs for the container.
"template" if passed must be a valid template name.
"flags" (optional) is an integer representing the optional
create flags to be passed.
"args" (optional)... | Create a new rootfs for the container.
"template" if passed must be a valid template name.
"flags" (optional) is an integer representing the optional
create flags to be passed.
"args" (optional) is a tuple of arguments to pass to the
template. It can also b... |
def get_hla_truthset(data):
"""Retrieve expected truth calls for annotating HLA called output.
"""
val_csv = tz.get_in(["config", "algorithm", "hlavalidate"], data)
out = {}
if val_csv and utils.file_exists(val_csv):
with open(val_csv) as in_handle:
reader = csv.reader(in_handle)... | Retrieve expected truth calls for annotating HLA called output. |
def lookup_tf(self, h):
'''Get stream IDs and term frequencies for a single hash.
This yields pairs of strings that can be retrieved using
:func:`streamcorpus_pipeline._kvlayer.get_kvlayer_stream_item`
and the corresponding term frequency.
..see:: :meth:`lookup`
'''
... | Get stream IDs and term frequencies for a single hash.
This yields pairs of strings that can be retrieved using
:func:`streamcorpus_pipeline._kvlayer.get_kvlayer_stream_item`
and the corresponding term frequency.
..see:: :meth:`lookup` |
def find_profile_dir_by_name(cls, ipython_dir, name=u'default', config=None):
"""Find an existing profile dir by profile name, return its ProfileDir.
This searches through a sequence of paths for a profile dir. If it
is not found, a :class:`ProfileDirError` exception will be raised.
T... | Find an existing profile dir by profile name, return its ProfileDir.
This searches through a sequence of paths for a profile dir. If it
is not found, a :class:`ProfileDirError` exception will be raised.
The search path algorithm is:
1. ``os.getcwdu()``
2. ``ipython_dir``
... |
def is_same_address(addr1, addr2):
"""
Where the two addresses are in the host:port
Returns true if ports are equals and hosts are the same using is_same_host
"""
hostport1 = addr1.split(":")
hostport2 = addr2.split(":")
return (is_same_host(hostport1[0], hostport2[0]) and
hostp... | Where the two addresses are in the host:port
Returns true if ports are equals and hosts are the same using is_same_host |
def search_regexp(self):
"""
Define the regexp used for the search
"""
if ((self.season == "") and (self.episode == "")):
regexp = '^%s.*' % self.title.lower()
elif (self.episode == ""):
regexp = '^%s.*(s[0]*%s|season[\s\_\-\.]*%s).*' % (self.title.lower()... | Define the regexp used for the search |
def clear_attributes(self):
"""
Remove the record_dict attribute from the object, as SeqRecords are not JSON-serializable. Also remove
the contig_lengths and longest_contig attributes, as they are large lists that make the .json file ugly
"""
for sample in self.metadata:
... | Remove the record_dict attribute from the object, as SeqRecords are not JSON-serializable. Also remove
the contig_lengths and longest_contig attributes, as they are large lists that make the .json file ugly |
def setup_sensors(self):
"""Setup some server sensors."""
self._add_result = Sensor.float("add.result",
"Last ?add result.", "", [-10000, 10000])
self._add_result.set_value(0, Sensor.UNREACHABLE)
self._time_result = Sensor.timestamp("time.result",
"Last ?time res... | Setup some server sensors. |
def filter_entries(self, request_type=None, content_type=None,
status_code=None, http_version=None, regex=True):
"""
Returns a ``list`` of entry objects based on the filter criteria.
:param request_type: ``str`` of request type (i.e. - GET or POST)
:param content_... | Returns a ``list`` of entry objects based on the filter criteria.
:param request_type: ``str`` of request type (i.e. - GET or POST)
:param content_type: ``str`` of regex to use for finding content type
:param status_code: ``int`` of the desired status code
:param http_version: ``str`` o... |
def do(self, changes, task_handle=taskhandle.NullTaskHandle()):
"""Apply the changes in a `ChangeSet`
Most of the time you call this function for committing the
changes for a refactoring.
"""
self.history.do(changes, task_handle=task_handle) | Apply the changes in a `ChangeSet`
Most of the time you call this function for committing the
changes for a refactoring. |
def spher2cart(rho, theta, phi):
"""Spherical to Cartesian coordinate conversion."""
st = np.sin(theta)
sp = np.sin(phi)
ct = np.cos(theta)
cp = np.cos(phi)
rhost = rho * st
x = rhost * cp
y = rhost * sp
z = rho * ct
return np.array([x, y, z]) | Spherical to Cartesian coordinate conversion. |
def _set_intf_type(self, v, load=False):
"""
Setter method for intf_type, mapped from YANG variable /logical_interface_state/main_interface_physical/intf_type (intf-type)
If this variable is read-only (config: false) in the
source YANG file, then _set_intf_type is considered as a private
method. Bac... | Setter method for intf_type, mapped from YANG variable /logical_interface_state/main_interface_physical/intf_type (intf-type)
If this variable is read-only (config: false) in the
source YANG file, then _set_intf_type is considered as a private
method. Backends looking to populate this variable should
do... |
def collection(name=None):
"""Render the collection page.
It renders it either with a collection specific template (aka
collection_{collection_name}.html) or with the default collection
template (collection.html).
"""
if name is None:
collection = Collection.query.get_or_404(1)
else... | Render the collection page.
It renders it either with a collection specific template (aka
collection_{collection_name}.html) or with the default collection
template (collection.html). |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'name') and self.name is not None:
_dict['name'] = self.name
if hasattr(self, 'role') and self.role is not None:
_dict['role'] = self.role
return _dict | Return a json dictionary representing this model. |
def selfSignCert(self, cert, pkey):
'''
Self-sign a certificate.
Args:
cert (OpenSSL.crypto.X509): The certificate to sign.
pkey (OpenSSL.crypto.PKey): The PKey with which to sign the certificate.
Examples:
Sign a given certificate with a given priva... | Self-sign a certificate.
Args:
cert (OpenSSL.crypto.X509): The certificate to sign.
pkey (OpenSSL.crypto.PKey): The PKey with which to sign the certificate.
Examples:
Sign a given certificate with a given private key:
cdir.selfSignCert(mycert, myoth... |
def get_repository(self, repository_id=None):
"""Gets the ``Repository`` specified by its ``Id``.
In plenary mode, the exact ``Id`` is found or a ``NotFound``
results. Otherwise, the returned ``Repository`` may have a
different ``Id`` than requested, such as the case where a
dup... | Gets the ``Repository`` specified by its ``Id``.
In plenary mode, the exact ``Id`` is found or a ``NotFound``
results. Otherwise, the returned ``Repository`` may have a
different ``Id`` than requested, such as the case where a
duplicate ``Id`` was assigned to a ``Repository`` and retain... |
def to_special_value(self, value):
"""
Return proper spdx term or Literal
"""
if isinstance(value, utils.NoAssert):
return self.spdx_namespace.noassertion
elif isinstance(value, utils.SPDXNone):
return self.spdx_namespace.none
else:
ret... | Return proper spdx term or Literal |
def save_project(self, project, filename=''):
r"""
Saves given Project to a 'pnm' file
This will include all of associated objects, including algorithms.
Parameters
----------
project : OpenPNM Project
The project to save.
filename : string, optiona... | r"""
Saves given Project to a 'pnm' file
This will include all of associated objects, including algorithms.
Parameters
----------
project : OpenPNM Project
The project to save.
filename : string, optional
If no filename is given, the given proje... |
def calculate_limits(array_dict, method='global', percentiles=None, limit=()):
"""
Calculate limits for a group of arrays in a flexible manner.
Returns a dictionary of calculated (vmin, vmax), with the same keys as
`array_dict`.
Useful for plotting heatmaps of multiple datasets, and the vmin/vmax ... | Calculate limits for a group of arrays in a flexible manner.
Returns a dictionary of calculated (vmin, vmax), with the same keys as
`array_dict`.
Useful for plotting heatmaps of multiple datasets, and the vmin/vmax values
of the colormaps need to be matched across all (or a subset) of heatmaps.
P... |
def create(cls, tx_signers, recipients, metadata=None, asset=None):
"""A simple way to generate a `CREATE` transaction.
Note:
This method currently supports the following Cryptoconditions
use cases:
- Ed25519
- ThresholdSha256
... | A simple way to generate a `CREATE` transaction.
Note:
This method currently supports the following Cryptoconditions
use cases:
- Ed25519
- ThresholdSha256
Additionally, it provides support for the following BigchainDB... |
def read_igpar(self):
"""
Renders accessible:
er_ev = e<r>_ev (dictionary with Spin.up/Spin.down as keys)
er_bp = e<r>_bp (dictionary with Spin.up/Spin.down as keys)
er_ev_tot = spin up + spin down summed
er_bp_tot = spin up + spin down summed
... | Renders accessible:
er_ev = e<r>_ev (dictionary with Spin.up/Spin.down as keys)
er_bp = e<r>_bp (dictionary with Spin.up/Spin.down as keys)
er_ev_tot = spin up + spin down summed
er_bp_tot = spin up + spin down summed
p_elc = spin up + spin down summed
... |
def num_pending(self, work_spec_name):
'''Get the number of pending work units for some work spec.
These are work units that some worker is currently working on
(hopefully; it could include work units assigned to workers that
died and that have not yet expired).
'''
ret... | Get the number of pending work units for some work spec.
These are work units that some worker is currently working on
(hopefully; it could include work units assigned to workers that
died and that have not yet expired). |
def _set_bfd_session_setup_delay(self, v, load=False):
"""
Setter method for bfd_session_setup_delay, mapped from YANG variable /rbridge_id/bfd_session_setup_delay (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_bfd_session_setup_delay is considered as a priv... | Setter method for bfd_session_setup_delay, mapped from YANG variable /rbridge_id/bfd_session_setup_delay (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_bfd_session_setup_delay is considered as a private
method. Backends looking to populate this variable should
... |
def create(self):
"""
Creates the full project
"""
# create virtualenv
self.create_virtualenv()
# create project
self.create_project()
# generate uwsgi script
self.create_uwsgi_script()
# generate nginx config
self.create_nginx_con... | Creates the full project |
def _set_isis_state(self, v, load=False):
"""
Setter method for isis_state, mapped from YANG variable /isis_state (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_isis_state is considered as a private
method. Backends looking to populate this variable shou... | Setter method for isis_state, mapped from YANG variable /isis_state (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_isis_state is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_isis_state() dir... |
def _GetStat(self):
"""Retrieves information about the file entry.
Returns:
VFSStat: a stat object.
"""
stat_object = super(LVMFileEntry, self)._GetStat()
if self._vslvm_logical_volume is not None:
stat_object.size = self._vslvm_logical_volume.size
return stat_object | Retrieves information about the file entry.
Returns:
VFSStat: a stat object. |
def _increment(self, what, host):
''' helper function to bump a statistic '''
self.processed[host] = 1
prev = (getattr(self, what)).get(host, 0)
getattr(self, what)[host] = prev+1 | helper function to bump a statistic |
def Boolean():
"""
Creates a validator that attempts to convert the given value to a boolean
or raises an error. The following rules are used:
``None`` is converted to ``False``.
``int`` values are ``True`` except for ``0``.
``str`` values converted in lower- and uppercase:
* ``y, yes, t... | Creates a validator that attempts to convert the given value to a boolean
or raises an error. The following rules are used:
``None`` is converted to ``False``.
``int`` values are ``True`` except for ``0``.
``str`` values converted in lower- and uppercase:
* ``y, yes, t, true``
* ``n, no, f, ... |
def asyncPipeFetch(context=None, _INPUT=None, conf=None, **kwargs):
"""A source that asynchronously fetches and parses one or more feeds to
return the feed entries. Loopable.
Parameters
----------
context : pipe2py.Context object
_INPUT : asyncPipe like object (twisted Deferred iterable of item... | A source that asynchronously fetches and parses one or more feeds to
return the feed entries. Loopable.
Parameters
----------
context : pipe2py.Context object
_INPUT : asyncPipe like object (twisted Deferred iterable of items)
conf : {
'URL': [
{'type': 'url', 'value': <url1... |
def sample_from_proposal(self, A: pd.DataFrame) -> None:
""" Sample a new transition matrix from the proposal distribution,
given a current candidate transition matrix. In practice, this amounts
to the in-place perturbation of an element of the transition matrix
currently being used by t... | Sample a new transition matrix from the proposal distribution,
given a current candidate transition matrix. In practice, this amounts
to the in-place perturbation of an element of the transition matrix
currently being used by the sampler.
Args |
def _apply_correction_on_genes(genes,
pathway_column_names,
pathway_definitions):
"""Helper function to create the gene-to-pathway
membership matrix and apply crosstalk correction on that
matrix. Returns the crosstalk-corrected pathway definition... | Helper function to create the gene-to-pathway
membership matrix and apply crosstalk correction on that
matrix. Returns the crosstalk-corrected pathway definitions
for the input `genes.` |
def unhook_all():
"""
Removes all keyboard hooks in use, including hotkeys, abbreviations, word
listeners, `record`ers and `wait`s.
"""
_listener.start_if_necessary()
_listener.blocking_keys.clear()
_listener.nonblocking_keys.clear()
del _listener.blocking_hooks[:]
del _listener.hand... | Removes all keyboard hooks in use, including hotkeys, abbreviations, word
listeners, `record`ers and `wait`s. |
def delete_copy_field(self, collection, copy_dict):
'''
Deletes a copy field.
copy_dict should look like ::
{'source':'source_field_name','dest':'destination_field_name'}
:param string collection: Name of the collection for the action
:param dict copy_field: Dictio... | Deletes a copy field.
copy_dict should look like ::
{'source':'source_field_name','dest':'destination_field_name'}
:param string collection: Name of the collection for the action
:param dict copy_field: Dictionary of field info |
def _next_page(self, response):
"""
return url path to next page of paginated data
"""
for link in response.getheader("link", "").split(","):
try:
(url, rel) = link.split(";")
if "next" in rel:
return url.lstrip("<").rstrip(... | return url path to next page of paginated data |
def as_uni_form(form):
"""
The original and still very useful way to generate a uni-form form/formset::
{% load uni_form_tags %}
<form class="uniForm" action="post">
{% csrf_token %}
{{ myform|as_uni_form }}
</form>
"""
if isinstance(form, BaseFormS... | The original and still very useful way to generate a uni-form form/formset::
{% load uni_form_tags %}
<form class="uniForm" action="post">
{% csrf_token %}
{{ myform|as_uni_form }}
</form> |
def export_original_data(self):
"""
Retrieves the original_data
"""
def export_field(value):
"""
Export item
"""
try:
return value.export_original_data()
except AttributeError:
return value
... | Retrieves the original_data |
def visit_Call(self, node):
"""
Visit a function call.
We expect every logging statement and string format to be a function call.
"""
# CASE 1: We're in a logging statement
if self.within_logging_statement():
if self.within_logging_argument() and self.is_for... | Visit a function call.
We expect every logging statement and string format to be a function call. |
def get_provider_id(self):
"""Gets the ``Id`` of the provider.
return: (osid.id.Id) - the provider ``Id``
*compliance: mandatory -- This method must be implemented.*
"""
if ('providerId' not in self.my_osid_object._my_map or
not self.my_osid_object._my_map['prov... | Gets the ``Id`` of the provider.
return: (osid.id.Id) - the provider ``Id``
*compliance: mandatory -- This method must be implemented.* |
def send_contributor_email(self, contributor):
"""Send an EmailMessage object for a given contributor."""
ContributorReport(
contributor,
month=self.month,
year=self.year,
deadline=self._deadline,
start=self._start,
end=self._end
... | Send an EmailMessage object for a given contributor. |
def process(in_path, boundaries_id=msaf.config.default_bound_id,
labels_id=msaf.config.default_label_id, annot_beats=False,
framesync=False, feature="pcp", hier=False, save=False,
out_file=None, n_jobs=4, annotator_id=0, config=None):
"""Main process to evaluate algorithms' resul... | Main process to evaluate algorithms' results.
Parameters
----------
in_path : str
Path to the dataset root folder.
boundaries_id : str
Boundaries algorithm identifier (e.g. siplca, cnmf)
labels_id : str
Labels algorithm identifier (e.g. siplca, cnmf)
ds_name : str
... |
def getAllFeatureSets(self):
"""
Returns all feature sets on the server.
"""
for dataset in self.getAllDatasets():
iterator = self._client.search_feature_sets(
dataset_id=dataset.id)
for featureSet in iterator:
yield featureSet | Returns all feature sets on the server. |
def get_exptime(self, img):
"""Obtain EXPTIME"""
header = self.get_header(img)
if 'EXPTIME' in header.keys():
etime = header['EXPTIME']
elif 'EXPOSED' in header.keys():
etime = header['EXPOSED']
else:
etime = 1.0
return etime | Obtain EXPTIME |
def combat(adata: AnnData, key: str = 'batch', covariates: Optional[Collection[str]] = None, inplace: bool = True):
"""ComBat function for batch effect correction [Johnson07]_ [Leek12]_ [Pedersen12]_.
Corrects for batch effects by fitting linear models, gains statistical power
via an EB framework where inf... | ComBat function for batch effect correction [Johnson07]_ [Leek12]_ [Pedersen12]_.
Corrects for batch effects by fitting linear models, gains statistical power
via an EB framework where information is borrowed across genes. This uses the
implementation of `ComBat <https://github.com/brentp/combat.py>`__ [Pe... |
def _fit(self, Z, parameter_iterable):
"""Actual fitting, performing the search over parameters."""
self.scorer_ = check_scoring(self.estimator, scoring=self.scoring)
cv = self.cv
cv = _check_cv(cv, Z)
if self.verbose > 0:
if isinstance(parameter_iterable, Sized):
... | Actual fitting, performing the search over parameters. |
def stdout_to_results(s):
"""Turns the multi-line output of a benchmark process into
a sequence of BenchmarkResult instances."""
results = s.strip().split('\n')
return [BenchmarkResult(*r.split()) for r in results] | Turns the multi-line output of a benchmark process into
a sequence of BenchmarkResult instances. |
def output_randomized_kronecker_to_pickle(
left_matrix, right_matrix,
train_indices_out_path, test_indices_out_path,
train_metadata_out_path=None, test_metadata_out_path=None,
remove_empty_rows=True):
"""Compute randomized Kronecker product and dump it on the fly.
A standard Kronecker product betwe... | Compute randomized Kronecker product and dump it on the fly.
A standard Kronecker product between matrices A and B produces
[[a_11 B, ..., a_1n B],
...
[a_m1 B, ..., a_mn B]]
(if A's size is (m, n) and B's size is (p, q) then A Kr... |
def yield_event(self, act):
"""
Hande completion for a request and return an (op, coro) to be
passed to the scheduler on the last completion loop of a proactor.
"""
if act in self.tokens:
coro = act.coro
op = self.try_run_act(act, self.tokens[act])
... | Hande completion for a request and return an (op, coro) to be
passed to the scheduler on the last completion loop of a proactor. |
def gen_headers() -> Dict[str, str]:
"""Generate a header pairing."""
ua_list: List[str] = ['Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.117 Safari/537.36']
headers: Dict[str, str] = {'User-Agent': ua_list[random.randint(0, len(ua_list) - 1)]}
return heade... | Generate a header pairing. |
def _delete_nxos_db(self, unused, vlan_id, device_id, host_id, vni,
is_provider_vlan):
"""Delete the nexus database entry.
Called during delete precommit port event.
"""
try:
rows = nxos_db.get_nexusvm_bindings(vlan_id, device_id)
for row ... | Delete the nexus database entry.
Called during delete precommit port event. |
def daily_bounds(network, snapshots):
""" This will bound the storage level to 0.5 max_level every 24th hour.
"""
sus = network.storage_units
# take every first hour of the clustered days
network.model.period_starts = network.snapshot_weightings.index[0::24]
network.model.storages = sus.index
... | This will bound the storage level to 0.5 max_level every 24th hour. |
def get_image_tags(self):
"""
Fetches image labels (repository / tags) from Docker.
:return: A dictionary, with image name and tags as the key and the image id as value.
:rtype: dict
"""
current_images = self.images()
tags = {tag: i['Id'] for i in current_images ... | Fetches image labels (repository / tags) from Docker.
:return: A dictionary, with image name and tags as the key and the image id as value.
:rtype: dict |
def connect(self, fn):
"""SQLite connect method initialize db"""
self.conn = sqlite3.connect(fn)
cur = self.get_cursor()
cur.execute('PRAGMA page_size=4096')
cur.execute('PRAGMA FOREIGN_KEYS=ON')
cur.execute('PRAGMA cache_size=10000')
cur.execute('PRAGMA journal_m... | SQLite connect method initialize db |
def update_settings(self, service_id, version_number, settings={}):
"""Update the settings for a particular service and version."""
body = urllib.urlencode(settings)
content = self._fetch("/service/%s/version/%d/settings" % (service_id, version_number), method="PUT", body=body)
return FastlySettings(self, conte... | Update the settings for a particular service and version. |
def event_log_filter_between_date(start, end, utc):
"""betweenDate Query filter that SoftLayer_EventLog likes
:param string start: lower bound date in mm/dd/yyyy format
:param string end: upper bound date in mm/dd/yyyy format
:param string utc: utc offset. Defaults to '+0000'
"""
return {
... | betweenDate Query filter that SoftLayer_EventLog likes
:param string start: lower bound date in mm/dd/yyyy format
:param string end: upper bound date in mm/dd/yyyy format
:param string utc: utc offset. Defaults to '+0000' |
def init_rotate(cls, radians):
"""Return a new :class:`Matrix` for a transformation
that rotates by :obj:`radians`.
:type radians: float
:param radians:
Angle of rotation, in radians.
The direction of rotation is defined such that
positive angles rota... | Return a new :class:`Matrix` for a transformation
that rotates by :obj:`radians`.
:type radians: float
:param radians:
Angle of rotation, in radians.
The direction of rotation is defined such that
positive angles rotate in the direction
from the p... |
def get_request_body_chunk(self, content: bytes, closed: bool,
more_content: bool) -> Dict[str, Any]:
'''
http://channels.readthedocs.io/en/stable/asgi/www.html#request-body-chunk
'''
return {
'content': content,
'closed': closed,
... | http://channels.readthedocs.io/en/stable/asgi/www.html#request-body-chunk |
def get_specific_subnodes(self, node, name, recursive=0):
"""Given a node and a name, return a list of child `ELEMENT_NODEs`, that
have a `tagName` matching the `name`. Search recursively for `recursive`
levels.
"""
children = [x for x in node.childNodes if x.nodeType == x.ELEMEN... | Given a node and a name, return a list of child `ELEMENT_NODEs`, that
have a `tagName` matching the `name`. Search recursively for `recursive`
levels. |
def public_url(self):
"""The public URL for this blob.
Use :meth:`make_public` to enable anonymous access via the returned
URL.
:rtype: `string`
:returns: The public URL for this blob.
"""
return "{storage_base_url}/{bucket_name}/{quoted_name}".format(
... | The public URL for this blob.
Use :meth:`make_public` to enable anonymous access via the returned
URL.
:rtype: `string`
:returns: The public URL for this blob. |
def from_callback(cls, cb, nx=None, nparams=None, **kwargs):
""" Generate a SymbolicSys instance from a callback.
Parameters
----------
cb : callable
Should have the signature ``cb(x, p, backend) -> list of exprs``.
nx : int
Number of unknowns, when not g... | Generate a SymbolicSys instance from a callback.
Parameters
----------
cb : callable
Should have the signature ``cb(x, p, backend) -> list of exprs``.
nx : int
Number of unknowns, when not given it is deduced from ``kwargs['names']``.
nparams : int
... |
def _playsoundOSX(sound, block = True):
'''
Utilizes AppKit.NSSound. Tested and known to work with MP3 and WAVE on
OS X 10.11 with Python 2.7. Probably works with anything QuickTime supports.
Probably works on OS X 10.5 and newer. Probably works with all versions of
Python.
Inspired by (but not... | Utilizes AppKit.NSSound. Tested and known to work with MP3 and WAVE on
OS X 10.11 with Python 2.7. Probably works with anything QuickTime supports.
Probably works on OS X 10.5 and newer. Probably works with all versions of
Python.
Inspired by (but not copied from) Aaron's Stack Overflow answer here:
... |
def _euristic_h_function(self, suffix, index):
"""
Вычисление h-эвристики из работы Hulden,2009 для текущей вершины словаря
Аргументы:
----------
suffix : string
непрочитанный суффикс входного слова
index : int
индекс текущего узла в словаре
... | Вычисление h-эвристики из работы Hulden,2009 для текущей вершины словаря
Аргументы:
----------
suffix : string
непрочитанный суффикс входного слова
index : int
индекс текущего узла в словаре
Возвращает:
-----------
cost : float
... |
def create_api_pool(self):
"""Get an instance of Api Pool services facade."""
return ApiPool(
self.networkapi_url,
self.user,
self.password,
self.user_ldap) | Get an instance of Api Pool services facade. |
def send_template_email(recipients, title_template, body_template, context, language):
"""Sends e-mail using templating system"""
send_emails = getattr(settings, 'SEND_PLANS_EMAILS', True)
if not send_emails:
return
site_name = getattr(settings, 'SITE_NAME', 'Please define settings.SITE_NAME')... | Sends e-mail using templating system |
def add_record(self, record):
"""Add a record to the OAISet.
:param record: Record to be added.
:type record: `invenio_records.api.Record` or derivative.
"""
record.setdefault('_oai', {}).setdefault('sets', [])
assert not self.has_record(record)
record['_oai'][... | Add a record to the OAISet.
:param record: Record to be added.
:type record: `invenio_records.api.Record` or derivative. |
def _executor_script(self):
"""Create shell-script in charge of executing the benchmark
and return its path.
"""
fd, path = tempfile.mkstemp(suffix='.sh', dir=os.getcwd())
os.close(fd)
with open(path, 'w') as ostr:
self._write_executor_script(ostr)
mod... | Create shell-script in charge of executing the benchmark
and return its path. |
def best_four_point_to_buy(self):
""" 判斷是否為四大買點
:rtype: str or False
"""
result = []
if self.check_mins_bias_ratio() and \
(self.best_buy_1() or self.best_buy_2() or self.best_buy_3() or \
self.best_buy_4()):
if self.best_buy_1():
... | 判斷是否為四大買點
:rtype: str or False |
def project_stored_info_type_path(cls, project, stored_info_type):
"""Return a fully-qualified project_stored_info_type string."""
return google.api_core.path_template.expand(
"projects/{project}/storedInfoTypes/{stored_info_type}",
project=project,
stored_info_type=s... | Return a fully-qualified project_stored_info_type string. |
def send_email(self, source, subject, body, to_addresses, cc_addresses=None,
bcc_addresses=None, format='text', reply_addresses=None,
return_path=None, text_body=None, html_body=None):
"""Composes an email message based on input data, and then immediately
queues the... | Composes an email message based on input data, and then immediately
queues the message for sending.
:type source: string
:param source: The sender's email address.
:type subject: string
:param subject: The subject of the message: A short summary of the
c... |
def _set_font(self, font):
""" Sets the base font for the ConsoleWidget to the specified QFont.
"""
font_metrics = QtGui.QFontMetrics(font)
self._control.setTabStopWidth(self.tab_width * font_metrics.width(' '))
self._completion_widget.setFont(font)
self._control.documen... | Sets the base font for the ConsoleWidget to the specified QFont. |
def _decdeg_distance(pt1, pt2):
"""
Earth surface distance (in km) between decimal latlong points using
Haversine approximation.
http://stackoverflow.com/questions/15736995/
how-can-i-quickly-estimate-the-distance-between-two-latitude-longitude-
points
"""
lat1, lon1 = pt1
lat2, lo... | Earth surface distance (in km) between decimal latlong points using
Haversine approximation.
http://stackoverflow.com/questions/15736995/
how-can-i-quickly-estimate-the-distance-between-two-latitude-longitude-
points |
def check_valid_rx_can_msg(result):
"""
Checks if function :meth:`UcanServer.read_can_msg` returns a valid CAN message.
:param ReturnCode result: Error code of the function.
:return: True if a valid CAN messages was received, otherwise False.
:rtype: bool
"""
return (result.value == ReturnC... | Checks if function :meth:`UcanServer.read_can_msg` returns a valid CAN message.
:param ReturnCode result: Error code of the function.
:return: True if a valid CAN messages was received, otherwise False.
:rtype: bool |
def wallet_destroy(self, wallet):
"""
Destroys **wallet** and all contained accounts
.. enable_control required
:param wallet: Wallet to destroy
:type wallet: str
:raises: :py:exc:`nano.rpc.RPCException`
>>> rpc.wallet_destroy(
... wallet="000D1BAE... | Destroys **wallet** and all contained accounts
.. enable_control required
:param wallet: Wallet to destroy
:type wallet: str
:raises: :py:exc:`nano.rpc.RPCException`
>>> rpc.wallet_destroy(
... wallet="000D1BAEC8EC208142C99059B393051BAC8380F9B5A2E6B2489A277D81789F... |
def is_flapping(self, alert, window=1800, count=2):
"""
Return true if alert severity has changed more than X times in Y seconds
"""
select = """
SELECT COUNT(*)
FROM alerts, unnest(history) h
WHERE environment=%(environment)s
AND res... | Return true if alert severity has changed more than X times in Y seconds |
def delete_member(self, user):
"""Returns a response after attempting to remove
a member from the list.
"""
if not self.email_enabled:
raise EmailNotEnabledError("See settings.EMAIL_ENABLED")
return requests.delete(
f"{self.api_url}/{self.address}/members/... | Returns a response after attempting to remove
a member from the list. |
def vflip(img):
"""Vertically flip the given PIL Image.
Args:
img (PIL Image): Image to be flipped.
Returns:
PIL Image: Vertically flipped image.
"""
if not _is_pil_image(img):
raise TypeError('img should be PIL Image. Got {}'.format(type(img)))
return img.transpose(I... | Vertically flip the given PIL Image.
Args:
img (PIL Image): Image to be flipped.
Returns:
PIL Image: Vertically flipped image. |
def insert_rows(self, row, no_rows=1):
"""Adds no_rows rows before row, appends if row > maxrows
and marks grid as changed
"""
# Mark content as changed
post_command_event(self.main_window, self.ContentChangedMsg)
tab = self.grid.current_table
self.code_array... | Adds no_rows rows before row, appends if row > maxrows
and marks grid as changed |
def handle(self, cycle_delay=0.1):
"""
Call this method to spend about ``cycle_delay`` seconds processing
requests in the pcaspy server. Under load, for example when running ``caget`` at a
high frequency, the actual time spent in the method may be much shorter. This effect
is not... | Call this method to spend about ``cycle_delay`` seconds processing
requests in the pcaspy server. Under load, for example when running ``caget`` at a
high frequency, the actual time spent in the method may be much shorter. This effect
is not corrected for.
:param cycle_delay: Approximat... |
async def send_file(
self, entity, file, *, caption=None, force_document=False,
progress_callback=None, reply_to=None, attributes=None,
thumb=None, allow_cache=True, parse_mode=(),
voice_note=False, video_note=False, buttons=None, silent=None,
supports_streami... | Sends a file to the specified entity.
Args:
entity (`entity`):
Who will receive the file.
file (`str` | `bytes` | `file` | `media`):
The file to send, which can be one of:
* A local file path to an in-disk file. The file name
... |
def from_path_by_ext(dir_path, ext):
"""Create a new FileCollection, and select all files that extension
matching ``ext``::
dir_path = "your/path"
fc = FileCollection.from_path_by_ext(dir_path, ext=[".jpg", ".png"])
"""
if isinstance(ext, (l... | Create a new FileCollection, and select all files that extension
matching ``ext``::
dir_path = "your/path"
fc = FileCollection.from_path_by_ext(dir_path, ext=[".jpg", ".png"]) |
def _make_valid_bounds(self, test_bounds):
"""
Private method: process input bounds into a form acceptable by scipy.optimize,
and check the validity of said bounds.
:param test_bounds: minimum and maximum weight of an asset
:type test_bounds: tuple
:raises ValueError: if... | Private method: process input bounds into a form acceptable by scipy.optimize,
and check the validity of said bounds.
:param test_bounds: minimum and maximum weight of an asset
:type test_bounds: tuple
:raises ValueError: if ``test_bounds`` is not a tuple of length two.
:raises ... |
def history_report(history, config=None, html=True):
"""
Test a model and save a history report.
Parameters
----------
history : memote.HistoryManager
The manager grants access to previous results.
config : dict, optional
The final test report configuration.
html : bool, opt... | Test a model and save a history report.
Parameters
----------
history : memote.HistoryManager
The manager grants access to previous results.
config : dict, optional
The final test report configuration.
html : bool, optional
Whether to render the report as full HTML or JSON (... |
def bound_pseudo(arnoldifyer, Wt,
g_norm=0.,
G_norm=0.,
GW_norm=0.,
WGW_norm=0.,
tol=1e-6,
pseudo_type='auto',
pseudo_kwargs=None,
delta_n=20,
terminate_factor=1.
... | r'''Bound residual norms of next deflated system.
:param arnoldifyer: an instance of
:py:class:`~krypy.deflation.Arnoldifyer`.
:param Wt: coefficients :math:`\tilde{W}\in\mathbb{C}^{n+d,k}` of the
considered deflation vectors :math:`W` for the basis :math:`[V,U]`
where ``V=last_solver.V`` and... |
def push_data(self, data):
"""Push data broadcasted from gateway to device"""
if not _validate_data(data):
return False
jdata = json.loads(data['data']) if int(self.proto[0:1]) == 1 else _list2map(data['params'])
if jdata is None:
return False
sid = data['... | Push data broadcasted from gateway to device |
def max(self, key=None):
"""
Find the maximum item in this RDD.
:param key: A function used to generate key for comparing
>>> rdd = sc.parallelize([1.0, 5.0, 43.0, 10.0])
>>> rdd.max()
43.0
>>> rdd.max(key=str)
5.0
"""
if key is None:
... | Find the maximum item in this RDD.
:param key: A function used to generate key for comparing
>>> rdd = sc.parallelize([1.0, 5.0, 43.0, 10.0])
>>> rdd.max()
43.0
>>> rdd.max(key=str)
5.0 |
def ports(self):
"""
:return: dict
{
# container -> host
"1234": "2345"
}
"""
if self._ports is None:
self._ports = {}
if self.net_settings["Ports"]:
for key, value in self.net_settings["Port... | :return: dict
{
# container -> host
"1234": "2345"
} |
def stage_import_from_file(self, fd, filename='upload.gz'):
"""Stage an import from a file upload.
:param fd: File-like object to upload.
:param filename: (optional) Filename to use for import as string.
:return: :class:`imports.Import <imports.Import>` object
"""
schema... | Stage an import from a file upload.
:param fd: File-like object to upload.
:param filename: (optional) Filename to use for import as string.
:return: :class:`imports.Import <imports.Import>` object |
def reading_dates(reading):
"""
Given a Reading, with start and end dates and granularities[1] it returns
an HTML string representing that period. eg:
* '1–6 Feb 2017'
* '1 Feb to 3 Mar 2017'
* 'Feb 2017 to Mar 2018'
* '2017–2018'
etc.
[1] https://www.flickr.com/ser... | Given a Reading, with start and end dates and granularities[1] it returns
an HTML string representing that period. eg:
* '1–6 Feb 2017'
* '1 Feb to 3 Mar 2017'
* 'Feb 2017 to Mar 2018'
* '2017–2018'
etc.
[1] https://www.flickr.com/services/api/misc.dates.html |
def register_laser_hooks(self, hook_type: str, hook: Callable):
"""registers the hook with this Laser VM"""
if hook_type == "add_world_state":
self._add_world_state_hooks.append(hook)
elif hook_type == "execute_state":
self._execute_state_hooks.append(hook)
elif h... | registers the hook with this Laser VM |
def pre_release(version):
"""Generates new docs, release announcements and creates a local tag."""
announce(version)
regen()
changelog(version, write_out=True)
fix_formatting()
msg = "Preparing release version {}".format(version)
check_call(["git", "commit", "-a", "-m", msg])
print()
... | Generates new docs, release announcements and creates a local tag. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.