code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def list_all_quantities(self, include_native=False, with_info=False):
"""
Return a list of all available quantities in this catalog.
If *include_native* is `True`, includes native quantities.
If *with_info* is `True`, return a dict with quantity info.
See also: list_all_native_... | Return a list of all available quantities in this catalog.
If *include_native* is `True`, includes native quantities.
If *with_info* is `True`, return a dict with quantity info.
See also: list_all_native_quantities |
def find_config(config_path: str) -> str:
"""
Derive configuration file path from the given path and check its existence.
The given path is expected to be either
1. path to the file
2. path to a dir, in such case the path is joined with ``CXF_CONFIG_FILE``
:param config_path: path to the conf... | Derive configuration file path from the given path and check its existence.
The given path is expected to be either
1. path to the file
2. path to a dir, in such case the path is joined with ``CXF_CONFIG_FILE``
:param config_path: path to the configuration file or its parent directory
:return: va... |
def create_essay_set(text, score, prompt_string, generate_additional=True):
"""
Creates an essay set from given data.
Text should be a list of strings corresponding to essay text.
Score should be a list of scores where score[n] corresponds to text[n]
Prompt string is just a string containing the ess... | Creates an essay set from given data.
Text should be a list of strings corresponding to essay text.
Score should be a list of scores where score[n] corresponds to text[n]
Prompt string is just a string containing the essay prompt.
Generate_additional indicates whether to generate additional essays at th... |
def fetch(self, end=values.unset, start=values.unset):
"""
Fetch a UsageInstance
:param unicode end: The end
:param unicode start: The start
:returns: Fetched UsageInstance
:rtype: twilio.rest.preview.wireless.sim.usage.UsageInstance
"""
return self._pro... | Fetch a UsageInstance
:param unicode end: The end
:param unicode start: The start
:returns: Fetched UsageInstance
:rtype: twilio.rest.preview.wireless.sim.usage.UsageInstance |
def adjust_frame(proc_obj, name, pos, absolute_pos):
"""Adjust stack frame by pos positions. If absolute_pos then
pos is an absolute number. Otherwise it is a relative number.
A negative number indexes from the other end."""
if not proc_obj.curframe:
proc_obj.errmsg("No stack.")
return
... | Adjust stack frame by pos positions. If absolute_pos then
pos is an absolute number. Otherwise it is a relative number.
A negative number indexes from the other end. |
def update_team(self, slug):
"""
Trigger update and cache invalidation for the team identified by the
given `slug`, if any. Returns `True` if the update was successful,
`False` otherwise.
:param slug: GitHub 'slug' name for the team to be updated.
"""
if self._or... | Trigger update and cache invalidation for the team identified by the
given `slug`, if any. Returns `True` if the update was successful,
`False` otherwise.
:param slug: GitHub 'slug' name for the team to be updated. |
def day_night_duration(
self,
daybreak: datetime.time = datetime.time(NORMAL_DAY_START_H),
nightfall: datetime.time = datetime.time(NORMAL_DAY_END_H)) \
-> Tuple[datetime.timedelta, datetime.timedelta]:
"""
Returns a ``(day, night)`` tuple of ``datetime.ti... | Returns a ``(day, night)`` tuple of ``datetime.timedelta`` objects
giving the duration of this interval that falls into day and night
respectively. |
def hdr_vals_for_overscan(root):
"""Retrieve header keyword values from RAW and SPT
FITS files to pass on to :func:`check_oscntab` and
:func:`check_overscan`.
Parameters
----------
root : str
Rootname of the observation. Can be relative path
to the file excluding the type of FIT... | Retrieve header keyword values from RAW and SPT
FITS files to pass on to :func:`check_oscntab` and
:func:`check_overscan`.
Parameters
----------
root : str
Rootname of the observation. Can be relative path
to the file excluding the type of FITS file and
extension, e.g., '/my... |
def send_execute_request(self, socket, code, silent=True, subheader=None, ident=None):
"""construct and send an execute request via a socket.
"""
if self._closed:
raise RuntimeError("Client cannot be used after its sockets have been closed")
# defaults:
sub... | construct and send an execute request via a socket. |
def sort_header(header_text):
"""sort the chromosomes in a header text"""
lines = header_text.rstrip().split("\n")
rlens = {}
for ln in lines:
m = re.match('@SQ\tSN:(\S+)\tLN:(\S+)',ln)
if m:
rlens[m.group(1)] = m.group(2)
output = ''
done_lens = False
for ln in lines:
if re.match('@SQ\t... | sort the chromosomes in a header text |
def logs_for_job(self, job_name, wait=False, poll=10): # noqa: C901 - suppress complexity warning for this method
"""Display the logs for a given training job, optionally tailing them until the
job is complete. If the output is a tty or a Jupyter cell, it will be color-coded
based on which inst... | Display the logs for a given training job, optionally tailing them until the
job is complete. If the output is a tty or a Jupyter cell, it will be color-coded
based on which instance the log entry is from.
Args:
job_name (str): Name of the training job to display the logs for.
... |
def deploy_docker(self, dockerfile_path, virtualbox_name='default'):
''' a method to deploy app to heroku using docker '''
title = '%s.deploy_docker' % self.__class__.__name__
# validate inputs
input_fields = {
'dockerfile_path': dockerfile_path,
'virtualb... | a method to deploy app to heroku using docker |
def add_ruleclause_name(self, ns_name, rid) -> bool:
"""Create a tree.Rule"""
ns_name.parser_tree = parsing.Rule(self.value(rid))
return True | Create a tree.Rule |
def to_comm(self, light_request=False):
'''
Convert `self` to :class:`.Publication`.
Returns:
obj: :class:`.Publication` instance.
'''
data = None
if not light_request:
data = read_as_base64(self.file_pointer)
return Publication(
... | Convert `self` to :class:`.Publication`.
Returns:
obj: :class:`.Publication` instance. |
def h2z(text, ignore='', kana=True, ascii=False, digit=False):
"""Convert Half-width (Hankaku) Katakana to Full-width (Zenkaku) Katakana
Parameters
----------
text : str
Half-width Katakana string.
ignore : str
Characters to be ignored in converting.
kana : bool
Either c... | Convert Half-width (Hankaku) Katakana to Full-width (Zenkaku) Katakana
Parameters
----------
text : str
Half-width Katakana string.
ignore : str
Characters to be ignored in converting.
kana : bool
Either converting Kana or not.
ascii : bool
Either converting asci... |
def get(ctx):
"""Get job.
Uses [Caching](/references/polyaxon-cli/#caching)
Examples:
\b
```bash
$ polyaxon job --job=1 get
```
\b
```bash
$ polyaxon job --job=1 --project=project_name get
```
"""
user, project_name, _job = get_job_or_local(ctx.obj.get('project'),... | Get job.
Uses [Caching](/references/polyaxon-cli/#caching)
Examples:
\b
```bash
$ polyaxon job --job=1 get
```
\b
```bash
$ polyaxon job --job=1 --project=project_name get
``` |
def is_prime( n ):
"""Return True if x is prime, False otherwise.
We use the Miller-Rabin test, as given in Menezes et al. p. 138.
This test is not exact: there are composite values n for which
it returns True.
In testing the odd numbers from 10000001 to 19999999,
about 66 composites got past the first te... | Return True if x is prime, False otherwise.
We use the Miller-Rabin test, as given in Menezes et al. p. 138.
This test is not exact: there are composite values n for which
it returns True.
In testing the odd numbers from 10000001 to 19999999,
about 66 composites got past the first test,
5 got past the sec... |
def expand_tile(units, axis):
"""
Expand and tile tensor along given axis
Args:
units: tf tensor with dimensions [batch_size, time_steps, n_input_features]
axis: axis along which expand and tile. Must be 1 or 2
"""
assert axis in (1, 2)
n_time_steps = K.int_shape(units)[1]
... | Expand and tile tensor along given axis
Args:
units: tf tensor with dimensions [batch_size, time_steps, n_input_features]
axis: axis along which expand and tile. Must be 1 or 2 |
def _join_summary_file(data, summary_filename="msd_summary_file.h5"):
""" Gets the trackinfo array by joining taste profile to the track summary file """
msd = h5py.File(summary_filename)
# create a lookup table of trackid -> position
track_lookup = dict((t.encode("utf8"), i) for i, t in enumerate(data... | Gets the trackinfo array by joining taste profile to the track summary file |
def get_code_indices(s: Union[str, 'ChainedBase']) -> Dict[int, str]:
""" Retrieve a dict of {index: escape_code} for a given string.
If no escape codes are found, an empty dict is returned.
"""
indices = {}
i = 0
codes = get_codes(s)
for code in codes:
codeindex = s.index(code)
... | Retrieve a dict of {index: escape_code} for a given string.
If no escape codes are found, an empty dict is returned. |
def decode(self, file_name):
"""
Parses the filename, creating a FileTag from it.
It will try both the old and the new conventions, if the filename does
not conform any of them, then an empty FileTag will be returned.
:param file_name: filename to parse
:return: a FileT... | Parses the filename, creating a FileTag from it.
It will try both the old and the new conventions, if the filename does
not conform any of them, then an empty FileTag will be returned.
:param file_name: filename to parse
:return: a FileTag instance |
def route_present(name, address_prefix, next_hop_type, route_table, resource_group, next_hop_ip_address=None,
connection_auth=None, **kwargs):
'''
.. versionadded:: 2019.2.0
Ensure a route exists within a route table.
:param name:
Name of the route.
:param address_prefix... | .. versionadded:: 2019.2.0
Ensure a route exists within a route table.
:param name:
Name of the route.
:param address_prefix:
The destination CIDR to which the route applies.
:param next_hop_type:
The type of Azure hop the packet should be sent to. Possible values are: 'Virtu... |
def _create(archive, compression, cmd, format, verbosity, filenames):
"""Create an LZMA or XZ archive with the lzma Python module."""
if len(filenames) > 1:
raise util.PatoolError('multi-file compression not supported in Python lzma')
try:
with lzma.LZMAFile(archive, mode='wb', **_get_lzma_o... | Create an LZMA or XZ archive with the lzma Python module. |
def example_bigbeds():
"""
Returns list of example bigBed files
"""
hits = []
d = data_dir()
for fn in os.listdir(d):
fn = os.path.join(d, fn)
if os.path.splitext(fn)[-1] == '.bigBed':
hits.append(os.path.abspath(fn))
return hits | Returns list of example bigBed files |
def iterable_source(iterable, target):
"""Convert an iterable into a stream of events.
Args:
iterable: A series of items which will be sent to the target one by one.
target: The target coroutine or sink.
Returns:
An iterator over any remaining items.
"""
it = iter(iterable)... | Convert an iterable into a stream of events.
Args:
iterable: A series of items which will be sent to the target one by one.
target: The target coroutine or sink.
Returns:
An iterator over any remaining items. |
def send(vm, target, key='uuid'):
'''
Send a vm to a directory
vm : string
vm to be sent
target : string
target directory
key : string [uuid|alias|hostname]
value type of 'vm' parameter
CLI Example:
.. code-block:: bash
salt '*' vmadm.send 186da9ab-7392-4f... | Send a vm to a directory
vm : string
vm to be sent
target : string
target directory
key : string [uuid|alias|hostname]
value type of 'vm' parameter
CLI Example:
.. code-block:: bash
salt '*' vmadm.send 186da9ab-7392-4f55-91a5-b8f1fe770543 /opt/backups
salt... |
def urls(model,form_class=None,fields=None,redirect=None,object_list=None,fail_if_empty=True):
"""
Returns URL patterns for creating, updating and deleting models. Supports lists and formsets as well
model Model class
form_class Form class for use in create, update and formset views (d... | Returns URL patterns for creating, updating and deleting models. Supports lists and formsets as well
model Model class
form_class Form class for use in create, update and formset views (default is None)
fields Required if form_class is not provided
redirect Redirection UR... |
def _get_fuzzy_padding(self, lean):
"""
This is not a perfect interpretation as fuzziness is introduced for
redundant uncertainly modifiers e.g. (2006~)~ will get two sets of
fuzziness.
"""
result = relativedelta(0)
if self.year_ua:
result += appsetti... | This is not a perfect interpretation as fuzziness is introduced for
redundant uncertainly modifiers e.g. (2006~)~ will get two sets of
fuzziness. |
def getExpectedValue(distribution):
"""
Calculates E[X] where X is a distribution.
"""
k = np.array(distribution.possibleValues)
return np.sum(k * distribution.pmf(k)) | Calculates E[X] where X is a distribution. |
def migrate(config):
"""Perform a migration according to config.
:param config: The configuration to be applied
:type config: Config
"""
webapp = WebApp(config.web_host, config.web_port,
custom_maintenance_file=config.web_custom_html)
webserver = WebServer(webapp)
webse... | Perform a migration according to config.
:param config: The configuration to be applied
:type config: Config |
def handle_termination(cls, pid, is_cancel=True):
'''
Internal method to terminate a subprocess spawned by `pexpect` representing an invocation of runner.
:param pid: the process id of the running the job.
:param is_cancel: flag showing whether this termination is caused by
... | Internal method to terminate a subprocess spawned by `pexpect` representing an invocation of runner.
:param pid: the process id of the running the job.
:param is_cancel: flag showing whether this termination is caused by
instance's cancel_flag. |
def recover_and_supervise(recovery_file):
""" Retrieve monitor data from recovery_file and resume monitoring """
try:
logging.info("Attempting to recover Supervisor data from " + recovery_file)
with open(recovery_file) as rf:
recovery_data = json.load(rf)
monitor_data = r... | Retrieve monitor data from recovery_file and resume monitoring |
def qrcode(self, data, **kwargs):
"""
Render given ``data`` as `QRCode <http://www.qrcode.com/en/>`_.
"""
barcode.validate_qrcode_args(**kwargs)
return self._qrcode_impl(data, **kwargs) | Render given ``data`` as `QRCode <http://www.qrcode.com/en/>`_. |
async def pack_message(wallet_handle: int,
message: str,
recipient_verkeys: list,
sender_verkey: Optional[str]) -> bytes:
"""
Packs a message by encrypting the message and serializes it in a JWE-like format (Experimental)
Note to use DID ... | Packs a message by encrypting the message and serializes it in a JWE-like format (Experimental)
Note to use DID keys with this function you can call did.key_for_did to get key id (verkey)
for specific DID.
#Params
command_handle: command handle to map callback to user context.
wallet_handle: walle... |
def from_series(self, series, add_index_column=True):
"""
Set tabular attributes to the writer from :py:class:`pandas.Series`.
Following attributes are set by the method:
- :py:attr:`~.headers`
- :py:attr:`~.value_matrix`
- :py:attr:`~.type_hints`
Ar... | Set tabular attributes to the writer from :py:class:`pandas.Series`.
Following attributes are set by the method:
- :py:attr:`~.headers`
- :py:attr:`~.value_matrix`
- :py:attr:`~.type_hints`
Args:
series(pandas.Series):
Input pandas.Series... |
def extended_stats(G, connectivity=False, anc=False, ecc=False, bc=False, cc=False):
"""
Calculate extended topological stats and metrics for a graph.
Many of these algorithms have an inherently high time complexity. Global
topological analysis of large complex networks is extremely time consuming
... | Calculate extended topological stats and metrics for a graph.
Many of these algorithms have an inherently high time complexity. Global
topological analysis of large complex networks is extremely time consuming
and may exhaust computer memory. Consider using function arguments to not
run metrics that re... |
def get(self, entity_id: EntityId, load: bool = False) -> Entity:
"""Get a Wikidata entity by its :class:`~.entity.EntityId`.
:param entity_id: The :attr:`~.entity.Entity.id` of
the :class:`~.entity.Entity` to find.
:type eneity_id: :class:`~.entity.EntityId`
:... | Get a Wikidata entity by its :class:`~.entity.EntityId`.
:param entity_id: The :attr:`~.entity.Entity.id` of
the :class:`~.entity.Entity` to find.
:type eneity_id: :class:`~.entity.EntityId`
:param load: Eager loading on :const:`True`.
Lazy loading... |
def connect(self):
""" Simple connect """
try:
self.telnet = Telnet(self.host, self.port)
time.sleep(1)
self.get()
self.get('login admin admin')
self.update()
except socket.gaierror:
self.telnet = None
LOGGER.err... | Simple connect |
def diff_result_to_cell(item):
'''diff.diff returns a dictionary with all the information we need,
but we want to extract the cell and change its metadata.'''
state = item['state']
if state == 'modified':
new_cell = item['modifiedvalue'].data
old_cell = item['originalvalue'].data
... | diff.diff returns a dictionary with all the information we need,
but we want to extract the cell and change its metadata. |
def _get_node_text(self, goid, goobj):
"""Return a string to be printed in a GO term box."""
txt = []
# Header line: "GO:0036464 L04 D06"
txt.append(self.pltvars.fmthdr.format(
GO=goobj.id.replace("GO:", "GO"),
level=goobj.level,
depth=goobj.depth))
... | Return a string to be printed in a GO term box. |
def write_to(self, f):
"""Writes this header to a file, in the format specified by WARC.
"""
f.write(self.version + "\r\n")
for name, value in self.items():
name = name.title()
# Use standard forms for commonly used patterns
name = name.replace("Warc-"... | Writes this header to a file, in the format specified by WARC. |
def list_all_products(cls, **kwargs):
"""List Products
Return a list of Products
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.list_all_products(async=True)
>>> result = thread.get()... | List Products
Return a list of Products
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.list_all_products(async=True)
>>> result = thread.get()
:param async bool
:param int pa... |
def map(self, func):
"""
Process all data with given function.
The scheme of function should be x,y -> x,y.
"""
if self._train_set:
self._train_set = map(func, self._train_set)
if self._valid_set:
self._valid_set = map(func, self._valid_set)
... | Process all data with given function.
The scheme of function should be x,y -> x,y. |
def add_entry(self, row):
"""This will parse the VCF entry and also store it within the VCFFile. It will also
return the VCFEntry as well.
"""
var_call = VCFEntry(self.individuals)
var_call.parse_entry( row )
self.entries[(var_call.chrom, var_call.pos)] = var_call
... | This will parse the VCF entry and also store it within the VCFFile. It will also
return the VCFEntry as well. |
def weekly_plots(
df,
variable,
renormalize = True,
plot = True,
scatter = False,
linestyle = "-",
linewidth = 1,
s = 1
):
"""
Create weekly plots of a variable in a DataFrame, optionally renormalized.
It is assumed that the variable `days_through... | Create weekly plots of a variable in a DataFrame, optionally renormalized.
It is assumed that the variable `days_through_week` exists. |
def fetch(self):
"""
Fetch a AddOnResultInstance
:returns: Fetched AddOnResultInstance
:rtype: twilio.rest.api.v2010.account.recording.add_on_result.AddOnResultInstance
"""
params = values.of({})
payload = self._version.fetch(
'GET',
self... | Fetch a AddOnResultInstance
:returns: Fetched AddOnResultInstance
:rtype: twilio.rest.api.v2010.account.recording.add_on_result.AddOnResultInstance |
def cancel(self):
"""Cancels the observer
No more notifications will be passed on
"""
LOG.debug('cancelling %s', self)
self._cancelled = True
self.clear_callbacks() # not strictly necessary, but may release references
while True:
try:
... | Cancels the observer
No more notifications will be passed on |
def ensure_sphinx_astropy_installed():
"""
Make sure that sphinx-astropy is available, installing it temporarily if not.
This returns the available version of sphinx-astropy as well as any
paths that should be added to sys.path for sphinx-astropy to be available.
"""
# We've split out the Sphin... | Make sure that sphinx-astropy is available, installing it temporarily if not.
This returns the available version of sphinx-astropy as well as any
paths that should be added to sys.path for sphinx-astropy to be available. |
def _delete_extraneous_files(self):
# type: (Uploader) -> None
"""Delete extraneous files on the remote
:param Uploader self: this
"""
if not self._spec.options.delete_extraneous_destination:
return
# list blobs for all destinations
checked = set()
... | Delete extraneous files on the remote
:param Uploader self: this |
def get_instance_field(self, field_name):
"""
Add management of dynamic fields: if a normal field cannot be retrieved,
check if it can be a dynamic field and in this case, create a copy with
the given name and associate it to the instance.
"""
try:
field = sup... | Add management of dynamic fields: if a normal field cannot be retrieved,
check if it can be a dynamic field and in this case, create a copy with
the given name and associate it to the instance. |
def to_dict(self):
"""Converts this embed object into a dict."""
# add in the raw data into the dict
result = {
key[1:]: getattr(self, key)
for key in self.__slots__
if key[0] == '_' and hasattr(self, key)
}
# deal with basic conven... | Converts this embed object into a dict. |
def sg_summary_audio(tensor, sample_rate=16000, prefix=None, name=None):
r"""Register `tensor` to summary report as audio
Args:
tensor: A `Tensor` to log as audio
sample_rate : An int. Sample rate to report. Default is 16000.
prefix: A `string`. A prefix to display in the tensor board web UI.... | r"""Register `tensor` to summary report as audio
Args:
tensor: A `Tensor` to log as audio
sample_rate : An int. Sample rate to report. Default is 16000.
prefix: A `string`. A prefix to display in the tensor board web UI.
name: A `string`. A name to display in the tensor board web UI.
R... |
def _proc_uri(self, request, result):
"""
Process the URI rules for the request. Both the desired API
version and desired content type can be determined from those
rules.
:param request: The Request object provided by WebOb.
:param result: The Result object to store the... | Process the URI rules for the request. Both the desired API
version and desired content type can be determined from those
rules.
:param request: The Request object provided by WebOb.
:param result: The Result object to store the results in. |
def with_continuations(**c):
"""
A decorator for defining tail-call optimized functions.
Example
-------
@with_continuations()
def factorial(n, k, self=None):
return self(n-1, k*n) if n > 1 else k
@with_continuations()
def identity(x, self=None):
... | A decorator for defining tail-call optimized functions.
Example
-------
@with_continuations()
def factorial(n, k, self=None):
return self(n-1, k*n) if n > 1 else k
@with_continuations()
def identity(x, self=None):
return x
@with... |
def f_lock_parameters(self):
"""Locks all non-empty parameters"""
for par in self._parameters.values():
if not par.f_is_empty():
par.f_lock() | Locks all non-empty parameters |
def generate_rss(self, path='rss.xml', only_excerpt=True, https=False):
"""
Generate the RSS feed.
Args:
path (str): Where to save the RSS file. Make sure that your jinja
templates refer to the same path using <link>.
only_excerpt (bool): If True (the default), don't include the full
body of ... | Generate the RSS feed.
Args:
path (str): Where to save the RSS file. Make sure that your jinja
templates refer to the same path using <link>.
only_excerpt (bool): If True (the default), don't include the full
body of posts in the RSS. Instead, include the first paragraph and
a "read more" l... |
def instance_present(name, instance_name=None, instance_id=None, image_id=None,
image_name=None, tags=None, key_name=None,
security_groups=None, user_data=None, instance_type=None,
placement=None, kernel_id=None, ramdisk_id=None,
vpc_id... | Ensure an EC2 instance is running with the given attributes and state.
name
(string) - The name of the state definition. Recommended that this
match the instance_name attribute (generally the FQDN of the instance).
instance_name
(string) - The name of the instance, generally its FQDN. ... |
def status_for_all_orders(self):
"""Status for all orders
https://starfighter.readme.io/docs/status-for-all-orders
"""
url_fragment = 'venues/{venue}/accounts/{account}/orders'.format(
venue=self.venue,
account=self.account,
)
url = urljoin(self.b... | Status for all orders
https://starfighter.readme.io/docs/status-for-all-orders |
def with_path(self, path, *, encoded=False):
"""Return a new URL with path replaced."""
if not encoded:
path = self._PATH_QUOTER(path)
if self.is_absolute():
path = self._normalize_path(path)
if len(path) > 0 and path[0] != "/":
path = "/" + pa... | Return a new URL with path replaced. |
def eventFilter( self, object, event ):
"""
Filters the chart widget for the resize event to modify this scenes
rect.
:param object | <QObject>
event | <QEvent>
"""
if ( event.type() != event.Resize ):
return False
... | Filters the chart widget for the resize event to modify this scenes
rect.
:param object | <QObject>
event | <QEvent> |
def dropHistoricalTable(apps, schema_editor):
"""
Drops the historical sap_success_factors table named herein.
"""
table_name = 'sap_success_factors_historicalsapsuccessfactorsenterprisecus80ad'
if table_name in connection.introspection.table_names():
migrations.DeleteModel(
name... | Drops the historical sap_success_factors table named herein. |
def update_os_image_from_image_reference(self, image_name, os_image):
'''
Updates metadata elements from a given OS image reference.
image_name:
The name of the image to update.
os_image:
An instance of OSImage class.
os_image.label: Optional. Specifies a... | Updates metadata elements from a given OS image reference.
image_name:
The name of the image to update.
os_image:
An instance of OSImage class.
os_image.label: Optional. Specifies an identifier for the image.
os_image.description: Optional. Specifies the descript... |
def _get_asset(self, asset_uid):
"""
Returns raw response for an given asset by its unique id.
"""
uri = self.uri + '/v2/assets/' + asset_uid
headers = self._get_headers()
return self.service._get(uri, headers=headers) | Returns raw response for an given asset by its unique id. |
def is_type(self):
"""
:return:
:rtype: bool
"""
if self.__is_type_result is not None:
return self.__is_type_result
self.__is_type_result = self.__is_type()
return self.__is_type_result | :return:
:rtype: bool |
def update_rejection_permissions(portal):
"""Adds the permission 'Reject Analysis Request' and update the permission
mappings accordingly """
updated = update_rejection_permissions_for(portal, "bika_ar_workflow",
"Reject Analysis Request")
if updated:
... | Adds the permission 'Reject Analysis Request' and update the permission
mappings accordingly |
def pos_development_directory(templates,
inventory,
context,
topics,
user,
item):
"""Return absolute path to development directory
Arguments:
templates (... | Return absolute path to development directory
Arguments:
templates (dict): templates.yaml
inventory (dict): inventory.yaml
context (dict): The be context, from context()
topics (list): Arguments to `in`
user (str): Current `be` user
item (str): Item from template-bin... |
def detect_images_and_galleries(generators):
"""Runs generator on both pages and articles."""
for generator in generators:
if isinstance(generator, ArticlesGenerator):
for article in itertools.chain(generator.articles, generator.translations, generator.drafts):
detect_image(g... | Runs generator on both pages and articles. |
def invert(self):
'''
Invert by swapping each value with its key.
Returns
-------
MultiDict
Inverted multi-dict.
Examples
--------
>>> MultiDict({1: {1}, 2: {1,2,3}}, 4: {}).invert()
MultiDict({1: {1,2}, 2: {2}, 3: {2}})
'''
... | Invert by swapping each value with its key.
Returns
-------
MultiDict
Inverted multi-dict.
Examples
--------
>>> MultiDict({1: {1}, 2: {1,2,3}}, 4: {}).invert()
MultiDict({1: {1,2}, 2: {2}, 3: {2}}) |
def select(self, template_name):
"""
Select a particular template from the tribe.
:type template_name: str
:param template_name: Template name to look-up
:return: Template
.. rubric:: Example
>>> tribe = Tribe(templates=[Template(name='c'), Template(name='b'),
... | Select a particular template from the tribe.
:type template_name: str
:param template_name: Template name to look-up
:return: Template
.. rubric:: Example
>>> tribe = Tribe(templates=[Template(name='c'), Template(name='b'),
... Template(name='a... |
def applies(self, src, dst):
"""Checks if this rule applies to the given src and dst paths, based on the src pattern and
dst pattern given in the constructor.
If src pattern was None, this rule will apply to any given src path (same for dst).
"""
if self._src_pattern and (src is... | Checks if this rule applies to the given src and dst paths, based on the src pattern and
dst pattern given in the constructor.
If src pattern was None, this rule will apply to any given src path (same for dst). |
def get_account(self):
"""Get details of the current account.
:returns: an account object.
:rtype: Account
"""
api = self._get_api(iam.DeveloperApi)
return Account(api.get_my_account_info(include="limits, policies")) | Get details of the current account.
:returns: an account object.
:rtype: Account |
def container_query(self, query, quiet=False):
'''search for a specific container.
This function would likely be similar to the above, but have different
filter criteria from the user (based on the query)
'''
results = self._list_containers()
matches = []
for result in results:
... | search for a specific container.
This function would likely be similar to the above, but have different
filter criteria from the user (based on the query) |
def _classic_get_grouped_dicoms(dicom_input):
"""
Search all dicoms in the dicom directory, sort and validate them
fast_read = True will only read the headers not the data
"""
# Loop overall files and build dict
# Order all dicom files by InstanceNumber
if [d for d in dicom_input if 'Instan... | Search all dicoms in the dicom directory, sort and validate them
fast_read = True will only read the headers not the data |
def stage(self, name, pipeline_counter=None):
"""Helper to instantiate a :class:`gocd.api.stage.Stage` object
Args:
name: The name of the stage
pipeline_counter:
Returns:
"""
return Stage(
self.server,
pipeline_name=self.name,
... | Helper to instantiate a :class:`gocd.api.stage.Stage` object
Args:
name: The name of the stage
pipeline_counter:
Returns: |
def watch_docs(ctx):
"""Run build the docs when a file changes."""
try:
import sphinx_autobuild # noqa
except ImportError:
print('ERROR: watch task requires the sphinx_autobuild package.')
print('Install it with:')
print(' pip install sphinx-autobuild')
sys.exit(1... | Run build the docs when a file changes. |
def format_time(time):
""" Formats the given time into HH:MM:SS """
h, r = divmod(time / 1000, 3600)
m, s = divmod(r, 60)
return "%02d:%02d:%02d" % (h, m, s) | Formats the given time into HH:MM:SS |
def _show_notification(self,
event, summary, message, icon,
*actions):
"""
Show a notification.
:param str event: event name
:param str summary: notification title
:param str message: notification body
:param str icon... | Show a notification.
:param str event: event name
:param str summary: notification title
:param str message: notification body
:param str icon: icon name
:param actions: each item is a tuple with parameters for _add_action |
def register_app(self, app):
"""Register the route object to a `bottle.Bottle` app instance.
Args:
app (instance):
Returns:
Route instance (for chaining purposes)
"""
app.route(self.uri, methods=self.methods)(self.callable_obj)
return self | Register the route object to a `bottle.Bottle` app instance.
Args:
app (instance):
Returns:
Route instance (for chaining purposes) |
def add_scalar(self, name, value, step):
"""Log a scalar variable."""
self.writer.add_scalar(name, value, step) | Log a scalar variable. |
def timezone(client, location, timestamp=None, language=None):
"""Get time zone for a location on the earth, as well as that location's
time offset from UTC.
:param location: The latitude/longitude value representing the location to
look up.
:type location: string, dict, list, or tuple
:pa... | Get time zone for a location on the earth, as well as that location's
time offset from UTC.
:param location: The latitude/longitude value representing the location to
look up.
:type location: string, dict, list, or tuple
:param timestamp: Timestamp specifies the desired time as seconds since
... |
def qtrim_front(self, name, size=1):
"""
Sets the list element at ``index`` to ``value``. An error is returned for out of
range indexes.
:param string name: the queue name
:param int size: the max length of removed elements
:return: the length of removed elements
... | Sets the list element at ``index`` to ``value``. An error is returned for out of
range indexes.
:param string name: the queue name
:param int size: the max length of removed elements
:return: the length of removed elements
:rtype: int |
def expand(self, v):
"""Calculates the differences between a series of given measure values:
it calculates baseline values from position values.
:params v: a measure (of type 'baseline', 'position' or 'uvw')
:returns: a `dict` with the value for key `measures` being a measure
... | Calculates the differences between a series of given measure values:
it calculates baseline values from position values.
:params v: a measure (of type 'baseline', 'position' or 'uvw')
:returns: a `dict` with the value for key `measures` being a measure
and the value for key `x... |
def volatility(tnet, distance_func_name='default', calc='global', communities=None, event_displacement=None):
r"""
Volatility of temporal networks.
Volatility is the average distance between consecutive time points of graphlets (difference is caclualted either globally or per edge).
Parameters
---... | r"""
Volatility of temporal networks.
Volatility is the average distance between consecutive time points of graphlets (difference is caclualted either globally or per edge).
Parameters
----------
tnet : array or dict
temporal network input (graphlet or contact). Nettype: 'bu','bd','wu','w... |
def getPointOnLine(x1, y1, x2, y2, n):
"""Returns the (x, y) tuple of the point that has progressed a proportion
n along the line defined by the two x, y coordinates.
Copied from pytweening module.
"""
x = ((x2 - x1) * n) + x1
y = ((y2 - y1) * n) + y1
return (x, y) | Returns the (x, y) tuple of the point that has progressed a proportion
n along the line defined by the two x, y coordinates.
Copied from pytweening module. |
def checkBim(fileName, minNumber, chromosome):
"""Checks the BIM file for chrN markers.
:param fileName:
:param minNumber:
:param chromosome:
:type fileName: str
:type minNumber: int
:type chromosome: str
:returns: ``True`` if there are at least ``minNumber`` markers on
... | Checks the BIM file for chrN markers.
:param fileName:
:param minNumber:
:param chromosome:
:type fileName: str
:type minNumber: int
:type chromosome: str
:returns: ``True`` if there are at least ``minNumber`` markers on
chromosome ``chromosome``, ``False`` otherwise. |
def can_take(attrs_to_freeze=(), defaults=None, source_attr='source', instance_property_name='snapshot', inner_class_name='Snapshot'):
"""
Decorator to make a class allow their instances to generate
snapshot of themselves.
Decorates the class by allowing it to have:
* A custom class to serve each... | Decorator to make a class allow their instances to generate
snapshot of themselves.
Decorates the class by allowing it to have:
* A custom class to serve each snapshot. Such class
will have a subset of attributes to serve from the object,
and a special designed attribute ('source', by def... |
def show_warning(self, index):
"""
Decide if showing a warning when the user is trying to view
a big variable associated to a Tablemodel index
This avoids getting the variables' value to know its
size and type, using instead those already computed by
the TableMode... | Decide if showing a warning when the user is trying to view
a big variable associated to a Tablemodel index
This avoids getting the variables' value to know its
size and type, using instead those already computed by
the TableModel.
The problem is when a variable ... |
def add_group(self, number, name, led_type):
""" Add a group.
:param number: Group number (1-4).
:param name: Group name.
:param led_type: Either `RGBW`, `WRGB`, `RGBWW`, `WHITE`, `DIMMER` or `BRIDGE_LED`.
:returns: Added group.
"""
group = group_factory(self, nu... | Add a group.
:param number: Group number (1-4).
:param name: Group name.
:param led_type: Either `RGBW`, `WRGB`, `RGBWW`, `WHITE`, `DIMMER` or `BRIDGE_LED`.
:returns: Added group. |
def __parse(value):
"""
Parse the string datetime.
Supports the subset of ISO8601 used by xsd:dateTime, but is lenient
with what is accepted, handling most reasonable syntax.
Subsecond information is rounded to microseconds due to a restriction
in the python datetime.da... | Parse the string datetime.
Supports the subset of ISO8601 used by xsd:dateTime, but is lenient
with what is accepted, handling most reasonable syntax.
Subsecond information is rounded to microseconds due to a restriction
in the python datetime.datetime/time implementation.
@pa... |
def get_instance(self, payload):
"""
Build an instance of SipInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.sip.SipInstance
:rtype: twilio.rest.api.v2010.account.sip.SipInstance
"""
return SipInstance(self._ve... | Build an instance of SipInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.sip.SipInstance
:rtype: twilio.rest.api.v2010.account.sip.SipInstance |
def _initialize_installation(self):
"""
:rtype: None
"""
private_key_client = security.generate_rsa_private_key()
installation = core.Installation.create(
self,
security.public_key_to_string(private_key_client.publickey())
).value
token = ... | :rtype: None |
def initialize(self, **kwargs):
"""
Transfer functions may need additional information before the
supplied numpy array can be modified in place. For instance,
transfer functions may have state which needs to be allocated
in memory with a certain size. In other cases, the transfe... | Transfer functions may need additional information before the
supplied numpy array can be modified in place. For instance,
transfer functions may have state which needs to be allocated
in memory with a certain size. In other cases, the transfer
function may need to know about the coordin... |
def _run_coro(self, value):
""" Start the coroutine as task """
# when LAST_DISTINCT is used only start coroutine when value changed
if self._options.mode is MODE.LAST_DISTINCT and \
value == self._last_emit:
self._future = None
return
# store th... | Start the coroutine as task |
def update(self, story, params={}, **options):
"""Updates the story and returns the full record for the updated story.
Only comment stories can have their text updated, and only comment stories and
attachment stories can be pinned. Only one of `text` and `html_text` can be specified.
P... | Updates the story and returns the full record for the updated story.
Only comment stories can have their text updated, and only comment stories and
attachment stories can be pinned. Only one of `text` and `html_text` can be specified.
Parameters
----------
story : {Id} Globally ... |
def set_interval(self, start, end, value, compact=False):
"""Set the value for the time series on an interval. If compact is
True, only set the value if it's different from what it would
be anyway.
"""
# for each interval to render
for i, (s, e, v) in enumerate(self.iter... | Set the value for the time series on an interval. If compact is
True, only set the value if it's different from what it would
be anyway. |
def filesampler(files, testsetsize = 0.1, devsetsize = 0, trainsetsize = 0, outputdir = '', encoding='utf-8'):
"""Extract a training set, test set and optimally a development set from one file, or multiple *interdependent* files (such as a parallel corpus). It is assumed each line contains one instance (such as... | Extract a training set, test set and optimally a development set from one file, or multiple *interdependent* files (such as a parallel corpus). It is assumed each line contains one instance (such as a word or sentence for example). |
def get_changes(self, dest_attr, new_name=None, resources=None,
task_handle=taskhandle.NullTaskHandle()):
"""Return the changes needed for this refactoring
Parameters:
- `dest_attr`: the name of the destination attribute
- `new_name`: the name of the new method; if ... | Return the changes needed for this refactoring
Parameters:
- `dest_attr`: the name of the destination attribute
- `new_name`: the name of the new method; if `None` uses
the old name
- `resources` can be a list of `rope.base.resources.File`\s to
apply this refactorin... |
def _set_child(self, name, child):
"""
Set child.
:param name: Child name.
:param child: Parentable object.
"""
if not isinstance(child, Parentable):
raise ValueError('Parentable child object expected, not {child}'.format(child=child))
child._set_pare... | Set child.
:param name: Child name.
:param child: Parentable object. |
def _ParseVSSProcessingOptions(self, options):
"""Parses the VSS processing options.
Args:
options (argparse.Namespace): command line arguments.
Raises:
BadConfigOption: if the options are invalid.
"""
vss_only = False
vss_stores = None
self._process_vss = not getattr(options,... | Parses the VSS processing options.
Args:
options (argparse.Namespace): command line arguments.
Raises:
BadConfigOption: if the options are invalid. |
def macro_list(self, args: argparse.Namespace) -> None:
"""List some or all macros"""
if args.name:
for cur_name in utils.remove_duplicates(args.name):
if cur_name in self.macros:
self.poutput("macro create {} {}".format(cur_name, self.macros[cur_name].val... | List some or all macros |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.