code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def next_unwrittable_on_row(view, coords):
"""Return position of the next (in row) letter that is unwrittable"""
x, y = coords
maxx = max(view.keys(), key=itemgetter(0))[0]
for offset in range(x + 1, maxx):
letter = view[offset, y]
if letter not in REWRITABLE_LETTERS:
return ... | Return position of the next (in row) letter that is unwrittable | Below is the the instruction that describes the task:
### Input:
Return position of the next (in row) letter that is unwrittable
### Response:
def next_unwrittable_on_row(view, coords):
"""Return position of the next (in row) letter that is unwrittable"""
x, y = coords
maxx = max(view.keys(), key=itemg... |
def notify(fn, opts, task, *args, **kwargs):
""" notify(on_success=True, on_failure=True, **kwargs)
Wraps a bound method of a task and guards its execution. Information about the execution (task
name, duration, etc) is collected and dispatched to all notification transports registered on
wrapped task vi... | notify(on_success=True, on_failure=True, **kwargs)
Wraps a bound method of a task and guards its execution. Information about the execution (task
name, duration, etc) is collected and dispatched to all notification transports registered on
wrapped task via adding :py:class:`law.NotifyParameter` parameters. ... | Below is the the instruction that describes the task:
### Input:
notify(on_success=True, on_failure=True, **kwargs)
Wraps a bound method of a task and guards its execution. Information about the execution (task
name, duration, etc) is collected and dispatched to all notification transports registered on
... |
def _pos_nt(pr, pos, stranded=False):
"""
Given a pileup read and a position, return the base that is covered by the
read at the given position if the position is covered.
Parameters
----------
pr : pysam.calignmentfile.PileupRead
Region of type chrom:start-end, chrom:start-end:strand, ... | Given a pileup read and a position, return the base that is covered by the
read at the given position if the position is covered.
Parameters
----------
pr : pysam.calignmentfile.PileupRead
Region of type chrom:start-end, chrom:start-end:strand, or [chrom,
pos : int
Zero-based p... | Below is the the instruction that describes the task:
### Input:
Given a pileup read and a position, return the base that is covered by the
read at the given position if the position is covered.
Parameters
----------
pr : pysam.calignmentfile.PileupRead
Region of type chrom:start-end, chrom... |
def search_list(text_list, pattern, flags=0):
"""
CommandLine:
python -m utool.util_list --test-search_list
Example:
>>> # ENABLE_DOCTEST
>>> import utool as ut
>>> text_list = ['ham', 'jam', 'eggs', 'spam']
>>> pattern = '.am'
>>> flags = 0
>>> (vali... | CommandLine:
python -m utool.util_list --test-search_list
Example:
>>> # ENABLE_DOCTEST
>>> import utool as ut
>>> text_list = ['ham', 'jam', 'eggs', 'spam']
>>> pattern = '.am'
>>> flags = 0
>>> (valid_index_list, valid_match_list) = ut.search_list(text_list... | Below is the the instruction that describes the task:
### Input:
CommandLine:
python -m utool.util_list --test-search_list
Example:
>>> # ENABLE_DOCTEST
>>> import utool as ut
>>> text_list = ['ham', 'jam', 'eggs', 'spam']
>>> pattern = '.am'
>>> flags = 0
... |
def dameraulevenshtein(seq1, seq2):
"""Calculate the Damerau-Levenshtein distance between sequences.
This distance is the number of additions, deletions, substitutions,
and transpositions needed to transform the first sequence into the
second. Although generally used with strings, any sequences of
... | Calculate the Damerau-Levenshtein distance between sequences.
This distance is the number of additions, deletions, substitutions,
and transpositions needed to transform the first sequence into the
second. Although generally used with strings, any sequences of
comparable objects will work.
Transpos... | Below is the the instruction that describes the task:
### Input:
Calculate the Damerau-Levenshtein distance between sequences.
This distance is the number of additions, deletions, substitutions,
and transpositions needed to transform the first sequence into the
second. Although generally used with stri... |
def init(main_dir: Path, logfile_path: Path, log_level: str):
"""
Initialize the _downloader. TODO.
:param main_dir: main directory
:type main_dir: ~pathlib.Path
:param logfile_path: logfile path
:type logfile_path: ~pathlib.Path
:param log_level: logging level
:type log_level: str
... | Initialize the _downloader. TODO.
:param main_dir: main directory
:type main_dir: ~pathlib.Path
:param logfile_path: logfile path
:type logfile_path: ~pathlib.Path
:param log_level: logging level
:type log_level: str | Below is the the instruction that describes the task:
### Input:
Initialize the _downloader. TODO.
:param main_dir: main directory
:type main_dir: ~pathlib.Path
:param logfile_path: logfile path
:type logfile_path: ~pathlib.Path
:param log_level: logging level
:type log_level: str
### Respo... |
def fwdl_status_output_fwdl_entries_blade_app(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
fwdl_status = ET.Element("fwdl_status")
config = fwdl_status
output = ET.SubElement(fwdl_status, "output")
fwdl_entries = ET.SubElement(output, ... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def fwdl_status_output_fwdl_entries_blade_app(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
fwdl_status = ET.Element("fwdl_status")
config = fwdl_st... |
def ashraeiam(aoi, b=0.05):
'''
Determine the incidence angle modifier using the ASHRAE transmission
model.
ashraeiam calculates the incidence angle modifier as developed in
[1], and adopted by ASHRAE (American Society of Heating,
Refrigeration, and Air Conditioning Engineers) [2]. The model ha... | Determine the incidence angle modifier using the ASHRAE transmission
model.
ashraeiam calculates the incidence angle modifier as developed in
[1], and adopted by ASHRAE (American Society of Heating,
Refrigeration, and Air Conditioning Engineers) [2]. The model has
been used by model programs such a... | Below is the the instruction that describes the task:
### Input:
Determine the incidence angle modifier using the ASHRAE transmission
model.
ashraeiam calculates the incidence angle modifier as developed in
[1], and adopted by ASHRAE (American Society of Heating,
Refrigeration, and Air Conditioning... |
def get_filters(self, filter_id=None, params=None):
"""
`<>`_
:arg filter_id: The ID of the filter to fetch
:arg from_: skips a number of filters
:arg size: specifies a max number of filters to get
"""
return self.transport.perform_request(
"GET", _ma... | `<>`_
:arg filter_id: The ID of the filter to fetch
:arg from_: skips a number of filters
:arg size: specifies a max number of filters to get | Below is the the instruction that describes the task:
### Input:
`<>`_
:arg filter_id: The ID of the filter to fetch
:arg from_: skips a number of filters
:arg size: specifies a max number of filters to get
### Response:
def get_filters(self, filter_id=None, params=None):
"""
... |
def check_sizes(size, width, height):
"""
Check that these arguments, if supplied, are consistent.
Return a (width, height) pair.
"""
if not size:
return width, height
if len(size) != 2:
raise ProtocolError(
"size argument should be a pair (width, height)")
if w... | Check that these arguments, if supplied, are consistent.
Return a (width, height) pair. | Below is the the instruction that describes the task:
### Input:
Check that these arguments, if supplied, are consistent.
Return a (width, height) pair.
### Response:
def check_sizes(size, width, height):
"""
Check that these arguments, if supplied, are consistent.
Return a (width, height) pair.
... |
def prepare_axes(wave, flux, fig=None, ax_lower=(0.1, 0.1),
ax_dim=(0.85, 0.65)):
"""Create fig and axes if needed and layout axes in fig."""
# Axes location in figure.
if not fig:
fig = plt.figure()
ax = fig.add_axes([ax_lower[0], ax_lower[1], ax_dim[0], ax_dim[1]])
ax.plot... | Create fig and axes if needed and layout axes in fig. | Below is the the instruction that describes the task:
### Input:
Create fig and axes if needed and layout axes in fig.
### Response:
def prepare_axes(wave, flux, fig=None, ax_lower=(0.1, 0.1),
ax_dim=(0.85, 0.65)):
"""Create fig and axes if needed and layout axes in fig."""
# Axes location... |
def parallel_apply_transformations(x, transforms, black_border_size=0):
"""
Apply image transformations in parallel.
:param transforms: TODO
:param black_border_size: int, size of black border to apply
Returns:
Transformed images
"""
transforms = tf.convert_to_tensor(transforms, dtype=tf.float32)
x ... | Apply image transformations in parallel.
:param transforms: TODO
:param black_border_size: int, size of black border to apply
Returns:
Transformed images | Below is the the instruction that describes the task:
### Input:
Apply image transformations in parallel.
:param transforms: TODO
:param black_border_size: int, size of black border to apply
Returns:
Transformed images
### Response:
def parallel_apply_transformations(x, transforms, black_border_size=0):
... |
def __VersionIsSupported(desiredVersion, serviceVersionDescription):
"""
Private method that returns true if the service version description document
indicates that the desired version is supported
@param desiredVersion: The version we want to see if the server supports
(eg. vim.v... | Private method that returns true if the service version description document
indicates that the desired version is supported
@param desiredVersion: The version we want to see if the server supports
(eg. vim.version.version2.
@type desiredVersion: string
@param serviceVersionDescr... | Below is the the instruction that describes the task:
### Input:
Private method that returns true if the service version description document
indicates that the desired version is supported
@param desiredVersion: The version we want to see if the server supports
(eg. vim.version.ver... |
def host_events(self, host):
'''
Given a host name, this will return all task events executed on that host
'''
all_host_events = filter(lambda x: 'event_data' in x and 'host' in x['event_data'] and x['event_data']['host'] == host,
self.events)
ret... | Given a host name, this will return all task events executed on that host | Below is the the instruction that describes the task:
### Input:
Given a host name, this will return all task events executed on that host
### Response:
def host_events(self, host):
'''
Given a host name, this will return all task events executed on that host
'''
all_host_events = f... |
def exists(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if a queue exists.
CLI Example:
.. code-block:: bash
salt myminion boto_sqs.exists myqueue region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
... | Check to see if a queue exists.
CLI Example:
.. code-block:: bash
salt myminion boto_sqs.exists myqueue region=us-east-1 | Below is the the instruction that describes the task:
### Input:
Check to see if a queue exists.
CLI Example:
.. code-block:: bash
salt myminion boto_sqs.exists myqueue region=us-east-1
### Response:
def exists(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if a... |
def is_close_to_int(x):
"""
Check if value is close to an integer
Parameters
----------
x : float
Numeric value to check
Returns
-------
out : bool
"""
if not np.isfinite(x):
return False
return abs(x - nearest_int(x)) < 1e-10 | Check if value is close to an integer
Parameters
----------
x : float
Numeric value to check
Returns
-------
out : bool | Below is the the instruction that describes the task:
### Input:
Check if value is close to an integer
Parameters
----------
x : float
Numeric value to check
Returns
-------
out : bool
### Response:
def is_close_to_int(x):
"""
Check if value is close to an integer
Par... |
def close_ns(symbol):
'''generates a closing names statement from a symbol'''
closing = ' '.join(['}' for x in symbol.module.name_parts])
name = '::'.join(symbol.module.name_parts)
return '{0} // namespace {1}'.format(closing, name) | generates a closing names statement from a symbol | Below is the the instruction that describes the task:
### Input:
generates a closing names statement from a symbol
### Response:
def close_ns(symbol):
'''generates a closing names statement from a symbol'''
closing = ' '.join(['}' for x in symbol.module.name_parts])
name = '::'.join(symbol.... |
def open(self):
"""Open the working area
Returns
-------
None
"""
self.path = self._prepare_dir(self.topdir)
self._copy_executable(area_path=self.path)
self._save_logging_levels(area_path=self.path)
self._put_python_modules(modules=self.python_mo... | Open the working area
Returns
-------
None | Below is the the instruction that describes the task:
### Input:
Open the working area
Returns
-------
None
### Response:
def open(self):
"""Open the working area
Returns
-------
None
"""
self.path = self._prepare_dir(self.topdir)
s... |
def match(self, path):
'''Match a path and return ``None`` if no matching, otherwise
a dictionary of matched variables with values. If there is more
to be match in the path, the remaining string is placed in the
``__remaining__`` key of the dictionary.'''
match = self._regex.sear... | Match a path and return ``None`` if no matching, otherwise
a dictionary of matched variables with values. If there is more
to be match in the path, the remaining string is placed in the
``__remaining__`` key of the dictionary. | Below is the the instruction that describes the task:
### Input:
Match a path and return ``None`` if no matching, otherwise
a dictionary of matched variables with values. If there is more
to be match in the path, the remaining string is placed in the
``__remaining__`` key of the dictionary.
... |
def beacon(config):
'''
Return status for requested information
'''
log.debug(config)
ctime = datetime.datetime.utcnow().isoformat()
if not config:
config = [{
'loadavg': ['all'],
'cpustats': ['all'],
'meminfo': ['all'],
'vmstats': ['all']... | Return status for requested information | Below is the the instruction that describes the task:
### Input:
Return status for requested information
### Response:
def beacon(config):
'''
Return status for requested information
'''
log.debug(config)
ctime = datetime.datetime.utcnow().isoformat()
if not config:
config = [{
... |
def on_recording_change(self, enable):
"""Triggered when recording settings have changed.
in enable of type bool
TODO
"""
if not isinstance(enable, bool):
raise TypeError("enable can only be an instance of type bool")
self._call("onRecordingChange",
... | Triggered when recording settings have changed.
in enable of type bool
TODO | Below is the the instruction that describes the task:
### Input:
Triggered when recording settings have changed.
in enable of type bool
TODO
### Response:
def on_recording_change(self, enable):
"""Triggered when recording settings have changed.
in enable of type bool
... |
def _digits(self):
""" 0-9 """
self.number += self.key
try:
if self.compact is False:
self.top.body.focus_position = \
self.items.index(self.items_com[max(int(self.number) - 1, 0)])
else:
self.top.body.focus_position = \... | 0-9 | Below is the the instruction that describes the task:
### Input:
0-9
### Response:
def _digits(self):
""" 0-9 """
self.number += self.key
try:
if self.compact is False:
self.top.body.focus_position = \
self.items.index(self.items_com[max(int(s... |
def add_value(self, value_type, value_min, value_max):
'''Add a tunable value to the ABC (fitness function must be
configured to handle it)
Args:
value_type (string): type of the value, 'int' or 'float'
value_min (int or float): minimum bound for the value
va... | Add a tunable value to the ABC (fitness function must be
configured to handle it)
Args:
value_type (string): type of the value, 'int' or 'float'
value_min (int or float): minimum bound for the value
value_max (int or float): maximum bound for the value
Retur... | Below is the the instruction that describes the task:
### Input:
Add a tunable value to the ABC (fitness function must be
configured to handle it)
Args:
value_type (string): type of the value, 'int' or 'float'
value_min (int or float): minimum bound for the value
... |
def createShadowHandlerWithName(self, shadowName, isPersistentSubscribe):
"""
**Description**
Create a device shadow handler using the specified shadow name and isPersistentSubscribe.
**Syntax**
.. code:: python
# Create a device shadow handler for shadow named "Bot... | **Description**
Create a device shadow handler using the specified shadow name and isPersistentSubscribe.
**Syntax**
.. code:: python
# Create a device shadow handler for shadow named "Bot1", using persistent subscription
Bot1Shadow = myAWSIoTMQTTShadowClient.createShadow... | Below is the the instruction that describes the task:
### Input:
**Description**
Create a device shadow handler using the specified shadow name and isPersistentSubscribe.
**Syntax**
.. code:: python
# Create a device shadow handler for shadow named "Bot1", using persistent subs... |
async def browse(self, device):
"""
Launch file manager on the mount path of the specified device.
:param device: device object, block device path or mount path
:returns: whether the program was successfully launched.
"""
device = self._find_device(device)
if not... | Launch file manager on the mount path of the specified device.
:param device: device object, block device path or mount path
:returns: whether the program was successfully launched. | Below is the the instruction that describes the task:
### Input:
Launch file manager on the mount path of the specified device.
:param device: device object, block device path or mount path
:returns: whether the program was successfully launched.
### Response:
async def browse(self, device):
... |
def _get_exec_binary(binary, kw):
"""
On win32, the subprocess module can only reliably resolve the
target binary if it's actually a binary; as for a Node.js script
it seems to only work iff shell=True was specified, presenting
a security risk. Resolve the target manually through which will
acc... | On win32, the subprocess module can only reliably resolve the
target binary if it's actually a binary; as for a Node.js script
it seems to only work iff shell=True was specified, presenting
a security risk. Resolve the target manually through which will
account for that.
The kw argument is the key... | Below is the the instruction that describes the task:
### Input:
On win32, the subprocess module can only reliably resolve the
target binary if it's actually a binary; as for a Node.js script
it seems to only work iff shell=True was specified, presenting
a security risk. Resolve the target manually thr... |
def verify(self):
"""
Verify that the information gathered from the on-the-wire
representation is of the right type.
This is supposed to be run before the info is deserialized.
:return: True/False
"""
for param in self.longs:
item = getattr(self, para... | Verify that the information gathered from the on-the-wire
representation is of the right type.
This is supposed to be run before the info is deserialized.
:return: True/False | Below is the the instruction that describes the task:
### Input:
Verify that the information gathered from the on-the-wire
representation is of the right type.
This is supposed to be run before the info is deserialized.
:return: True/False
### Response:
def verify(self):
"""
... |
def present(name, brand, zonepath, properties=None, resources=None):
'''
Ensure a zone with certain properties and resources
name : string
name of the zone
brand : string
brand of the zone
zonepath : string
path of the zone
properties : list of key-value pairs
di... | Ensure a zone with certain properties and resources
name : string
name of the zone
brand : string
brand of the zone
zonepath : string
path of the zone
properties : list of key-value pairs
dict of properties
resources : list of key-value pairs
dict of resource... | Below is the the instruction that describes the task:
### Input:
Ensure a zone with certain properties and resources
name : string
name of the zone
brand : string
brand of the zone
zonepath : string
path of the zone
properties : list of key-value pairs
dict of proper... |
def global_position_int_cov_send(self, time_boot_ms, time_utc, estimator_type, lat, lon, alt, relative_alt, vx, vy, vz, covariance, force_mavlink1=False):
'''
The filtered global position (e.g. fused GPS and accelerometers). The
position is in GPS-frame (right-handed, Z-u... | The filtered global position (e.g. fused GPS and accelerometers). The
position is in GPS-frame (right-handed, Z-up). It is
designed as scaled integer message since the
resolution of float is not sufficient. NOTE: This
message is intended for onboard netwo... | Below is the the instruction that describes the task:
### Input:
The filtered global position (e.g. fused GPS and accelerometers). The
position is in GPS-frame (right-handed, Z-up). It is
designed as scaled integer message since the
resolution of float is not suffici... |
def _parse_return(cls, result):
"""Extract the result, return value and context from a result object
"""
return_value = None
success = result['result']
context = result['context']
if 'return_value' in result:
return_value = result['return_value']
re... | Extract the result, return value and context from a result object | Below is the the instruction that describes the task:
### Input:
Extract the result, return value and context from a result object
### Response:
def _parse_return(cls, result):
"""Extract the result, return value and context from a result object
"""
return_value = None
success = re... |
def _stage_local_files(local_dir, local_files={}):
"""
Either ``local_files`` and/or ``context`` should be supplied.
Will stage a ``local_files`` dictionary of path:filename pairs where path
is relative to ``local_dir`` into a local tmp staging directory.
Returns a path to the temporary lo... | Either ``local_files`` and/or ``context`` should be supplied.
Will stage a ``local_files`` dictionary of path:filename pairs where path
is relative to ``local_dir`` into a local tmp staging directory.
Returns a path to the temporary local staging directory | Below is the the instruction that describes the task:
### Input:
Either ``local_files`` and/or ``context`` should be supplied.
Will stage a ``local_files`` dictionary of path:filename pairs where path
is relative to ``local_dir`` into a local tmp staging directory.
Returns a path to the tempor... |
def load_from_string(self, content, container, **options):
"""
Load configuration data from given string 'content'.
:param content: Configuration string
:param container: callble to make a container object
:param options: keyword options passed to '_load_from_string_fn'
... | Load configuration data from given string 'content'.
:param content: Configuration string
:param container: callble to make a container object
:param options: keyword options passed to '_load_from_string_fn'
:return: container object holding the configuration data | Below is the the instruction that describes the task:
### Input:
Load configuration data from given string 'content'.
:param content: Configuration string
:param container: callble to make a container object
:param options: keyword options passed to '_load_from_string_fn'
:return: ... |
def notifications_get(input_params={}, always_retry=True, **kwargs):
"""
Invokes the /notifications/get API method.
"""
return DXHTTPRequest('/notifications/get', input_params, always_retry=always_retry, **kwargs) | Invokes the /notifications/get API method. | Below is the the instruction that describes the task:
### Input:
Invokes the /notifications/get API method.
### Response:
def notifications_get(input_params={}, always_retry=True, **kwargs):
"""
Invokes the /notifications/get API method.
"""
return DXHTTPRequest('/notifications/get', input_params, ... |
def slug_exists(self, request):
"""Check if given url slug exists.
Check if slug given in query parameter ``name`` exists. Return
``True`` if slug already exists and ``False`` otherwise.
"""
if not request.user.is_authenticated:
return Response(status=status.HTTP_40... | Check if given url slug exists.
Check if slug given in query parameter ``name`` exists. Return
``True`` if slug already exists and ``False`` otherwise. | Below is the the instruction that describes the task:
### Input:
Check if given url slug exists.
Check if slug given in query parameter ``name`` exists. Return
``True`` if slug already exists and ``False`` otherwise.
### Response:
def slug_exists(self, request):
"""Check if given url slug ... |
def style(self):
"""Add summaries and convert to Pandas Styler"""
row_titles = [a.title for a in self._cleaned_summary_rows]
col_titles = [a.title for a in self._cleaned_summary_cols]
row_ix = pd.IndexSlice[row_titles, :]
col_ix = pd.IndexSlice[:, col_titles]
def handle_... | Add summaries and convert to Pandas Styler | Below is the the instruction that describes the task:
### Input:
Add summaries and convert to Pandas Styler
### Response:
def style(self):
"""Add summaries and convert to Pandas Styler"""
row_titles = [a.title for a in self._cleaned_summary_rows]
col_titles = [a.title for a in self._cleaned... |
def load(self, patterns, dirs, ignore=None):
"""Load objects from the filesystem into the ``paths`` dictionary
Also include an attribute on the object, ``relative_path`` which is the
shortened, relative path the package/module
"""
for dir_ in dirs:
dir_root = dir_
... | Load objects from the filesystem into the ``paths`` dictionary
Also include an attribute on the object, ``relative_path`` which is the
shortened, relative path the package/module | Below is the the instruction that describes the task:
### Input:
Load objects from the filesystem into the ``paths`` dictionary
Also include an attribute on the object, ``relative_path`` which is the
shortened, relative path the package/module
### Response:
def load(self, patterns, dirs, ignore=No... |
def get_model(self):
"""
Get a model if the formula was previously satisfied.
"""
if self.lingeling and self.status == True:
model = pysolvers.lingeling_model(self.lingeling)
return model if model != None else [] | Get a model if the formula was previously satisfied. | Below is the the instruction that describes the task:
### Input:
Get a model if the formula was previously satisfied.
### Response:
def get_model(self):
"""
Get a model if the formula was previously satisfied.
"""
if self.lingeling and self.status == True:
model = p... |
def is_binary(filename):
"""
:param filename: File to check.
:returns: True if it's a binary file, otherwise False.
"""
logger.debug('is_binary: %(filename)r', locals())
# Check if the file extension is in a list of known binary types
binary_extensions = ['pyc', 'iso', 'zip', 'pdf']
for... | :param filename: File to check.
:returns: True if it's a binary file, otherwise False. | Below is the the instruction that describes the task:
### Input:
:param filename: File to check.
:returns: True if it's a binary file, otherwise False.
### Response:
def is_binary(filename):
"""
:param filename: File to check.
:returns: True if it's a binary file, otherwise False.
"""
logge... |
def exec_command(self, cmd, tmp_path, sudo_user, sudoable=False, executable='/bin/sh'):
''' run a command on the remote host '''
vvv("EXEC COMMAND %s" % cmd)
if self.runner.sudo and sudoable:
raise errors.AnsibleError("fireball does not use sudo, but runs as whoever it was initiate... | run a command on the remote host | Below is the the instruction that describes the task:
### Input:
run a command on the remote host
### Response:
def exec_command(self, cmd, tmp_path, sudo_user, sudoable=False, executable='/bin/sh'):
''' run a command on the remote host '''
vvv("EXEC COMMAND %s" % cmd)
if self.runner.sudo... |
def hw_pipette(self) -> Dict[str, Any]:
""" View the information returned by the hardware API directly.
:raises: a :py:class:`.types.PipetteNotAttachedError` if the pipette is
no longer attached (should not happen).
"""
pipette = self._hw_manager.hardware.attached_instr... | View the information returned by the hardware API directly.
:raises: a :py:class:`.types.PipetteNotAttachedError` if the pipette is
no longer attached (should not happen). | Below is the the instruction that describes the task:
### Input:
View the information returned by the hardware API directly.
:raises: a :py:class:`.types.PipetteNotAttachedError` if the pipette is
no longer attached (should not happen).
### Response:
def hw_pipette(self) -> Dict[str, Any]... |
def applyTransformOnGroup(self, transform, group):
"""Apply an SVG transformation to a RL Group shape.
The transformation is the value of an SVG transform attribute
like transform="scale(1, -1) translate(10, 30)".
rotate(<angle> [<cx> <cy>]) is equivalent to:
translate(<cx> <... | Apply an SVG transformation to a RL Group shape.
The transformation is the value of an SVG transform attribute
like transform="scale(1, -1) translate(10, 30)".
rotate(<angle> [<cx> <cy>]) is equivalent to:
translate(<cx> <cy>) rotate(<angle>) translate(-<cx> -<cy>) | Below is the the instruction that describes the task:
### Input:
Apply an SVG transformation to a RL Group shape.
The transformation is the value of an SVG transform attribute
like transform="scale(1, -1) translate(10, 30)".
rotate(<angle> [<cx> <cy>]) is equivalent to:
translate... |
def int_to_string(number, alphabet, padding=None):
"""
Convert a number to a string, using the given alphabet.
The output has the most significant digit first.
"""
output = ""
alpha_len = len(alphabet)
while number:
number, digit = divmod(number, alpha_len)
output += alphabet... | Convert a number to a string, using the given alphabet.
The output has the most significant digit first. | Below is the the instruction that describes the task:
### Input:
Convert a number to a string, using the given alphabet.
The output has the most significant digit first.
### Response:
def int_to_string(number, alphabet, padding=None):
"""
Convert a number to a string, using the given alphabet.
The ... |
def load_config_from_setup(app):
"""
Replace values in app.config from package metadata
"""
# for now, assume project root is one level up
root = os.path.join(app.confdir, '..')
setup_script = os.path.join(root, 'setup.py')
fields = ['--name', '--version', '--url', '--author']
dist_info_... | Replace values in app.config from package metadata | Below is the the instruction that describes the task:
### Input:
Replace values in app.config from package metadata
### Response:
def load_config_from_setup(app):
"""
Replace values in app.config from package metadata
"""
# for now, assume project root is one level up
root = os.path.join(app.co... |
def sql_flush(self, style, tables, sequences, allow_cascade=False):
"""
Returns a list of SQL statements required to remove all data from
the given database tables (without actually removing the tables
themselves).
The `style` argument is a Style object as returned by either
... | Returns a list of SQL statements required to remove all data from
the given database tables (without actually removing the tables
themselves).
The `style` argument is a Style object as returned by either
color_style() or no_style() in django.core.management.color. | Below is the the instruction that describes the task:
### Input:
Returns a list of SQL statements required to remove all data from
the given database tables (without actually removing the tables
themselves).
The `style` argument is a Style object as returned by either
color_style() ... |
def get_model_fields(model, add_reserver_flag=True):
"""
Creating fields suit for model_config , id will be skipped.
"""
import uliweb.orm as orm
fields = []
m = {'type':'type_name', 'hint':'hint',
'default':'default', 'required':'required'}
m1 = {'index':'index', 'unique':'unique'... | Creating fields suit for model_config , id will be skipped. | Below is the the instruction that describes the task:
### Input:
Creating fields suit for model_config , id will be skipped.
### Response:
def get_model_fields(model, add_reserver_flag=True):
"""
Creating fields suit for model_config , id will be skipped.
"""
import uliweb.orm as orm
fields = ... |
def get_formset_class(self, **kwargs):
"""
Returns the formset for the queryset,
if a form class is available.
"""
form_class = self.get_formset_form_class()
if form_class:
kwargs['formfield_callback'] = self.formfield_for_dbfield
return model_form... | Returns the formset for the queryset,
if a form class is available. | Below is the the instruction that describes the task:
### Input:
Returns the formset for the queryset,
if a form class is available.
### Response:
def get_formset_class(self, **kwargs):
"""
Returns the formset for the queryset,
if a form class is available.
"""
form_... |
def get_items_from_response(self, response):
"""Yield :class:`.taskqueue.task.Task` items from response.
:type response: dict
:param response: The JSON API response for a page of tasks.
"""
for item in response.get('items', []):
id = item.get('id')
task =... | Yield :class:`.taskqueue.task.Task` items from response.
:type response: dict
:param response: The JSON API response for a page of tasks. | Below is the the instruction that describes the task:
### Input:
Yield :class:`.taskqueue.task.Task` items from response.
:type response: dict
:param response: The JSON API response for a page of tasks.
### Response:
def get_items_from_response(self, response):
"""Yield :class:`.taskqueue.... |
def send_until(self,
send,
regexps,
not_there=False,
shutit_pexpect_child=None,
cadence=5,
retries=100,
echo=None,
note=None,
debug_command=None,
pause_point_on... | Send string on a regular cadence until a string is either seen, or the timeout is triggered.
@param send: See send()
@param regexps: List of regexps to wait for.
@param not_there: If True, wait until this a regexp is not seen in the output. If False
... | Below is the the instruction that describes the task:
### Input:
Send string on a regular cadence until a string is either seen, or the timeout is triggered.
@param send: See send()
@param regexps: List of regexps to wait for.
@param not_there: If True, wait until this... |
def fullqualname_py3(obj):
"""Fully qualified name for objects in Python 3."""
if type(obj).__name__ == 'builtin_function_or_method':
return _fullqualname_builtin_py3(obj)
elif type(obj).__name__ == 'function':
return _fullqualname_function_py3(obj)
elif type(obj).__name__ in ['memb... | Fully qualified name for objects in Python 3. | Below is the the instruction that describes the task:
### Input:
Fully qualified name for objects in Python 3.
### Response:
def fullqualname_py3(obj):
"""Fully qualified name for objects in Python 3."""
if type(obj).__name__ == 'builtin_function_or_method':
return _fullqualname_builtin_py3(obj)
... |
def stage(x, staging):
"""
Stage an object to the `staging` directory.
If the object is a Track and is one of the types that needs an index file
(bam, vcfTabix), then the index file will be staged as well.
Returns a list of the linknames created.
"""
linknames = []
# Objects that don'... | Stage an object to the `staging` directory.
If the object is a Track and is one of the types that needs an index file
(bam, vcfTabix), then the index file will be staged as well.
Returns a list of the linknames created. | Below is the the instruction that describes the task:
### Input:
Stage an object to the `staging` directory.
If the object is a Track and is one of the types that needs an index file
(bam, vcfTabix), then the index file will be staged as well.
Returns a list of the linknames created.
### Response:
de... |
def arrange_plots_on_one_canvas(FigureAxTupleArray, title='', SubtitleArray = [], show_fig=True):
"""
Arranges plots, given in an array of tuples consisting of fig and axs,
onto a subplot-figure consisting of 2 horizontal times the lenght of the
passed (fig,axs)-array divided by 2 vertical subplots
... | Arranges plots, given in an array of tuples consisting of fig and axs,
onto a subplot-figure consisting of 2 horizontal times the lenght of the
passed (fig,axs)-array divided by 2 vertical subplots
Parameters
----------
FigureAxTupleArray : array-like
array of Tuples(fig, axs) outputted f... | Below is the the instruction that describes the task:
### Input:
Arranges plots, given in an array of tuples consisting of fig and axs,
onto a subplot-figure consisting of 2 horizontal times the lenght of the
passed (fig,axs)-array divided by 2 vertical subplots
Parameters
----------
FigureAx... |
def floating_ip_create(kwargs, call=None):
'''
Allocate a floating IP
.. versionadded:: 2016.3.0
'''
if call != 'function':
raise SaltCloudSystemExit(
'The floating_ip_create action must be called with -f or --function'
)
if 'pool' not in kwargs:
log.error('... | Allocate a floating IP
.. versionadded:: 2016.3.0 | Below is the the instruction that describes the task:
### Input:
Allocate a floating IP
.. versionadded:: 2016.3.0
### Response:
def floating_ip_create(kwargs, call=None):
'''
Allocate a floating IP
.. versionadded:: 2016.3.0
'''
if call != 'function':
raise SaltCloudSystemExit(
... |
def set_formatter(name, func):
"""Replace the formatter function used by the trace decorator to
handle formatting a specific kind of argument. There are several
kinds of arguments that trace discriminates between:
* instance argument - the object bound to an instance method.
* class argument - the... | Replace the formatter function used by the trace decorator to
handle formatting a specific kind of argument. There are several
kinds of arguments that trace discriminates between:
* instance argument - the object bound to an instance method.
* class argument - the class object bound to a class method.... | Below is the the instruction that describes the task:
### Input:
Replace the formatter function used by the trace decorator to
handle formatting a specific kind of argument. There are several
kinds of arguments that trace discriminates between:
* instance argument - the object bound to an instance met... |
def do_alarm_definition_list(mc, args):
'''List alarm definitions for this tenant.'''
fields = {}
if args.name:
fields['name'] = args.name
if args.dimensions:
fields['dimensions'] = utils.format_dimensions_query(args.dimensions)
if args.severity:
if not _validate_severity(arg... | List alarm definitions for this tenant. | Below is the the instruction that describes the task:
### Input:
List alarm definitions for this tenant.
### Response:
def do_alarm_definition_list(mc, args):
'''List alarm definitions for this tenant.'''
fields = {}
if args.name:
fields['name'] = args.name
if args.dimensions:
field... |
def frame2string(frame):
"""Return info about frame.
Keyword arg:
frame
Return string in format:
File {file name}, line {line number}, in
{name of parent of code object} {newline}
Line from file at line number
"""
lineno = frame.f_lineno # or f_lasti
co = frame.f_code
... | Return info about frame.
Keyword arg:
frame
Return string in format:
File {file name}, line {line number}, in
{name of parent of code object} {newline}
Line from file at line number | Below is the the instruction that describes the task:
### Input:
Return info about frame.
Keyword arg:
frame
Return string in format:
File {file name}, line {line number}, in
{name of parent of code object} {newline}
Line from file at line number
### Response:
def frame2string(frame... |
def views_preview(self, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/views#previewing-views"
api_path = "/api/v2/views/preview.json"
return self.call(api_path, method="POST", data=data, **kwargs) | https://developer.zendesk.com/rest_api/docs/core/views#previewing-views | Below is the the instruction that describes the task:
### Input:
https://developer.zendesk.com/rest_api/docs/core/views#previewing-views
### Response:
def views_preview(self, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/views#previewing-views"
api_path = "/api/v2/views/preview... |
def parse(self, configManager, config):
"""
Parse configuration options out of a YAML configuration file.
Inputs: configManager - Our parent ConfigManager instance which is constructing the Config object.
config - The _Config object containing configuration options popula... | Parse configuration options out of a YAML configuration file.
Inputs: configManager - Our parent ConfigManager instance which is constructing the Config object.
config - The _Config object containing configuration options populated thus far.
Outputs: A dictionary of new configur... | Below is the the instruction that describes the task:
### Input:
Parse configuration options out of a YAML configuration file.
Inputs: configManager - Our parent ConfigManager instance which is constructing the Config object.
config - The _Config object containing configuration optio... |
def list_user_participants(self, id, registration_status=None):
"""
List user participants.
List users that are (or may be) participating in this appointment group.
Refer to the Users API for the response fields. Returns no results for
appointment groups with the "Group" p... | List user participants.
List users that are (or may be) participating in this appointment group.
Refer to the Users API for the response fields. Returns no results for
appointment groups with the "Group" participant_type. | Below is the the instruction that describes the task:
### Input:
List user participants.
List users that are (or may be) participating in this appointment group.
Refer to the Users API for the response fields. Returns no results for
appointment groups with the "Group" participant_type.
... |
def compose(self, other, qargs=None, front=False):
"""Return the composition channel self∘other.
Args:
other (QuantumChannel): a quantum channel.
qargs (list): a list of subsystem positions to compose other on.
front (bool): If False compose in standard order other(s... | Return the composition channel self∘other.
Args:
other (QuantumChannel): a quantum channel.
qargs (list): a list of subsystem positions to compose other on.
front (bool): If False compose in standard order other(self(input))
otherwise compose in rev... | Below is the the instruction that describes the task:
### Input:
Return the composition channel self∘other.
Args:
other (QuantumChannel): a quantum channel.
qargs (list): a list of subsystem positions to compose other on.
front (bool): If False compose in standard order ... |
def list_types(pdb_list, sleep_time=.1):
'''Given a list of PDB IDs, look up their associated structure type
Parameters
----------
pdb_list : list of str
List of PDB IDs
sleep_time : float
Time (in seconds) to wait between requests. If this number is too small
the... | Given a list of PDB IDs, look up their associated structure type
Parameters
----------
pdb_list : list of str
List of PDB IDs
sleep_time : float
Time (in seconds) to wait between requests. If this number is too small
the API will stop working, but it appears to vary a... | Below is the the instruction that describes the task:
### Input:
Given a list of PDB IDs, look up their associated structure type
Parameters
----------
pdb_list : list of str
List of PDB IDs
sleep_time : float
Time (in seconds) to wait between requests. If this number is ... |
def load_plugins(builtin=True, others=True):
"""Load plugins, either builtin, others, or both.
"""
for entry_point in pkg_resources.iter_entry_points('yolk.plugins'):
#LOG.debug("load plugin %s" % entry_point)
try:
plugin = entry_point.load()
except KeyboardInterrupt:
... | Load plugins, either builtin, others, or both. | Below is the the instruction that describes the task:
### Input:
Load plugins, either builtin, others, or both.
### Response:
def load_plugins(builtin=True, others=True):
"""Load plugins, either builtin, others, or both.
"""
for entry_point in pkg_resources.iter_entry_points('yolk.plugins'):
#L... |
def save_plot(self, filename, img_format="eps", ylim=None,
zero_to_efermi=True, smooth=False):
"""
Save matplotlib plot to a file.
Args:
filename: Filename to write to.
img_format: Image format to use. Defaults to EPS.
ylim: Specifies the y-... | Save matplotlib plot to a file.
Args:
filename: Filename to write to.
img_format: Image format to use. Defaults to EPS.
ylim: Specifies the y-axis limits. | Below is the the instruction that describes the task:
### Input:
Save matplotlib plot to a file.
Args:
filename: Filename to write to.
img_format: Image format to use. Defaults to EPS.
ylim: Specifies the y-axis limits.
### Response:
def save_plot(self, filename, img_fo... |
def execute(self):
""" Executes all main windows by starting the Qt main application
"""
logger.info("Starting Argos event loop...")
exitCode = self.qApplication.exec_()
logger.info("Argos event loop finished with exit code: {}".format(exitCode))
return exitCode | Executes all main windows by starting the Qt main application | Below is the the instruction that describes the task:
### Input:
Executes all main windows by starting the Qt main application
### Response:
def execute(self):
""" Executes all main windows by starting the Qt main application
"""
logger.info("Starting Argos event loop...")
exitCode ... |
def proxy_set(self, value):
"""
A helper to easily call the proxy_setter of the field
"""
setter = getattr(self, self.proxy_setter)
if isinstance(value, (list, tuple, set)):
result = setter(*value)
elif isinstance(value, dict):
result = setter(**va... | A helper to easily call the proxy_setter of the field | Below is the the instruction that describes the task:
### Input:
A helper to easily call the proxy_setter of the field
### Response:
def proxy_set(self, value):
"""
A helper to easily call the proxy_setter of the field
"""
setter = getattr(self, self.proxy_setter)
if isinsta... |
def do_handle_log(self, workunit, level, *msg_elements):
"""Implementation of Reporter callback."""
entry_info = {
'level': self._log_level_str[level],
'messages': self._render_messages(*msg_elements),
}
root_id = str(workunit.root().id)
current_stack = self._root_id_to_workunit_stack[... | Implementation of Reporter callback. | Below is the the instruction that describes the task:
### Input:
Implementation of Reporter callback.
### Response:
def do_handle_log(self, workunit, level, *msg_elements):
"""Implementation of Reporter callback."""
entry_info = {
'level': self._log_level_str[level],
'messages': self._render_m... |
def _list_clouds(self):
"""
Request a list of all added clouds.
Populates self._clouds dict with mist.client.model.Cloud instances
"""
req = self.request(self.uri + '/clouds')
clouds = req.get().json()
if clouds:
for cloud in clouds:
s... | Request a list of all added clouds.
Populates self._clouds dict with mist.client.model.Cloud instances | Below is the the instruction that describes the task:
### Input:
Request a list of all added clouds.
Populates self._clouds dict with mist.client.model.Cloud instances
### Response:
def _list_clouds(self):
"""
Request a list of all added clouds.
Populates self._clouds dict with mi... |
def NoExclusions(self):
"""Determine that there are no exclusion criterion in play
:return: True if there is no real boundary specification of any kind.
Simple method allowing parsers to short circuit the determination of
missingness, which can be moderately compute intensive.
... | Determine that there are no exclusion criterion in play
:return: True if there is no real boundary specification of any kind.
Simple method allowing parsers to short circuit the determination of
missingness, which can be moderately compute intensive. | Below is the the instruction that describes the task:
### Input:
Determine that there are no exclusion criterion in play
:return: True if there is no real boundary specification of any kind.
Simple method allowing parsers to short circuit the determination of
missingness, which can be mode... |
def overlay_type_data(graph: BELGraph,
data: Mapping[str, float],
func: str,
namespace: str,
label: Optional[str] = None,
overwrite: bool = False,
impute: Optional[float] = None,
... | Overlay tabular data on the network for data that comes from an data set with identifiers that lack
namespaces.
For example, if you want to overlay differential gene expression data from a table, that table
probably has HGNC identifiers, but no specific annotations that they are in the HGNC namespace or
... | Below is the the instruction that describes the task:
### Input:
Overlay tabular data on the network for data that comes from an data set with identifiers that lack
namespaces.
For example, if you want to overlay differential gene expression data from a table, that table
probably has HGNC identifiers, ... |
def run_script_on_server(
script_name,
server_name,
inputs=None,
timeout_s=10,
output=sys.stdout
):
"""
Runs a RightScript and polls for status.
Sample usage::
from rightscale import run_script_on_server
run_script_on_server(
... | Runs a RightScript and polls for status.
Sample usage::
from rightscale import run_script_on_server
run_script_on_server(
'my cool bob lol script',
'some server',
inputs={'BOB': 'blah blah', 'LOL': 'fubar'},
)
Sample output::
... | Below is the the instruction that describes the task:
### Input:
Runs a RightScript and polls for status.
Sample usage::
from rightscale import run_script_on_server
run_script_on_server(
'my cool bob lol script',
'some server',
inputs={'BOB': 'bl... |
async def set_endpoint_for_did(wallet_handle: int,
did: str,
address: str,
transport_key: str) -> None:
"""
Set/replaces endpoint information for the given DID.
:param wallet_handle: Wallet handle (created by open_... | Set/replaces endpoint information for the given DID.
:param wallet_handle: Wallet handle (created by open_wallet).
:param did: The DID to resolve endpoint.
:param address: The DIDs endpoint address.
:param transport_key: The DIDs transport key (ver key, key id).
:return: Error code | Below is the the instruction that describes the task:
### Input:
Set/replaces endpoint information for the given DID.
:param wallet_handle: Wallet handle (created by open_wallet).
:param did: The DID to resolve endpoint.
:param address: The DIDs endpoint address.
:param transport_key: The DIDs tran... |
def EvalGeneric(self, hashers=None):
"""Causes the entire file to be hashed by the given hash functions.
This sets up a 'finger' for fingerprinting, where the entire file
is passed through a pre-defined (or user defined) set of hash functions.
Args:
hashers: An iterable of hash classes (e.g. out... | Causes the entire file to be hashed by the given hash functions.
This sets up a 'finger' for fingerprinting, where the entire file
is passed through a pre-defined (or user defined) set of hash functions.
Args:
hashers: An iterable of hash classes (e.g. out of hashlib) which will
be in... | Below is the the instruction that describes the task:
### Input:
Causes the entire file to be hashed by the given hash functions.
This sets up a 'finger' for fingerprinting, where the entire file
is passed through a pre-defined (or user defined) set of hash functions.
Args:
hashers: An iterable ... |
def create_signature(public_key, private_key, data, scheme='ecdsa-sha2-nistp256'):
"""
<Purpose>
Return a (signature, scheme) tuple.
>>> requested_scheme = 'ecdsa-sha2-nistp256'
>>> public, private = generate_public_and_private(requested_scheme)
>>> data = b'The quick brown fox jumps over the lazy ... | <Purpose>
Return a (signature, scheme) tuple.
>>> requested_scheme = 'ecdsa-sha2-nistp256'
>>> public, private = generate_public_and_private(requested_scheme)
>>> data = b'The quick brown fox jumps over the lazy dog'
>>> signature, scheme = create_signature(public, private, data, requested_scheme)
... | Below is the the instruction that describes the task:
### Input:
<Purpose>
Return a (signature, scheme) tuple.
>>> requested_scheme = 'ecdsa-sha2-nistp256'
>>> public, private = generate_public_and_private(requested_scheme)
>>> data = b'The quick brown fox jumps over the lazy dog'
>>> signature... |
def _supports(self, data):
""" Simply checks if data is supported """
if isinstance(data, Quantity):
return True
elif super(Brian2Result, self)._supports(data):
return True
return False | Simply checks if data is supported | Below is the the instruction that describes the task:
### Input:
Simply checks if data is supported
### Response:
def _supports(self, data):
""" Simply checks if data is supported """
if isinstance(data, Quantity):
return True
elif super(Brian2Result, self)._supports(data):
... |
def encap(self, pkt):
"""encapsulate a frame using this Secure Association"""
if pkt.name != Ether().name:
raise TypeError('cannot encapsulate packet in MACsec, must be Ethernet') # noqa: E501
hdr = copy.deepcopy(pkt)
payload = hdr.payload
del hdr.payload
tag... | encapsulate a frame using this Secure Association | Below is the the instruction that describes the task:
### Input:
encapsulate a frame using this Secure Association
### Response:
def encap(self, pkt):
"""encapsulate a frame using this Secure Association"""
if pkt.name != Ether().name:
raise TypeError('cannot encapsulate packet in MACse... |
def import_namespaced_class(path):
"""Pass in a string in the format of foo.Bar, foo.bar.Baz, foo.bar.baz.Qux
and it will return a handle to the class
:param str path: The object path
:rtype: class
"""
parts = path.split('.')
return getattr(importlib.import_module('.'.join(parts[0:-1])), p... | Pass in a string in the format of foo.Bar, foo.bar.Baz, foo.bar.baz.Qux
and it will return a handle to the class
:param str path: The object path
:rtype: class | Below is the the instruction that describes the task:
### Input:
Pass in a string in the format of foo.Bar, foo.bar.Baz, foo.bar.baz.Qux
and it will return a handle to the class
:param str path: The object path
:rtype: class
### Response:
def import_namespaced_class(path):
"""Pass in a string in t... |
def _len_frame(obj):
'''Length of a frame object.
'''
c = getattr(obj, 'f_code', None)
if c:
n = _len_code(c)
else:
n = 0
return n | Length of a frame object. | Below is the the instruction that describes the task:
### Input:
Length of a frame object.
### Response:
def _len_frame(obj):
'''Length of a frame object.
'''
c = getattr(obj, 'f_code', None)
if c:
n = _len_code(c)
else:
n = 0
return n |
def _prepare_experiment(self):
"""Called by the environment to make some initial configurations before performing the
individual runs.
Checks if all parameters marked for presetting were preset. If not raises a
DefaultReplacementError.
Locks all parameters.
Removal of ... | Called by the environment to make some initial configurations before performing the
individual runs.
Checks if all parameters marked for presetting were preset. If not raises a
DefaultReplacementError.
Locks all parameters.
Removal of potential results of previous runs in case... | Below is the the instruction that describes the task:
### Input:
Called by the environment to make some initial configurations before performing the
individual runs.
Checks if all parameters marked for presetting were preset. If not raises a
DefaultReplacementError.
Locks all param... |
def line_spacing_rule(self):
"""
A member of the :ref:`WdLineSpacing` enumeration indicating how the
value of :attr:`line_spacing` should be interpreted. Assigning any of
the :ref:`WdLineSpacing` members :attr:`SINGLE`, :attr:`DOUBLE`, or
:attr:`ONE_POINT_FIVE` will cause the val... | A member of the :ref:`WdLineSpacing` enumeration indicating how the
value of :attr:`line_spacing` should be interpreted. Assigning any of
the :ref:`WdLineSpacing` members :attr:`SINGLE`, :attr:`DOUBLE`, or
:attr:`ONE_POINT_FIVE` will cause the value of :attr:`line_spacing`
to be updated ... | Below is the the instruction that describes the task:
### Input:
A member of the :ref:`WdLineSpacing` enumeration indicating how the
value of :attr:`line_spacing` should be interpreted. Assigning any of
the :ref:`WdLineSpacing` members :attr:`SINGLE`, :attr:`DOUBLE`, or
:attr:`ONE_POINT_FIVE... |
def color_array_by_hue_mix(value, palette):
"""
Figure out the appropriate color for a binary string value by averaging
the colors corresponding the indices of each one that it contains. Makes
for visualizations that intuitively show patch overlap.
"""
if int(value, 2) > 0:
# Convert bi... | Figure out the appropriate color for a binary string value by averaging
the colors corresponding the indices of each one that it contains. Makes
for visualizations that intuitively show patch overlap. | Below is the the instruction that describes the task:
### Input:
Figure out the appropriate color for a binary string value by averaging
the colors corresponding the indices of each one that it contains. Makes
for visualizations that intuitively show patch overlap.
### Response:
def color_array_by_hue_mix(... |
def paginator(self):
"""
The paginator instance associated with the view, or `None`.
"""
if not hasattr(self, '_paginator'):
if self.pagination_class is None:
self._paginator = None
else:
self._paginator = self.pagination_class()
... | The paginator instance associated with the view, or `None`. | Below is the the instruction that describes the task:
### Input:
The paginator instance associated with the view, or `None`.
### Response:
def paginator(self):
"""
The paginator instance associated with the view, or `None`.
"""
if not hasattr(self, '_paginator'):
if self... |
def wl_uris(self):
"""\
Returns cable IRIs to WikiLeaks (mirrors).
"""
def year_month(d):
date, time = d.split()
return date.split('-')[:2]
if not self.created:
raise ValueError('The "created" property must be provided')
year, month = y... | \
Returns cable IRIs to WikiLeaks (mirrors). | Below is the the instruction that describes the task:
### Input:
\
Returns cable IRIs to WikiLeaks (mirrors).
### Response:
def wl_uris(self):
"""\
Returns cable IRIs to WikiLeaks (mirrors).
"""
def year_month(d):
date, time = d.split()
return date.sp... |
def num_rows(self):
"""
Returns the number of rows.
Returns
-------
out : int
Number of rows in the SFrame.
"""
if self._is_vertex_frame():
return self.__graph__.summary()['num_vertices']
elif self._is_edge_frame():
ret... | Returns the number of rows.
Returns
-------
out : int
Number of rows in the SFrame. | Below is the the instruction that describes the task:
### Input:
Returns the number of rows.
Returns
-------
out : int
Number of rows in the SFrame.
### Response:
def num_rows(self):
"""
Returns the number of rows.
Returns
-------
out : ... |
def read_as_text(self):
'''Read and return the dataset contents as text.'''
return self.workspace._rest.read_intermediate_dataset_contents_text(
self.workspace.workspace_id,
self.experiment.experiment_id,
self.node_id,
self.port_name
) | Read and return the dataset contents as text. | Below is the the instruction that describes the task:
### Input:
Read and return the dataset contents as text.
### Response:
def read_as_text(self):
'''Read and return the dataset contents as text.'''
return self.workspace._rest.read_intermediate_dataset_contents_text(
self.workspace.wo... |
async def send(self, msg: Message):
"""
Sends a message.
Args:
msg (spade.message.Message): the message to be sent.
"""
if not msg.sender:
msg.sender = str(self.agent.jid)
logger.debug(f"Adding agent's jid as sender to message: {msg}")
... | Sends a message.
Args:
msg (spade.message.Message): the message to be sent. | Below is the the instruction that describes the task:
### Input:
Sends a message.
Args:
msg (spade.message.Message): the message to be sent.
### Response:
async def send(self, msg: Message):
"""
Sends a message.
Args:
msg (spade.message.Message): the messag... |
def create(self, stylename, **kwargs):
""" Creates a new style which inherits from the default style,
or any other style which name is supplied to the optional template parameter.
"""
if stylename == "default":
self[stylename] = style(stylename, self._ctx, **kwargs)
... | Creates a new style which inherits from the default style,
or any other style which name is supplied to the optional template parameter. | Below is the the instruction that describes the task:
### Input:
Creates a new style which inherits from the default style,
or any other style which name is supplied to the optional template parameter.
### Response:
def create(self, stylename, **kwargs):
""" Creates a new style which inherits from ... |
def emit(self, record):
"""
Mostly copy-paste from :obj:`logging.StreamHandler`.
"""
try:
msg = self.format(record)
if record.levelno < self.splitLevel:
stream = self.outStream
else:
stream = self.errStream
f... | Mostly copy-paste from :obj:`logging.StreamHandler`. | Below is the the instruction that describes the task:
### Input:
Mostly copy-paste from :obj:`logging.StreamHandler`.
### Response:
def emit(self, record):
"""
Mostly copy-paste from :obj:`logging.StreamHandler`.
"""
try:
msg = self.format(record)
if record.l... |
def alias_objective(self, objective_id, alias_id):
"""Adds an ``Id`` to an ``Objective`` for the purpose of creating compatibility.
The primary ``Id`` of the ``Objective`` is determined by the
provider. The new ``Id`` performs as an alias to the primary
``Id``. If the alias is a pointer... | Adds an ``Id`` to an ``Objective`` for the purpose of creating compatibility.
The primary ``Id`` of the ``Objective`` is determined by the
provider. The new ``Id`` performs as an alias to the primary
``Id``. If the alias is a pointer to another objective, it is
reassigned to the given o... | Below is the the instruction that describes the task:
### Input:
Adds an ``Id`` to an ``Objective`` for the purpose of creating compatibility.
The primary ``Id`` of the ``Objective`` is determined by the
provider. The new ``Id`` performs as an alias to the primary
``Id``. If the alias is a ... |
def ensure_rng(random_state=None):
"""
Creates a random number generator based on an optional seed. This can be
an integer or another random state for a seeded rng, or None for an
unseeded rng.
"""
if random_state is None:
random_state = np.random.RandomState()
elif isinstance(rando... | Creates a random number generator based on an optional seed. This can be
an integer or another random state for a seeded rng, or None for an
unseeded rng. | Below is the the instruction that describes the task:
### Input:
Creates a random number generator based on an optional seed. This can be
an integer or another random state for a seeded rng, or None for an
unseeded rng.
### Response:
def ensure_rng(random_state=None):
"""
Creates a random number g... |
def print_table(document, *columns):
""" Print json document as table """
headers = []
for _, header in columns:
headers.append(header)
table = []
for element in document:
row = []
for item, _ in columns:
if item in element:
row.append(element[item... | Print json document as table | Below is the the instruction that describes the task:
### Input:
Print json document as table
### Response:
def print_table(document, *columns):
""" Print json document as table """
headers = []
for _, header in columns:
headers.append(header)
table = []
for element in document:
... |
def remove_team_repo(repo_name, team_name, profile="github"):
'''
Removes a repository from a team with team_name.
repo_name
The name of the repository to remove.
team_name
The name of the team of which to remove the repository.
profile
The name of the profile configuratio... | Removes a repository from a team with team_name.
repo_name
The name of the repository to remove.
team_name
The name of the team of which to remove the repository.
profile
The name of the profile configuration to use. Defaults to ``github``.
CLI Example:
.. code-block:: b... | Below is the the instruction that describes the task:
### Input:
Removes a repository from a team with team_name.
repo_name
The name of the repository to remove.
team_name
The name of the team of which to remove the repository.
profile
The name of the profile configuration to ... |
def _trim_tree(state):
"""Trim empty leaf nodes from the tree.
- To simplify the tree conversion, empty nodes are added before it is known if they
will contain items that connect back to the authenticated subject. If there are
no connections, the nodes remain empty, which causes them to be removed ... | Trim empty leaf nodes from the tree.
- To simplify the tree conversion, empty nodes are added before it is known if they
will contain items that connect back to the authenticated subject. If there are
no connections, the nodes remain empty, which causes them to be removed here.
- Removing a leaf n... | Below is the the instruction that describes the task:
### Input:
Trim empty leaf nodes from the tree.
- To simplify the tree conversion, empty nodes are added before it is known if they
will contain items that connect back to the authenticated subject. If there are
no connections, the nodes remain ... |
def start(self):
"""
Initiate the session by starting to execute the command with the peer.
:return: The :attr:`~.xso.Command.first_payload` of the response
This sends an empty command IQ request with the
:attr:`~.ActionType.EXECUTE` action.
The :attr:`status`, :attr:`... | Initiate the session by starting to execute the command with the peer.
:return: The :attr:`~.xso.Command.first_payload` of the response
This sends an empty command IQ request with the
:attr:`~.ActionType.EXECUTE` action.
The :attr:`status`, :attr:`response` and related attributes get ... | Below is the the instruction that describes the task:
### Input:
Initiate the session by starting to execute the command with the peer.
:return: The :attr:`~.xso.Command.first_payload` of the response
This sends an empty command IQ request with the
:attr:`~.ActionType.EXECUTE` action.
... |
def absolute_git_root_dir(fpath=""):
"""Absolute path to the git root directory containing a given file or
directory.
"""
if len(fpath) == 0:
dirname_str = os.getcwd()
else:
dirname_str = os.path.dirname(fpath)
dirname_str = os.path.abspath(dirname_str)
dirnames = dirname_str... | Absolute path to the git root directory containing a given file or
directory. | Below is the the instruction that describes the task:
### Input:
Absolute path to the git root directory containing a given file or
directory.
### Response:
def absolute_git_root_dir(fpath=""):
"""Absolute path to the git root directory containing a given file or
directory.
"""
if len(fpath) ==... |
def adjust(self, date, mode):
"""
Adjust the date to the closest work date.
Args:
date (date, datetime or str): Date to be adjusted.
mode (integer): FOLLOWING, PREVIOUS or MODIFIEDFOLLOWING.
Note:
If date is already a business date than it i... | Adjust the date to the closest work date.
Args:
date (date, datetime or str): Date to be adjusted.
mode (integer): FOLLOWING, PREVIOUS or MODIFIEDFOLLOWING.
Note:
If date is already a business date than it is returned unchanged.
How to use the ad... | Below is the the instruction that describes the task:
### Input:
Adjust the date to the closest work date.
Args:
date (date, datetime or str): Date to be adjusted.
mode (integer): FOLLOWING, PREVIOUS or MODIFIEDFOLLOWING.
Note:
If date is already a busine... |
def getWorkitem(self, workitem_id, returned_properties=None):
"""Get :class:`rtcclient.workitem.Workitem` object by its id/number
:param workitem_id: the workitem id/number
(integer or equivalent string)
:param returned_properties: the returned properties that you want.
... | Get :class:`rtcclient.workitem.Workitem` object by its id/number
:param workitem_id: the workitem id/number
(integer or equivalent string)
:param returned_properties: the returned properties that you want.
Refer to :class:`rtcclient.client.RTCClient` for more explanations
... | Below is the the instruction that describes the task:
### Input:
Get :class:`rtcclient.workitem.Workitem` object by its id/number
:param workitem_id: the workitem id/number
(integer or equivalent string)
:param returned_properties: the returned properties that you want.
Refe... |
def summarize(self):
"""Some summary information."""
# force shrinkage to be calculated
self.covariance_
return """time-structure based Independent Components Analysis (tICA)
-----------------------------------------------------------
n_components : {n_components}
shrinkage ... | Some summary information. | Below is the the instruction that describes the task:
### Input:
Some summary information.
### Response:
def summarize(self):
"""Some summary information."""
# force shrinkage to be calculated
self.covariance_
return """time-structure based Independent Components Analysis (tICA)
--... |
def init(self, app):
"""
Initialise from flask app
This gets configuration values from a flask application.
:param app: flask.Flask
:return: boiler.user.user_servce.UserService
"""
cfg = app.config
self.welcome_message = cfg.get('USER_SEND_WELCOME_MESSAGE'... | Initialise from flask app
This gets configuration values from a flask application.
:param app: flask.Flask
:return: boiler.user.user_servce.UserService | Below is the the instruction that describes the task:
### Input:
Initialise from flask app
This gets configuration values from a flask application.
:param app: flask.Flask
:return: boiler.user.user_servce.UserService
### Response:
def init(self, app):
"""
Initialise from fla... |
def get_renderer_from_definition(config):
"""Returns a renderer object based on the configuration (as a dictionary)"""
options = config.get('options', {})
try:
renderer_type = config['type']
renderer_colors = [(float(x[0]), hex_to_color(x[1])) for x in config['colors']]
fill_value ... | Returns a renderer object based on the configuration (as a dictionary) | Below is the the instruction that describes the task:
### Input:
Returns a renderer object based on the configuration (as a dictionary)
### Response:
def get_renderer_from_definition(config):
"""Returns a renderer object based on the configuration (as a dictionary)"""
options = config.get('options', {})
... |
def _process_cities_file(self, file, city_country_mapping):
""" Iterate over cities info and extract useful data """
data = {'all_regions': list(), 'regions': list(), 'cities': list(), 'city_region_mapping': dict()}
allowed_countries = settings.IPGEOBASE_ALLOWED_COUNTRIES
for geo_info in... | Iterate over cities info and extract useful data | Below is the the instruction that describes the task:
### Input:
Iterate over cities info and extract useful data
### Response:
def _process_cities_file(self, file, city_country_mapping):
""" Iterate over cities info and extract useful data """
data = {'all_regions': list(), 'regions': list(), 'cit... |
def remove_model(self, propname=None, mode=['model', 'data']):
r"""
Removes model and data from object.
Parameters
----------
propname : string or list of strings
The property or list of properties to remove
mode : list of strings
Controls what i... | r"""
Removes model and data from object.
Parameters
----------
propname : string or list of strings
The property or list of properties to remove
mode : list of strings
Controls what is removed. Options are:
*'model'* : Removes the model but... | Below is the the instruction that describes the task:
### Input:
r"""
Removes model and data from object.
Parameters
----------
propname : string or list of strings
The property or list of properties to remove
mode : list of strings
Controls what is ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.