code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def _to_DOM(self):
"""
Dumps object data to a fully traversable DOM representation of the
object.
:returns: a ``xml.etree.Element`` object
"""
root_node = ET.Element("forecast")
interval_node = ET.SubElement(root_node, "interval")
interval_node.text = se... | Dumps object data to a fully traversable DOM representation of the
object.
:returns: a ``xml.etree.Element`` object | Below is the the instruction that describes the task:
### Input:
Dumps object data to a fully traversable DOM representation of the
object.
:returns: a ``xml.etree.Element`` object
### Response:
def _to_DOM(self):
"""
Dumps object data to a fully traversable DOM representation of t... |
def value(self):
"""
Return the current evaluation of a condition statement
"""
return ''.join(map(str, self.evaluate(self.trigger.user))) | Return the current evaluation of a condition statement | Below is the the instruction that describes the task:
### Input:
Return the current evaluation of a condition statement
### Response:
def value(self):
"""
Return the current evaluation of a condition statement
"""
return ''.join(map(str, self.evaluate(self.trigger.user))) |
def get_monophyletic(self, values, target_attr):
"""
Returns a list of nodes matching the provided monophyly
criteria. For a node to be considered a match, all
`target_attr` values within and node, and exclusively them,
should be grouped.
:param values: a set of values f... | Returns a list of nodes matching the provided monophyly
criteria. For a node to be considered a match, all
`target_attr` values within and node, and exclusively them,
should be grouped.
:param values: a set of values for which monophyly is
expected.
:param target_at... | Below is the the instruction that describes the task:
### Input:
Returns a list of nodes matching the provided monophyly
criteria. For a node to be considered a match, all
`target_attr` values within and node, and exclusively them,
should be grouped.
:param values: a set of values f... |
def is_fraction(value,
minimum = None,
maximum = None,
**kwargs):
"""Indicate whether ``value`` is a :class:`Fraction <python:fractions.Fraction>`.
:param value: The value to evaluate.
:param minimum: If supplied, will make sure that ``value`` is greater tha... | Indicate whether ``value`` is a :class:`Fraction <python:fractions.Fraction>`.
:param value: The value to evaluate.
:param minimum: If supplied, will make sure that ``value`` is greater than or
equal to this value.
:type minimum: numeric
:param maximum: If supplied, will make sure that ``value`... | Below is the the instruction that describes the task:
### Input:
Indicate whether ``value`` is a :class:`Fraction <python:fractions.Fraction>`.
:param value: The value to evaluate.
:param minimum: If supplied, will make sure that ``value`` is greater than or
equal to this value.
:type minimum: n... |
def call_function(self, c, i):
"""
Implement the CALL_FUNCTION_ operation.
.. _CALL_FUNCTION: https://docs.python.org/3/library/dis.html#opcode-CALL_FUNCTION
"""
callable_ = self.__stack[-1-i.arg]
args = tuple(self.__stack[len(self.__stack) - i.arg:])
... | Implement the CALL_FUNCTION_ operation.
.. _CALL_FUNCTION: https://docs.python.org/3/library/dis.html#opcode-CALL_FUNCTION | Below is the the instruction that describes the task:
### Input:
Implement the CALL_FUNCTION_ operation.
.. _CALL_FUNCTION: https://docs.python.org/3/library/dis.html#opcode-CALL_FUNCTION
### Response:
def call_function(self, c, i):
"""
Implement the CALL_FUNCTION_ operation.
.. _... |
def filter_rank_genes_groups(adata, key=None, groupby=None, use_raw=True, log=True,
key_added='rank_genes_groups_filtered',
min_in_group_fraction=0.25, min_fold_change=2,
max_out_group_fraction=0.5):
"""Filters out genes based on... | Filters out genes based on fold change and fraction of genes expressing the gene within and outside the `groupby` categories.
See :func:`~scanpy.tl.rank_genes_groups`.
Results are stored in `adata.uns[key_added]` (default: 'rank_genes_groups_filtered').
To preserve the original structure of adata.uns['ra... | Below is the the instruction that describes the task:
### Input:
Filters out genes based on fold change and fraction of genes expressing the gene within and outside the `groupby` categories.
See :func:`~scanpy.tl.rank_genes_groups`.
Results are stored in `adata.uns[key_added]` (default: 'rank_genes_groups... |
def add(self, value):
"""Add element *value* to the set."""
# Raise TypeError if value is not hashable
hash(value)
self.redis.sadd(self.key, self._pickle(value)) | Add element *value* to the set. | Below is the the instruction that describes the task:
### Input:
Add element *value* to the set.
### Response:
def add(self, value):
"""Add element *value* to the set."""
# Raise TypeError if value is not hashable
hash(value)
self.redis.sadd(self.key, self._pickle(value)) |
def setWorker(self, *args, **kwargs):
"""Add a worker assignation
Arguments and order to pass are defined in LAUNCHING_ARGUMENTS
Using named args is advised.
"""
try:
la = self.LAUNCHING_ARGUMENTS(*args, **kwargs)
except TypeError as e:
sco... | Add a worker assignation
Arguments and order to pass are defined in LAUNCHING_ARGUMENTS
Using named args is advised. | Below is the the instruction that describes the task:
### Input:
Add a worker assignation
Arguments and order to pass are defined in LAUNCHING_ARGUMENTS
Using named args is advised.
### Response:
def setWorker(self, *args, **kwargs):
"""Add a worker assignation
Arguments... |
def emg_linear_envelope(emg, sampling_rate=1000, freqs=[10, 400], lfreq=4):
r"""Calculate the linear envelope of a signal.
Parameters
----------
emg : array
raw EMG signal.
sampling_rate : int
Sampling rate (samples/second).
freqs : list [fc_h, fc_l], optional
cutoff... | r"""Calculate the linear envelope of a signal.
Parameters
----------
emg : array
raw EMG signal.
sampling_rate : int
Sampling rate (samples/second).
freqs : list [fc_h, fc_l], optional
cutoff frequencies for the band-pass filter (in Hz).
lfreq : number, optional
... | Below is the the instruction that describes the task:
### Input:
r"""Calculate the linear envelope of a signal.
Parameters
----------
emg : array
raw EMG signal.
sampling_rate : int
Sampling rate (samples/second).
freqs : list [fc_h, fc_l], optional
cutoff frequencie... |
def extract_value_from_output(canary, split_offset, kal_out):
"""Return value parsed from output.
Args:
canary(str): This string must exist in the target line.
split_offset(int): Split offset for target value in string.
kal_out(int): Output from kal.
"""
retval = ""
while re... | Return value parsed from output.
Args:
canary(str): This string must exist in the target line.
split_offset(int): Split offset for target value in string.
kal_out(int): Output from kal. | Below is the the instruction that describes the task:
### Input:
Return value parsed from output.
Args:
canary(str): This string must exist in the target line.
split_offset(int): Split offset for target value in string.
kal_out(int): Output from kal.
### Response:
def extract_value_fro... |
def set_chksum(self, doc, chk_sum):
"""
Sets the external document reference's check sum, if not already set.
chk_sum - The checksum value in the form of a string.
"""
if chk_sum:
doc.ext_document_references[-1].check_sum = checksum.Algorithm(
'SHA1', ... | Sets the external document reference's check sum, if not already set.
chk_sum - The checksum value in the form of a string. | Below is the the instruction that describes the task:
### Input:
Sets the external document reference's check sum, if not already set.
chk_sum - The checksum value in the form of a string.
### Response:
def set_chksum(self, doc, chk_sum):
"""
Sets the external document reference's check sum... |
def fix_varscan_output(line, normal_name="", tumor_name=""):
"""Fix a varscan VCF line.
Fixes the ALT column and also fixes floating point values
output as strings to by Floats: FREQ, SSC.
This function was contributed by Sean Davis <sdavis2@mail.nih.gov>,
with minor modifications by Luca Beltrame... | Fix a varscan VCF line.
Fixes the ALT column and also fixes floating point values
output as strings to by Floats: FREQ, SSC.
This function was contributed by Sean Davis <sdavis2@mail.nih.gov>,
with minor modifications by Luca Beltrame <luca.beltrame@marionegri.it>. | Below is the the instruction that describes the task:
### Input:
Fix a varscan VCF line.
Fixes the ALT column and also fixes floating point values
output as strings to by Floats: FREQ, SSC.
This function was contributed by Sean Davis <sdavis2@mail.nih.gov>,
with minor modifications by Luca Beltram... |
def _convert_to_json(self, response):
"""Converts response to JSON.
If the response cannot be converted to JSON then `None` is returned.
Args:
response - An object of type `requests.models.Response`
Returns:
Response in JSON format if the response can be converte... | Converts response to JSON.
If the response cannot be converted to JSON then `None` is returned.
Args:
response - An object of type `requests.models.Response`
Returns:
Response in JSON format if the response can be converted to JSON. `None` otherwise. | Below is the the instruction that describes the task:
### Input:
Converts response to JSON.
If the response cannot be converted to JSON then `None` is returned.
Args:
response - An object of type `requests.models.Response`
Returns:
Response in JSON format if the resp... |
def _GetLink(self):
"""Retrieves the link.
Returns:
str: full path of the linked file entry.
"""
if self._link is None:
self._link = ''
if self.entry_type != definitions.FILE_ENTRY_TYPE_LINK:
return self._link
cpio_archive_file = self._file_system.GetCPIOArchiveFile()
... | Retrieves the link.
Returns:
str: full path of the linked file entry. | Below is the the instruction that describes the task:
### Input:
Retrieves the link.
Returns:
str: full path of the linked file entry.
### Response:
def _GetLink(self):
"""Retrieves the link.
Returns:
str: full path of the linked file entry.
"""
if self._link is None:
self._... |
def download_file(save_path, file_url):
""" Download file from http url link """
r = requests.get(file_url) # create HTTP response object
with open(save_path, 'wb') as f:
f.write(r.content)
return save_path | Download file from http url link | Below is the the instruction that describes the task:
### Input:
Download file from http url link
### Response:
def download_file(save_path, file_url):
""" Download file from http url link """
r = requests.get(file_url) # create HTTP response object
with open(save_path, 'wb') as f:
f.write(r... |
def refresh_token(self):
"""
Refreshing the current expired access token
"""
self.token = self.oauth.refresh_token(self.access_token_url, refresh_token=self.get_refresh_token())
self.access_token = self.token.get("access_token") | Refreshing the current expired access token | Below is the the instruction that describes the task:
### Input:
Refreshing the current expired access token
### Response:
def refresh_token(self):
"""
Refreshing the current expired access token
"""
self.token = self.oauth.refresh_token(self.access_token_url, refresh_token=self.get... |
def render_local_template(service_name, environment, repo_root, template_file):
"""
Render a given service's template for a given environment and return it
"""
cmd = 'cd {} && ef-cf {} {} --devel --verbose'.format(repo_root, template_file, environment)
p = subprocess.Popen(cmd, shell=True, stdout=su... | Render a given service's template for a given environment and return it | Below is the the instruction that describes the task:
### Input:
Render a given service's template for a given environment and return it
### Response:
def render_local_template(service_name, environment, repo_root, template_file):
"""
Render a given service's template for a given environment and return it
... |
def get_cookies(self):
'''
Retreive the cookies from the remote browser.
Return value is a list of http.cookiejar.Cookie() instances.
These can be directly used with the various http.cookiejar.XXXCookieJar
cookie management classes.
'''
ret = self.Network_getAllCookies()
assert 'result' in ret, "No re... | Retreive the cookies from the remote browser.
Return value is a list of http.cookiejar.Cookie() instances.
These can be directly used with the various http.cookiejar.XXXCookieJar
cookie management classes. | Below is the the instruction that describes the task:
### Input:
Retreive the cookies from the remote browser.
Return value is a list of http.cookiejar.Cookie() instances.
These can be directly used with the various http.cookiejar.XXXCookieJar
cookie management classes.
### Response:
def get_cookies(self):
... |
def _webfinger(provider, request, **kwargs):
"""Handle webfinger requests."""
params = urlparse.parse_qs(request)
if params["rel"][0] == OIC_ISSUER:
wf = WebFinger()
return Response(wf.response(params["resource"][0], provider.baseurl),
headers=[("Content-Type", "appli... | Handle webfinger requests. | Below is the the instruction that describes the task:
### Input:
Handle webfinger requests.
### Response:
def _webfinger(provider, request, **kwargs):
"""Handle webfinger requests."""
params = urlparse.parse_qs(request)
if params["rel"][0] == OIC_ISSUER:
wf = WebFinger()
return Response... |
def tofits(self, filename, overwrite=True, velocity=True,
optical=True, bitpix=-32, minpix=1, maxpix=-1):
"""Write the image to a file in FITS format.
`filename`
FITS file name
`overwrite`
If False, an exception is raised if the new image file already exists.
... | Write the image to a file in FITS format.
`filename`
FITS file name
`overwrite`
If False, an exception is raised if the new image file already exists.
Default is True.
`velocity`
By default a velocity primary spectral axis is written if possible.
... | Below is the the instruction that describes the task:
### Input:
Write the image to a file in FITS format.
`filename`
FITS file name
`overwrite`
If False, an exception is raised if the new image file already exists.
Default is True.
`velocity`
By defa... |
def register_watcher(self, event_type, callback, register_timeout=None):
"""
Register a callback for a given event type.
"""
self._push_watchers[event_type].add(callback)
self.wait_for_response(
RegisterMessage(event_list=[event_type]),
timeout=register_ti... | Register a callback for a given event type. | Below is the the instruction that describes the task:
### Input:
Register a callback for a given event type.
### Response:
def register_watcher(self, event_type, callback, register_timeout=None):
"""
Register a callback for a given event type.
"""
self._push_watchers[event_type].add... |
async def _start_payloads(self, nursery):
"""Start all queued payloads"""
with self._lock:
for coroutine in self._payloads:
nursery.start_soon(coroutine)
self._payloads.clear()
await trio.sleep(0) | Start all queued payloads | Below is the the instruction that describes the task:
### Input:
Start all queued payloads
### Response:
async def _start_payloads(self, nursery):
"""Start all queued payloads"""
with self._lock:
for coroutine in self._payloads:
nursery.start_soon(coroutine)
... |
def dump(u, *args, **kwargs):
"""Dump the users as a list of dictionaries.
:param u: User to be dumped.
:type u: `invenio.modules.accounts.models.User [Invenio2.x]` or namedtuple.
:returns: User serialized to dictionary.
:rtype: dict
"""
return dict(
id=u.id,
email=u.email,
... | Dump the users as a list of dictionaries.
:param u: User to be dumped.
:type u: `invenio.modules.accounts.models.User [Invenio2.x]` or namedtuple.
:returns: User serialized to dictionary.
:rtype: dict | Below is the the instruction that describes the task:
### Input:
Dump the users as a list of dictionaries.
:param u: User to be dumped.
:type u: `invenio.modules.accounts.models.User [Invenio2.x]` or namedtuple.
:returns: User serialized to dictionary.
:rtype: dict
### Response:
def dump(u, *args,... |
def parse_html(html):
"""Attempt to convert html to plain text while keeping line breaks.
Returns a list of paragraphs, each being a list of lines.
"""
paragraphs = re.split("</?p[^>]*>", html)
# Convert <br>s to line breaks and remove empty paragraphs
paragraphs = [re.split("<br */?>", p) for ... | Attempt to convert html to plain text while keeping line breaks.
Returns a list of paragraphs, each being a list of lines. | Below is the the instruction that describes the task:
### Input:
Attempt to convert html to plain text while keeping line breaks.
Returns a list of paragraphs, each being a list of lines.
### Response:
def parse_html(html):
"""Attempt to convert html to plain text while keeping line breaks.
Returns a l... |
def cwt_coefficients(x, param):
"""
Calculates a Continuous wavelet transform for the Ricker wavelet, also known as the "Mexican hat wavelet" which is
defined by
.. math::
\\frac{2}{\\sqrt{3a} \\pi^{\\frac{1}{4}}} (1 - \\frac{x^2}{a^2}) exp(-\\frac{x^2}{2a^2})
where :math:`a` is the width ... | Calculates a Continuous wavelet transform for the Ricker wavelet, also known as the "Mexican hat wavelet" which is
defined by
.. math::
\\frac{2}{\\sqrt{3a} \\pi^{\\frac{1}{4}}} (1 - \\frac{x^2}{a^2}) exp(-\\frac{x^2}{2a^2})
where :math:`a` is the width parameter of the wavelet function.
This... | Below is the the instruction that describes the task:
### Input:
Calculates a Continuous wavelet transform for the Ricker wavelet, also known as the "Mexican hat wavelet" which is
defined by
.. math::
\\frac{2}{\\sqrt{3a} \\pi^{\\frac{1}{4}}} (1 - \\frac{x^2}{a^2}) exp(-\\frac{x^2}{2a^2})
wher... |
def makeRecord(self, name, level, fn, lno, msg, args, exc_info, func=None, extra=None, sinfo=None):
"""Override default logger to allow overriding of internal attributes."""
# See below commented section for a simple example of what the docstring refers to
if six.PY2:
rv = logging.Lo... | Override default logger to allow overriding of internal attributes. | Below is the the instruction that describes the task:
### Input:
Override default logger to allow overriding of internal attributes.
### Response:
def makeRecord(self, name, level, fn, lno, msg, args, exc_info, func=None, extra=None, sinfo=None):
"""Override default logger to allow overriding of internal a... |
def _disambiguate_pos(self, terms, pos):
"""
Disambiguates a list of tokens of a given PoS.
"""
# Map the terms to candidate concepts
# Consider only the top 3 most common senses
candidate_map = {term: wn.synsets(term, pos=pos)[:3] for term in terms}
# Filter to ... | Disambiguates a list of tokens of a given PoS. | Below is the the instruction that describes the task:
### Input:
Disambiguates a list of tokens of a given PoS.
### Response:
def _disambiguate_pos(self, terms, pos):
"""
Disambiguates a list of tokens of a given PoS.
"""
# Map the terms to candidate concepts
# Consider only... |
def create(cls, pid_value, **kwargs):
"""Create a new record identifier.
For more information about parameters,
see :meth:`invenio_pidstore.providers.BaseProvider.create`.
:param pid_value: Persistent identifier value.
:params **kwargs: See
:meth:`invenio_pidstore.p... | Create a new record identifier.
For more information about parameters,
see :meth:`invenio_pidstore.providers.BaseProvider.create`.
:param pid_value: Persistent identifier value.
:params **kwargs: See
:meth:`invenio_pidstore.providers.base.BaseProvider.create` extra
... | Below is the the instruction that describes the task:
### Input:
Create a new record identifier.
For more information about parameters,
see :meth:`invenio_pidstore.providers.BaseProvider.create`.
:param pid_value: Persistent identifier value.
:params **kwargs: See
:meth... |
def disable_svc_freshness_check(self, service):
"""Disable freshness check for a service
Format of the line that triggers function call::
DISABLE_SERVICE_FRESHNESS_CHECK;<host_name>;<service_description>
:param service: service to edit
:type service: alignak.objects.service.Ser... | Disable freshness check for a service
Format of the line that triggers function call::
DISABLE_SERVICE_FRESHNESS_CHECK;<host_name>;<service_description>
:param service: service to edit
:type service: alignak.objects.service.Service
:return: None | Below is the the instruction that describes the task:
### Input:
Disable freshness check for a service
Format of the line that triggers function call::
DISABLE_SERVICE_FRESHNESS_CHECK;<host_name>;<service_description>
:param service: service to edit
:type service: alignak.objects.s... |
def _simple_cmd(cmd, app, url='http://localhost:8080/manager', timeout=180):
'''
Simple command wrapper to commands that need only a path option
'''
try:
opts = {
'path': app,
'version': ls(url)[app]['version']
}
return '\n'.join(_wget(cmd, opts, url, tim... | Simple command wrapper to commands that need only a path option | Below is the the instruction that describes the task:
### Input:
Simple command wrapper to commands that need only a path option
### Response:
def _simple_cmd(cmd, app, url='http://localhost:8080/manager', timeout=180):
'''
Simple command wrapper to commands that need only a path option
'''
try:
... |
def filter_factory(global_conf, **local_conf):
"""Returns a WSGI filter app for use with paste.deploy."""
conf = global_conf.copy()
conf.update(local_conf)
def check_last_ip(app):
return LastIpCheck(app, conf)
return check_last_ip | Returns a WSGI filter app for use with paste.deploy. | Below is the the instruction that describes the task:
### Input:
Returns a WSGI filter app for use with paste.deploy.
### Response:
def filter_factory(global_conf, **local_conf):
"""Returns a WSGI filter app for use with paste.deploy."""
conf = global_conf.copy()
conf.update(local_conf)
def check_... |
def set(self, value, *keys):
"""
Sets the dict of the information as read from the yaml file. To access
the file safely, you can use the keys in the order of the access.
Example: set("{'project':{'fg82':[i0-i10]}}", "provisioner","policy")
will set the value of config["provisione... | Sets the dict of the information as read from the yaml file. To access
the file safely, you can use the keys in the order of the access.
Example: set("{'project':{'fg82':[i0-i10]}}", "provisioner","policy")
will set the value of config["provisioner"]["policy"] in the yaml file if
it does... | Below is the the instruction that describes the task:
### Input:
Sets the dict of the information as read from the yaml file. To access
the file safely, you can use the keys in the order of the access.
Example: set("{'project':{'fg82':[i0-i10]}}", "provisioner","policy")
will set the value o... |
def update_status(self, progress):
"""
waits for a signal emitted from a thread and updates the gui
Args:
progress:
Returns:
"""
# interval at which the gui will be updated, if requests come in faster than they will be ignored
update_interval = 0.2
... | waits for a signal emitted from a thread and updates the gui
Args:
progress:
Returns: | Below is the the instruction that describes the task:
### Input:
waits for a signal emitted from a thread and updates the gui
Args:
progress:
Returns:
### Response:
def update_status(self, progress):
"""
waits for a signal emitted from a thread and updates the gui
... |
def render(self, is_unicode=False, pretty_print=False):
"""Last thing to do before rendering"""
for f in self.graph.xml_filters:
self.root = f(self.root)
args = {'encoding': 'utf-8'}
svg = b''
if etree.lxml:
args['pretty_print'] = pretty_print
if... | Last thing to do before rendering | Below is the the instruction that describes the task:
### Input:
Last thing to do before rendering
### Response:
def render(self, is_unicode=False, pretty_print=False):
"""Last thing to do before rendering"""
for f in self.graph.xml_filters:
self.root = f(self.root)
args = {'enc... |
def dump(thing, query, from_date, file_prefix, chunk_size, limit, thing_flags):
"""Dump data from Invenio legacy."""
init_app_context()
file_prefix = file_prefix if file_prefix else '{0}_dump'.format(thing)
kwargs = dict((f.strip('-').replace('-', '_'), True) for f in thing_flags)
try:
th... | Dump data from Invenio legacy. | Below is the the instruction that describes the task:
### Input:
Dump data from Invenio legacy.
### Response:
def dump(thing, query, from_date, file_prefix, chunk_size, limit, thing_flags):
"""Dump data from Invenio legacy."""
init_app_context()
file_prefix = file_prefix if file_prefix else '{0}_dump'... |
def create_cloudwatch_log_event(app_name, env, region, rules):
"""Create cloudwatch log event for lambda from rules.
Args:
app_name (str): name of the lambda function
env (str): Environment/Account for lambda function
region (str): AWS region of the lambda function
rules (str): ... | Create cloudwatch log event for lambda from rules.
Args:
app_name (str): name of the lambda function
env (str): Environment/Account for lambda function
region (str): AWS region of the lambda function
rules (str): Trigger rules from the settings | Below is the the instruction that describes the task:
### Input:
Create cloudwatch log event for lambda from rules.
Args:
app_name (str): name of the lambda function
env (str): Environment/Account for lambda function
region (str): AWS region of the lambda function
rules (str): T... |
def update_factor(self, name, body):
"""Update Guardian factor
Useful to enable / disable factor
Args:
name (str): Either push-notification or sms
body (dict): Attributes to modify.
See: https://auth0.com/docs/api/management/v2#!/Guardian/put_factors_by_name
... | Update Guardian factor
Useful to enable / disable factor
Args:
name (str): Either push-notification or sms
body (dict): Attributes to modify.
See: https://auth0.com/docs/api/management/v2#!/Guardian/put_factors_by_name | Below is the the instruction that describes the task:
### Input:
Update Guardian factor
Useful to enable / disable factor
Args:
name (str): Either push-notification or sms
body (dict): Attributes to modify.
See: https://auth0.com/docs/api/management/v2#!/Guardian... |
def make_hash(o):
r"""
Makes a hash from a dictionary, list, tuple or set to any level, that
contains only other hashable types (including any lists, tuples, sets, and
dictionaries). In the case where other kinds of objects (like classes) need
to be hashed, pass in a collection of object attributes ... | r"""
Makes a hash from a dictionary, list, tuple or set to any level, that
contains only other hashable types (including any lists, tuples, sets, and
dictionaries). In the case where other kinds of objects (like classes) need
to be hashed, pass in a collection of object attributes that are pertinent.
... | Below is the the instruction that describes the task:
### Input:
r"""
Makes a hash from a dictionary, list, tuple or set to any level, that
contains only other hashable types (including any lists, tuples, sets, and
dictionaries). In the case where other kinds of objects (like classes) need
to be has... |
def create_loadbalancer(self, datacenter_id, loadbalancer):
"""
Creates a load balancer within the specified data center.
:param datacenter_id: The unique ID of the data center.
:type datacenter_id: ``str``
:param loadbalancer: The load balancer object to be cre... | Creates a load balancer within the specified data center.
:param datacenter_id: The unique ID of the data center.
:type datacenter_id: ``str``
:param loadbalancer: The load balancer object to be created.
:type loadbalancer: ``dict`` | Below is the the instruction that describes the task:
### Input:
Creates a load balancer within the specified data center.
:param datacenter_id: The unique ID of the data center.
:type datacenter_id: ``str``
:param loadbalancer: The load balancer object to be created.
... |
def siphashx24(message, key=b'', encoder=nacl.encoding.HexEncoder):
"""
Computes a keyed MAC of ``message`` using the 128 bit variant of the
siphash-2-4 construction.
:param message: The message to hash.
:type message: bytes
:param key: the message authentication key for the siphash MAC constru... | Computes a keyed MAC of ``message`` using the 128 bit variant of the
siphash-2-4 construction.
:param message: The message to hash.
:type message: bytes
:param key: the message authentication key for the siphash MAC construct
:type key: bytes(:const:`SIPHASHX_KEYBYTES`)
:param encoder: A class ... | Below is the the instruction that describes the task:
### Input:
Computes a keyed MAC of ``message`` using the 128 bit variant of the
siphash-2-4 construction.
:param message: The message to hash.
:type message: bytes
:param key: the message authentication key for the siphash MAC construct
:typ... |
def additive_noise(stream, key='X', scale=1e-1):
'''Add noise to a data stream.
Parameters
----------
stream : iterable
A stream that yields data objects.
key : string, default='X'
Name of the field to add noise.
scale : float, default=0.1
Scale factor for gaussian noi... | Add noise to a data stream.
Parameters
----------
stream : iterable
A stream that yields data objects.
key : string, default='X'
Name of the field to add noise.
scale : float, default=0.1
Scale factor for gaussian noise.
Yields
------
data : dict
Updat... | Below is the the instruction that describes the task:
### Input:
Add noise to a data stream.
Parameters
----------
stream : iterable
A stream that yields data objects.
key : string, default='X'
Name of the field to add noise.
scale : float, default=0.1
Scale factor for... |
def get_path_matching(name):
"""Get path matching a name.
Parameters
----------
name : string
Name to search for.
Returns
-------
string
Full filepath.
"""
# first try looking in the user folder
p = os.path.join(os.path.expanduser("~"), name)
# then try expa... | Get path matching a name.
Parameters
----------
name : string
Name to search for.
Returns
-------
string
Full filepath. | Below is the the instruction that describes the task:
### Input:
Get path matching a name.
Parameters
----------
name : string
Name to search for.
Returns
-------
string
Full filepath.
### Response:
def get_path_matching(name):
"""Get path matching a name.
Paramet... |
def tree_type_checker(*ref):
'''Tree type checker functor
Returns:
Functor that takes a tree, and returns true if that tree matches any of
NeuriteTypes in ref
Ex:
>>> from neurom.core.types import NeuriteType, tree_type_checker
>>> tree_filter = tree_type_checker(NeuriteTyp... | Tree type checker functor
Returns:
Functor that takes a tree, and returns true if that tree matches any of
NeuriteTypes in ref
Ex:
>>> from neurom.core.types import NeuriteType, tree_type_checker
>>> tree_filter = tree_type_checker(NeuriteType.axon, NeuriteType.basal_dendrite)
... | Below is the the instruction that describes the task:
### Input:
Tree type checker functor
Returns:
Functor that takes a tree, and returns true if that tree matches any of
NeuriteTypes in ref
Ex:
>>> from neurom.core.types import NeuriteType, tree_type_checker
>>> tree_filt... |
def _compile_bus_injection(self):
"""Impose injections on buses"""
string = '"""\n'
for device, series in zip(self.devices, self.series):
if series:
string += 'system.' + device + '.gcall(system.dae)\n'
string += '\n'
string += 'system.dae.reset_small_... | Impose injections on buses | Below is the the instruction that describes the task:
### Input:
Impose injections on buses
### Response:
def _compile_bus_injection(self):
"""Impose injections on buses"""
string = '"""\n'
for device, series in zip(self.devices, self.series):
if series:
string +... |
def DataIsInteger(self):
"""Determines, based on the data type, if the data is an integer.
The data types considered strings are: REG_DWORD (REG_DWORD_LITTLE_ENDIAN),
REG_DWORD_BIG_ENDIAN and REG_QWORD.
Returns:
bool: True if the data is an integer, False otherwise.
"""
return self.data_... | Determines, based on the data type, if the data is an integer.
The data types considered strings are: REG_DWORD (REG_DWORD_LITTLE_ENDIAN),
REG_DWORD_BIG_ENDIAN and REG_QWORD.
Returns:
bool: True if the data is an integer, False otherwise. | Below is the the instruction that describes the task:
### Input:
Determines, based on the data type, if the data is an integer.
The data types considered strings are: REG_DWORD (REG_DWORD_LITTLE_ENDIAN),
REG_DWORD_BIG_ENDIAN and REG_QWORD.
Returns:
bool: True if the data is an integer, False oth... |
async def send_request(self, connection: Connection, payment_handle: int):
"""
Approves the credential offer and submits a credential request. The result will be a credential stored in the prover's wallet.
:param connection: connection to submit request from
:param payment_handle: curren... | Approves the credential offer and submits a credential request. The result will be a credential stored in the prover's wallet.
:param connection: connection to submit request from
:param payment_handle: currently unused
:return:
Example:
connection = await Connection.create(sourc... | Below is the the instruction that describes the task:
### Input:
Approves the credential offer and submits a credential request. The result will be a credential stored in the prover's wallet.
:param connection: connection to submit request from
:param payment_handle: currently unused
:return... |
def is_username(string, minlen=1, maxlen=15):
""" Determines whether the @string pattern is username-like
@string: #str being tested
@minlen: minimum required username length
@maxlen: maximum username length
-> #bool
"""
if string:
string = string.strip()
ret... | Determines whether the @string pattern is username-like
@string: #str being tested
@minlen: minimum required username length
@maxlen: maximum username length
-> #bool | Below is the the instruction that describes the task:
### Input:
Determines whether the @string pattern is username-like
@string: #str being tested
@minlen: minimum required username length
@maxlen: maximum username length
-> #bool
### Response:
def is_username(string, minlen=1, ma... |
def properties(lines):
"""Parse properties block
Returns:
dict: {property_type: (atom_index, value)}
"""
results = {}
for i, line in enumerate(lines):
type_ = line[3:6]
if type_ not in ["CHG", "RAD", "ISO"]:
continue # Other properties are not supported yet
... | Parse properties block
Returns:
dict: {property_type: (atom_index, value)} | Below is the the instruction that describes the task:
### Input:
Parse properties block
Returns:
dict: {property_type: (atom_index, value)}
### Response:
def properties(lines):
"""Parse properties block
Returns:
dict: {property_type: (atom_index, value)}
"""
results = {}
f... |
def get_album(self, object_id, relation=None, **kwargs):
"""
Get the album with the provided id
:returns: an :class:`~deezer.resources.Album` object
"""
return self.get_object("album", object_id, relation=relation, **kwargs) | Get the album with the provided id
:returns: an :class:`~deezer.resources.Album` object | Below is the the instruction that describes the task:
### Input:
Get the album with the provided id
:returns: an :class:`~deezer.resources.Album` object
### Response:
def get_album(self, object_id, relation=None, **kwargs):
"""
Get the album with the provided id
:returns: an :clas... |
def _tobinarray_really(self, start, end, pad, size):
"""Return binary array."""
if pad is None:
pad = self.padding
bin = array('B')
if self._buf == {} and None in (start, end):
return bin
if size is not None and size <= 0:
raise ValueError("tob... | Return binary array. | Below is the the instruction that describes the task:
### Input:
Return binary array.
### Response:
def _tobinarray_really(self, start, end, pad, size):
"""Return binary array."""
if pad is None:
pad = self.padding
bin = array('B')
if self._buf == {} and None in (start, ... |
def get_single_header(headers, key):
"""
Get a single value for the given key out of the given set of headers.
:param twisted.web.http_headers.Headers headers:
The set of headers in which to look for the header value
:param str key:
The header key
"""
raw_headers = headers.getRa... | Get a single value for the given key out of the given set of headers.
:param twisted.web.http_headers.Headers headers:
The set of headers in which to look for the header value
:param str key:
The header key | Below is the the instruction that describes the task:
### Input:
Get a single value for the given key out of the given set of headers.
:param twisted.web.http_headers.Headers headers:
The set of headers in which to look for the header value
:param str key:
The header key
### Response:
def ... |
def get_l2cap_options (sock):
"""get_l2cap_options (sock, mtu)
Gets L2CAP options for the specified L2CAP socket.
Options are: omtu, imtu, flush_to, mode, fcs, max_tx, txwin_size.
"""
# TODO this should be in the C module, because it depends
# directly on struct l2cap_options layout.
s = so... | get_l2cap_options (sock, mtu)
Gets L2CAP options for the specified L2CAP socket.
Options are: omtu, imtu, flush_to, mode, fcs, max_tx, txwin_size. | Below is the the instruction that describes the task:
### Input:
get_l2cap_options (sock, mtu)
Gets L2CAP options for the specified L2CAP socket.
Options are: omtu, imtu, flush_to, mode, fcs, max_tx, txwin_size.
### Response:
def get_l2cap_options (sock):
"""get_l2cap_options (sock, mtu)
Gets L2C... |
def untracable(object):
"""
Marks decorated object as non tracable.
:param object: Object to decorate.
:type object: object
:return: Object.
:rtype: object
"""
@functools.wraps(object)
def untracable_wrapper(*args, **kwargs):
"""
Marks decorated object as non tracab... | Marks decorated object as non tracable.
:param object: Object to decorate.
:type object: object
:return: Object.
:rtype: object | Below is the the instruction that describes the task:
### Input:
Marks decorated object as non tracable.
:param object: Object to decorate.
:type object: object
:return: Object.
:rtype: object
### Response:
def untracable(object):
"""
Marks decorated object as non tracable.
:param obj... |
def _check_frames(self, frames, fill_value):
"""Reduce frames to no more than are available in the file."""
if self.seekable():
remaining_frames = self.frames - self.tell()
if frames < 0 or (frames > remaining_frames and
fill_value is None):
... | Reduce frames to no more than are available in the file. | Below is the the instruction that describes the task:
### Input:
Reduce frames to no more than are available in the file.
### Response:
def _check_frames(self, frames, fill_value):
"""Reduce frames to no more than are available in the file."""
if self.seekable():
remaining_frames = self... |
def get_safe_type(self):
"""Determines the type of ESA product.
In 2016 ESA changed structure and naming of data. Therefore the class must
distinguish between old product type and compact (new) product type.
:return: type of ESA product
:rtype: constants.EsaSafeType
:ra... | Determines the type of ESA product.
In 2016 ESA changed structure and naming of data. Therefore the class must
distinguish between old product type and compact (new) product type.
:return: type of ESA product
:rtype: constants.EsaSafeType
:raises: ValueError | Below is the the instruction that describes the task:
### Input:
Determines the type of ESA product.
In 2016 ESA changed structure and naming of data. Therefore the class must
distinguish between old product type and compact (new) product type.
:return: type of ESA product
:rtype: ... |
def fastp_read_n_plot(self):
""" Make the read N content plot for Fastp """
data_labels, pdata = self.filter_pconfig_pdata_subplots(self.fastp_n_content_data, 'Base Content Percent')
pconfig = {
'id': 'fastp-seq-content-n-plot',
'title': 'Fastp: Read N Content',
... | Make the read N content plot for Fastp | Below is the the instruction that describes the task:
### Input:
Make the read N content plot for Fastp
### Response:
def fastp_read_n_plot(self):
""" Make the read N content plot for Fastp """
data_labels, pdata = self.filter_pconfig_pdata_subplots(self.fastp_n_content_data, 'Base Content Percent'... |
def add_layer_to_canvas(layer, name):
"""Helper method to add layer to QGIS.
:param layer: The layer.
:type layer: QgsMapLayer
:param name: Layer name.
:type name: str
"""
if qgis_version() >= 21800:
layer.setName(name)
else:
layer.setLayerName(name)
QgsProject.in... | Helper method to add layer to QGIS.
:param layer: The layer.
:type layer: QgsMapLayer
:param name: Layer name.
:type name: str | Below is the the instruction that describes the task:
### Input:
Helper method to add layer to QGIS.
:param layer: The layer.
:type layer: QgsMapLayer
:param name: Layer name.
:type name: str
### Response:
def add_layer_to_canvas(layer, name):
"""Helper method to add layer to QGIS.
:para... |
def bufsize_validator(kwargs):
""" a validator to prevent a user from saying that they want custom
buffering when they're using an in/out object that will be os.dup'd to the
process, and has its own buffering. an example is a pipe or a tty. it
doesn't make sense to tell them to have a custom buffering... | a validator to prevent a user from saying that they want custom
buffering when they're using an in/out object that will be os.dup'd to the
process, and has its own buffering. an example is a pipe or a tty. it
doesn't make sense to tell them to have a custom buffering, since the os
controls this. | Below is the the instruction that describes the task:
### Input:
a validator to prevent a user from saying that they want custom
buffering when they're using an in/out object that will be os.dup'd to the
process, and has its own buffering. an example is a pipe or a tty. it
doesn't make sense to tell t... |
def send(self, message):
""" Send a message by forwarding it to the server
:param message: Message
:type message: smsframework.data.OutgoingMessage
:rtype: smsframework.data.OutgoingMessage
:raise Exception: any exception reported by the other side
:raise urllib2.URLError... | Send a message by forwarding it to the server
:param message: Message
:type message: smsframework.data.OutgoingMessage
:rtype: smsframework.data.OutgoingMessage
:raise Exception: any exception reported by the other side
:raise urllib2.URLError: Connection error | Below is the the instruction that describes the task:
### Input:
Send a message by forwarding it to the server
:param message: Message
:type message: smsframework.data.OutgoingMessage
:rtype: smsframework.data.OutgoingMessage
:raise Exception: any exception reported by the other side... |
def _pprint(self, cycle=False, flat=False, annotate=False, onlychanged=True, level=1, tab = ' '):
"""
Pretty printer that prints only the modified keywords and
generates flat representations (for repr) and optionally
annotates the top of the repr with a comment.
"""
(kw... | Pretty printer that prints only the modified keywords and
generates flat representations (for repr) and optionally
annotates the top of the repr with a comment. | Below is the the instruction that describes the task:
### Input:
Pretty printer that prints only the modified keywords and
generates flat representations (for repr) and optionally
annotates the top of the repr with a comment.
### Response:
def _pprint(self, cycle=False, flat=False, annotate=False, ... |
def next_unused_name_in_group(grp, length):
""" Gives a name that isn't used in a Group.
Generates a name of the desired length that is not a Dataset or
Group in the given group. Note, if length is not large enough and
`grp` is full enough, there may be no available names meaning that
this function... | Gives a name that isn't used in a Group.
Generates a name of the desired length that is not a Dataset or
Group in the given group. Note, if length is not large enough and
`grp` is full enough, there may be no available names meaning that
this function will hang.
Parameters
----------
grp :... | Below is the the instruction that describes the task:
### Input:
Gives a name that isn't used in a Group.
Generates a name of the desired length that is not a Dataset or
Group in the given group. Note, if length is not large enough and
`grp` is full enough, there may be no available names meaning that
... |
def objectnames_conesearch(racenter,
declcenter,
searchradiusarcsec,
simbad_mirror='simbad',
returnformat='csv',
forcefetch=False,
cachedir='~/.astrobase/simb... | This queries the SIMBAD TAP service for a list of object names near the
coords. This is effectively a "reverse" name resolver (i.e. this does the
opposite of SESAME).
Parameters
----------
racenter,declcenter : float
The cone-search center coordinates in decimal degrees
searchradiusar... | Below is the the instruction that describes the task:
### Input:
This queries the SIMBAD TAP service for a list of object names near the
coords. This is effectively a "reverse" name resolver (i.e. this does the
opposite of SESAME).
Parameters
----------
racenter,declcenter : float
The ... |
def _is_modification_or_activity(feature):
"""Return True if the feature is a modification"""
if not (isinstance(feature, _bp('ModificationFeature')) or \
isinstance(feature, _bpimpl('ModificationFeature'))):
return None
mf_type = feature.getModificationType()
if mf_type is None:
... | Return True if the feature is a modification | Below is the the instruction that describes the task:
### Input:
Return True if the feature is a modification
### Response:
def _is_modification_or_activity(feature):
"""Return True if the feature is a modification"""
if not (isinstance(feature, _bp('ModificationFeature')) or \
isinstance(featu... |
def _get_current_deployment_label(self):
'''
Helper method to find the deployment label that the stage_name is currently associated with.
'''
deploymentId = self._get_current_deployment_id()
deployment = __salt__['boto_apigateway.describe_api_deployment'](restApiId=self.restApiId... | Helper method to find the deployment label that the stage_name is currently associated with. | Below is the the instruction that describes the task:
### Input:
Helper method to find the deployment label that the stage_name is currently associated with.
### Response:
def _get_current_deployment_label(self):
'''
Helper method to find the deployment label that the stage_name is currently associ... |
def get_processes(sort_by_name=True):
"""Retrieve a list of processes sorted by name.
Args:
sort_by_name (bool): Sort the list by name or by process ID's.
Returns:
list of (int, str) or list of (int, str, str): List of process id,
process name and optional cmdline tuple... | Retrieve a list of processes sorted by name.
Args:
sort_by_name (bool): Sort the list by name or by process ID's.
Returns:
list of (int, str) or list of (int, str, str): List of process id,
process name and optional cmdline tuples. | Below is the the instruction that describes the task:
### Input:
Retrieve a list of processes sorted by name.
Args:
sort_by_name (bool): Sort the list by name or by process ID's.
Returns:
list of (int, str) or list of (int, str, str): List of process id,
process name and... |
def list(self, name, platform='', genre=''):
""" The name argument is required for this method as per the API
server specification. This method also provides the platform and genre
optional arguments as filters.
"""
data_list = self.db.get_data(self.list_path, name=name,
... | The name argument is required for this method as per the API
server specification. This method also provides the platform and genre
optional arguments as filters. | Below is the the instruction that describes the task:
### Input:
The name argument is required for this method as per the API
server specification. This method also provides the platform and genre
optional arguments as filters.
### Response:
def list(self, name, platform='', genre=''):
""" ... |
def tail(self, path, tail_length=1024, append=False):
# Note: append is currently not implemented.
''' Show the end of the file - default 1KB, supports up to the Hadoop block size.
:param path: Path to read
:type path: string
:param tail_length: The length to read from the end o... | Show the end of the file - default 1KB, supports up to the Hadoop block size.
:param path: Path to read
:type path: string
:param tail_length: The length to read from the end of the file - default 1KB, up to block size.
:type tail_length: int
:param append: Currently not impleme... | Below is the the instruction that describes the task:
### Input:
Show the end of the file - default 1KB, supports up to the Hadoop block size.
:param path: Path to read
:type path: string
:param tail_length: The length to read from the end of the file - default 1KB, up to block size.
... |
def date_range_builder(self, start='2013-02-11', end=None):
"""
Builds date range query.
:param start:
Date string. format: YYYY-MM-DD
:type start:
String
:param end:
date string. format: YYYY-MM-DD
:type end:
String
... | Builds date range query.
:param start:
Date string. format: YYYY-MM-DD
:type start:
String
:param end:
date string. format: YYYY-MM-DD
:type end:
String
:returns:
String | Below is the the instruction that describes the task:
### Input:
Builds date range query.
:param start:
Date string. format: YYYY-MM-DD
:type start:
String
:param end:
date string. format: YYYY-MM-DD
:type end:
String
:returns... |
def _delete_from_indices(self, pipeline):
"""Deletes the object's id from the sets(indices) it has been added
to and removes its list of indices (used for housekeeping).
"""
s = Set(self.key()['_indices'])
z = Set(self.key()['_zindices'])
for index in s.members:
... | Deletes the object's id from the sets(indices) it has been added
to and removes its list of indices (used for housekeeping). | Below is the the instruction that describes the task:
### Input:
Deletes the object's id from the sets(indices) it has been added
to and removes its list of indices (used for housekeeping).
### Response:
def _delete_from_indices(self, pipeline):
"""Deletes the object's id from the sets(indices) it ... |
def save(filename, obj, overwrite=False, create_directories=False):
'''
pimms.save(filename, obj) attempts to pickle the given object obj in the filename (or stream,
if given). An error is raised when this cannot be accomplished; the first argument is always
returned; though if the argument is a fil... | pimms.save(filename, obj) attempts to pickle the given object obj in the filename (or stream,
if given). An error is raised when this cannot be accomplished; the first argument is always
returned; though if the argument is a filename, it may be a differet string that refers to
the same file.
The ... | Below is the the instruction that describes the task:
### Input:
pimms.save(filename, obj) attempts to pickle the given object obj in the filename (or stream,
if given). An error is raised when this cannot be accomplished; the first argument is always
returned; though if the argument is a filename, it m... |
def _zforce(self,R,z,phi=0.,t=0.):
"""
NAME:
_zforce
PURPOSE:
evaluate the vertical force for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
... | NAME:
_zforce
PURPOSE:
evaluate the vertical force for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
the vertical force
HISTORY:
... | Below is the the instruction that describes the task:
### Input:
NAME:
_zforce
PURPOSE:
evaluate the vertical force for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
... |
def file_transfer_protocol_send(self, target_network, target_system, target_component, payload, force_mavlink1=False):
'''
File transfer message
target_network : Network ID (0 for broadcast) (uint8_t)
target_system : System ID (0 fo... | File transfer message
target_network : Network ID (0 for broadcast) (uint8_t)
target_system : System ID (0 for broadcast) (uint8_t)
target_component : Component ID (0 for broadcast) (uint8_t)
payload : Var... | Below is the the instruction that describes the task:
### Input:
File transfer message
target_network : Network ID (0 for broadcast) (uint8_t)
target_system : System ID (0 for broadcast) (uint8_t)
target_component : Component ID (0 for... |
def ssh(self, enable=True, comment=None):
"""
Enable or disable SSH
:param bool enable: enable or disable SSH daemon
:param str comment: optional comment for audit
:raises NodeCommandFailed: cannot enable SSH daemon
:return: None
"""
self.make_request(
... | Enable or disable SSH
:param bool enable: enable or disable SSH daemon
:param str comment: optional comment for audit
:raises NodeCommandFailed: cannot enable SSH daemon
:return: None | Below is the the instruction that describes the task:
### Input:
Enable or disable SSH
:param bool enable: enable or disable SSH daemon
:param str comment: optional comment for audit
:raises NodeCommandFailed: cannot enable SSH daemon
:return: None
### Response:
def ssh(self, enabl... |
def get_open_clinvar_submission(self, user_id, institute_id):
"""Retrieve the database id of an open clinvar submission for a user and institute,
if none is available then create a new submission and return it
Args:
user_id(str): a user ID
institute_id(str)... | Retrieve the database id of an open clinvar submission for a user and institute,
if none is available then create a new submission and return it
Args:
user_id(str): a user ID
institute_id(str): an institute ID
Returns:
submission(obj) : ... | Below is the the instruction that describes the task:
### Input:
Retrieve the database id of an open clinvar submission for a user and institute,
if none is available then create a new submission and return it
Args:
user_id(str): a user ID
institute_id(str): an... |
def slides(self):
"""
|Slides| object containing the slides in this presentation.
"""
sldIdLst = self._element.get_or_add_sldIdLst()
self.part.rename_slide_parts([sldId.rId for sldId in sldIdLst])
return Slides(sldIdLst, self) | |Slides| object containing the slides in this presentation. | Below is the the instruction that describes the task:
### Input:
|Slides| object containing the slides in this presentation.
### Response:
def slides(self):
"""
|Slides| object containing the slides in this presentation.
"""
sldIdLst = self._element.get_or_add_sldIdLst()
sel... |
def total_memory():
""" Returns the the amount of memory available for use.
The memory is obtained from MemTotal entry in /proc/meminfo.
Notes
=====
This function is not very useful and not very portable.
"""
with file('/proc/meminfo', 'r') as f:
for line ... | Returns the the amount of memory available for use.
The memory is obtained from MemTotal entry in /proc/meminfo.
Notes
=====
This function is not very useful and not very portable. | Below is the the instruction that describes the task:
### Input:
Returns the the amount of memory available for use.
The memory is obtained from MemTotal entry in /proc/meminfo.
Notes
=====
This function is not very useful and not very portable.
### Response:
def total_mem... |
def get(self, block=1, delay=None):
"""Get a request from a queue, optionally block until a request
is available."""
if _debug: IOQueue._debug("get block=%r delay=%r", block, delay)
# if the queue is empty and we do not block return None
if not block and not self.notempty.isSet(... | Get a request from a queue, optionally block until a request
is available. | Below is the the instruction that describes the task:
### Input:
Get a request from a queue, optionally block until a request
is available.
### Response:
def get(self, block=1, delay=None):
"""Get a request from a queue, optionally block until a request
is available."""
if _debug: I... |
def validate(user_input, ret_errs=False, print_errs=False):
"""
Wrapper for run_validator function that returns True if the user_input
contains a valid STIX pattern or False otherwise. The error messages may
also be returned or printed based upon the ret_errs and print_errs arg
values.
"""
... | Wrapper for run_validator function that returns True if the user_input
contains a valid STIX pattern or False otherwise. The error messages may
also be returned or printed based upon the ret_errs and print_errs arg
values. | Below is the the instruction that describes the task:
### Input:
Wrapper for run_validator function that returns True if the user_input
contains a valid STIX pattern or False otherwise. The error messages may
also be returned or printed based upon the ret_errs and print_errs arg
values.
### Response:
d... |
def size(args):
"""
%prog size fastqfile
Find the total base pairs in a list of fastq files
"""
p = OptionParser(size.__doc__)
opts, args = p.parse_args(args)
if len(args) < 1:
sys.exit(not p.print_help())
total_size = total_numrecords = 0
for f in args:
cur_size =... | %prog size fastqfile
Find the total base pairs in a list of fastq files | Below is the the instruction that describes the task:
### Input:
%prog size fastqfile
Find the total base pairs in a list of fastq files
### Response:
def size(args):
"""
%prog size fastqfile
Find the total base pairs in a list of fastq files
"""
p = OptionParser(size.__doc__)
opts, a... |
def receive_empty(self, message):
"""
Pair ACKs with requests.
:type message: Message
:param message: the received message
:rtype : Transaction
:return: the transaction to which the message belongs to
"""
logger.debug("receive_empty - " + str(message))
... | Pair ACKs with requests.
:type message: Message
:param message: the received message
:rtype : Transaction
:return: the transaction to which the message belongs to | Below is the the instruction that describes the task:
### Input:
Pair ACKs with requests.
:type message: Message
:param message: the received message
:rtype : Transaction
:return: the transaction to which the message belongs to
### Response:
def receive_empty(self, message):
... |
def validate(cls, code, prefix):
'''
Validates an octoDNS geo code making sure that it is a valid and
corresponding:
* continent
* continent & country
* continent, country, & province
'''
reasons = []
pieces = code.split('-')
n... | Validates an octoDNS geo code making sure that it is a valid and
corresponding:
* continent
* continent & country
* continent, country, & province | Below is the the instruction that describes the task:
### Input:
Validates an octoDNS geo code making sure that it is a valid and
corresponding:
* continent
* continent & country
* continent, country, & province
### Response:
def validate(cls, code, prefix):
'''
... |
def to_csv(self, file: str, opts: dict = None) -> str:
"""
This method will export a SAS Data Set to a file in CSV format.
:param file: the OS filesystem path of the file to be created (exported from this SAS Data Set)
:return:
"""
opts = opts if opts is not None else {}... | This method will export a SAS Data Set to a file in CSV format.
:param file: the OS filesystem path of the file to be created (exported from this SAS Data Set)
:return: | Below is the the instruction that describes the task:
### Input:
This method will export a SAS Data Set to a file in CSV format.
:param file: the OS filesystem path of the file to be created (exported from this SAS Data Set)
:return:
### Response:
def to_csv(self, file: str, opts: dict = None) -> ... |
def add_items(self, items, index_items):
"""
Add items to template if is template, else add in item list
:param items: items list to add
:type items: alignak.objects.item.Items
:param index_items: Flag indicating if the items should be indexed on the fly.
:type index_ite... | Add items to template if is template, else add in item list
:param items: items list to add
:type items: alignak.objects.item.Items
:param index_items: Flag indicating if the items should be indexed on the fly.
:type index_items: bool
:return: None | Below is the the instruction that describes the task:
### Input:
Add items to template if is template, else add in item list
:param items: items list to add
:type items: alignak.objects.item.Items
:param index_items: Flag indicating if the items should be indexed on the fly.
:type i... |
def write(self, chunk: Union[str, bytes, dict]) -> None:
"""Writes the given chunk to the output buffer.
To write the output to the network, use the `flush()` method below.
If the given chunk is a dictionary, we write it as JSON and set
the Content-Type of the response to be ``applicat... | Writes the given chunk to the output buffer.
To write the output to the network, use the `flush()` method below.
If the given chunk is a dictionary, we write it as JSON and set
the Content-Type of the response to be ``application/json``.
(if you want to send JSON as a different ``Conte... | Below is the the instruction that describes the task:
### Input:
Writes the given chunk to the output buffer.
To write the output to the network, use the `flush()` method below.
If the given chunk is a dictionary, we write it as JSON and set
the Content-Type of the response to be ``applica... |
def lookup_subclass(cls, d):
"""Look up a class based on a serialized dictionary containing a typeid
Args:
d (dict): Dictionary with key "typeid"
Returns:
Serializable subclass
"""
try:
typeid = d["typeid"]
except KeyError:
... | Look up a class based on a serialized dictionary containing a typeid
Args:
d (dict): Dictionary with key "typeid"
Returns:
Serializable subclass | Below is the the instruction that describes the task:
### Input:
Look up a class based on a serialized dictionary containing a typeid
Args:
d (dict): Dictionary with key "typeid"
Returns:
Serializable subclass
### Response:
def lookup_subclass(cls, d):
"""Look up a... |
def accuracy(self, outputs):
'''Build a Theano expression for computing the accuracy of graph output.
Parameters
----------
outputs : dict of Theano expressions
A dictionary mapping network output names to Theano expressions
representing the outputs of a computat... | Build a Theano expression for computing the accuracy of graph output.
Parameters
----------
outputs : dict of Theano expressions
A dictionary mapping network output names to Theano expressions
representing the outputs of a computation graph.
Returns
----... | Below is the the instruction that describes the task:
### Input:
Build a Theano expression for computing the accuracy of graph output.
Parameters
----------
outputs : dict of Theano expressions
A dictionary mapping network output names to Theano expressions
represent... |
def memoize(func):
"""Decorator that stores function results in a dictionary to be used on the
next time that the same arguments were informed."""
func._cache_dict = {}
@wraps(func)
def _inner(*args, **kwargs):
return _get_memoized_value(func, args, kwargs)
return _inner | Decorator that stores function results in a dictionary to be used on the
next time that the same arguments were informed. | Below is the the instruction that describes the task:
### Input:
Decorator that stores function results in a dictionary to be used on the
next time that the same arguments were informed.
### Response:
def memoize(func):
"""Decorator that stores function results in a dictionary to be used on the
next ti... |
def get_topic_sha3(event_block):
'''
takes an event block and returns a signature for sha3 hashing
:param event_block:
:return:
'''
sig = ""
sig += event_block["name"]
if not event_block["inputs"]:
sig += "()"
return sig
sig += "("
for input in event_block["inpu... | takes an event block and returns a signature for sha3 hashing
:param event_block:
:return: | Below is the the instruction that describes the task:
### Input:
takes an event block and returns a signature for sha3 hashing
:param event_block:
:return:
### Response:
def get_topic_sha3(event_block):
'''
takes an event block and returns a signature for sha3 hashing
:param event_block:
:r... |
def get_symbol_size(version, scale=1, border=None):
"""\
Returns the symbol size (width x height) with the provided border and
scaling factor.
:param int version: A version constant.
:param scale: Indicates the size of a single module (default: 1).
The size of a module depends on the us... | \
Returns the symbol size (width x height) with the provided border and
scaling factor.
:param int version: A version constant.
:param scale: Indicates the size of a single module (default: 1).
The size of a module depends on the used output format; i.e.
in a PNG context, a scal... | Below is the the instruction that describes the task:
### Input:
\
Returns the symbol size (width x height) with the provided border and
scaling factor.
:param int version: A version constant.
:param scale: Indicates the size of a single module (default: 1).
The size of a module depends... |
def parse_domain_users(domain_users_file, domain_groups_file):
"""
Parses the domain users and groups files.
"""
with open(domain_users_file) as f:
users = json.loads(f.read())
domain_groups = {}
if domain_groups_file:
with open(domain_groups_file) as f:
groups =... | Parses the domain users and groups files. | Below is the the instruction that describes the task:
### Input:
Parses the domain users and groups files.
### Response:
def parse_domain_users(domain_users_file, domain_groups_file):
"""
Parses the domain users and groups files.
"""
with open(domain_users_file) as f:
users = json.loads... |
def run(self):
"""Increments counter and raises an exception for first two runs."""
self.count += 1
print('FailTwicePlug: Run number %s' % (self.count))
if self.count < 3:
raise RuntimeError('Fails a couple times')
return True | Increments counter and raises an exception for first two runs. | Below is the the instruction that describes the task:
### Input:
Increments counter and raises an exception for first two runs.
### Response:
def run(self):
"""Increments counter and raises an exception for first two runs."""
self.count += 1
print('FailTwicePlug: Run number %s' % (self.count))
if s... |
def char_style(self, style):
'''Sets the character style.
Args:
style: The desired character style. Choose from 'normal', 'outline', 'shadow', and 'outlineshadow'
Returns:
None
Raises:
RuntimeError: Invalid character style
'''
... | Sets the character style.
Args:
style: The desired character style. Choose from 'normal', 'outline', 'shadow', and 'outlineshadow'
Returns:
None
Raises:
RuntimeError: Invalid character style | Below is the the instruction that describes the task:
### Input:
Sets the character style.
Args:
style: The desired character style. Choose from 'normal', 'outline', 'shadow', and 'outlineshadow'
Returns:
None
Raises:
RuntimeError: Invalid charact... |
def get_response_signer(self):
"""Returns the response signer for this version of the signature.
"""
if not hasattr(self, "response_signer"):
self.response_signer = V2ResponseSigner(self.digest, orig=self)
return self.response_signer | Returns the response signer for this version of the signature. | Below is the the instruction that describes the task:
### Input:
Returns the response signer for this version of the signature.
### Response:
def get_response_signer(self):
"""Returns the response signer for this version of the signature.
"""
if not hasattr(self, "response_signer"):
... |
def visc_rad_kap_sc(T,rho,X):
'''
Radiative viscosity (Thomas, 1930) for e- scattering opacity
Parameters
----------
X : float
H mass fraction
T : float
temperature in K
rho : float
density in cgs
Returns
-------
nu : float
radiative diffusivity in [... | Radiative viscosity (Thomas, 1930) for e- scattering opacity
Parameters
----------
X : float
H mass fraction
T : float
temperature in K
rho : float
density in cgs
Returns
-------
nu : float
radiative diffusivity in [cm**2/s]
Examples
--------
>>... | Below is the the instruction that describes the task:
### Input:
Radiative viscosity (Thomas, 1930) for e- scattering opacity
Parameters
----------
X : float
H mass fraction
T : float
temperature in K
rho : float
density in cgs
Returns
-------
nu : float
... |
def list_images(self, repository_name, registry_id=None):
"""
maxResults and filtering not implemented
"""
repository = None
found = False
if repository_name in self.repositories:
repository = self.repositories[repository_name]
if registry_id:
... | maxResults and filtering not implemented | Below is the the instruction that describes the task:
### Input:
maxResults and filtering not implemented
### Response:
def list_images(self, repository_name, registry_id=None):
"""
maxResults and filtering not implemented
"""
repository = None
found = False
if repos... |
def trim_docstring(docstring):
"""Taken from http://www.python.org/dev/peps/pep-0257/"""
if not docstring:
return ''
# Convert tabs to spaces (following the normal Python rules)
# and split into a list of lines:
lines = docstring.expandtabs().splitlines()
# Determine minimum indentatio... | Taken from http://www.python.org/dev/peps/pep-0257/ | Below is the the instruction that describes the task:
### Input:
Taken from http://www.python.org/dev/peps/pep-0257/
### Response:
def trim_docstring(docstring):
"""Taken from http://www.python.org/dev/peps/pep-0257/"""
if not docstring:
return ''
# Convert tabs to spaces (following the normal... |
def list_namespaced_pod(self, namespace, **kwargs):
"""
list or watch objects of kind Pod
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_namespaced_pod(namespace, async_req=True)
... | list or watch objects of kind Pod
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_namespaced_pod(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool
:pa... | Below is the the instruction that describes the task:
### Input:
list or watch objects of kind Pod
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_namespaced_pod(namespace, async_req=True)
... |
def get_request_date(cls, req):
"""
Try to pull a date from the request by looking first at the
x-amz-date header, and if that's not present then the Date header.
Return a datetime.date object, or None if neither date header
is found or is in a recognisable format.
req ... | Try to pull a date from the request by looking first at the
x-amz-date header, and if that's not present then the Date header.
Return a datetime.date object, or None if neither date header
is found or is in a recognisable format.
req -- a requests PreparedRequest object | Below is the the instruction that describes the task:
### Input:
Try to pull a date from the request by looking first at the
x-amz-date header, and if that's not present then the Date header.
Return a datetime.date object, or None if neither date header
is found or is in a recognisable form... |
def find_methods(self, classname=".*", methodname=".*", descriptor=".*",
accessflags=".*", no_external=False):
"""
Find a method by name using regular expression.
This method will return all MethodClassAnalysis objects, which match the
classname, methodname, descriptor and ac... | Find a method by name using regular expression.
This method will return all MethodClassAnalysis objects, which match the
classname, methodname, descriptor and accessflags of the method.
:param classname: regular expression for the classname
:param methodname: regular expression for the ... | Below is the the instruction that describes the task:
### Input:
Find a method by name using regular expression.
This method will return all MethodClassAnalysis objects, which match the
classname, methodname, descriptor and accessflags of the method.
:param classname: regular expression for... |
def set_used_labels(self, labels):
""" Specify which trials to use in subsequent analysis steps.
This function masks trials based on their class labels.
Parameters
----------
labels : list of class labels
Marks all trials that have a label that is in the `labels` li... | Specify which trials to use in subsequent analysis steps.
This function masks trials based on their class labels.
Parameters
----------
labels : list of class labels
Marks all trials that have a label that is in the `labels` list for further processing.
Returns
... | Below is the the instruction that describes the task:
### Input:
Specify which trials to use in subsequent analysis steps.
This function masks trials based on their class labels.
Parameters
----------
labels : list of class labels
Marks all trials that have a label that... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.