code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def delete_profile_extension_members(self, profile_extension, query_column, ids_to_delete):
""" Responsys.deleteProfileExtensionRecords call
Accepts:
InteractObject profile_extension
list field_list
list ids_to_retrieve
string query_column
... | Responsys.deleteProfileExtensionRecords call
Accepts:
InteractObject profile_extension
list field_list
list ids_to_retrieve
string query_column
default: 'RIID'
Returns list of DeleteResults | Below is the the instruction that describes the task:
### Input:
Responsys.deleteProfileExtensionRecords call
Accepts:
InteractObject profile_extension
list field_list
list ids_to_retrieve
string query_column
default: 'RIID'
Returns l... |
def makeHandler(self, dialect):
"""create and cache the handler object for this dialect"""
if dialect not in self.dialects:
m = "The dialect specified, '{}', wasn't whitelisted in change_hook".format(dialect)
log.msg(m)
log.msg(
"Note: if dialect is 'b... | create and cache the handler object for this dialect | Below is the the instruction that describes the task:
### Input:
create and cache the handler object for this dialect
### Response:
def makeHandler(self, dialect):
"""create and cache the handler object for this dialect"""
if dialect not in self.dialects:
m = "The dialect specified, '{}... |
def format_value(self):
"""
Return the formatted (interpreted) data according to `data_type`.
"""
return format_value(
self.data_type,
self.data,
self.parent.stringpool_main.getString
) | Return the formatted (interpreted) data according to `data_type`. | Below is the the instruction that describes the task:
### Input:
Return the formatted (interpreted) data according to `data_type`.
### Response:
def format_value(self):
"""
Return the formatted (interpreted) data according to `data_type`.
"""
return format_value(
self.da... |
def _normalize_to_unit(self, value, unit):
"""Normalize the value to the unit returned.
We use base-1000 for second-based units, and base-1024 for
byte-based units. Sadly, the Nagios-Plugins specification doesn't
disambiguate base-1000 (KB) and base-1024 (KiB).
"""
if un... | Normalize the value to the unit returned.
We use base-1000 for second-based units, and base-1024 for
byte-based units. Sadly, the Nagios-Plugins specification doesn't
disambiguate base-1000 (KB) and base-1024 (KiB). | Below is the the instruction that describes the task:
### Input:
Normalize the value to the unit returned.
We use base-1000 for second-based units, and base-1024 for
byte-based units. Sadly, the Nagios-Plugins specification doesn't
disambiguate base-1000 (KB) and base-1024 (KiB).
### Respon... |
def addInternalLink(self, link):
'''Appends InternalLink
'''
if isinstance(link, InternalLink):
self.internalLinks.append(link)
else:
raise InternalLinkError(
'link Type should be InternalLink, not %s' % type(link)) | Appends InternalLink | Below is the the instruction that describes the task:
### Input:
Appends InternalLink
### Response:
def addInternalLink(self, link):
'''Appends InternalLink
'''
if isinstance(link, InternalLink):
self.internalLinks.append(link)
else:
raise InternalLi... |
def rotate(self, azimuth, axis=None):
"""Rotate the trackball about the "Up" axis by azimuth radians.
Parameters
----------
azimuth : float
The number of radians to rotate.
"""
target = self._target
y_axis = self._n_pose[:3, 1].flatten()
if a... | Rotate the trackball about the "Up" axis by azimuth radians.
Parameters
----------
azimuth : float
The number of radians to rotate. | Below is the the instruction that describes the task:
### Input:
Rotate the trackball about the "Up" axis by azimuth radians.
Parameters
----------
azimuth : float
The number of radians to rotate.
### Response:
def rotate(self, azimuth, axis=None):
"""Rotate the trackba... |
def add_subgroups(self, subgroups):
"""
Add a list of SubGroupDefinition objects to this composite.
Note that in contrast to :meth:`BaseTrack`, which takes a single
dictionary indicating the particular subgroups for the track, this
method takes a list of :class:`SubGroupDefiniti... | Add a list of SubGroupDefinition objects to this composite.
Note that in contrast to :meth:`BaseTrack`, which takes a single
dictionary indicating the particular subgroups for the track, this
method takes a list of :class:`SubGroupDefinition` objects representing
the allowed subgroups f... | Below is the the instruction that describes the task:
### Input:
Add a list of SubGroupDefinition objects to this composite.
Note that in contrast to :meth:`BaseTrack`, which takes a single
dictionary indicating the particular subgroups for the track, this
method takes a list of :class:`Sub... |
def floats(self, n: int = 2) -> List[float]:
"""Generate a list of random float numbers.
:param n: Raise 10 to the 'n' power.
:return: The list of floating-point numbers.
"""
nums = [self.random.random()
for _ in range(10 ** int(n))]
return nums | Generate a list of random float numbers.
:param n: Raise 10 to the 'n' power.
:return: The list of floating-point numbers. | Below is the the instruction that describes the task:
### Input:
Generate a list of random float numbers.
:param n: Raise 10 to the 'n' power.
:return: The list of floating-point numbers.
### Response:
def floats(self, n: int = 2) -> List[float]:
"""Generate a list of random float numbers.... |
def add_jac(self, m, val, row, col):
"""Add tuples (val, row, col) to the Jacobian matrix ``m``
Implemented in numpy.arrays for temporary storage.
"""
assert m in ('Fx', 'Fy', 'Gx', 'Gy', 'Fx0', 'Fy0', 'Gx0', 'Gy0'), \
'Wrong Jacobian matrix name <{0}>'.format(m)
if... | Add tuples (val, row, col) to the Jacobian matrix ``m``
Implemented in numpy.arrays for temporary storage. | Below is the the instruction that describes the task:
### Input:
Add tuples (val, row, col) to the Jacobian matrix ``m``
Implemented in numpy.arrays for temporary storage.
### Response:
def add_jac(self, m, val, row, col):
"""Add tuples (val, row, col) to the Jacobian matrix ``m``
Impleme... |
def copy(self):
"""Return a clone of this retry manager"""
return Retry(max_tries=self.max_tries, delay=self.delay, backoff=self.backoff,
max_jitter=self.max_jitter / 100.0, max_delay=self.max_delay, sleep_func=self.sleep_func,
deadline=self.deadline, retry_exce... | Return a clone of this retry manager | Below is the the instruction that describes the task:
### Input:
Return a clone of this retry manager
### Response:
def copy(self):
"""Return a clone of this retry manager"""
return Retry(max_tries=self.max_tries, delay=self.delay, backoff=self.backoff,
max_jitter=self.max_jitt... |
def accel_fl(q: np.ndarray):
"""Accelaration in the earth-sun system using Fluxion potential energy"""
# Infer number of dimensions from q
dims: int = len(q)
# Number of celestial bodies
B: int = dims // 3
# The force given the positions q of the bodies
f = force(q)
# The accelerations... | Accelaration in the earth-sun system using Fluxion potential energy | Below is the the instruction that describes the task:
### Input:
Accelaration in the earth-sun system using Fluxion potential energy
### Response:
def accel_fl(q: np.ndarray):
"""Accelaration in the earth-sun system using Fluxion potential energy"""
# Infer number of dimensions from q
dims: int = len(q... |
def lint_cli(ctx, exclude, skip_untracked, commit_only):
# type: (click.Context, List[str], bool, bool) -> None
""" Run pep8 and pylint on all project files.
You can configure the linting paths using the lint.paths config variable.
This should be a list of paths that will be linted. If a path to a dire... | Run pep8 and pylint on all project files.
You can configure the linting paths using the lint.paths config variable.
This should be a list of paths that will be linted. If a path to a directory
is given, all files in that directory and it's subdirectories will be
used.
The pep8 and pylint config pa... | Below is the the instruction that describes the task:
### Input:
Run pep8 and pylint on all project files.
You can configure the linting paths using the lint.paths config variable.
This should be a list of paths that will be linted. If a path to a directory
is given, all files in that directory and it'... |
def validate_content(*objs):
"""Runs the correct validator for given `obj`ects. Assumes all same type"""
from .main import Collection, Module
validator = {
Collection: cnxml.validate_collxml,
Module: cnxml.validate_cnxml,
}[type(objs[0])]
return validator(*[obj.file for obj in objs]) | Runs the correct validator for given `obj`ects. Assumes all same type | Below is the the instruction that describes the task:
### Input:
Runs the correct validator for given `obj`ects. Assumes all same type
### Response:
def validate_content(*objs):
"""Runs the correct validator for given `obj`ects. Assumes all same type"""
from .main import Collection, Module
validator = ... |
def is_best_response(self, own_action, opponents_actions, tol=None):
"""
Return True if `own_action` is a best response to
`opponents_actions`.
Parameters
----------
own_action : scalar(int) or array_like(float, ndim=1)
An integer representing a pure action, ... | Return True if `own_action` is a best response to
`opponents_actions`.
Parameters
----------
own_action : scalar(int) or array_like(float, ndim=1)
An integer representing a pure action, or an array of floats
representing a mixed action.
opponents_actions... | Below is the the instruction that describes the task:
### Input:
Return True if `own_action` is a best response to
`opponents_actions`.
Parameters
----------
own_action : scalar(int) or array_like(float, ndim=1)
An integer representing a pure action, or an array of float... |
def set_name(self, name):
"""
RETURN NEW FILE WITH GIVEN EXTENSION
"""
path = self._filename.split("/")
parts = path[-1].split(".")
if len(parts) == 1:
path[-1] = name
else:
path[-1] = name + "." + parts[-1]
return File("/".join(pat... | RETURN NEW FILE WITH GIVEN EXTENSION | Below is the the instruction that describes the task:
### Input:
RETURN NEW FILE WITH GIVEN EXTENSION
### Response:
def set_name(self, name):
"""
RETURN NEW FILE WITH GIVEN EXTENSION
"""
path = self._filename.split("/")
parts = path[-1].split(".")
if len(parts) == 1:... |
def _vector_pattern_uniform_op_right(func):
"""decorator for operator overloading when VectorPatternUniform is on
the right"""
@wraps(func)
def verif(self, patt):
if isinstance(patt, numbers.Number):
return TransversePatternUniform(func(self, self._tdsph... | decorator for operator overloading when VectorPatternUniform is on
the right | Below is the the instruction that describes the task:
### Input:
decorator for operator overloading when VectorPatternUniform is on
the right
### Response:
def _vector_pattern_uniform_op_right(func):
"""decorator for operator overloading when VectorPatternUniform is on
the right"""
... |
def statvfs(path):
'''
.. versionadded:: 2014.1.0
Perform a statvfs call against the filesystem that the file resides on
CLI Example:
.. code-block:: bash
salt '*' file.statvfs /path/to/file
'''
path = os.path.expanduser(path)
if not os.path.isabs(path):
raise SaltIn... | .. versionadded:: 2014.1.0
Perform a statvfs call against the filesystem that the file resides on
CLI Example:
.. code-block:: bash
salt '*' file.statvfs /path/to/file | Below is the the instruction that describes the task:
### Input:
.. versionadded:: 2014.1.0
Perform a statvfs call against the filesystem that the file resides on
CLI Example:
.. code-block:: bash
salt '*' file.statvfs /path/to/file
### Response:
def statvfs(path):
'''
.. versionadd... |
def get_folders(self):
""" Returns a list of all folders for this account
Returns:
List[:class:`Folder <pyOutlook.core.folder.Folder>`]
"""
endpoint = 'https://outlook.office.com/api/v2.0/me/MailFolders/'
r = requests.get(endpoint, headers=self._headers)
... | Returns a list of all folders for this account
Returns:
List[:class:`Folder <pyOutlook.core.folder.Folder>`] | Below is the the instruction that describes the task:
### Input:
Returns a list of all folders for this account
Returns:
List[:class:`Folder <pyOutlook.core.folder.Folder>`]
### Response:
def get_folders(self):
""" Returns a list of all folders for this account
Ret... |
def UploadArtifactYamlFile(file_content,
overwrite=True,
overwrite_system_artifacts=False):
"""Upload a yaml or json file as an artifact to the datastore."""
loaded_artifacts = []
registry_obj = artifact_registry.REGISTRY
# Make sure all artifacts are loaded... | Upload a yaml or json file as an artifact to the datastore. | Below is the the instruction that describes the task:
### Input:
Upload a yaml or json file as an artifact to the datastore.
### Response:
def UploadArtifactYamlFile(file_content,
overwrite=True,
overwrite_system_artifacts=False):
"""Upload a yaml or json fil... |
def _environment_sanity_check(environment):
"""Perform a sanity check on the environment."""
assert issubclass(environment.undefined, Undefined), 'undefined must ' \
'be a subclass of undefined because filters depend on it.'
assert environment.block_start_string != \
environment.variable_sta... | Perform a sanity check on the environment. | Below is the the instruction that describes the task:
### Input:
Perform a sanity check on the environment.
### Response:
def _environment_sanity_check(environment):
"""Perform a sanity check on the environment."""
assert issubclass(environment.undefined, Undefined), 'undefined must ' \
'be a subcl... |
def filter(self, query, inplace=True):
"""Use a query statement to filter data. Note that you specify the data
to be removed!
Parameters
----------
query : string
The query string to be evaluated. Is directly provided to
pandas.DataFrame.query
inp... | Use a query statement to filter data. Note that you specify the data
to be removed!
Parameters
----------
query : string
The query string to be evaluated. Is directly provided to
pandas.DataFrame.query
inplace : bool
if True, change the contai... | Below is the the instruction that describes the task:
### Input:
Use a query statement to filter data. Note that you specify the data
to be removed!
Parameters
----------
query : string
The query string to be evaluated. Is directly provided to
pandas.DataFram... |
def main(): # pragma: no cover
"""Simple tests."""
opts = [
Option('--foo'),
Option('--bar'),
Option('--baz'),
Option('--key', group='secret', mutually_exclusive=True),
Option('--key-file', group='secret', mutually_exclusive=True),
Option('--key-thing', group='se... | Simple tests. | Below is the the instruction that describes the task:
### Input:
Simple tests.
### Response:
def main(): # pragma: no cover
"""Simple tests."""
opts = [
Option('--foo'),
Option('--bar'),
Option('--baz'),
Option('--key', group='secret', mutually_exclusive=True),
Opti... |
def destroy_balancer(balancer_id, profile, **libcloud_kwargs):
'''
Destroy a load balancer
:param balancer_id: LoadBalancer ID which should be used
:type balancer_id: ``str``
:param profile: The profile key
:type profile: ``str``
:param libcloud_kwargs: Extra arguments for the driver's ... | Destroy a load balancer
:param balancer_id: LoadBalancer ID which should be used
:type balancer_id: ``str``
:param profile: The profile key
:type profile: ``str``
:param libcloud_kwargs: Extra arguments for the driver's destroy_balancer method
:type libcloud_kwargs: ``dict``
:return: ... | Below is the the instruction that describes the task:
### Input:
Destroy a load balancer
:param balancer_id: LoadBalancer ID which should be used
:type balancer_id: ``str``
:param profile: The profile key
:type profile: ``str``
:param libcloud_kwargs: Extra arguments for the driver's destro... |
def jsonrpc_method(name,
authenticated=False,
authentication_arguments=['username', 'password'],
safe=False,
validate=False,
site=default_site):
"""
Wraps a function turns it into a json-rpc method. Adds several attri... | Wraps a function turns it into a json-rpc method. Adds several attributes
to the function specific to the JSON-RPC machinery and adds it to the default
jsonrpc_site if one isn't provided. You must import the module containing
these functions in your urls.py.
name
The name of your metho... | Below is the the instruction that describes the task:
### Input:
Wraps a function turns it into a json-rpc method. Adds several attributes
to the function specific to the JSON-RPC machinery and adds it to the default
jsonrpc_site if one isn't provided. You must import the module containing
these functio... |
def get_rarity_info(self, rarity: str):
"""Returns card info from constants
Parameters
---------
rarity: str
A rarity name
Returns None or Constants
"""
for c in self.constants.rarities:
if c.name == rarity:
return c | Returns card info from constants
Parameters
---------
rarity: str
A rarity name
Returns None or Constants | Below is the the instruction that describes the task:
### Input:
Returns card info from constants
Parameters
---------
rarity: str
A rarity name
Returns None or Constants
### Response:
def get_rarity_info(self, rarity: str):
"""Returns card info from constants
... |
def clamp(color, min_v, max_v):
"""
Clamps a color such that the value is between min_v and max_v.
"""
h, s, v = rgb_to_hsv(*map(down_scale, color))
min_v, max_v = map(down_scale, (min_v, max_v))
v = min(max(min_v, v), max_v)
return tuple(map(up_scale, hsv_to_rgb(h, s, v))) | Clamps a color such that the value is between min_v and max_v. | Below is the the instruction that describes the task:
### Input:
Clamps a color such that the value is between min_v and max_v.
### Response:
def clamp(color, min_v, max_v):
"""
Clamps a color such that the value is between min_v and max_v.
"""
h, s, v = rgb_to_hsv(*map(down_scale, color))
min_... |
def _init_map(self, record_types=None, **kwargs):
"""Initialize form map"""
osid_objects.OsidObjectForm._init_map(self, record_types=record_types)
self._my_map['rubricId'] = self._rubric_default
self._my_map['assignedBankIds'] = [str(kwargs['bank_id'])]
self._my_map['levelId'] = ... | Initialize form map | Below is the the instruction that describes the task:
### Input:
Initialize form map
### Response:
def _init_map(self, record_types=None, **kwargs):
"""Initialize form map"""
osid_objects.OsidObjectForm._init_map(self, record_types=record_types)
self._my_map['rubricId'] = self._rubric_defau... |
def getresponse(self):
"""
Pass-thru method to make this class behave a little like HTTPConnection
"""
resp = self.http.getresponse()
self.log.info("resp is %s", str(resp))
if resp.status < 400:
return resp
else:
errtext = resp.read()
... | Pass-thru method to make this class behave a little like HTTPConnection | Below is the the instruction that describes the task:
### Input:
Pass-thru method to make this class behave a little like HTTPConnection
### Response:
def getresponse(self):
"""
Pass-thru method to make this class behave a little like HTTPConnection
"""
resp = self.http.getresponse()
... |
def cli(yaml_paths, pptx_template_path, font_size, master_slide_idx, slide_layout_idx, dst_dir, font_name,
slide_txt_alignment, validate):
"""
A powerpoint builder
https://github.com/sukujgrg/pptx-builder-from-yaml
"""
dst_dir = Path(dst_dir)
pptx_template_path = Path(pptx_template_p... | A powerpoint builder
https://github.com/sukujgrg/pptx-builder-from-yaml | Below is the the instruction that describes the task:
### Input:
A powerpoint builder
https://github.com/sukujgrg/pptx-builder-from-yaml
### Response:
def cli(yaml_paths, pptx_template_path, font_size, master_slide_idx, slide_layout_idx, dst_dir, font_name,
slide_txt_alignment, validate):
"""
... |
def Memory_setPressureNotificationsSuppressed(self, suppressed):
"""
Function path: Memory.setPressureNotificationsSuppressed
Domain: Memory
Method name: setPressureNotificationsSuppressed
Parameters:
Required arguments:
'suppressed' (type: boolean) -> If true, memory pressure notifications wil... | Function path: Memory.setPressureNotificationsSuppressed
Domain: Memory
Method name: setPressureNotificationsSuppressed
Parameters:
Required arguments:
'suppressed' (type: boolean) -> If true, memory pressure notifications will be suppressed.
No return value.
Description: Enable/disable su... | Below is the the instruction that describes the task:
### Input:
Function path: Memory.setPressureNotificationsSuppressed
Domain: Memory
Method name: setPressureNotificationsSuppressed
Parameters:
Required arguments:
'suppressed' (type: boolean) -> If true, memory pressure notifications will be... |
def follow_link_by_selector(self, selector):
"""
Navigate to the href of the element matching the CSS selector.
N.B. this does not click the link, but changes the browser's URL.
"""
elem = find_element_by_jquery(world.browser, selector)
href = elem.get_attribute('href')
world.browser.get(hr... | Navigate to the href of the element matching the CSS selector.
N.B. this does not click the link, but changes the browser's URL. | Below is the the instruction that describes the task:
### Input:
Navigate to the href of the element matching the CSS selector.
N.B. this does not click the link, but changes the browser's URL.
### Response:
def follow_link_by_selector(self, selector):
"""
Navigate to the href of the element matching ... |
def get_all_tags(filters=None, region=None, key=None, keyid=None, profile=None):
'''
Describe all tags matching the filter criteria, or all tags in the account otherwise.
.. versionadded:: 2018.3.0
filters
(dict) - Additional constraints on which volumes to return. Note that valid filters var... | Describe all tags matching the filter criteria, or all tags in the account otherwise.
.. versionadded:: 2018.3.0
filters
(dict) - Additional constraints on which volumes to return. Note that valid filters vary
extensively depending on the resource type. When in doubt, search first without a ... | Below is the the instruction that describes the task:
### Input:
Describe all tags matching the filter criteria, or all tags in the account otherwise.
.. versionadded:: 2018.3.0
filters
(dict) - Additional constraints on which volumes to return. Note that valid filters vary
extensively de... |
def expire_data(self):
"""Expire data within the samples collection."""
# Do we need to start deleting stuff?
while self.sample_storage_size() > self.samples_cap:
# This should return the 'oldest' record in samples
record = self.database[self.sample_collection].find().s... | Expire data within the samples collection. | Below is the the instruction that describes the task:
### Input:
Expire data within the samples collection.
### Response:
def expire_data(self):
"""Expire data within the samples collection."""
# Do we need to start deleting stuff?
while self.sample_storage_size() > self.samples_cap:
... |
def fetch(self):
'''
Fetch the repo. If the local copy was updated, return True. If the
local copy was already up-to-date, return False.
This function requires that a _fetch() function be implemented in a
sub-class.
'''
try:
with self.gen_lock(lock_ty... | Fetch the repo. If the local copy was updated, return True. If the
local copy was already up-to-date, return False.
This function requires that a _fetch() function be implemented in a
sub-class. | Below is the the instruction that describes the task:
### Input:
Fetch the repo. If the local copy was updated, return True. If the
local copy was already up-to-date, return False.
This function requires that a _fetch() function be implemented in a
sub-class.
### Response:
def fetch(self):... |
def get_ipv4fs_table(self):
"""Returns global IPv4 Flow Specification table.
Creates the table if it does not exist.
"""
ipv4fs_table = self._global_tables.get(RF_IPv4_FLOWSPEC)
# Lazy initialization of the table.
if not ipv4fs_table:
ipv4fs_table = IPv4FlowS... | Returns global IPv4 Flow Specification table.
Creates the table if it does not exist. | Below is the the instruction that describes the task:
### Input:
Returns global IPv4 Flow Specification table.
Creates the table if it does not exist.
### Response:
def get_ipv4fs_table(self):
"""Returns global IPv4 Flow Specification table.
Creates the table if it does not exist.
... |
def get_files():
"""
Return the list of all source/header files in `c/` directory.
The files will have pathnames relative to the current folder, for example
"c/csv/reader_utils.cc".
"""
sources = []
headers = ["datatable/include/datatable.h"]
assert os.path.isfile(headers[0])
for di... | Return the list of all source/header files in `c/` directory.
The files will have pathnames relative to the current folder, for example
"c/csv/reader_utils.cc". | Below is the the instruction that describes the task:
### Input:
Return the list of all source/header files in `c/` directory.
The files will have pathnames relative to the current folder, for example
"c/csv/reader_utils.cc".
### Response:
def get_files():
"""
Return the list of all source/header ... |
def Pack(self, msg, type_url_prefix='type.googleapis.com/'):
"""Packs the specified message into current Any message."""
if len(type_url_prefix) < 1 or type_url_prefix[-1] != '/':
self.type_url = '%s/%s' % (type_url_prefix, msg.DESCRIPTOR.full_name)
else:
self.type_url = '%s%s' % (type_url_prefi... | Packs the specified message into current Any message. | Below is the the instruction that describes the task:
### Input:
Packs the specified message into current Any message.
### Response:
def Pack(self, msg, type_url_prefix='type.googleapis.com/'):
"""Packs the specified message into current Any message."""
if len(type_url_prefix) < 1 or type_url_prefix[-1] !=... |
def update_dois(self):
"""Remove duplicate BibMatch DOIs."""
dois = record_get_field_instances(self.record, '024', ind1="7")
all_dois = {}
for field in dois:
subs = field_get_subfield_instances(field)
subs_dict = dict(subs)
if subs_dict.get('a'):
... | Remove duplicate BibMatch DOIs. | Below is the the instruction that describes the task:
### Input:
Remove duplicate BibMatch DOIs.
### Response:
def update_dois(self):
"""Remove duplicate BibMatch DOIs."""
dois = record_get_field_instances(self.record, '024', ind1="7")
all_dois = {}
for field in dois:
su... |
def send_registration_mail(email, *, request, **kwargs):
"""send_registration_mail(email, *, request, **kwargs)
Sends the registration mail
* ``email``: The email address where the registration link should be
sent to.
* ``request``: A HTTP request instance, used to construct the complete
UR... | send_registration_mail(email, *, request, **kwargs)
Sends the registration mail
* ``email``: The email address where the registration link should be
sent to.
* ``request``: A HTTP request instance, used to construct the complete
URL (including protocol and domain) for the registration link.
... | Below is the the instruction that describes the task:
### Input:
send_registration_mail(email, *, request, **kwargs)
Sends the registration mail
* ``email``: The email address where the registration link should be
sent to.
* ``request``: A HTTP request instance, used to construct the complete
... |
def store(self, value, context=None):
"""
Converts the value to one that is safe to store on a record within
the record values dictionary
:param value | <variant>
:return <variant>
"""
if isinstance(value, (str, unicode)):
value = self.value... | Converts the value to one that is safe to store on a record within
the record values dictionary
:param value | <variant>
:return <variant> | Below is the the instruction that describes the task:
### Input:
Converts the value to one that is safe to store on a record within
the record values dictionary
:param value | <variant>
:return <variant>
### Response:
def store(self, value, context=None):
"""
Conv... |
def code(self):
"""the http status code to return to the client, by default, 200 if a body is present otherwise 204"""
code = getattr(self, '_code', None)
if not code:
if self.has_body():
code = 200
else:
code = 204
return code | the http status code to return to the client, by default, 200 if a body is present otherwise 204 | Below is the the instruction that describes the task:
### Input:
the http status code to return to the client, by default, 200 if a body is present otherwise 204
### Response:
def code(self):
"""the http status code to return to the client, by default, 200 if a body is present otherwise 204"""
code... |
def get_rosetta_sequence_to_atom_json_map(self):
'''Returns the mapping from Rosetta residue IDs to PDB ATOM residue IDs in JSON format.'''
import json
if not self.rosetta_to_atom_sequence_maps and self.rosetta_sequences:
raise Exception('The PDB to Rosetta mapping has not been deter... | Returns the mapping from Rosetta residue IDs to PDB ATOM residue IDs in JSON format. | Below is the the instruction that describes the task:
### Input:
Returns the mapping from Rosetta residue IDs to PDB ATOM residue IDs in JSON format.
### Response:
def get_rosetta_sequence_to_atom_json_map(self):
'''Returns the mapping from Rosetta residue IDs to PDB ATOM residue IDs in JSON format.'''
... |
def cylinder(cls, **kwargs):
""" Returns a cylinder.
Kwargs:
start (list): Start of cylinder, default [0, -1, 0].
end (list): End of cylinder, default [0, 1, 0].
radius (float): Radius of cylinder, default... | Returns a cylinder.
Kwargs:
start (list): Start of cylinder, default [0, -1, 0].
end (list): End of cylinder, default [0, 1, 0].
radius (float): Radius of cylinder, default 1.0.
sl... | Below is the the instruction that describes the task:
### Input:
Returns a cylinder.
Kwargs:
start (list): Start of cylinder, default [0, -1, 0].
end (list): End of cylinder, default [0, 1, 0].
radius (float):... |
def __apply(self, migration=None, run_all=False):
"""
If a migration is supplied, runs that migration and appends to state.
If run_all==True, runs all migrations.
Raises a ValueError if neither "migration" nor "run_all" are provided.
"""
out = StringIO()
trace = N... | If a migration is supplied, runs that migration and appends to state.
If run_all==True, runs all migrations.
Raises a ValueError if neither "migration" nor "run_all" are provided. | Below is the the instruction that describes the task:
### Input:
If a migration is supplied, runs that migration and appends to state.
If run_all==True, runs all migrations.
Raises a ValueError if neither "migration" nor "run_all" are provided.
### Response:
def __apply(self, migration=None, run_al... |
def on_connection_open(self, connection):
"""This method is called by pika once the connection to RabbitMQ has
been established.
:type connection: pika.TornadoConnection
"""
LOGGER.debug('Connection opened')
connection.add_on_connection_blocked_callback(
sel... | This method is called by pika once the connection to RabbitMQ has
been established.
:type connection: pika.TornadoConnection | Below is the the instruction that describes the task:
### Input:
This method is called by pika once the connection to RabbitMQ has
been established.
:type connection: pika.TornadoConnection
### Response:
def on_connection_open(self, connection):
"""This method is called by pika once the co... |
async def get_departures(self):
"""Get departure info from stopid."""
from .common import CommonFunctions
common = CommonFunctions(self.loop, self.session)
departures = []
endpoint = '{}/StopVisit/GetDepartures/{}'.format(BASE_URL,
... | Get departure info from stopid. | Below is the the instruction that describes the task:
### Input:
Get departure info from stopid.
### Response:
async def get_departures(self):
"""Get departure info from stopid."""
from .common import CommonFunctions
common = CommonFunctions(self.loop, self.session)
departures = []
... |
def build_docs(location="doc-source", target=None, library="icetea_lib"):
"""
Build documentation for Icetea. Start by autogenerating module documentation
and finish by building html.
:param location: Documentation source
:param target: Documentation target path
:param library: Library location... | Build documentation for Icetea. Start by autogenerating module documentation
and finish by building html.
:param location: Documentation source
:param target: Documentation target path
:param library: Library location for autodoc.
:return: -1 if something fails. 0 if successfull. | Below is the the instruction that describes the task:
### Input:
Build documentation for Icetea. Start by autogenerating module documentation
and finish by building html.
:param location: Documentation source
:param target: Documentation target path
:param library: Library location for autodoc.
... |
def _receive(self, msg):
"""
Receive a message from the input source and perhaps raise an Exception.
"""
msg = self._convert(msg)
if msg is None:
return
str_msg = self.verbose and self._msg_to_str(msg)
if self.verbose and log.is_debug():
l... | Receive a message from the input source and perhaps raise an Exception. | Below is the the instruction that describes the task:
### Input:
Receive a message from the input source and perhaps raise an Exception.
### Response:
def _receive(self, msg):
"""
Receive a message from the input source and perhaps raise an Exception.
"""
msg = self._convert(msg)
... |
def get_ribo_counts(ribo_fileobj, transcript_name, read_lengths, read_offsets):
"""For each mapped read of the given transcript in the BAM file
(pysam AlignmentFile object), return the position (+1) and the
corresponding frame (1, 2 or 3) to which it aligns.
Keyword arguments:
ribo_fileobj -- file ... | For each mapped read of the given transcript in the BAM file
(pysam AlignmentFile object), return the position (+1) and the
corresponding frame (1, 2 or 3) to which it aligns.
Keyword arguments:
ribo_fileobj -- file object - BAM file opened using pysam AlignmentFile
transcript_name -- Name of trans... | Below is the the instruction that describes the task:
### Input:
For each mapped read of the given transcript in the BAM file
(pysam AlignmentFile object), return the position (+1) and the
corresponding frame (1, 2 or 3) to which it aligns.
Keyword arguments:
ribo_fileobj -- file object - BAM file ... |
def _get_select_commands(self, source, tables):
"""
Create select queries for all of the tables from a source database.
:param source: Source database name
:param tables: Iterable of table names
:return: Dictionary of table keys, command values
"""
# Create dicti... | Create select queries for all of the tables from a source database.
:param source: Source database name
:param tables: Iterable of table names
:return: Dictionary of table keys, command values | Below is the the instruction that describes the task:
### Input:
Create select queries for all of the tables from a source database.
:param source: Source database name
:param tables: Iterable of table names
:return: Dictionary of table keys, command values
### Response:
def _get_select_co... |
def identify_image(image):
"""Provides a tuple of image's UNIQUE_IMAGE_ATTRIBUTES. Note:
this is not guaranteed to be unique (and will often not be)
for pre-1.1 metadata, as subvariant did not exist. Provided as
a function so consumers can use it on plain image dicts read from
the metadata or PDC.
... | Provides a tuple of image's UNIQUE_IMAGE_ATTRIBUTES. Note:
this is not guaranteed to be unique (and will often not be)
for pre-1.1 metadata, as subvariant did not exist. Provided as
a function so consumers can use it on plain image dicts read from
the metadata or PDC. | Below is the the instruction that describes the task:
### Input:
Provides a tuple of image's UNIQUE_IMAGE_ATTRIBUTES. Note:
this is not guaranteed to be unique (and will often not be)
for pre-1.1 metadata, as subvariant did not exist. Provided as
a function so consumers can use it on plain image dicts r... |
def reproject_geometry(
geometry, src_crs=None, dst_crs=None, error_on_clip=False, validity_check=True,
antimeridian_cutting=False
):
"""
Reproject a geometry to target CRS.
Also, clips geometry if it lies outside the destination CRS boundary.
Supported destination CRSes for clipping: 4326 (WGS... | Reproject a geometry to target CRS.
Also, clips geometry if it lies outside the destination CRS boundary.
Supported destination CRSes for clipping: 4326 (WGS84), 3857 (Spherical
Mercator) and 3035 (ETRS89 / ETRS-LAEA).
Parameters
----------
geometry : ``shapely.geometry``
src_crs : ``raste... | Below is the the instruction that describes the task:
### Input:
Reproject a geometry to target CRS.
Also, clips geometry if it lies outside the destination CRS boundary.
Supported destination CRSes for clipping: 4326 (WGS84), 3857 (Spherical
Mercator) and 3035 (ETRS89 / ETRS-LAEA).
Parameters
... |
def checkCursor(self):
'Keep cursor in bounds of data and screen.'
# keep cursor within actual available rowset
if self.nRows == 0 or self.cursorRowIndex <= 0:
self.cursorRowIndex = 0
elif self.cursorRowIndex >= self.nRows:
self.cursorRowIndex = self.nRows-1
... | Keep cursor in bounds of data and screen. | Below is the the instruction that describes the task:
### Input:
Keep cursor in bounds of data and screen.
### Response:
def checkCursor(self):
'Keep cursor in bounds of data and screen.'
# keep cursor within actual available rowset
if self.nRows == 0 or self.cursorRowIndex <= 0:
... |
def update_payment_request(self, tid, currency=None, amount=None,
action=None, ledger=None, callback_uri=None,
display_message_uri=None, capture_id=None,
additional_amount=None, text=None, refund_id=None,
... | Update payment request, reauthorize, capture, release or abort
It is possible to update ledger and the callback URIs for a payment
request. Changes are always appended to the open report of a ledger,
and notifications are sent to the callback registered at the time of
notification.
... | Below is the the instruction that describes the task:
### Input:
Update payment request, reauthorize, capture, release or abort
It is possible to update ledger and the callback URIs for a payment
request. Changes are always appended to the open report of a ledger,
and notifications are sent... |
def create_snapshot(self, systemId, snapshotSpecificationObject):
"""
Create snapshot for list of volumes
:param systemID: Cluster ID
:param snapshotSpecificationObject: Of class SnapshotSpecification
:rtype: SnapshotGroupId
"""
self.conn.connection._check_login(... | Create snapshot for list of volumes
:param systemID: Cluster ID
:param snapshotSpecificationObject: Of class SnapshotSpecification
:rtype: SnapshotGroupId | Below is the the instruction that describes the task:
### Input:
Create snapshot for list of volumes
:param systemID: Cluster ID
:param snapshotSpecificationObject: Of class SnapshotSpecification
:rtype: SnapshotGroupId
### Response:
def create_snapshot(self, systemId, snapshotSpecificatio... |
def login(self, login, password, set_auth=False):
"""
Attempts a login to the remote server
and on success returns user id and session
or None
Warning: Do not depend on this. This will be deprecated
with SSO.
param set_auth: sets the authentication on the client... | Attempts a login to the remote server
and on success returns user id and session
or None
Warning: Do not depend on this. This will be deprecated
with SSO.
param set_auth: sets the authentication on the client | Below is the the instruction that describes the task:
### Input:
Attempts a login to the remote server
and on success returns user id and session
or None
Warning: Do not depend on this. This will be deprecated
with SSO.
param set_auth: sets the authentication on the client
... |
def putParamset(self, paramset, data={}):
"""
Some devices act upon changes to paramsets.
A "putted" paramset must not contain all keys available in the specified paramset,
just the ones which are writable and should be changed.
"""
try:
if paramset in self._P... | Some devices act upon changes to paramsets.
A "putted" paramset must not contain all keys available in the specified paramset,
just the ones which are writable and should be changed. | Below is the the instruction that describes the task:
### Input:
Some devices act upon changes to paramsets.
A "putted" paramset must not contain all keys available in the specified paramset,
just the ones which are writable and should be changed.
### Response:
def putParamset(self, paramset, data=... |
def get_outputs_from_cm(index, cm):
"""Return indices of the outputs of node with the given index."""
return tuple(i for i in range(cm.shape[0]) if cm[index][i]) | Return indices of the outputs of node with the given index. | Below is the the instruction that describes the task:
### Input:
Return indices of the outputs of node with the given index.
### Response:
def get_outputs_from_cm(index, cm):
"""Return indices of the outputs of node with the given index."""
return tuple(i for i in range(cm.shape[0]) if cm[index][i]) |
def load_scenario(self, scenario_name, **kwargs):
"""Load a scenario into the emulated object.
Scenarios are specific states of an an object that can be customized
with keyword parameters. Typical examples are:
- data logger with full storage
- device with low battery indi... | Load a scenario into the emulated object.
Scenarios are specific states of an an object that can be customized
with keyword parameters. Typical examples are:
- data logger with full storage
- device with low battery indication on
Args:
scenario_name (str): The... | Below is the the instruction that describes the task:
### Input:
Load a scenario into the emulated object.
Scenarios are specific states of an an object that can be customized
with keyword parameters. Typical examples are:
- data logger with full storage
- device with low batt... |
def to_api_data(self, restrict_keys=None):
""" Returns a dict to communicate with the server
:param restrict_keys: a set of keys to restrict the returned data to
:rtype: dict
"""
cc = self._cc # alias
data = {
cc('column_hidden'): self._column_hidden,
... | Returns a dict to communicate with the server
:param restrict_keys: a set of keys to restrict the returned data to
:rtype: dict | Below is the the instruction that describes the task:
### Input:
Returns a dict to communicate with the server
:param restrict_keys: a set of keys to restrict the returned data to
:rtype: dict
### Response:
def to_api_data(self, restrict_keys=None):
""" Returns a dict to communicate with t... |
def get_sample_frame(self):
"""Return first available image in observation result"""
for frame in self.frames:
return frame.open()
for res in self.results.values():
return res.open()
return None | Return first available image in observation result | Below is the the instruction that describes the task:
### Input:
Return first available image in observation result
### Response:
def get_sample_frame(self):
"""Return first available image in observation result"""
for frame in self.frames:
return frame.open()
for res in self.r... |
def get_single_allele_from_reads(allele_reads):
"""
Given a sequence of AlleleRead objects, which are expected to all have
the same allele, return that allele.
"""
allele_reads = list(allele_reads)
if len(allele_reads) == 0:
raise ValueError("Expected non-empty list of AlleleRead object... | Given a sequence of AlleleRead objects, which are expected to all have
the same allele, return that allele. | Below is the the instruction that describes the task:
### Input:
Given a sequence of AlleleRead objects, which are expected to all have
the same allele, return that allele.
### Response:
def get_single_allele_from_reads(allele_reads):
"""
Given a sequence of AlleleRead objects, which are expected to al... |
def delete(self):
"""
Delete a loopback cluster virtual interface from this engine.
Changes to the engine configuration are done immediately.
You can find cluster virtual loopbacks by iterating at the
engine level::
for loopbacks in engine.loopback_... | Delete a loopback cluster virtual interface from this engine.
Changes to the engine configuration are done immediately.
You can find cluster virtual loopbacks by iterating at the
engine level::
for loopbacks in engine.loopback_interface:
...
... | Below is the the instruction that describes the task:
### Input:
Delete a loopback cluster virtual interface from this engine.
Changes to the engine configuration are done immediately.
You can find cluster virtual loopbacks by iterating at the
engine level::
fo... |
def write_display(self):
"""Write display buffer to display hardware."""
for i, value in enumerate(self.buffer):
self._device.write8(i, value) | Write display buffer to display hardware. | Below is the the instruction that describes the task:
### Input:
Write display buffer to display hardware.
### Response:
def write_display(self):
"""Write display buffer to display hardware."""
for i, value in enumerate(self.buffer):
self._device.write8(i, value) |
def char_sets():
"""Return a list of the IANA Character Sets, or an empty list if the
IANA website is unreachable.
Store it as a function attribute so that we only build the list once.
"""
if not hasattr(char_sets, 'setlist'):
clist = []
try:
data = requests.get('http://w... | Return a list of the IANA Character Sets, or an empty list if the
IANA website is unreachable.
Store it as a function attribute so that we only build the list once. | Below is the the instruction that describes the task:
### Input:
Return a list of the IANA Character Sets, or an empty list if the
IANA website is unreachable.
Store it as a function attribute so that we only build the list once.
### Response:
def char_sets():
"""Return a list of the IANA Character Set... |
def get(self, reset=True):
"""
Get time since last initialisation / reset.
Parameters
----------
reset = bool, optional
Should the clock be reset after returning time?
Returns
----------
float
Time passed in milliseconds.
... | Get time since last initialisation / reset.
Parameters
----------
reset = bool, optional
Should the clock be reset after returning time?
Returns
----------
float
Time passed in milliseconds.
Example
----------
>>> import ... | Below is the the instruction that describes the task:
### Input:
Get time since last initialisation / reset.
Parameters
----------
reset = bool, optional
Should the clock be reset after returning time?
Returns
----------
float
Time passed in ... |
def check_fast(self, r, k=None):
'''Fast check if there's any error in a message+ecc. Can be used before decoding, in addition to hashes to detect if the message was tampered, or after decoding to check that the message was fully recovered.
returns True/False
'''
n = self.n
if no... | Fast check if there's any error in a message+ecc. Can be used before decoding, in addition to hashes to detect if the message was tampered, or after decoding to check that the message was fully recovered.
returns True/False | Below is the the instruction that describes the task:
### Input:
Fast check if there's any error in a message+ecc. Can be used before decoding, in addition to hashes to detect if the message was tampered, or after decoding to check that the message was fully recovered.
returns True/False
### Response:
def ... |
def create_point(self, x, y):
"""Create an ECDSA point on the SECP256k1 curve with the given coords.
:param x: The x coordinate on the curve
:type x: long
:param y: The y coodinate on the curve
:type y: long
"""
if (not isinstance(x, six.integer_types) or
... | Create an ECDSA point on the SECP256k1 curve with the given coords.
:param x: The x coordinate on the curve
:type x: long
:param y: The y coodinate on the curve
:type y: long | Below is the the instruction that describes the task:
### Input:
Create an ECDSA point on the SECP256k1 curve with the given coords.
:param x: The x coordinate on the curve
:type x: long
:param y: The y coodinate on the curve
:type y: long
### Response:
def create_point(self, x, y)... |
def timeseries(self, start, end, **kwargs):
r""" Returns a time series of observations at a user specified location for a specified time. Users must specify
at least one geographic search parameter ('stid', 'state', 'country', 'county', 'radius', 'bbox', 'cwa',
'nwsfirezone', 'gacc', or 'subgacc... | r""" Returns a time series of observations at a user specified location for a specified time. Users must specify
at least one geographic search parameter ('stid', 'state', 'country', 'county', 'radius', 'bbox', 'cwa',
'nwsfirezone', 'gacc', or 'subgacc') to obtain observation data. Other parameters may ... | Below is the the instruction that describes the task:
### Input:
r""" Returns a time series of observations at a user specified location for a specified time. Users must specify
at least one geographic search parameter ('stid', 'state', 'country', 'county', 'radius', 'bbox', 'cwa',
'nwsfirezone', 'g... |
def GetFileEntryByPathSpec(self, path_spec):
"""Retrieves a file entry for a path specification.
Args:
path_spec (PathSpec): path specification.
Returns:
FileEntry: a file entry or None.
"""
row_index = getattr(path_spec, 'row_index', None)
row_condition = getattr(path_spec, 'row_c... | Retrieves a file entry for a path specification.
Args:
path_spec (PathSpec): path specification.
Returns:
FileEntry: a file entry or None. | Below is the the instruction that describes the task:
### Input:
Retrieves a file entry for a path specification.
Args:
path_spec (PathSpec): path specification.
Returns:
FileEntry: a file entry or None.
### Response:
def GetFileEntryByPathSpec(self, path_spec):
"""Retrieves a file entry ... |
def _canonicalize_query(self, query):
"""
Transform the query dictionary to replace e.g. documents with __ref__ fields.
"""
def transform_query(q):
for encoder in self.query_encoders:
q = encoder.encode(q,[])
if isinstance(q, dict):
... | Transform the query dictionary to replace e.g. documents with __ref__ fields. | Below is the the instruction that describes the task:
### Input:
Transform the query dictionary to replace e.g. documents with __ref__ fields.
### Response:
def _canonicalize_query(self, query):
"""
Transform the query dictionary to replace e.g. documents with __ref__ fields.
"""
... |
def dragMoveEvent( self, event ):
"""
Processes the drag drop event using the filter set by the \
setDragDropFilter
:param event | <QDragEvent>
"""
filt = self.dragDropFilter()
if ( not filt ):
super(XCalendarWidget, self).dragMo... | Processes the drag drop event using the filter set by the \
setDragDropFilter
:param event | <QDragEvent> | Below is the the instruction that describes the task:
### Input:
Processes the drag drop event using the filter set by the \
setDragDropFilter
:param event | <QDragEvent>
### Response:
def dragMoveEvent( self, event ):
"""
Processes the drag drop event using the f... |
def cmd_map(self, args):
'''map commands'''
from MAVProxy.modules.mavproxy_map import mp_slipmap
if len(args) < 1:
print("usage: map <icon|set>")
elif args[0] == "icon":
if len(args) < 3:
print("Usage: map icon <lat> <lon> <icon>")
else... | map commands | Below is the the instruction that describes the task:
### Input:
map commands
### Response:
def cmd_map(self, args):
'''map commands'''
from MAVProxy.modules.mavproxy_map import mp_slipmap
if len(args) < 1:
print("usage: map <icon|set>")
elif args[0] == "icon":
... |
async def i2c_read_request(self, command):
"""
This method sends an I2C read request to Firmata. It is qualified by a single shot, continuous
read, or stop reading command.
Special Note: for the read type supply one of the following string values:
"0" = I2C_READ
"1" =... | This method sends an I2C read request to Firmata. It is qualified by a single shot, continuous
read, or stop reading command.
Special Note: for the read type supply one of the following string values:
"0" = I2C_READ
"1" = I2C_READ | I2C_END_TX_MASK"
"2" = I2C_READ_CONTINUOU... | Below is the the instruction that describes the task:
### Input:
This method sends an I2C read request to Firmata. It is qualified by a single shot, continuous
read, or stop reading command.
Special Note: for the read type supply one of the following string values:
"0" = I2C_READ
... |
def read_image(image, path=''):
"""Read one image.
Parameters
-----------
image : str
The image file name.
path : str
The image folder path.
Returns
-------
numpy.array
The image.
"""
return imageio.imread(os.path.join(path, image)) | Read one image.
Parameters
-----------
image : str
The image file name.
path : str
The image folder path.
Returns
-------
numpy.array
The image. | Below is the the instruction that describes the task:
### Input:
Read one image.
Parameters
-----------
image : str
The image file name.
path : str
The image folder path.
Returns
-------
numpy.array
The image.
### Response:
def read_image(image, path=''):
"... |
def save(package, data, params={}, is_public=False):
"""Build and push data to Quilt registry at user/package/data_node,
associating params as metadata for the data node.
:param package: short package specifier string, i.e. 'team:user/pkg/subpath'
:param data: data to save (np.ndarray or pd.DataFrame)
... | Build and push data to Quilt registry at user/package/data_node,
associating params as metadata for the data node.
:param package: short package specifier string, i.e. 'team:user/pkg/subpath'
:param data: data to save (np.ndarray or pd.DataFrame)
:param params: metadata dictionary
:param is_public: ... | Below is the the instruction that describes the task:
### Input:
Build and push data to Quilt registry at user/package/data_node,
associating params as metadata for the data node.
:param package: short package specifier string, i.e. 'team:user/pkg/subpath'
:param data: data to save (np.ndarray or pd.Dat... |
def _DropCommonSuffixes(filename):
"""Drops common suffixes like _test.cc or -inl.h from filename.
For example:
>>> _DropCommonSuffixes('foo/foo-inl.h')
'foo/foo'
>>> _DropCommonSuffixes('foo/bar/foo.cc')
'foo/bar/foo'
>>> _DropCommonSuffixes('foo/foo_internal.h')
'foo/foo'
>>> _DropCom... | Drops common suffixes like _test.cc or -inl.h from filename.
For example:
>>> _DropCommonSuffixes('foo/foo-inl.h')
'foo/foo'
>>> _DropCommonSuffixes('foo/bar/foo.cc')
'foo/bar/foo'
>>> _DropCommonSuffixes('foo/foo_internal.h')
'foo/foo'
>>> _DropCommonSuffixes('foo/foo_unusualinternal.h')... | Below is the the instruction that describes the task:
### Input:
Drops common suffixes like _test.cc or -inl.h from filename.
For example:
>>> _DropCommonSuffixes('foo/foo-inl.h')
'foo/foo'
>>> _DropCommonSuffixes('foo/bar/foo.cc')
'foo/bar/foo'
>>> _DropCommonSuffixes('foo/foo_internal.h')
... |
def psd(self):
"""
A pyCBC FrequencySeries holding the appropriate PSD.
Return the PSD used in the metric calculation.
"""
if not self._psd:
errMsg = "The PSD has not been set in the metricParameters "
errMsg += "instance."
raise ValueError(err... | A pyCBC FrequencySeries holding the appropriate PSD.
Return the PSD used in the metric calculation. | Below is the the instruction that describes the task:
### Input:
A pyCBC FrequencySeries holding the appropriate PSD.
Return the PSD used in the metric calculation.
### Response:
def psd(self):
"""
A pyCBC FrequencySeries holding the appropriate PSD.
Return the PSD used in the metri... |
def fail_remaining(self):
"""
Mark all unfinished tasks (including currently running ones) as
failed.
"""
self._failed.update(self._graph.nodes)
self._graph = Graph()
self._running = set() | Mark all unfinished tasks (including currently running ones) as
failed. | Below is the the instruction that describes the task:
### Input:
Mark all unfinished tasks (including currently running ones) as
failed.
### Response:
def fail_remaining(self):
"""
Mark all unfinished tasks (including currently running ones) as
failed.
"""
self._fail... |
def _render_our_module_flags(self, module, output_lines, prefix=''):
"""Returns a help string for a given module."""
flags = self._get_flags_defined_by_module(module)
if flags:
self._render_module_flags(module, flags, output_lines, prefix) | Returns a help string for a given module. | Below is the the instruction that describes the task:
### Input:
Returns a help string for a given module.
### Response:
def _render_our_module_flags(self, module, output_lines, prefix=''):
"""Returns a help string for a given module."""
flags = self._get_flags_defined_by_module(module)
if flags:
... |
def _kamb_count(cos_dist, sigma=3):
"""Original Kamb kernel function (raw count within radius)."""
n = float(cos_dist.size)
dist = _kamb_radius(n, sigma)
count = (cos_dist >= dist).astype(float)
return count, _kamb_units(n, dist) | Original Kamb kernel function (raw count within radius). | Below is the the instruction that describes the task:
### Input:
Original Kamb kernel function (raw count within radius).
### Response:
def _kamb_count(cos_dist, sigma=3):
"""Original Kamb kernel function (raw count within radius)."""
n = float(cos_dist.size)
dist = _kamb_radius(n, sigma)
count = (... |
def cancel_order(self, order_id, stock):
"""Cancel An Order
https://starfighter.readme.io/docs/cancel-an-order
"""
url_fragment = 'venues/{venue}/stocks/{stock}/orders/{order_id}'.format(
venue=self.venue,
stock=stock,
order_id=order_id,
)
... | Cancel An Order
https://starfighter.readme.io/docs/cancel-an-order | Below is the the instruction that describes the task:
### Input:
Cancel An Order
https://starfighter.readme.io/docs/cancel-an-order
### Response:
def cancel_order(self, order_id, stock):
"""Cancel An Order
https://starfighter.readme.io/docs/cancel-an-order
"""
url_fragment... |
def _flush_graph_val(self):
"""Send all new and changed graph values to the database."""
if not self._graphvals2set:
return
delafter = {}
for graph, key, branch, turn, tick, value in self._graphvals2set:
if (graph, key, branch) in delafter:
delafte... | Send all new and changed graph values to the database. | Below is the the instruction that describes the task:
### Input:
Send all new and changed graph values to the database.
### Response:
def _flush_graph_val(self):
"""Send all new and changed graph values to the database."""
if not self._graphvals2set:
return
delafter = {}
... |
def run(self, target, payload, instance_id=None, hook_id=None, **kwargs):
"""
target: the url to receive the payload.
payload: a python primitive data structure
instance_id: a possibly None "trigger" instance ID
hook_id: the ID of defining Hook object
"""
... | target: the url to receive the payload.
payload: a python primitive data structure
instance_id: a possibly None "trigger" instance ID
hook_id: the ID of defining Hook object | Below is the the instruction that describes the task:
### Input:
target: the url to receive the payload.
payload: a python primitive data structure
instance_id: a possibly None "trigger" instance ID
hook_id: the ID of defining Hook object
### Response:
def run(self, target, p... |
def make_release(cts):
'''Make and upload the release.
Changelog:
- v0.2.1 -- 2016-11-18 -- specify downloading of non-cached version of the
package for multiple formats can be properly and
individually tested.
- 0.2.2 -- 2016-11028 -- mov... | Make and upload the release.
Changelog:
- v0.2.1 -- 2016-11-18 -- specify downloading of non-cached version of the
package for multiple formats can be properly and
individually tested.
- 0.2.2 -- 2016-11028 -- move configuration to top of file | Below is the the instruction that describes the task:
### Input:
Make and upload the release.
Changelog:
- v0.2.1 -- 2016-11-18 -- specify downloading of non-cached version of the
package for multiple formats can be properly and
individually te... |
async def _process_latching(self, key, latching_entry):
"""
This is a private utility method.
This method process latching events and either returns them via
callback or stores them in the latch map
:param key: Encoded pin
:param latching_entry: a latch table entry
... | This is a private utility method.
This method process latching events and either returns them via
callback or stores them in the latch map
:param key: Encoded pin
:param latching_entry: a latch table entry
:returns: Callback or store data in latch map | Below is the the instruction that describes the task:
### Input:
This is a private utility method.
This method process latching events and either returns them via
callback or stores them in the latch map
:param key: Encoded pin
:param latching_entry: a latch table entry
:r... |
def _sanitize(self, value):
"""
Remove the control characters that are not allowed in XML:
https://www.w3.org/TR/xml/#charsets
Leave all other characters.
"""
if isinstance(value, six.binary_type):
value = value.decode('utf-8')
if isinstance(value, six... | Remove the control characters that are not allowed in XML:
https://www.w3.org/TR/xml/#charsets
Leave all other characters. | Below is the the instruction that describes the task:
### Input:
Remove the control characters that are not allowed in XML:
https://www.w3.org/TR/xml/#charsets
Leave all other characters.
### Response:
def _sanitize(self, value):
"""
Remove the control characters that are not allowe... |
def download_file_from_google_drive(ID, destination):
"""Download file from Google Drive.
See ``tl.files.load_celebA_dataset`` for example.
Parameters
--------------
ID : str
The driver ID.
destination : str
The destination for save file.
"""
def save_response_content... | Download file from Google Drive.
See ``tl.files.load_celebA_dataset`` for example.
Parameters
--------------
ID : str
The driver ID.
destination : str
The destination for save file. | Below is the the instruction that describes the task:
### Input:
Download file from Google Drive.
See ``tl.files.load_celebA_dataset`` for example.
Parameters
--------------
ID : str
The driver ID.
destination : str
The destination for save file.
### Response:
def download_fil... |
def offset_range(self, start, end):
"""
Database start/end entries are always ordered such that
start < end. This makes computing a relative position (e.g. of a stop
codon relative to its transcript) complicated since the "end"
position of a backwards locus is actually earlir on ... | Database start/end entries are always ordered such that
start < end. This makes computing a relative position (e.g. of a stop
codon relative to its transcript) complicated since the "end"
position of a backwards locus is actually earlir on the strand.
This function correctly selects a st... | Below is the the instruction that describes the task:
### Input:
Database start/end entries are always ordered such that
start < end. This makes computing a relative position (e.g. of a stop
codon relative to its transcript) complicated since the "end"
position of a backwards locus is actual... |
def GET_user_profile( self, path_info, user_id ):
"""
Get a user profile.
Reply the profile on success
Return 404 on failure to load
"""
if not check_name(user_id) and not check_subdomain(user_id):
return self._reply_json({'error': 'Invalid name or subdomain'}... | Get a user profile.
Reply the profile on success
Return 404 on failure to load | Below is the the instruction that describes the task:
### Input:
Get a user profile.
Reply the profile on success
Return 404 on failure to load
### Response:
def GET_user_profile( self, path_info, user_id ):
"""
Get a user profile.
Reply the profile on success
Return... |
def list_xz (archive, compression, cmd, verbosity, interactive):
"""List a XZ archive."""
cmdlist = [cmd]
cmdlist.append('-l')
if verbosity > 1:
cmdlist.append('-v')
cmdlist.append(archive)
return cmdlist | List a XZ archive. | Below is the the instruction that describes the task:
### Input:
List a XZ archive.
### Response:
def list_xz (archive, compression, cmd, verbosity, interactive):
"""List a XZ archive."""
cmdlist = [cmd]
cmdlist.append('-l')
if verbosity > 1:
cmdlist.append('-v')
cmdlist.append(archive)... |
def imagetransformer_base_10l_8h_big_uncond_dr03_dan_64_2d():
"""big 1d model for unconditional generation on imagenet."""
hparams = image_transformer2d_base()
hparams.unconditional = True
hparams.hidden_size = 512
hparams.batch_size = 1
hparams.img_len = 64
hparams.num_heads = 8
hparams.filter_size = 2... | big 1d model for unconditional generation on imagenet. | Below is the the instruction that describes the task:
### Input:
big 1d model for unconditional generation on imagenet.
### Response:
def imagetransformer_base_10l_8h_big_uncond_dr03_dan_64_2d():
"""big 1d model for unconditional generation on imagenet."""
hparams = image_transformer2d_base()
hparams.uncondi... |
def newer_pairwise_group(sources_groups, targets):
"""Walk both arguments in parallel, testing if each source group is newer
than its corresponding target. Returns a pair of lists (sources_groups,
targets) where sources is newer than target, according to the semantics
of 'newer_group()'.
"""
if ... | Walk both arguments in parallel, testing if each source group is newer
than its corresponding target. Returns a pair of lists (sources_groups,
targets) where sources is newer than target, according to the semantics
of 'newer_group()'. | Below is the the instruction that describes the task:
### Input:
Walk both arguments in parallel, testing if each source group is newer
than its corresponding target. Returns a pair of lists (sources_groups,
targets) where sources is newer than target, according to the semantics
of 'newer_group()'.
### ... |
def get_unread(self, request, notifications, mark_as_read):
"""
return unread notifications and mark as read
(unless read=false param is passed)
"""
notifications = notifications.filter(is_read=False)
serializer = UnreadNotificationSerializer(list(notifications), # evalu... | return unread notifications and mark as read
(unless read=false param is passed) | Below is the the instruction that describes the task:
### Input:
return unread notifications and mark as read
(unless read=false param is passed)
### Response:
def get_unread(self, request, notifications, mark_as_read):
"""
return unread notifications and mark as read
(unless read=f... |
def delete_lifecycle(self, policy=None, params=None):
"""
`<https://www.elastic.co/guide/en/elasticsearch/reference/current/ilm-delete-lifecycle.html>`_
:arg policy: The name of the index lifecycle policy
"""
return self.transport.perform_request(
"DELETE", _make_pat... | `<https://www.elastic.co/guide/en/elasticsearch/reference/current/ilm-delete-lifecycle.html>`_
:arg policy: The name of the index lifecycle policy | Below is the the instruction that describes the task:
### Input:
`<https://www.elastic.co/guide/en/elasticsearch/reference/current/ilm-delete-lifecycle.html>`_
:arg policy: The name of the index lifecycle policy
### Response:
def delete_lifecycle(self, policy=None, params=None):
"""
`<http... |
def geocentric_to_ecef(latitude, longitude, altitude):
"""Convert geocentric coordinates into ECEF
Parameters
----------
latitude : float or array_like
Geocentric latitude (degrees)
longitude : float or array_like
Geocentric longitude (degrees)
altitude : float or array_like... | Convert geocentric coordinates into ECEF
Parameters
----------
latitude : float or array_like
Geocentric latitude (degrees)
longitude : float or array_like
Geocentric longitude (degrees)
altitude : float or array_like
Height (km) above presumed spherical Earth with radiu... | Below is the the instruction that describes the task:
### Input:
Convert geocentric coordinates into ECEF
Parameters
----------
latitude : float or array_like
Geocentric latitude (degrees)
longitude : float or array_like
Geocentric longitude (degrees)
altitude : float or arr... |
def delete(overlay):
'''
Remove the given overlay from the your locally installed overlays.
Specify 'ALL' to remove all overlays.
Return a list of the overlays(s) that were removed:
CLI Example:
.. code-block:: bash
salt '*' layman.delete <overlay name>
'''
ret = list()
o... | Remove the given overlay from the your locally installed overlays.
Specify 'ALL' to remove all overlays.
Return a list of the overlays(s) that were removed:
CLI Example:
.. code-block:: bash
salt '*' layman.delete <overlay name> | Below is the the instruction that describes the task:
### Input:
Remove the given overlay from the your locally installed overlays.
Specify 'ALL' to remove all overlays.
Return a list of the overlays(s) that were removed:
CLI Example:
.. code-block:: bash
salt '*' layman.delete <overlay ... |
def shape_vecs(*args):
'''Reshape all ndarrays with ``shape==(n,)`` to ``shape==(n,1)``.
Recognizes ndarrays and ignores all others.'''
ret_args = []
flat_vecs = True
for arg in args:
if type(arg) is numpy.ndarray:
if len(arg.shape) == 1:
arg = shape_vec(arg)
... | Reshape all ndarrays with ``shape==(n,)`` to ``shape==(n,1)``.
Recognizes ndarrays and ignores all others. | Below is the the instruction that describes the task:
### Input:
Reshape all ndarrays with ``shape==(n,)`` to ``shape==(n,1)``.
Recognizes ndarrays and ignores all others.
### Response:
def shape_vecs(*args):
'''Reshape all ndarrays with ``shape==(n,)`` to ``shape==(n,1)``.
Recognizes ndarrays and ig... |
def _first_of_month(self, day_of_week):
"""
Modify to the first occurrence of a given day of the week
in the current month. If no day_of_week is provided,
modify to the first day of the month. Use the supplied consts
to indicate the desired day_of_week, ex. DateTime.MONDAY.
... | Modify to the first occurrence of a given day of the week
in the current month. If no day_of_week is provided,
modify to the first day of the month. Use the supplied consts
to indicate the desired day_of_week, ex. DateTime.MONDAY.
:type day_of_week: int
:rtype: DateTime | Below is the the instruction that describes the task:
### Input:
Modify to the first occurrence of a given day of the week
in the current month. If no day_of_week is provided,
modify to the first day of the month. Use the supplied consts
to indicate the desired day_of_week, ex. DateTime.MOND... |
def closed(self, reason):
"""Callback performed when the transport is closed."""
self.server.remove_connection(self)
self.protocol.connection_lost(reason)
if not isinstance(reason, ConnectionClosed):
logger.warn("connection closed, reason: %s" % str(reason))
else:
... | Callback performed when the transport is closed. | Below is the the instruction that describes the task:
### Input:
Callback performed when the transport is closed.
### Response:
def closed(self, reason):
"""Callback performed when the transport is closed."""
self.server.remove_connection(self)
self.protocol.connection_lost(reason)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.