code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def get_user_information(self):
"""Gets the current user information, including sensor ID
Args:
None
Returns:
dictionary object containing information about the current user
"""
url = "https://api.neur.io/v1/users/current"
headers = self.__gen_headers()
headers["Content-Type"]... | Gets the current user information, including sensor ID
Args:
None
Returns:
dictionary object containing information about the current user | Below is the the instruction that describes the task:
### Input:
Gets the current user information, including sensor ID
Args:
None
Returns:
dictionary object containing information about the current user
### Response:
def get_user_information(self):
"""Gets the current user information, i... |
def prog(text):
"""
Decorator used to specify the program name for the console script
help message.
:param text: The text to use for the program name.
"""
def decorator(func):
adaptor = ScriptAdaptor._get_adaptor(func)
adaptor.prog = text
return func
return decorato... | Decorator used to specify the program name for the console script
help message.
:param text: The text to use for the program name. | Below is the the instruction that describes the task:
### Input:
Decorator used to specify the program name for the console script
help message.
:param text: The text to use for the program name.
### Response:
def prog(text):
"""
Decorator used to specify the program name for the console script
... |
def linseg(self, value, samples):
'''
Create a linear section moving from current value to new value over acertain number of
samples.
:param value: New value
:param samples: Length of segment in samples
:return:
'''
if self.params.length > self.pos and sam... | Create a linear section moving from current value to new value over acertain number of
samples.
:param value: New value
:param samples: Length of segment in samples
:return: | Below is the the instruction that describes the task:
### Input:
Create a linear section moving from current value to new value over acertain number of
samples.
:param value: New value
:param samples: Length of segment in samples
:return:
### Response:
def linseg(self, value, sample... |
def flat_data(self):
"""
Function to pass our modified values to the original ones
"""
def flat_field(value):
"""
Flat item
"""
try:
value.flat_data()
return value
except AttributeError:
... | Function to pass our modified values to the original ones | Below is the the instruction that describes the task:
### Input:
Function to pass our modified values to the original ones
### Response:
def flat_data(self):
"""
Function to pass our modified values to the original ones
"""
def flat_field(value):
"""
Flat it... |
def email_addresses595(self, key, value):
"""Populates the ``email_addresses`` field using the 595 MARCXML field.
Also populates ``_private_notes`` as a side effect.
"""
emails = self.get('email_addresses', [])
if value.get('o'):
emails.append({
'value': value.get('o'),
... | Populates the ``email_addresses`` field using the 595 MARCXML field.
Also populates ``_private_notes`` as a side effect. | Below is the the instruction that describes the task:
### Input:
Populates the ``email_addresses`` field using the 595 MARCXML field.
Also populates ``_private_notes`` as a side effect.
### Response:
def email_addresses595(self, key, value):
"""Populates the ``email_addresses`` field using the 595 MARCXML... |
def set_rtscts(self, enable):
'''enable/disable RTS/CTS if applicable'''
try:
self.port.setRtsCts(enable)
except Exception:
self.port.rtscts = enable
self.rtscts = enable | enable/disable RTS/CTS if applicable | Below is the the instruction that describes the task:
### Input:
enable/disable RTS/CTS if applicable
### Response:
def set_rtscts(self, enable):
'''enable/disable RTS/CTS if applicable'''
try:
self.port.setRtsCts(enable)
except Exception:
self.port.rtscts = enable
... |
def ListFiles(self, ext_attrs=None):
"""List all the files in the directory."""
del ext_attrs # Unused.
if not self.IsDirectory():
raise IOError("%s is not a directory" % self.pathspec.CollapsePath())
for f in self.fd.as_directory():
try:
name = _DecodeUTF8WithWarning(f.info.name.... | List all the files in the directory. | Below is the the instruction that describes the task:
### Input:
List all the files in the directory.
### Response:
def ListFiles(self, ext_attrs=None):
"""List all the files in the directory."""
del ext_attrs # Unused.
if not self.IsDirectory():
raise IOError("%s is not a directory" % self.pat... |
def _get_file(src):
""" Return content from local or remote file. """
try:
if '://' in src or src[0:2] == '//': # Most likely this is remote file
response = urllib2.urlopen(src)
return response.read()
else:
with open(src, 'rb') as fh:
return f... | Return content from local or remote file. | Below is the the instruction that describes the task:
### Input:
Return content from local or remote file.
### Response:
def _get_file(src):
""" Return content from local or remote file. """
try:
if '://' in src or src[0:2] == '//': # Most likely this is remote file
response = urllib2.... |
def format_vars(args):
"""Format the given vars in the form: 'flag=value'"""
variables = []
for key, value in args.items():
if value:
variables += ['{0}={1}'.format(key, value)]
return variables | Format the given vars in the form: 'flag=value | Below is the the instruction that describes the task:
### Input:
Format the given vars in the form: 'flag=value
### Response:
def format_vars(args):
"""Format the given vars in the form: 'flag=value'"""
variables = []
for key, value in args.items():
if value:
variables += ['{0}={1}'... |
def check_extensions(extensions: Set[str], allow_multifile: bool = False):
"""
Utility method to check that all extensions in the provided set are valid
:param extensions:
:param allow_multifile:
:return:
"""
check_var(extensions, var_types=set, var_name='extensions')
# -- check them o... | Utility method to check that all extensions in the provided set are valid
:param extensions:
:param allow_multifile:
:return: | Below is the the instruction that describes the task:
### Input:
Utility method to check that all extensions in the provided set are valid
:param extensions:
:param allow_multifile:
:return:
### Response:
def check_extensions(extensions: Set[str], allow_multifile: bool = False):
"""
Utility me... |
def center_data(data, vmin, vmax):
"""Clips data on [vmin, vmax]; then rescales to [0,1]"""
ans = data - vmin
ans /= (vmax - vmin)
return np.clip(ans, 0, 1) | Clips data on [vmin, vmax]; then rescales to [0,1] | Below is the the instruction that describes the task:
### Input:
Clips data on [vmin, vmax]; then rescales to [0,1]
### Response:
def center_data(data, vmin, vmax):
"""Clips data on [vmin, vmax]; then rescales to [0,1]"""
ans = data - vmin
ans /= (vmax - vmin)
return np.clip(ans, 0, 1) |
def _get_relative_pythonpath(self):
"""Return PYTHONPATH list as relative paths"""
# Workaround to replace os.path.relpath (new in Python v2.6):
offset = len(self.root_path)+len(os.pathsep)
return [path[offset:] for path in self.pythonpath] | Return PYTHONPATH list as relative paths | Below is the the instruction that describes the task:
### Input:
Return PYTHONPATH list as relative paths
### Response:
def _get_relative_pythonpath(self):
"""Return PYTHONPATH list as relative paths"""
# Workaround to replace os.path.relpath (new in Python v2.6):
offset = len(self.root_... |
def ridgecircle(self, x, expo=0.5):
"""happy cat by HG Beyer"""
a = len(x)
s = sum(x**2)
return ((s - a)**2)**(expo / 2) + s / a + sum(x) / a | happy cat by HG Beyer | Below is the the instruction that describes the task:
### Input:
happy cat by HG Beyer
### Response:
def ridgecircle(self, x, expo=0.5):
"""happy cat by HG Beyer"""
a = len(x)
s = sum(x**2)
return ((s - a)**2)**(expo / 2) + s / a + sum(x) / a |
def encode(raw):
"""Encode SLIP message."""
return raw \
.replace(bytes([SLIP_ESC]), bytes([SLIP_ESC, SLIP_ESC_ESC])) \
.replace(bytes([SLIP_END]), bytes([SLIP_ESC, SLIP_ESC_END])) | Encode SLIP message. | Below is the the instruction that describes the task:
### Input:
Encode SLIP message.
### Response:
def encode(raw):
"""Encode SLIP message."""
return raw \
.replace(bytes([SLIP_ESC]), bytes([SLIP_ESC, SLIP_ESC_ESC])) \
.replace(bytes([SLIP_END]), bytes([SLIP_ESC, SLIP_ESC_END])) |
def datetime2gtd(time: Union[str, datetime.datetime, np.datetime64],
glon: Union[float, List[float], np.ndarray] = np.nan) -> Tuple[int, float, float]:
"""
Inputs:
time: Numpy 1-D array of datetime.datetime OR string for dateutil.parser.parse
glon: Numpy 2-D array of geodetic longitudes... | Inputs:
time: Numpy 1-D array of datetime.datetime OR string for dateutil.parser.parse
glon: Numpy 2-D array of geodetic longitudes (degrees)
Outputs:
iyd: day of year
utsec: seconds from midnight utc
stl: local solar time | Below is the the instruction that describes the task:
### Input:
Inputs:
time: Numpy 1-D array of datetime.datetime OR string for dateutil.parser.parse
glon: Numpy 2-D array of geodetic longitudes (degrees)
Outputs:
iyd: day of year
utsec: seconds from midnight utc
stl: local solar time
###... |
def decode(stream, strict=True):
"""
Decodes a SOL stream. L{strict} mode ensures that the sol stream is as spec
compatible as possible.
@return: A C{tuple} containing the C{root_name} and a C{dict} of name,
value pairs.
"""
if not isinstance(stream, util.BufferedByteStream):
st... | Decodes a SOL stream. L{strict} mode ensures that the sol stream is as spec
compatible as possible.
@return: A C{tuple} containing the C{root_name} and a C{dict} of name,
value pairs. | Below is the the instruction that describes the task:
### Input:
Decodes a SOL stream. L{strict} mode ensures that the sol stream is as spec
compatible as possible.
@return: A C{tuple} containing the C{root_name} and a C{dict} of name,
value pairs.
### Response:
def decode(stream, strict=True):
... |
def init(*args, **kwargs):
"""Returns an initialized instance of the Batch class"""
# set up cellpy logger
default_log_level = kwargs.pop("default_log_level", None)
import cellpy.log as log
log.setup_logging(custom_log_dir=prms.Paths["filelogdir"],
default_level=default_log_lev... | Returns an initialized instance of the Batch class | Below is the the instruction that describes the task:
### Input:
Returns an initialized instance of the Batch class
### Response:
def init(*args, **kwargs):
"""Returns an initialized instance of the Batch class"""
# set up cellpy logger
default_log_level = kwargs.pop("default_log_level", None)
impo... |
def _check_file_exists_unix(self, remote_cmd=""):
"""Check if the dest_file already exists on the file system (return boolean)."""
if self.direction == "put":
self.ssh_ctl_chan._enter_shell()
remote_cmd = "ls {}".format(self.file_system)
remote_out = self.ssh_ctl_chan... | Check if the dest_file already exists on the file system (return boolean). | Below is the the instruction that describes the task:
### Input:
Check if the dest_file already exists on the file system (return boolean).
### Response:
def _check_file_exists_unix(self, remote_cmd=""):
"""Check if the dest_file already exists on the file system (return boolean)."""
if self.direct... |
def _clauses(lexer, varname, nvars):
"""Return a tuple of DIMACS CNF clauses."""
tok = next(lexer)
toktype = type(tok)
if toktype is OP_not or toktype is IntegerToken:
lexer.unpop_token(tok)
first = _clause(lexer, varname, nvars)
rest = _clauses(lexer, varname, nvars)
ret... | Return a tuple of DIMACS CNF clauses. | Below is the the instruction that describes the task:
### Input:
Return a tuple of DIMACS CNF clauses.
### Response:
def _clauses(lexer, varname, nvars):
"""Return a tuple of DIMACS CNF clauses."""
tok = next(lexer)
toktype = type(tok)
if toktype is OP_not or toktype is IntegerToken:
lexer.... |
def find_object(self, object_type):
"""Finds the closest object of a given type."""
node = self
while node is not None:
if isinstance(node.obj, object_type):
return node.obj
node = node.parent | Finds the closest object of a given type. | Below is the the instruction that describes the task:
### Input:
Finds the closest object of a given type.
### Response:
def find_object(self, object_type):
"""Finds the closest object of a given type."""
node = self
while node is not None:
if isinstance(node.obj, object_type):
... |
def create_or_update_tags(self, tags):
"""
Creates new tags or updates existing tags for an Auto Scaling group.
:type tags: List of :class:`boto.ec2.autoscale.tag.Tag`
:param tags: The new or updated tags.
"""
params = {}
for i, tag in enumerate(tags):
... | Creates new tags or updates existing tags for an Auto Scaling group.
:type tags: List of :class:`boto.ec2.autoscale.tag.Tag`
:param tags: The new or updated tags. | Below is the the instruction that describes the task:
### Input:
Creates new tags or updates existing tags for an Auto Scaling group.
:type tags: List of :class:`boto.ec2.autoscale.tag.Tag`
:param tags: The new or updated tags.
### Response:
def create_or_update_tags(self, tags):
"""
... |
def read_file(fname, *args, **kwargs):
"""Read data from a file saved in the standard IAMC format
or a table with year/value columns
"""
if not isstr(fname):
raise ValueError('reading multiple files not supported, '
'please use `pyam.IamDataFrame.append()`')
logger()... | Read data from a file saved in the standard IAMC format
or a table with year/value columns | Below is the the instruction that describes the task:
### Input:
Read data from a file saved in the standard IAMC format
or a table with year/value columns
### Response:
def read_file(fname, *args, **kwargs):
"""Read data from a file saved in the standard IAMC format
or a table with year/value columns
... |
def clean_text(self, address, **kwargs):
"""Basic clean-up."""
address = self.LINE_BREAKS.sub(', ', address)
address = self.COMMATA.sub(', ', address)
address = collapse_spaces(address)
if len(address):
return address | Basic clean-up. | Below is the the instruction that describes the task:
### Input:
Basic clean-up.
### Response:
def clean_text(self, address, **kwargs):
"""Basic clean-up."""
address = self.LINE_BREAKS.sub(', ', address)
address = self.COMMATA.sub(', ', address)
address = collapse_spaces(address)
... |
def bounds(self):
"""
Return the overall bounding box of the scene.
Returns
--------
bounds: (2,3) float points for min, max corner
"""
corners = self.bounds_corners
bounds = np.array([corners.min(axis=0),
corners.max(axis=0)])
... | Return the overall bounding box of the scene.
Returns
--------
bounds: (2,3) float points for min, max corner | Below is the the instruction that describes the task:
### Input:
Return the overall bounding box of the scene.
Returns
--------
bounds: (2,3) float points for min, max corner
### Response:
def bounds(self):
"""
Return the overall bounding box of the scene.
Returns
... |
def _handle_retryable_error(self, e, retry_count):
"""Sleep based on the type of :class:`RetryableAsanaError`"""
if isinstance(e, error.RateLimitEnforcedError):
time.sleep(e.retry_after)
else:
time.sleep(self.RETRY_DELAY * (self.RETRY_BACKOFF ** retry_count)) | Sleep based on the type of :class:`RetryableAsanaError` | Below is the the instruction that describes the task:
### Input:
Sleep based on the type of :class:`RetryableAsanaError`
### Response:
def _handle_retryable_error(self, e, retry_count):
"""Sleep based on the type of :class:`RetryableAsanaError`"""
if isinstance(e, error.RateLimitEnforcedError):
... |
def record(self):
# type: () -> bytes
'''
Generate a string representing the Rock Ridge Relocated Directory
record.
Parameters:
None.
Returns:
String containing the Rock Ridge record.
'''
if not self._initialized:
raise pycdl... | Generate a string representing the Rock Ridge Relocated Directory
record.
Parameters:
None.
Returns:
String containing the Rock Ridge record. | Below is the the instruction that describes the task:
### Input:
Generate a string representing the Rock Ridge Relocated Directory
record.
Parameters:
None.
Returns:
String containing the Rock Ridge record.
### Response:
def record(self):
# type: () -> bytes
... |
def inspect_workers(self):
"""Updates the workers status.
Returns the workers which have unexpectedly ended.
"""
workers = tuple(self.workers.values())
expired = tuple(w for w in workers if not w.is_alive())
for worker in expired:
self.workers.pop(worker.pi... | Updates the workers status.
Returns the workers which have unexpectedly ended. | Below is the the instruction that describes the task:
### Input:
Updates the workers status.
Returns the workers which have unexpectedly ended.
### Response:
def inspect_workers(self):
"""Updates the workers status.
Returns the workers which have unexpectedly ended.
"""
w... |
def _clear_context():
'''
Clear any lxc variables set in __context__
'''
for var in [x for x in __context__ if x.startswith('lxc.')]:
log.trace('Clearing __context__[\'%s\']', var)
__context__.pop(var, None) | Clear any lxc variables set in __context__ | Below is the the instruction that describes the task:
### Input:
Clear any lxc variables set in __context__
### Response:
def _clear_context():
'''
Clear any lxc variables set in __context__
'''
for var in [x for x in __context__ if x.startswith('lxc.')]:
log.trace('Clearing __context__[\'%... |
def _parse_search_results_html(self, doc):
""" parse search result html, return subgroups
subgroups: [{ 'title': title, 'link': link}]
"""
subgroups = []
soup = bs4.BeautifulSoup(doc, 'lxml')
ele_divs = soup.select('div.item.prel')
if not ele_divs:
ret... | parse search result html, return subgroups
subgroups: [{ 'title': title, 'link': link}] | Below is the the instruction that describes the task:
### Input:
parse search result html, return subgroups
subgroups: [{ 'title': title, 'link': link}]
### Response:
def _parse_search_results_html(self, doc):
""" parse search result html, return subgroups
subgroups: [{ 'title': title, 'lin... |
def reload(self):
"""Reloades the configuration
This method will reload the configuration instance using the last
known filename. Note this method will initially clear the
configuration and reload all entries.
"""
for section in self.sections():
self.remove... | Reloades the configuration
This method will reload the configuration instance using the last
known filename. Note this method will initially clear the
configuration and reload all entries. | Below is the the instruction that describes the task:
### Input:
Reloades the configuration
This method will reload the configuration instance using the last
known filename. Note this method will initially clear the
configuration and reload all entries.
### Response:
def reload(self):
... |
def p_qualifier(p):
"""qualifier : qualifierName
| qualifierName ':' flavorList
| qualifierName qualifierParameter
| qualifierName qualifierParameter ':' flavorList
"""
# pylint: disable=too-many-branches
qname = p[1]
ns = p.parser.han... | qualifier : qualifierName
| qualifierName ':' flavorList
| qualifierName qualifierParameter
| qualifierName qualifierParameter ':' flavorList | Below is the the instruction that describes the task:
### Input:
qualifier : qualifierName
| qualifierName ':' flavorList
| qualifierName qualifierParameter
| qualifierName qualifierParameter ':' flavorList
### Response:
def p_qualifier(p):
"""qualifier : qual... |
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
"""
# extracting dictionary of coefficients specific to required
#... | See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values. | Below is the the instruction that describes the task:
### Input:
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
### Response:
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
See :m... |
def grant(self, fail_on_found=False, **kwargs):
"""Add a user or a team to a role. Required information:
1) Type of the role
2) Resource of the role, inventory, credential, or any other
3) A user or a team to add to the role
=====API DOCS=====
Add a user or a team to a r... | Add a user or a team to a role. Required information:
1) Type of the role
2) Resource of the role, inventory, credential, or any other
3) A user or a team to add to the role
=====API DOCS=====
Add a user or a team to a role. Required information:
* Type of the role.
... | Below is the the instruction that describes the task:
### Input:
Add a user or a team to a role. Required information:
1) Type of the role
2) Resource of the role, inventory, credential, or any other
3) A user or a team to add to the role
=====API DOCS=====
Add a user or a t... |
def visit_str(self, node, _):
"""Regex rule for quoted string allowing escaped quotes inside.
Arguments
---------
node : parsimonious.nodes.Node.
_ (children) : list, unused
Result
------
str
The wanted string, with quoted characters unquoted... | Regex rule for quoted string allowing escaped quotes inside.
Arguments
---------
node : parsimonious.nodes.Node.
_ (children) : list, unused
Result
------
str
The wanted string, with quoted characters unquoted.
Example
-------
... | Below is the the instruction that describes the task:
### Input:
Regex rule for quoted string allowing escaped quotes inside.
Arguments
---------
node : parsimonious.nodes.Node.
_ (children) : list, unused
Result
------
str
The wanted string, wit... |
def convert_point(self, point):
'''
Converts the relative position of @point into an absolute position. To
be used for event considerations, blitting is handled directly by the
Container().
'''
return self.container.convert_point(Vector(point) + self.pos) | Converts the relative position of @point into an absolute position. To
be used for event considerations, blitting is handled directly by the
Container(). | Below is the the instruction that describes the task:
### Input:
Converts the relative position of @point into an absolute position. To
be used for event considerations, blitting is handled directly by the
Container().
### Response:
def convert_point(self, point):
'''
Converts the... |
def dump(self):
"""
Dump topology to disk
"""
try:
topo = project_to_topology(self)
path = self._topology_file()
log.debug("Write %s", path)
with open(path + ".tmp", "w+", encoding="utf-8") as f:
json.dump(topo, f, indent=4,... | Dump topology to disk | Below is the the instruction that describes the task:
### Input:
Dump topology to disk
### Response:
def dump(self):
"""
Dump topology to disk
"""
try:
topo = project_to_topology(self)
path = self._topology_file()
log.debug("Write %s", path)
... |
def set_thumbnail(self, **kwargs):
"""
set thumbnail of embed
:keyword url: source url of thumbnail (only supports http(s) and attachments)
:keyword proxy_url: a proxied thumbnail of the image
:keyword height: height of thumbnail
:keyword width: width of thumbnail
... | set thumbnail of embed
:keyword url: source url of thumbnail (only supports http(s) and attachments)
:keyword proxy_url: a proxied thumbnail of the image
:keyword height: height of thumbnail
:keyword width: width of thumbnail | Below is the the instruction that describes the task:
### Input:
set thumbnail of embed
:keyword url: source url of thumbnail (only supports http(s) and attachments)
:keyword proxy_url: a proxied thumbnail of the image
:keyword height: height of thumbnail
:keyword width: width of thu... |
def by_symbol(symbol, country_code=None):
"""Get list of possible currencies for symbol; filter by country_code
Look for all currencies that use the `symbol`. If there are currencies used
in the country of `country_code`, return only those; otherwise return all
found currencies.
Parameters:
... | Get list of possible currencies for symbol; filter by country_code
Look for all currencies that use the `symbol`. If there are currencies used
in the country of `country_code`, return only those; otherwise return all
found currencies.
Parameters:
symbol: unicode Currency symbo... | Below is the the instruction that describes the task:
### Input:
Get list of possible currencies for symbol; filter by country_code
Look for all currencies that use the `symbol`. If there are currencies used
in the country of `country_code`, return only those; otherwise return all
found currencies.
... |
def get_max_tail_check(y_Arai, y_tail, t_Arai, tail_temps, n_tail):
"""
input: y_Arai, y_tail, t_Arai, tail_temps, n_tail
output: max_check, diffs
"""
if not n_tail:
return float('nan'), []
tail_compare = []
y_Arai_compare = []
for temp in tail_temps[:n_tail]:
tail_index ... | input: y_Arai, y_tail, t_Arai, tail_temps, n_tail
output: max_check, diffs | Below is the the instruction that describes the task:
### Input:
input: y_Arai, y_tail, t_Arai, tail_temps, n_tail
output: max_check, diffs
### Response:
def get_max_tail_check(y_Arai, y_tail, t_Arai, tail_temps, n_tail):
"""
input: y_Arai, y_tail, t_Arai, tail_temps, n_tail
output: max_check, diff... |
def from_wif_file(path: str) -> SigningKeyType:
"""
Return SigningKey instance from Duniter WIF file
:param path: Path to WIF file
"""
with open(path, 'r') as fh:
wif_content = fh.read()
# check data field
regex = compile('Data: ([1-9A-HJ-NP-Za-km-z]... | Return SigningKey instance from Duniter WIF file
:param path: Path to WIF file | Below is the the instruction that describes the task:
### Input:
Return SigningKey instance from Duniter WIF file
:param path: Path to WIF file
### Response:
def from_wif_file(path: str) -> SigningKeyType:
"""
Return SigningKey instance from Duniter WIF file
:param path: Path to W... |
def getFieldMax(self, fieldName):
"""
If underlying implementation does not support min/max stats collection,
or if a field type does not support min/max (non scalars), the return
value will be None.
:param fieldName: (string) name of field to get max
:returns: current maximum value for the fie... | If underlying implementation does not support min/max stats collection,
or if a field type does not support min/max (non scalars), the return
value will be None.
:param fieldName: (string) name of field to get max
:returns: current maximum value for the field ``fieldName``. | Below is the the instruction that describes the task:
### Input:
If underlying implementation does not support min/max stats collection,
or if a field type does not support min/max (non scalars), the return
value will be None.
:param fieldName: (string) name of field to get max
:returns: current ma... |
def resolve_absolute_name(self, name):
'''
Resolve a field from an absolute name.
An absolute name is just like unix absolute path,
starts with '/' and each name component is separated by '/'.
:param name: absolute name, e.g. "/container/subcontainer/field"
:return: fiel... | Resolve a field from an absolute name.
An absolute name is just like unix absolute path,
starts with '/' and each name component is separated by '/'.
:param name: absolute name, e.g. "/container/subcontainer/field"
:return: field with this absolute name
:raises: KittyException i... | Below is the the instruction that describes the task:
### Input:
Resolve a field from an absolute name.
An absolute name is just like unix absolute path,
starts with '/' and each name component is separated by '/'.
:param name: absolute name, e.g. "/container/subcontainer/field"
:re... |
def parse_message(self, tup_tree):
"""
::
<!ELEMENT MESSAGE (SIMPLEREQ | MULTIREQ | SIMPLERSP | MULTIRSP |
SIMPLEEXPREQ | MULTIEXPREQ | SIMPLEEXPRSP |
MULTIEXPRSP)
<!ATTLIST MESSAGE
ID CDATA #REQUIRE... | ::
<!ELEMENT MESSAGE (SIMPLEREQ | MULTIREQ | SIMPLERSP | MULTIRSP |
SIMPLEEXPREQ | MULTIEXPREQ | SIMPLEEXPRSP |
MULTIEXPRSP)
<!ATTLIST MESSAGE
ID CDATA #REQUIRED
PROTOCOLVERSION CDATA #REQUIRED> | Below is the the instruction that describes the task:
### Input:
::
<!ELEMENT MESSAGE (SIMPLEREQ | MULTIREQ | SIMPLERSP | MULTIRSP |
SIMPLEEXPREQ | MULTIEXPREQ | SIMPLEEXPRSP |
MULTIEXPRSP)
<!ATTLIST MESSAGE
ID CD... |
def save_shared_file(self, sharekey=None):
"""
Save a SharedFile to your Shake.
Args:
sharekey (str): Sharekey for the file to save.
Returns:
SharedFile saved to your shake.
"""
endpoint = '/api/sharedfile/{sharekey}/save'.format(sharekey=shareke... | Save a SharedFile to your Shake.
Args:
sharekey (str): Sharekey for the file to save.
Returns:
SharedFile saved to your shake. | Below is the the instruction that describes the task:
### Input:
Save a SharedFile to your Shake.
Args:
sharekey (str): Sharekey for the file to save.
Returns:
SharedFile saved to your shake.
### Response:
def save_shared_file(self, sharekey=None):
"""
Save... |
def check_encoder_decoder_args(args) -> None:
"""
Check possible encoder-decoder argument conflicts.
:param args: Arguments as returned by argparse.
"""
encoder_embed_dropout, decoder_embed_dropout = args.embed_dropout
encoder_rnn_dropout_inputs, decoder_rnn_dropout_inputs = args.rnn_dropout_in... | Check possible encoder-decoder argument conflicts.
:param args: Arguments as returned by argparse. | Below is the the instruction that describes the task:
### Input:
Check possible encoder-decoder argument conflicts.
:param args: Arguments as returned by argparse.
### Response:
def check_encoder_decoder_args(args) -> None:
"""
Check possible encoder-decoder argument conflicts.
:param args: Argum... |
def nunique(expr):
"""
The distinct count.
:param expr:
:return:
"""
output_type = types.int64
if isinstance(expr, SequenceExpr):
return NUnique(_value_type=output_type, _inputs=[expr])
elif isinstance(expr, SequenceGroupBy):
return GroupedNUnique(_data_type=output_type... | The distinct count.
:param expr:
:return: | Below is the the instruction that describes the task:
### Input:
The distinct count.
:param expr:
:return:
### Response:
def nunique(expr):
"""
The distinct count.
:param expr:
:return:
"""
output_type = types.int64
if isinstance(expr, SequenceExpr):
return NUnique(_v... |
def init(self, key_value_pairs):
"""Initialize datastore.
Only sets values for keys that are not in the datastore already.
:param dict key_value_pairs:
A set of key value pairs to use to initialize the datastore.
"""
for k, v in key_value_pairs.items():
... | Initialize datastore.
Only sets values for keys that are not in the datastore already.
:param dict key_value_pairs:
A set of key value pairs to use to initialize the datastore. | Below is the the instruction that describes the task:
### Input:
Initialize datastore.
Only sets values for keys that are not in the datastore already.
:param dict key_value_pairs:
A set of key value pairs to use to initialize the datastore.
### Response:
def init(self, key_value_pair... |
def vamp_e_score(K, C00_train, C0t_train, Ctt_train, C00_test, C0t_test, Ctt_test, k=None):
""" Computes the VAMP-E score of a kinetic model.
Ranks the kinetic model described by the estimation of covariances C00, C0t and Ctt,
defined by:
:math:`C_{0t}^{train} = E_t[x_t x_{t+\tau}^T]`
:ma... | Computes the VAMP-E score of a kinetic model.
Ranks the kinetic model described by the estimation of covariances C00, C0t and Ctt,
defined by:
:math:`C_{0t}^{train} = E_t[x_t x_{t+\tau}^T]`
:math:`C_{tt}^{train} = E_t[x_{t+\tau} x_{t+\tau}^T]`
These model covariances might have been subj... | Below is the the instruction that describes the task:
### Input:
Computes the VAMP-E score of a kinetic model.
Ranks the kinetic model described by the estimation of covariances C00, C0t and Ctt,
defined by:
:math:`C_{0t}^{train} = E_t[x_t x_{t+\tau}^T]`
:math:`C_{tt}^{train} = E_t[x_{t+\... |
def MakeDynamicPotentialFunc(kBT_Gamma, density, SpringPotnlFunc):
"""
Creates the function that calculates the potential given
the position (in volts) and the radius of the particle.
Parameters
----------
kBT_Gamma : float
Value of kB*T/Gamma
density : float
density of the... | Creates the function that calculates the potential given
the position (in volts) and the radius of the particle.
Parameters
----------
kBT_Gamma : float
Value of kB*T/Gamma
density : float
density of the nanoparticle
SpringPotnlFunc : function
Function which takes the v... | Below is the the instruction that describes the task:
### Input:
Creates the function that calculates the potential given
the position (in volts) and the radius of the particle.
Parameters
----------
kBT_Gamma : float
Value of kB*T/Gamma
density : float
density of the nanoparti... |
def step_undefined_step_snippets_should_exist_for_table(context):
"""
Checks if undefined-step snippets are provided.
EXAMPLE:
Then undefined-step snippets should exist for:
| Step |
| When an undefined step is used |
| Then another undefined step is used |
"... | Checks if undefined-step snippets are provided.
EXAMPLE:
Then undefined-step snippets should exist for:
| Step |
| When an undefined step is used |
| Then another undefined step is used | | Below is the the instruction that describes the task:
### Input:
Checks if undefined-step snippets are provided.
EXAMPLE:
Then undefined-step snippets should exist for:
| Step |
| When an undefined step is used |
| Then another undefined step is used |
### Response: ... |
def do_interact(self, arg):
"""
interact
Start an interative interpreter whose global namespace
contains all the names found in the current scope.
"""
ns = self.curframe.f_globals.copy()
ns.update(self.curframe_locals)
code.interact("*interactive*", local... | interact
Start an interative interpreter whose global namespace
contains all the names found in the current scope. | Below is the the instruction that describes the task:
### Input:
interact
Start an interative interpreter whose global namespace
contains all the names found in the current scope.
### Response:
def do_interact(self, arg):
"""
interact
Start an interative interpreter whose ... |
def get_content_item_inlines(plugins=None, base=BaseContentItemInline):
"""
Dynamically generate genuine django inlines for all registered content item types.
When the `plugins` parameter is ``None``, all plugin inlines are returned.
"""
COPY_FIELDS = (
'form', 'raw_id_fields', 'filter_verti... | Dynamically generate genuine django inlines for all registered content item types.
When the `plugins` parameter is ``None``, all plugin inlines are returned. | Below is the the instruction that describes the task:
### Input:
Dynamically generate genuine django inlines for all registered content item types.
When the `plugins` parameter is ``None``, all plugin inlines are returned.
### Response:
def get_content_item_inlines(plugins=None, base=BaseContentItemInline):
... |
def _item_to_blob(iterator, item):
"""Convert a JSON blob to the native object.
.. note::
This assumes that the ``bucket`` attribute has been
added to the iterator after being created.
:type iterator: :class:`~google.api_core.page_iterator.Iterator`
:param iterator: The iterator that ... | Convert a JSON blob to the native object.
.. note::
This assumes that the ``bucket`` attribute has been
added to the iterator after being created.
:type iterator: :class:`~google.api_core.page_iterator.Iterator`
:param iterator: The iterator that has retrieved the item.
:type item: d... | Below is the the instruction that describes the task:
### Input:
Convert a JSON blob to the native object.
.. note::
This assumes that the ``bucket`` attribute has been
added to the iterator after being created.
:type iterator: :class:`~google.api_core.page_iterator.Iterator`
:param i... |
def create_scans(urls_file):
"""
This method is rather simple, it will group the urls to be scanner together
based on (protocol, domain and port).
:param urls_file: The filename with all the URLs
:return: A list of scans to be run
"""
cli_logger.debug('Starting to process batch input file')... | This method is rather simple, it will group the urls to be scanner together
based on (protocol, domain and port).
:param urls_file: The filename with all the URLs
:return: A list of scans to be run | Below is the the instruction that describes the task:
### Input:
This method is rather simple, it will group the urls to be scanner together
based on (protocol, domain and port).
:param urls_file: The filename with all the URLs
:return: A list of scans to be run
### Response:
def create_scans(urls_fil... |
def _notify_delete(self, index_or_slice):
"""Notify about a deletion at an index_or_slice.
:return: a function that notifies about an add at the same place.
"""
if isinstance(index_or_slice, int):
length = len(self)
if -length <= index_or_slice < length:
... | Notify about a deletion at an index_or_slice.
:return: a function that notifies about an add at the same place. | Below is the the instruction that describes the task:
### Input:
Notify about a deletion at an index_or_slice.
:return: a function that notifies about an add at the same place.
### Response:
def _notify_delete(self, index_or_slice):
"""Notify about a deletion at an index_or_slice.
:return... |
def notify_badge_added_certified(sender, kind=''):
'''
Send an email when a `CERTIFIED` badge is added to an `Organization`
Parameters
----------
sender
The object that emitted the event.
kind: str
The kind of `Badge` object awarded.
'''
if kind == CERTIFIED and isinstan... | Send an email when a `CERTIFIED` badge is added to an `Organization`
Parameters
----------
sender
The object that emitted the event.
kind: str
The kind of `Badge` object awarded. | Below is the the instruction that describes the task:
### Input:
Send an email when a `CERTIFIED` badge is added to an `Organization`
Parameters
----------
sender
The object that emitted the event.
kind: str
The kind of `Badge` object awarded.
### Response:
def notify_badge_added_c... |
def _ensure_core_connections(self):
"""
If any host has fewer than the configured number of core connections
open, attempt to open connections until that number is met.
"""
for session in tuple(self.sessions):
for pool in tuple(session._pools.values()):
... | If any host has fewer than the configured number of core connections
open, attempt to open connections until that number is met. | Below is the the instruction that describes the task:
### Input:
If any host has fewer than the configured number of core connections
open, attempt to open connections until that number is met.
### Response:
def _ensure_core_connections(self):
"""
If any host has fewer than the configured n... |
def paint( self, painter, option, widget ):
"""
Paints this item.
:param painter | <QPainter>
option | <QGraphicsOption>
widget | <QWidget>
"""
painter.save()
pen = QPen(self.color())
pen.setWidth(2... | Paints this item.
:param painter | <QPainter>
option | <QGraphicsOption>
widget | <QWidget> | Below is the the instruction that describes the task:
### Input:
Paints this item.
:param painter | <QPainter>
option | <QGraphicsOption>
widget | <QWidget>
### Response:
def paint( self, painter, option, widget ):
"""
Paints thi... |
def _access_user_info(self):
"""
Accesses the :attr:`.user_info_url`.
:returns:
:class:`.UserInfoResponse`
"""
url = self.user_info_url.format(**self.user.__dict__)
return self.access(url) | Accesses the :attr:`.user_info_url`.
:returns:
:class:`.UserInfoResponse` | Below is the the instruction that describes the task:
### Input:
Accesses the :attr:`.user_info_url`.
:returns:
:class:`.UserInfoResponse`
### Response:
def _access_user_info(self):
"""
Accesses the :attr:`.user_info_url`.
:returns:
:class:`.UserInfoRespons... |
def FindDevice(self, address):
'''Find a specific device by bluetooth address.
'''
for obj in mockobject.objects.keys():
if obj.startswith('/org/bluez/') and 'dev_' in obj:
o = mockobject.objects[obj]
if o.props[DEVICE_IFACE]['Address'] \
== dbus.String(ad... | Find a specific device by bluetooth address. | Below is the the instruction that describes the task:
### Input:
Find a specific device by bluetooth address.
### Response:
def FindDevice(self, address):
'''Find a specific device by bluetooth address.
'''
for obj in mockobject.objects.keys():
if obj.startswith('/org/bluez/') and 'dev_' in obj... |
def get(self, identity):
"""
Constructs a EntityContext
:param identity: Unique identity of the Entity
:returns: twilio.rest.authy.v1.service.entity.EntityContext
:rtype: twilio.rest.authy.v1.service.entity.EntityContext
"""
return EntityContext(self._version, s... | Constructs a EntityContext
:param identity: Unique identity of the Entity
:returns: twilio.rest.authy.v1.service.entity.EntityContext
:rtype: twilio.rest.authy.v1.service.entity.EntityContext | Below is the the instruction that describes the task:
### Input:
Constructs a EntityContext
:param identity: Unique identity of the Entity
:returns: twilio.rest.authy.v1.service.entity.EntityContext
:rtype: twilio.rest.authy.v1.service.entity.EntityContext
### Response:
def get(self, iden... |
def query_for_observations(mjd, observable, runid_list):
"""Do a QUERY on the TAP service for all observations that are part of runid,
where taken after mjd and have calibration 'observable'.
Schema is at: http://www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/tap/tables
mjd : float
observable: str ( 2 or ... | Do a QUERY on the TAP service for all observations that are part of runid,
where taken after mjd and have calibration 'observable'.
Schema is at: http://www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/tap/tables
mjd : float
observable: str ( 2 or 1 )
runid: tuple eg. ('13AP05', '13AP06') | Below is the the instruction that describes the task:
### Input:
Do a QUERY on the TAP service for all observations that are part of runid,
where taken after mjd and have calibration 'observable'.
Schema is at: http://www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/tap/tables
mjd : float
observable: str ( ... |
def delete(self, symbol):
"""
Deletes a Symbol.
Parameters
----------
symbol : str or Symbol
"""
if isinstance(symbol, (str, unicode)):
sym = self.get(symbol)
elif isinstance(symbol, Symbol):
sym = symbol
... | Deletes a Symbol.
Parameters
----------
symbol : str or Symbol | Below is the the instruction that describes the task:
### Input:
Deletes a Symbol.
Parameters
----------
symbol : str or Symbol
### Response:
def delete(self, symbol):
"""
Deletes a Symbol.
Parameters
----------
symbol : st... |
def wait_stop(self):
"""
Stop the stream and wait for it to stop.
See :meth:`stop` for the general stopping conditions. You can assume
that :meth:`stop` is the first thing this coroutine calls.
"""
if not self.running:
return
self.stop()
try:
... | Stop the stream and wait for it to stop.
See :meth:`stop` for the general stopping conditions. You can assume
that :meth:`stop` is the first thing this coroutine calls. | Below is the the instruction that describes the task:
### Input:
Stop the stream and wait for it to stop.
See :meth:`stop` for the general stopping conditions. You can assume
that :meth:`stop` is the first thing this coroutine calls.
### Response:
def wait_stop(self):
"""
Stop the ... |
def logger(self):
""":class:`logging.Logger` of this instance"""
if not self.is_main:
return self.main.logger
try:
return self._logger
except AttributeError:
name = '%s.%s.%s' % (self.__module__, self.__class__.__name__,
... | :class:`logging.Logger` of this instance | Below is the the instruction that describes the task:
### Input:
:class:`logging.Logger` of this instance
### Response:
def logger(self):
""":class:`logging.Logger` of this instance"""
if not self.is_main:
return self.main.logger
try:
return self._logger
exce... |
def get_tpm_status(d_info):
"""Get the TPM support status.
Get the TPM support status of the node.
:param d_info: the list of ipmitool parameters for accessing a node.
:returns: TPM support status
"""
# note:
# Get TPM support status : ipmi cmd '0xF5', valid flags '0xC0'
#
# $ ipm... | Get the TPM support status.
Get the TPM support status of the node.
:param d_info: the list of ipmitool parameters for accessing a node.
:returns: TPM support status | Below is the the instruction that describes the task:
### Input:
Get the TPM support status.
Get the TPM support status of the node.
:param d_info: the list of ipmitool parameters for accessing a node.
:returns: TPM support status
### Response:
def get_tpm_status(d_info):
"""Get the TPM support s... |
def calc_db(peak, refval, mphonecaldb=0):
u"""
Converts voltage difference into decibels : 20*log10(peak/refval)
:param peak: amplitude
:type peak: float or np.array
:param refval: This can be either a another sound peak(or RMS val), to get the dB difference, or the microphone mphone_sensitivi... | u"""
Converts voltage difference into decibels : 20*log10(peak/refval)
:param peak: amplitude
:type peak: float or np.array
:param refval: This can be either a another sound peak(or RMS val), to get the dB difference, or the microphone mphone_sensitivity
:type refval: float
:param mphoneca... | Below is the the instruction that describes the task:
### Input:
u"""
Converts voltage difference into decibels : 20*log10(peak/refval)
:param peak: amplitude
:type peak: float or np.array
:param refval: This can be either a another sound peak(or RMS val), to get the dB difference, or the micr... |
def get_dimension_array(array):
"""
Get dimension of an array getting the number of rows and the max num of
columns.
"""
if all(isinstance(el, list) for el in array):
result = [len(array), len(max([x for x in array], key=len,))]
# elif array and isinstance(array, list):
else:
... | Get dimension of an array getting the number of rows and the max num of
columns. | Below is the the instruction that describes the task:
### Input:
Get dimension of an array getting the number of rows and the max num of
columns.
### Response:
def get_dimension_array(array):
"""
Get dimension of an array getting the number of rows and the max num of
columns.
"""
if all(isi... |
def get_property_func(key):
"""
Get the accessor function for an instance to look for `key`.
Look for it as an attribute, and if that does not work, look to see if it
is a tag.
"""
def get_it(obj):
try:
return getattr(obj, key)
except AttributeError:
retu... | Get the accessor function for an instance to look for `key`.
Look for it as an attribute, and if that does not work, look to see if it
is a tag. | Below is the the instruction that describes the task:
### Input:
Get the accessor function for an instance to look for `key`.
Look for it as an attribute, and if that does not work, look to see if it
is a tag.
### Response:
def get_property_func(key):
"""
Get the accessor function for an instance ... |
def get_data(self, file_id):
"""
Acquires the data from the table identified by the id.
The file is read only once, consecutive calls to this method will
return the sale collection.
:param file_id: identifier for the table
:return: all the values from the table
... | Acquires the data from the table identified by the id.
The file is read only once, consecutive calls to this method will
return the sale collection.
:param file_id: identifier for the table
:return: all the values from the table | Below is the the instruction that describes the task:
### Input:
Acquires the data from the table identified by the id.
The file is read only once, consecutive calls to this method will
return the sale collection.
:param file_id: identifier for the table
:return: all the values fro... |
def _swap_slice_indices(self, slc, make_slice=False):
'''Swap slice indices
Change slice indices from Verilog slicing (e.g. IEEE 1800-2012) to Python slicing.
'''
try:
start = slc.start
stop = slc.stop
slc_step = slc.step
except AttributeError... | Swap slice indices
Change slice indices from Verilog slicing (e.g. IEEE 1800-2012) to Python slicing. | Below is the the instruction that describes the task:
### Input:
Swap slice indices
Change slice indices from Verilog slicing (e.g. IEEE 1800-2012) to Python slicing.
### Response:
def _swap_slice_indices(self, slc, make_slice=False):
'''Swap slice indices
Change slice indices from Verilo... |
def prompt_user_to_select_link(self, links):
"""
Prompt the user to select a link from a list to open.
Return the link that was selected, or ``None`` if no link was selected.
"""
link_pages = self.get_link_pages(links)
n = 0
while n in range(len(link_pages)):
... | Prompt the user to select a link from a list to open.
Return the link that was selected, or ``None`` if no link was selected. | Below is the the instruction that describes the task:
### Input:
Prompt the user to select a link from a list to open.
Return the link that was selected, or ``None`` if no link was selected.
### Response:
def prompt_user_to_select_link(self, links):
"""
Prompt the user to select a link fro... |
def track_request(self, name: str, url: str, success: bool, start_time: str=None,
duration: int=None, response_code: str =None, http_method: str=None,
properties: Dict[str, object]=None, measurements: Dict[str, object]=None,
request_id: str=None):
"... | Sends a single request that was captured for the application.
:param name: The name for this request. All requests with the same name will be grouped together.
:param url: The actual URL for this request (to show in individual request instances).
:param success: True if the request ended in succ... | Below is the the instruction that describes the task:
### Input:
Sends a single request that was captured for the application.
:param name: The name for this request. All requests with the same name will be grouped together.
:param url: The actual URL for this request (to show in individual request ... |
def state():
'''Get The playback state: 'playing', 'paused', or 'stopped'.
If PLAYING or PAUSED, show information on current track.
Calls PlaybackController.get_state(), and if state is PLAYING or PAUSED, get
PlaybackController.get_current_track() and
PlaybackController.get_time_position()'''
... | Get The playback state: 'playing', 'paused', or 'stopped'.
If PLAYING or PAUSED, show information on current track.
Calls PlaybackController.get_state(), and if state is PLAYING or PAUSED, get
PlaybackController.get_current_track() and
PlaybackController.get_time_position() | Below is the the instruction that describes the task:
### Input:
Get The playback state: 'playing', 'paused', or 'stopped'.
If PLAYING or PAUSED, show information on current track.
Calls PlaybackController.get_state(), and if state is PLAYING or PAUSED, get
PlaybackController.get_current_track() and... |
def fit(self, x, y=None):
"""Do nothing and return the estimator unchanged
This method is just there to implement the usual API and hence work in pipelines.
"""
if self._dtype is not None:
iter2array(x, dtype=self._dtype)
else:
iter2array(x)
retur... | Do nothing and return the estimator unchanged
This method is just there to implement the usual API and hence work in pipelines. | Below is the the instruction that describes the task:
### Input:
Do nothing and return the estimator unchanged
This method is just there to implement the usual API and hence work in pipelines.
### Response:
def fit(self, x, y=None):
"""Do nothing and return the estimator unchanged
This me... |
def get_map_location(self):
"""Get the location of the player, converted to world coordinates.
:return: a tuple (x, y, z).
"""
map_data = self.get_map()
(bounds_e, bounds_n), (bounds_w, bounds_s) = map_data["continent_rect"]
(map_e, map_n), (map_w, map_s) = map_data["ma... | Get the location of the player, converted to world coordinates.
:return: a tuple (x, y, z). | Below is the the instruction that describes the task:
### Input:
Get the location of the player, converted to world coordinates.
:return: a tuple (x, y, z).
### Response:
def get_map_location(self):
"""Get the location of the player, converted to world coordinates.
:return: a tuple (x, y,... |
def get_queryset(self):
""" Returns all the approved topics or posts. """
qs = super().get_queryset()
qs = qs.filter(approved=True)
return qs | Returns all the approved topics or posts. | Below is the the instruction that describes the task:
### Input:
Returns all the approved topics or posts.
### Response:
def get_queryset(self):
""" Returns all the approved topics or posts. """
qs = super().get_queryset()
qs = qs.filter(approved=True)
return qs |
def on_state_changed(self, state):
"""Connect/disconnect sig_key_pressed signal."""
if state:
self.editor.sig_key_pressed.connect(self._on_key_pressed)
else:
self.editor.sig_key_pressed.disconnect(self._on_key_pressed) | Connect/disconnect sig_key_pressed signal. | Below is the the instruction that describes the task:
### Input:
Connect/disconnect sig_key_pressed signal.
### Response:
def on_state_changed(self, state):
"""Connect/disconnect sig_key_pressed signal."""
if state:
self.editor.sig_key_pressed.connect(self._on_key_pressed)
else:... |
def collect_output(self, out_file=None):
"""
Run :func:`collect_output` on the job's output directory.
"""
if self.logger.isEnabledFor(logging.INFO):
self.logger.info(
"collecting output %s", " to %s" % out_file if out_file else ''
)
se... | Run :func:`collect_output` on the job's output directory. | Below is the the instruction that describes the task:
### Input:
Run :func:`collect_output` on the job's output directory.
### Response:
def collect_output(self, out_file=None):
"""
Run :func:`collect_output` on the job's output directory.
"""
if self.logger.isEnabledFor(logging.INF... |
def autocommand(func):
""" A simplified decorator for making a single function a Command
instance. In the future this will leverage PEP0484 to do really smart
function parsing and conversion to argparse actions. """
name = func.__name__
title, desc = command.parse_docstring(func)
if not title:
... | A simplified decorator for making a single function a Command
instance. In the future this will leverage PEP0484 to do really smart
function parsing and conversion to argparse actions. | Below is the the instruction that describes the task:
### Input:
A simplified decorator for making a single function a Command
instance. In the future this will leverage PEP0484 to do really smart
function parsing and conversion to argparse actions.
### Response:
def autocommand(func):
""" A simplifie... |
def enable_alarm_actions(self, alarm_names):
"""
Enables actions for the specified alarms.
:type alarms: list
:param alarms: List of alarm names.
"""
params = {}
self.build_list_params(params, alarm_names, 'AlarmNames.member.%s')
return self.get_status('E... | Enables actions for the specified alarms.
:type alarms: list
:param alarms: List of alarm names. | Below is the the instruction that describes the task:
### Input:
Enables actions for the specified alarms.
:type alarms: list
:param alarms: List of alarm names.
### Response:
def enable_alarm_actions(self, alarm_names):
"""
Enables actions for the specified alarms.
:type ... |
def _get_module(self, module):
"""Get module."""
if isinstance(module, str):
mod = importlib.import_module(module)
for name in ('get_plugin', 'get_filter'):
attr = getattr(mod, name, None)
if attr is not None:
break
if name == 'get... | Get module. | Below is the the instruction that describes the task:
### Input:
Get module.
### Response:
def _get_module(self, module):
"""Get module."""
if isinstance(module, str):
mod = importlib.import_module(module)
for name in ('get_plugin', 'get_filter'):
attr = getattr(mod... |
def create(self, alpha_sender):
"""
Create a new AlphaSenderInstance
:param unicode alpha_sender: An Alphanumeric Sender ID string, up to 11 characters.
:returns: Newly created AlphaSenderInstance
:rtype: twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderInstance
... | Create a new AlphaSenderInstance
:param unicode alpha_sender: An Alphanumeric Sender ID string, up to 11 characters.
:returns: Newly created AlphaSenderInstance
:rtype: twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderInstance | Below is the the instruction that describes the task:
### Input:
Create a new AlphaSenderInstance
:param unicode alpha_sender: An Alphanumeric Sender ID string, up to 11 characters.
:returns: Newly created AlphaSenderInstance
:rtype: twilio.rest.messaging.v1.service.alpha_sender.AlphaSende... |
def do_dimension_value_list(mc, args):
'''List names of metric dimensions.'''
fields = {}
fields['dimension_name'] = args.dimension_name
if args.metric_name:
fields['metric_name'] = args.metric_name
if args.limit:
fields['limit'] = args.limit
if args.offset:
fields['offse... | List names of metric dimensions. | Below is the the instruction that describes the task:
### Input:
List names of metric dimensions.
### Response:
def do_dimension_value_list(mc, args):
'''List names of metric dimensions.'''
fields = {}
fields['dimension_name'] = args.dimension_name
if args.metric_name:
fields['metric_name']... |
def ddx(data, axis=0, dx=None, x=None, axis_x=0, boundary='forward-backward'):
'''
Calculates a second-order centered finite difference derivative of data
along the specified axis.
Parameters
----------
data : ndarray
Data on which we are taking a derivative.
axis : int
Index of the data array on which to... | Calculates a second-order centered finite difference derivative of data
along the specified axis.
Parameters
----------
data : ndarray
Data on which we are taking a derivative.
axis : int
Index of the data array on which to take the derivative.
dx : float, optional
Constant grid spacing value. Will assume... | Below is the the instruction that describes the task:
### Input:
Calculates a second-order centered finite difference derivative of data
along the specified axis.
Parameters
----------
data : ndarray
Data on which we are taking a derivative.
axis : int
Index of the data array on which to take the derivati... |
def DeleteFile(target_filename):
'''
Deletes the given local filename.
.. note:: If file doesn't exist this method has no effect.
:param unicode target_filename:
A local filename
:raises NotImplementedForRemotePathError:
If trying to delete a non-local path
:raises FileOnlyAc... | Deletes the given local filename.
.. note:: If file doesn't exist this method has no effect.
:param unicode target_filename:
A local filename
:raises NotImplementedForRemotePathError:
If trying to delete a non-local path
:raises FileOnlyActionError:
Raised when filename refer... | Below is the the instruction that describes the task:
### Input:
Deletes the given local filename.
.. note:: If file doesn't exist this method has no effect.
:param unicode target_filename:
A local filename
:raises NotImplementedForRemotePathError:
If trying to delete a non-local path... |
def terminate(self):
"""Terminate DMESG job"""
if self.__thread:
cmd = ["who am i"]
status, output, _ = cij.util.execute(cmd, shell=True, echo=True)
if status:
cij.warn("cij.dmesg.terminate: who am i failed")
return 1
tty ... | Terminate DMESG job | Below is the the instruction that describes the task:
### Input:
Terminate DMESG job
### Response:
def terminate(self):
"""Terminate DMESG job"""
if self.__thread:
cmd = ["who am i"]
status, output, _ = cij.util.execute(cmd, shell=True, echo=True)
if status:
... |
def remove_rows_containing(df, column, match):
"""
Return a ``DataFrame`` with rows where `column` values containing `match` are removed.
The selected `column` series of values from the supplied Pandas ``DataFrame`` is compared
to `match`, and those rows that contain it are removed from the DataFrame.
... | Return a ``DataFrame`` with rows where `column` values containing `match` are removed.
The selected `column` series of values from the supplied Pandas ``DataFrame`` is compared
to `match`, and those rows that contain it are removed from the DataFrame.
:param df: Pandas ``DataFrame``
:param column: Col... | Below is the the instruction that describes the task:
### Input:
Return a ``DataFrame`` with rows where `column` values containing `match` are removed.
The selected `column` series of values from the supplied Pandas ``DataFrame`` is compared
to `match`, and those rows that contain it are removed from the D... |
def update_descriptor_le(self, lineedit, tf):
"""Update the given line edit to show the descriptor that is stored in the index
:param lineedit: the line edit to update with the descriptor
:type lineedit: QLineEdit
:param tf: the selected taskfileinfo
:type tf: :class:`TaskFileIn... | Update the given line edit to show the descriptor that is stored in the index
:param lineedit: the line edit to update with the descriptor
:type lineedit: QLineEdit
:param tf: the selected taskfileinfo
:type tf: :class:`TaskFileInfo` | None
:returns: None
:rtype: None
... | Below is the the instruction that describes the task:
### Input:
Update the given line edit to show the descriptor that is stored in the index
:param lineedit: the line edit to update with the descriptor
:type lineedit: QLineEdit
:param tf: the selected taskfileinfo
:type tf: :class... |
def hashes_get(versions_file, base_path):
"""
Gets hashes for currently checked out version.
@param versions_file: a common.VersionsFile instance to check against.
@param base_path: where to look for files. e.g. './.update-workspace/silverstripe/'
@return: checksums {'file1': 'hash1'}
"""
fi... | Gets hashes for currently checked out version.
@param versions_file: a common.VersionsFile instance to check against.
@param base_path: where to look for files. e.g. './.update-workspace/silverstripe/'
@return: checksums {'file1': 'hash1'} | Below is the the instruction that describes the task:
### Input:
Gets hashes for currently checked out version.
@param versions_file: a common.VersionsFile instance to check against.
@param base_path: where to look for files. e.g. './.update-workspace/silverstripe/'
@return: checksums {'file1': 'hash1'}... |
def __security_definitions_descriptor(self, issuers):
"""Create a descriptor for the security definitions.
Args:
issuers: dict, mapping issuer names to Issuer tuples
Returns:
The dict representing the security definitions descriptor.
"""
if not issuers:
result = {
_DEFA... | Create a descriptor for the security definitions.
Args:
issuers: dict, mapping issuer names to Issuer tuples
Returns:
The dict representing the security definitions descriptor. | Below is the the instruction that describes the task:
### Input:
Create a descriptor for the security definitions.
Args:
issuers: dict, mapping issuer names to Issuer tuples
Returns:
The dict representing the security definitions descriptor.
### Response:
def __security_definitions_descriptor... |
def get_target_dimensions(self):
"""
Returns the target dimensions and calculates them if necessary.
The target dimensions are display independent.
:return: Target dimensions as a tuple (width, height)
:rtype: (int, int)
"""
if self.target_height is None:
... | Returns the target dimensions and calculates them if necessary.
The target dimensions are display independent.
:return: Target dimensions as a tuple (width, height)
:rtype: (int, int) | Below is the the instruction that describes the task:
### Input:
Returns the target dimensions and calculates them if necessary.
The target dimensions are display independent.
:return: Target dimensions as a tuple (width, height)
:rtype: (int, int)
### Response:
def get_target_dimensions(se... |
def upload_image(self, path=None, url=None, title=None, description=None,
album=None):
"""
Upload the image at either path or url.
:param path: The path to the image you want to upload.
:param url: The url to the image you want to upload.
:param title: The t... | Upload the image at either path or url.
:param path: The path to the image you want to upload.
:param url: The url to the image you want to upload.
:param title: The title the image will have when uploaded.
:param description: The description the image will have when uploaded.
:... | Below is the the instruction that describes the task:
### Input:
Upload the image at either path or url.
:param path: The path to the image you want to upload.
:param url: The url to the image you want to upload.
:param title: The title the image will have when uploaded.
:param desc... |
def parse_control_options(controls, variable_defaults=None):
""" Parse a set of control options.
Args:
controls: The dictionary of control options.
variable_defaults: If the controls are for a Query with variables, then this is the
default variable values defined in the Query module. The options in... | Parse a set of control options.
Args:
controls: The dictionary of control options.
variable_defaults: If the controls are for a Query with variables, then this is the
default variable values defined in the Query module. The options in the controls
parameter can override these but if a variabl... | Below is the the instruction that describes the task:
### Input:
Parse a set of control options.
Args:
controls: The dictionary of control options.
variable_defaults: If the controls are for a Query with variables, then this is the
default variable values defined in the Query module. The options ... |
def move_to(self, thing, destination):
"Move a thing to a new location."
thing.bump = self.some_things_at(destination, Obstacle)
if not thing.bump:
thing.location = destination
for o in self.observers:
o.thing_moved(thing) | Move a thing to a new location. | Below is the the instruction that describes the task:
### Input:
Move a thing to a new location.
### Response:
def move_to(self, thing, destination):
"Move a thing to a new location."
thing.bump = self.some_things_at(destination, Obstacle)
if not thing.bump:
thing.location = des... |
def print_model(self, include_unsigned_edges=False):
"""Return a SIF string of the assembled model.
Parameters
----------
include_unsigned_edges : bool
If True, includes edges with an unknown activating/inactivating
relationship (e.g., most PTMs). Default is Fals... | Return a SIF string of the assembled model.
Parameters
----------
include_unsigned_edges : bool
If True, includes edges with an unknown activating/inactivating
relationship (e.g., most PTMs). Default is False. | Below is the the instruction that describes the task:
### Input:
Return a SIF string of the assembled model.
Parameters
----------
include_unsigned_edges : bool
If True, includes edges with an unknown activating/inactivating
relationship (e.g., most PTMs). Default is... |
def setup_core_catalogs(portal):
"""Setup core catalogs
"""
logger.info("*** Setup Core Catalogs ***")
to_reindex = []
for catalog, name, attribute, meta_type in INDEXES:
c = api.get_tool(catalog)
indexes = c.indexes()
if name in indexes:
logger.info("*** Index '... | Setup core catalogs | Below is the the instruction that describes the task:
### Input:
Setup core catalogs
### Response:
def setup_core_catalogs(portal):
"""Setup core catalogs
"""
logger.info("*** Setup Core Catalogs ***")
to_reindex = []
for catalog, name, attribute, meta_type in INDEXES:
c = api.get_tool... |
def boot_priority(self, boot_priority):
"""
Sets the boot priority for this QEMU VM.
:param boot_priority: QEMU boot priority
"""
self._boot_priority = boot_priority
log.info('QEMU VM "{name}" [{id}] has set the boot priority to {boot_priority}'.format(name=self._name,
... | Sets the boot priority for this QEMU VM.
:param boot_priority: QEMU boot priority | Below is the the instruction that describes the task:
### Input:
Sets the boot priority for this QEMU VM.
:param boot_priority: QEMU boot priority
### Response:
def boot_priority(self, boot_priority):
"""
Sets the boot priority for this QEMU VM.
:param boot_priority: QEMU boot pri... |
def check_for_lane_permission(self):
"""
One or more permissions can be associated with a lane
of a workflow. In a similar way, a lane can be
restricted with relation to other lanes of the workflow.
This method called on lane changes and checks user has
required permissi... | One or more permissions can be associated with a lane
of a workflow. In a similar way, a lane can be
restricted with relation to other lanes of the workflow.
This method called on lane changes and checks user has
required permissions and relations.
Raises:
HTTPForb... | Below is the the instruction that describes the task:
### Input:
One or more permissions can be associated with a lane
of a workflow. In a similar way, a lane can be
restricted with relation to other lanes of the workflow.
This method called on lane changes and checks user has
requi... |
def index(self, slide_layout):
"""Return zero-based index of *slide_layout* in this collection.
Raises ValueError if *slide_layout* is not present in this collection.
"""
for idx, this_layout in enumerate(self):
if slide_layout == this_layout:
return idx
... | Return zero-based index of *slide_layout* in this collection.
Raises ValueError if *slide_layout* is not present in this collection. | Below is the the instruction that describes the task:
### Input:
Return zero-based index of *slide_layout* in this collection.
Raises ValueError if *slide_layout* is not present in this collection.
### Response:
def index(self, slide_layout):
"""Return zero-based index of *slide_layout* in this co... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.