code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def as_dfile(self):
"""
Return the dataset representation in BMDS .(d) file.
"""
rows = ["Dose Response"]
for dose, response in zip(self.individual_doses, self.responses):
dose_idx = self.doses.index(dose)
if dose_idx >= self.num_dose_groups:
... | Return the dataset representation in BMDS .(d) file. | Below is the the instruction that describes the task:
### Input:
Return the dataset representation in BMDS .(d) file.
### Response:
def as_dfile(self):
"""
Return the dataset representation in BMDS .(d) file.
"""
rows = ["Dose Response"]
for dose, response in zip(self.indivi... |
def _process_extensions(exts):
"""
Generate the `Extensions String` from an iterable of data forms.
:param exts: The data forms to generate the extensions string from.
:type exts: :class:`~collections.abc.Iterable` of
:class:`~.forms.xso.Data`
:return: The `Extensions String`
:rtype: :c... | Generate the `Extensions String` from an iterable of data forms.
:param exts: The data forms to generate the extensions string from.
:type exts: :class:`~collections.abc.Iterable` of
:class:`~.forms.xso.Data`
:return: The `Extensions String`
:rtype: :class:`bytes`
Generate the `Extensions ... | Below is the the instruction that describes the task:
### Input:
Generate the `Extensions String` from an iterable of data forms.
:param exts: The data forms to generate the extensions string from.
:type exts: :class:`~collections.abc.Iterable` of
:class:`~.forms.xso.Data`
:return: The `Extensi... |
def image(self):
"""
Returns a PngImageFile instance of the chart
You must have PIL installed for this to work
"""
try:
try:
import Image
except ImportError:
from PIL import Image
except ImportError:
rai... | Returns a PngImageFile instance of the chart
You must have PIL installed for this to work | Below is the the instruction that describes the task:
### Input:
Returns a PngImageFile instance of the chart
You must have PIL installed for this to work
### Response:
def image(self):
"""
Returns a PngImageFile instance of the chart
You must have PIL installed for this to work
... |
def operator(self, text):
"""Push an operator onto the token queue."""
cls = self.OPERATORS[text]
self.push_token(cls(text, self.lineno, self.offset)) | Push an operator onto the token queue. | Below is the the instruction that describes the task:
### Input:
Push an operator onto the token queue.
### Response:
def operator(self, text):
"""Push an operator onto the token queue."""
cls = self.OPERATORS[text]
self.push_token(cls(text, self.lineno, self.offset)) |
def exists_locally(cls, path):
"""Returns whether the resource exists locally, at `resource.path`."""
# If INFO file doesn't exist, consider resource does NOT exist, as it would
# prevent guessing the `extract_method`.
return (tf.io.gfile.exists(path) and
tf.io.gfile.exists(_get_info_path(pa... | Returns whether the resource exists locally, at `resource.path`. | Below is the the instruction that describes the task:
### Input:
Returns whether the resource exists locally, at `resource.path`.
### Response:
def exists_locally(cls, path):
"""Returns whether the resource exists locally, at `resource.path`."""
# If INFO file doesn't exist, consider resource does NOT exis... |
def validate_scenario(blocks, scenario_directory):
"""Function to validate input layer stored in scenario file.
Check whether the files that are used in scenario file need to be
updated or not.
:param blocks: dictionary from read_scenarios
:type blocks: dictionary
:param scenario_directory: d... | Function to validate input layer stored in scenario file.
Check whether the files that are used in scenario file need to be
updated or not.
:param blocks: dictionary from read_scenarios
:type blocks: dictionary
:param scenario_directory: directory where scenario text file is saved
:type scena... | Below is the the instruction that describes the task:
### Input:
Function to validate input layer stored in scenario file.
Check whether the files that are used in scenario file need to be
updated or not.
:param blocks: dictionary from read_scenarios
:type blocks: dictionary
:param scenario_d... |
def _detect(self):
""" Detect the constant function changing the state
Recursively visit the calls
Returns:
list: {'vuln', 'filename,'contract','func','#varsWritten'}
"""
results = []
for c in self.contracts:
for f in c.functions:
... | Detect the constant function changing the state
Recursively visit the calls
Returns:
list: {'vuln', 'filename,'contract','func','#varsWritten'} | Below is the the instruction that describes the task:
### Input:
Detect the constant function changing the state
Recursively visit the calls
Returns:
list: {'vuln', 'filename,'contract','func','#varsWritten'}
### Response:
def _detect(self):
""" Detect the constant function cha... |
def check_params_types(self, method):
'''Types in argument annotations must be instances, not classes.'''
mn = method.__name__
annos = dict(method.__annotations__)
errors = []
# Take a look at the syntax
msg_tuple = 'Parameter {} in method {} is not annotated with a tuple... | Types in argument annotations must be instances, not classes. | Below is the the instruction that describes the task:
### Input:
Types in argument annotations must be instances, not classes.
### Response:
def check_params_types(self, method):
'''Types in argument annotations must be instances, not classes.'''
mn = method.__name__
annos = dict(method.__a... |
def calc_mass(nu_max, delta_nu, teff):
""" asteroseismic scaling relations """
NU_MAX = 3140.0 # microHz
DELTA_NU = 135.03 # microHz
TEFF = 5777.0
return (nu_max/NU_MAX)**3 * (delta_nu/DELTA_NU)**(-4) * (teff/TEFF)**1.5 | asteroseismic scaling relations | Below is the the instruction that describes the task:
### Input:
asteroseismic scaling relations
### Response:
def calc_mass(nu_max, delta_nu, teff):
""" asteroseismic scaling relations """
NU_MAX = 3140.0 # microHz
DELTA_NU = 135.03 # microHz
TEFF = 5777.0
return (nu_max/NU_MAX)**3 * (delta_nu... |
def gen_opt_str(ser_rec: pd.Series)->str:
'''generate rst option string
Parameters
----------
ser_rec : pd.Series
record for specifications
Returns
-------
str
rst string
'''
name = ser_rec.name
indent = r' '
str_opt = f'.. option:: {name}'+'\n\n'
fo... | generate rst option string
Parameters
----------
ser_rec : pd.Series
record for specifications
Returns
-------
str
rst string | Below is the the instruction that describes the task:
### Input:
generate rst option string
Parameters
----------
ser_rec : pd.Series
record for specifications
Returns
-------
str
rst string
### Response:
def gen_opt_str(ser_rec: pd.Series)->str:
'''generate rst option... |
def map_column(self, value):
"""
Applied to each column of every row returned by `rows`.
Default behaviour is to escape special characters and identify any self.null_values.
"""
if value in self.null_values:
return r'\\N'
else:
return default_esca... | Applied to each column of every row returned by `rows`.
Default behaviour is to escape special characters and identify any self.null_values. | Below is the the instruction that describes the task:
### Input:
Applied to each column of every row returned by `rows`.
Default behaviour is to escape special characters and identify any self.null_values.
### Response:
def map_column(self, value):
"""
Applied to each column of every row r... |
def imshow(data, title=None, vmin=0, vmax=None, cmap=None,
bitspersample=None, photometric='rgb', interpolation='nearest',
dpi=96, figure=None, subplot=111, maxdim=4096, **kwargs):
"""Plot n-dimensional images using matplotlib.pyplot.
Return figure, subplot and plot axis.
Requires pyp... | Plot n-dimensional images using matplotlib.pyplot.
Return figure, subplot and plot axis.
Requires pyplot already imported ``from matplotlib import pyplot``.
Parameters
----------
bitspersample : int or None
Number of bits per channel in integer RGB images.
photometric : {'miniswhite', ... | Below is the the instruction that describes the task:
### Input:
Plot n-dimensional images using matplotlib.pyplot.
Return figure, subplot and plot axis.
Requires pyplot already imported ``from matplotlib import pyplot``.
Parameters
----------
bitspersample : int or None
Number of bits... |
def merge_programs(prog_list):
"""
Merges a list of pyQuil programs into a single one by appending them in sequence.
If multiple programs in the list contain the same gate and/or noisy gate definition
with identical name, this definition will only be applied once. If different definitions
with the s... | Merges a list of pyQuil programs into a single one by appending them in sequence.
If multiple programs in the list contain the same gate and/or noisy gate definition
with identical name, this definition will only be applied once. If different definitions
with the same name appear multiple times in the progr... | Below is the the instruction that describes the task:
### Input:
Merges a list of pyQuil programs into a single one by appending them in sequence.
If multiple programs in the list contain the same gate and/or noisy gate definition
with identical name, this definition will only be applied once. If different ... |
def _bracket_complete_sig(self, symbol, fullsymbol):
"""Returns the call signature and docstring for the executable
immediately preceding a bracket '(' that was typed."""
if symbol != fullsymbol:
#We have a sym%sym%... chain and the completion just needs to
#be the signat... | Returns the call signature and docstring for the executable
immediately preceding a bracket '(' that was typed. | Below is the the instruction that describes the task:
### Input:
Returns the call signature and docstring for the executable
immediately preceding a bracket '(' that was typed.
### Response:
def _bracket_complete_sig(self, symbol, fullsymbol):
"""Returns the call signature and docstring for the exe... |
def event_return(events):
'''
Return event to one of potentially many clustered cassandra nodes
Requires that configuration be enabled via 'event_return'
option in master config.
Cassandra does not support an auto-increment feature due to the
highly inefficient nature of creating a monotonical... | Return event to one of potentially many clustered cassandra nodes
Requires that configuration be enabled via 'event_return'
option in master config.
Cassandra does not support an auto-increment feature due to the
highly inefficient nature of creating a monotonically increasing
number across all no... | Below is the the instruction that describes the task:
### Input:
Return event to one of potentially many clustered cassandra nodes
Requires that configuration be enabled via 'event_return'
option in master config.
Cassandra does not support an auto-increment feature due to the
highly inefficient n... |
def corner(xs, bins=20, range=None, weights=None, color="k",
smooth=None, smooth1d=None,
labels=None, label_kwargs=None,
show_titles=False, title_fmt=".2f", title_kwargs=None,
truths=None, truth_color="#4682b4",
scale_hist=False, quantiles=None, verbose=False, fig=... | Make a *sick* corner plot showing the projections of a data set in a
multi-dimensional space. kwargs are passed to hist2d() or used for
`matplotlib` styling.
Parameters
----------
xs : array_like (nsamples, ndim)
The samples. This should be a 1- or 2-dimensional array. For a 1-D
arr... | Below is the the instruction that describes the task:
### Input:
Make a *sick* corner plot showing the projections of a data set in a
multi-dimensional space. kwargs are passed to hist2d() or used for
`matplotlib` styling.
Parameters
----------
xs : array_like (nsamples, ndim)
The sampl... |
def _add_meta(xs, sample=None, config=None):
"""Add top level information about the sample or flowcell to output.
Sorts outputs into sample names (sample input) and project (config input).
"""
out = []
for x in xs:
if not isinstance(x["path"], six.string_types) or not os.path.exists(x["path... | Add top level information about the sample or flowcell to output.
Sorts outputs into sample names (sample input) and project (config input). | Below is the the instruction that describes the task:
### Input:
Add top level information about the sample or flowcell to output.
Sorts outputs into sample names (sample input) and project (config input).
### Response:
def _add_meta(xs, sample=None, config=None):
"""Add top level information about the sa... |
def _rangeGen(data, std=1):
"""
Return reasonable min/max values to use given the data.
"""
dataStd = np.std(data)
if dataStd == 0:
dataStd = 1
minval = np.min(data) - std * dataStd
maxval = np.max(data) + std * dataStd
return minval, maxval | Return reasonable min/max values to use given the data. | Below is the the instruction that describes the task:
### Input:
Return reasonable min/max values to use given the data.
### Response:
def _rangeGen(data, std=1):
"""
Return reasonable min/max values to use given the data.
"""
dataStd = np.std(data)
if dataStd == 0:
dataStd = 1
minval = np.min(data... |
def set_Name(self, Name, SaveName=None,
Include=defInclude,
ForceUpdate=False):
""" Set the Name of the instance, automatically updating the SaveName
The name should be a str without spaces or underscores (removed)
When the name is changed, if SaveName (i.e. th... | Set the Name of the instance, automatically updating the SaveName
The name should be a str without spaces or underscores (removed)
When the name is changed, if SaveName (i.e. the name used for saving)
was not user-defined, it is automatically updated
Parameters
----------
... | Below is the the instruction that describes the task:
### Input:
Set the Name of the instance, automatically updating the SaveName
The name should be a str without spaces or underscores (removed)
When the name is changed, if SaveName (i.e. the name used for saving)
was not user-defined, it ... |
def list_datacenters(kwargs=None, call=None):
'''
List all the data centers for this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f list_datacenters my-vmware-config
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_datacenters fun... | List all the data centers for this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f list_datacenters my-vmware-config | Below is the the instruction that describes the task:
### Input:
List all the data centers for this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f list_datacenters my-vmware-config
### Response:
def list_datacenters(kwargs=None, call=None):
'''
List all the data cente... |
def readVersion(self):
""" Read the document version.
::
<designspace format="3">
"""
ds = self.root.findall("[@format]")[0]
raw_format = ds.attrib['format']
try:
self.documentFormatVersion = int(raw_format)
except ValueError:
#... | Read the document version.
::
<designspace format="3"> | Below is the the instruction that describes the task:
### Input:
Read the document version.
::
<designspace format="3">
### Response:
def readVersion(self):
""" Read the document version.
::
<designspace format="3">
"""
ds = self.root.findall("[@forma... |
def send_contributor_email(self, contributor):
"""Send an EmailMessage object for a given contributor."""
ContributorReport(
contributor,
month=self.month,
year=self.year,
deadline=self._deadline,
start=self._start,
end=self._end
... | Send an EmailMessage object for a given contributor. | Below is the the instruction that describes the task:
### Input:
Send an EmailMessage object for a given contributor.
### Response:
def send_contributor_email(self, contributor):
"""Send an EmailMessage object for a given contributor."""
ContributorReport(
contributor,
month... |
def make_json_error(error):
"""
Handle errors by logging and
"""
message = extract_error_message(error)
status_code = extract_status_code(error)
context = extract_context(error)
retryable = extract_retryable(error)
headers = extract_headers(error)
# Flask will not log user exception... | Handle errors by logging and | Below is the the instruction that describes the task:
### Input:
Handle errors by logging and
### Response:
def make_json_error(error):
"""
Handle errors by logging and
"""
message = extract_error_message(error)
status_code = extract_status_code(error)
context = extract_context(error)
r... |
def apply_async(self, args=None, kwargs=None, **options):
"""
Checks whether task must be skipped and decreases the counter in that case.
"""
key = self._get_cache_key(args, kwargs)
counter, penalty = cache.get(key, (0, 0))
if not counter:
return super(Penaliz... | Checks whether task must be skipped and decreases the counter in that case. | Below is the the instruction that describes the task:
### Input:
Checks whether task must be skipped and decreases the counter in that case.
### Response:
def apply_async(self, args=None, kwargs=None, **options):
"""
Checks whether task must be skipped and decreases the counter in that case.
... |
def fillPelicanHole(site, username, password, tstat_name, start_time, end_time):
"""Fill a hole in a Pelican thermostat's data stream.
Arguments:
site -- The thermostat's Pelican site name
username -- The Pelican username for the site
password -- The Pelican password for the site
... | Fill a hole in a Pelican thermostat's data stream.
Arguments:
site -- The thermostat's Pelican site name
username -- The Pelican username for the site
password -- The Pelican password for the site
tstat_name -- The name of the thermostat, as identified by Pelican
start_time ... | Below is the the instruction that describes the task:
### Input:
Fill a hole in a Pelican thermostat's data stream.
Arguments:
site -- The thermostat's Pelican site name
username -- The Pelican username for the site
password -- The Pelican password for the site
tstat_name -- The... |
def store_vector(self, hash_name, bucket_key, v, data):
"""
Stores vector and JSON-serializable data in bucket with specified key.
"""
if not hash_name in self.buckets:
self.buckets[hash_name] = {}
if not bucket_key in self.buckets[hash_name]:
self.bucke... | Stores vector and JSON-serializable data in bucket with specified key. | Below is the the instruction that describes the task:
### Input:
Stores vector and JSON-serializable data in bucket with specified key.
### Response:
def store_vector(self, hash_name, bucket_key, v, data):
"""
Stores vector and JSON-serializable data in bucket with specified key.
"""
... |
def _list_available_hosts(self, *args):
''' returns a list of hosts that haven't failed and aren't dark '''
return [ h for h in self.inventory.list_hosts(*args) if (h not in self.stats.failures) and (h not in self.stats.dark)] | returns a list of hosts that haven't failed and aren't dark | Below is the the instruction that describes the task:
### Input:
returns a list of hosts that haven't failed and aren't dark
### Response:
def _list_available_hosts(self, *args):
''' returns a list of hosts that haven't failed and aren't dark '''
return [ h for h in self.inventory.list_hosts(*args... |
def _cursor_position(self, row=0, column=0):
"""
Set the cursor to a specific row and column.
Obnoxiously row/column is 1 based, instead of zero based, so we need
to compensate. I know I've created bugs in here somehow.
Confoundingly, inputs of 0 are still acceptable, and shou... | Set the cursor to a specific row and column.
Obnoxiously row/column is 1 based, instead of zero based, so we need
to compensate. I know I've created bugs in here somehow.
Confoundingly, inputs of 0 are still acceptable, and should move to
the beginning of the row/column as if they wer... | Below is the the instruction that describes the task:
### Input:
Set the cursor to a specific row and column.
Obnoxiously row/column is 1 based, instead of zero based, so we need
to compensate. I know I've created bugs in here somehow.
Confoundingly, inputs of 0 are still acceptable, and ... |
def clean_line(str, delimiter):
"""Split string on given delimiter, remove whitespace from each field."""
return [x.strip() for x in str.strip().split(delimiter) if x != ''] | Split string on given delimiter, remove whitespace from each field. | Below is the the instruction that describes the task:
### Input:
Split string on given delimiter, remove whitespace from each field.
### Response:
def clean_line(str, delimiter):
"""Split string on given delimiter, remove whitespace from each field."""
return [x.strip() for x in str.strip().split(delimite... |
def output_kernels(gandi, flavor, name_list, justify=14):
""" Helper to output kernel flavor versions."""
output_line(gandi, 'flavor', flavor, justify)
for name in name_list:
output_line(gandi, 'version', name, justify) | Helper to output kernel flavor versions. | Below is the the instruction that describes the task:
### Input:
Helper to output kernel flavor versions.
### Response:
def output_kernels(gandi, flavor, name_list, justify=14):
""" Helper to output kernel flavor versions."""
output_line(gandi, 'flavor', flavor, justify)
for name in name_list:
... |
def toDict(self, msg: Dict) -> Dict:
"""
Return a dictionary form of the message
:param msg: the message to be sent
:raises: ValueError if msg cannot be converted to an appropriate format
for transmission
"""
if isinstance(msg, Request):
tmsg = m... | Return a dictionary form of the message
:param msg: the message to be sent
:raises: ValueError if msg cannot be converted to an appropriate format
for transmission | Below is the the instruction that describes the task:
### Input:
Return a dictionary form of the message
:param msg: the message to be sent
:raises: ValueError if msg cannot be converted to an appropriate format
for transmission
### Response:
def toDict(self, msg: Dict) -> Dict:
... |
def sodium_unpad(s, blocksize):
"""
Remove ISO/IEC 7816-4 padding from the input byte array ``s``
:param s: input bytes string
:type s: bytes
:param blocksize:
:type blocksize: int
:return: unpadded string
:rtype: bytes
"""
ensure(isinstance(s, bytes),
raising=exc.Typ... | Remove ISO/IEC 7816-4 padding from the input byte array ``s``
:param s: input bytes string
:type s: bytes
:param blocksize:
:type blocksize: int
:return: unpadded string
:rtype: bytes | Below is the the instruction that describes the task:
### Input:
Remove ISO/IEC 7816-4 padding from the input byte array ``s``
:param s: input bytes string
:type s: bytes
:param blocksize:
:type blocksize: int
:return: unpadded string
:rtype: bytes
### Response:
def sodium_unpad(s, blocksi... |
def get_changesets(self, project=None, max_comment_length=None, skip=None, top=None, orderby=None, search_criteria=None):
"""GetChangesets.
Retrieve Tfvc Changesets
:param str project: Project ID or project name
:param int max_comment_length: Include details about associated work items i... | GetChangesets.
Retrieve Tfvc Changesets
:param str project: Project ID or project name
:param int max_comment_length: Include details about associated work items in the response. Default: null
:param int skip: Number of results to skip. Default: null
:param int top: The maximum n... | Below is the the instruction that describes the task:
### Input:
GetChangesets.
Retrieve Tfvc Changesets
:param str project: Project ID or project name
:param int max_comment_length: Include details about associated work items in the response. Default: null
:param int skip: Number of... |
def highlight_block(context, nodelist, lexer, **kwargs):
"""
Code is nodelist ``rendered`` in ``context``
Returns highlighted code ``div`` tag from ``HtmlFormatter``
Lexer is guessed by ``lexer`` name
arguments are passed into the formatter
Syntax::
{% highlight_block [lexer na... | Code is nodelist ``rendered`` in ``context``
Returns highlighted code ``div`` tag from ``HtmlFormatter``
Lexer is guessed by ``lexer`` name
arguments are passed into the formatter
Syntax::
{% highlight_block [lexer name] [formatter options] %}
... source code ..
... | Below is the the instruction that describes the task:
### Input:
Code is nodelist ``rendered`` in ``context``
Returns highlighted code ``div`` tag from ``HtmlFormatter``
Lexer is guessed by ``lexer`` name
arguments are passed into the formatter
Syntax::
{% highlight_block [lexer na... |
def ssml_w(self, words, role=None, **kwargs):
"""
Create a <W> element
:param words: Words to speak
:param role: Customize the pronunciation of words by specifying the word’s part of speech or alternate meaning
:param kwargs: additional attributes
:returns: <W> element
... | Create a <W> element
:param words: Words to speak
:param role: Customize the pronunciation of words by specifying the word’s part of speech or alternate meaning
:param kwargs: additional attributes
:returns: <W> element | Below is the the instruction that describes the task:
### Input:
Create a <W> element
:param words: Words to speak
:param role: Customize the pronunciation of words by specifying the word’s part of speech or alternate meaning
:param kwargs: additional attributes
:returns: <W> eleme... |
def lmom_fit(self, data=[], lmom_ratios=[]):
"""
Fit the distribution function to the given data or given L-moments.
:param data: Data to use in calculating the distribution parameters
:type data: array_like
:param lmom_ratios: L-moments (ratios) l1, l2, t3, t4, .. to use in cal... | Fit the distribution function to the given data or given L-moments.
:param data: Data to use in calculating the distribution parameters
:type data: array_like
:param lmom_ratios: L-moments (ratios) l1, l2, t3, t4, .. to use in calculating the distribution parameters
:type lmom_ratios: a... | Below is the the instruction that describes the task:
### Input:
Fit the distribution function to the given data or given L-moments.
:param data: Data to use in calculating the distribution parameters
:type data: array_like
:param lmom_ratios: L-moments (ratios) l1, l2, t3, t4, .. to use in... |
def refresh_stats(self):
"""
only need this when generating terrain (sea = 100 - perc_land at start).
This function forces a recount, otherwise just call the variables
"""
self.tot_pix = 0
self.tot_sea = 0
self.tot_land = 0
self.tot_blocked = 0
for... | only need this when generating terrain (sea = 100 - perc_land at start).
This function forces a recount, otherwise just call the variables | Below is the the instruction that describes the task:
### Input:
only need this when generating terrain (sea = 100 - perc_land at start).
This function forces a recount, otherwise just call the variables
### Response:
def refresh_stats(self):
"""
only need this when generating terrain (sea ... |
def get_versions(default=DEFAULT, verbose=False):
"""This variation of get_versions() will be used in versioneer.py ."""
# returns dict with two keys: 'version' and 'full'
assert versionfile_source is not None, "please set versioneer.versionfile_source"
assert tag_prefix is not None, "please set versi... | This variation of get_versions() will be used in versioneer.py . | Below is the the instruction that describes the task:
### Input:
This variation of get_versions() will be used in versioneer.py .
### Response:
def get_versions(default=DEFAULT, verbose=False):
"""This variation of get_versions() will be used in versioneer.py ."""
# returns dict with two keys: 'version' ... |
def _transform(self, node):
"""Call matching transforms for the given node if any and return the
transformed node.
"""
cls = node.__class__
if cls not in self.transforms:
# no transform registered for this class of node
return node
transforms = se... | Call matching transforms for the given node if any and return the
transformed node. | Below is the the instruction that describes the task:
### Input:
Call matching transforms for the given node if any and return the
transformed node.
### Response:
def _transform(self, node):
"""Call matching transforms for the given node if any and return the
transformed node.
"""
... |
def call(self, timeout=None):
"""Run command with arguments. Wait for command to complete.
same as:
1. :meth:`start`
2. :meth:`wait`
3. :meth:`stop`
:rtype: self
"""
self.start().wait(timeout=timeout)
if self.is_alive():
self.stop... | Run command with arguments. Wait for command to complete.
same as:
1. :meth:`start`
2. :meth:`wait`
3. :meth:`stop`
:rtype: self | Below is the the instruction that describes the task:
### Input:
Run command with arguments. Wait for command to complete.
same as:
1. :meth:`start`
2. :meth:`wait`
3. :meth:`stop`
:rtype: self
### Response:
def call(self, timeout=None):
"""Run command with argu... |
def cli_ping(context, prefix):
"""
Performs a ping test.
See :py:mod:`swiftly.cli.ping` for context usage information.
See :py:class:`CLIPing` for more information.
:param context: The :py:class:`swiftly.cli.context.CLIContext` to
use.
:param prefix: The container name prefix to use. ... | Performs a ping test.
See :py:mod:`swiftly.cli.ping` for context usage information.
See :py:class:`CLIPing` for more information.
:param context: The :py:class:`swiftly.cli.context.CLIContext` to
use.
:param prefix: The container name prefix to use. Default:
swiftly-ping | Below is the the instruction that describes the task:
### Input:
Performs a ping test.
See :py:mod:`swiftly.cli.ping` for context usage information.
See :py:class:`CLIPing` for more information.
:param context: The :py:class:`swiftly.cli.context.CLIContext` to
use.
:param prefix: The cont... |
def httpdo(method, url, data=None):
"""
Do HTTP Request
"""
if isinstance(data, dict):
data = json.dumps(data)
if DEBUG:
print "Shell: curl -X {method} -d '{data}' '{url}'".format(method=method, data=data or '', url=url)
fn = dict(GET=requests.get, POST=requests.post, D... | Do HTTP Request | Below is the the instruction that describes the task:
### Input:
Do HTTP Request
### Response:
def httpdo(method, url, data=None):
"""
Do HTTP Request
"""
if isinstance(data, dict):
data = json.dumps(data)
if DEBUG:
print "Shell: curl -X {method} -d '{data}' '{url}'".form... |
def fillup_layer(layer_length, arrow_char):
"""
Creates a layer with BreakWire elements.
Args:
layer_length (int): The length of the layer to create
arrow_char (char): The char used to create the BreakWire element.
Returns:
list: The new layer.
... | Creates a layer with BreakWire elements.
Args:
layer_length (int): The length of the layer to create
arrow_char (char): The char used to create the BreakWire element.
Returns:
list: The new layer. | Below is the the instruction that describes the task:
### Input:
Creates a layer with BreakWire elements.
Args:
layer_length (int): The length of the layer to create
arrow_char (char): The char used to create the BreakWire element.
Returns:
list: The new layer.
#... |
def calibrate_pressure(self):
'''calibrate pressure'''
if self.mavlink10():
self.mav.command_long_send(self.target_system, self.target_component,
mavlink.MAV_CMD_PREFLIGHT_CALIBRATION, 0,
0, 0, 1, 0, 0, 0, 0)
... | calibrate pressure | Below is the the instruction that describes the task:
### Input:
calibrate pressure
### Response:
def calibrate_pressure(self):
'''calibrate pressure'''
if self.mavlink10():
self.mav.command_long_send(self.target_system, self.target_component,
mavl... |
def call(self, obj, name, method, args, kwargs):
"""Trigger a method along with its beforebacks and afterbacks.
Parameters
----------
name: str
The name of the method that will be called
args: tuple
The arguments that will be passed to the base method
... | Trigger a method along with its beforebacks and afterbacks.
Parameters
----------
name: str
The name of the method that will be called
args: tuple
The arguments that will be passed to the base method
kwargs: dict
The keyword args that will be ... | Below is the the instruction that describes the task:
### Input:
Trigger a method along with its beforebacks and afterbacks.
Parameters
----------
name: str
The name of the method that will be called
args: tuple
The arguments that will be passed to the base m... |
def ksl(A, y0, tau, verb=1, scheme='symm', space=8, rmax=2000, use_normest=1):
""" Dynamical tensor-train approximation based on projector splitting
This function performs one step of dynamical tensor-train approximation
for the equation
.. math ::
\\frac{dy}{dt} = A y, \\quad y... | Dynamical tensor-train approximation based on projector splitting
This function performs one step of dynamical tensor-train approximation
for the equation
.. math ::
\\frac{dy}{dt} = A y, \\quad y(0) = y_0
and outputs approximation for :math:`y(\\tau)`
:References:
... | Below is the the instruction that describes the task:
### Input:
Dynamical tensor-train approximation based on projector splitting
This function performs one step of dynamical tensor-train approximation
for the equation
.. math ::
\\frac{dy}{dt} = A y, \\quad y(0) = y_0
... |
def get_managed_policy_document(policy_arn, policy_metadata=None, client=None, **kwargs):
"""Retrieve the currently active (i.e. 'default') policy version document for a policy.
:param policy_arn:
:param policy_metadata: This is a previously fetch managed policy response from boto/cloudaux.
... | Retrieve the currently active (i.e. 'default') policy version document for a policy.
:param policy_arn:
:param policy_metadata: This is a previously fetch managed policy response from boto/cloudaux.
This is used to prevent unnecessary API calls to get the initial policy default vers... | Below is the the instruction that describes the task:
### Input:
Retrieve the currently active (i.e. 'default') policy version document for a policy.
:param policy_arn:
:param policy_metadata: This is a previously fetch managed policy response from boto/cloudaux.
This is used to... |
def default_format(self):
"""
Returns full name (first and last) if name is available.
If not, returns username if available.
If not available too, returns the user id as a string.
"""
user = self.user
if user.first_name is not None:
return self.full_n... | Returns full name (first and last) if name is available.
If not, returns username if available.
If not available too, returns the user id as a string. | Below is the the instruction that describes the task:
### Input:
Returns full name (first and last) if name is available.
If not, returns username if available.
If not available too, returns the user id as a string.
### Response:
def default_format(self):
"""
Returns full name (firs... |
def standardize_language(language, plugin):
"""Maps a string to the equivalent Pygments language.
Returns the standardized language string.
"""
if not language:
return None
# standardize language for this plugin
if plugin:
plugin = plugin.split(' ')[-1].split('/')[0].split('-'... | Maps a string to the equivalent Pygments language.
Returns the standardized language string. | Below is the the instruction that describes the task:
### Input:
Maps a string to the equivalent Pygments language.
Returns the standardized language string.
### Response:
def standardize_language(language, plugin):
"""Maps a string to the equivalent Pygments language.
Returns the standardized langua... |
def plot(self, x, y, **kw):
"""plot x, y values (erasing old plot),
for method options see PlotPanel.plot.
"""
return self.frame.plot(x,y,**kw) | plot x, y values (erasing old plot),
for method options see PlotPanel.plot. | Below is the the instruction that describes the task:
### Input:
plot x, y values (erasing old plot),
for method options see PlotPanel.plot.
### Response:
def plot(self, x, y, **kw):
"""plot x, y values (erasing old plot),
for method options see PlotPanel.plot.
"""
return ... |
def _closest_centroid(self, x):
"""Returns the index of the closest centroid to the sample
"""
closest_centroid = 0
distance = 10^9
for i in range(self.n_clusters):
current_distance = linalg.norm(x - self.centroids[i])
if current_distance < distance:
... | Returns the index of the closest centroid to the sample | Below is the the instruction that describes the task:
### Input:
Returns the index of the closest centroid to the sample
### Response:
def _closest_centroid(self, x):
"""Returns the index of the closest centroid to the sample
"""
closest_centroid = 0
distance = 10^9
for i i... |
def total_reads_from_grabix(in_file):
"""Retrieve total reads in a fastq file from grabix index.
"""
gbi_file = _get_grabix_index(in_file)
if gbi_file:
with open(gbi_file) as in_handle:
next(in_handle) # throw away
num_lines = int(next(in_handle).strip())
assert ... | Retrieve total reads in a fastq file from grabix index. | Below is the the instruction that describes the task:
### Input:
Retrieve total reads in a fastq file from grabix index.
### Response:
def total_reads_from_grabix(in_file):
"""Retrieve total reads in a fastq file from grabix index.
"""
gbi_file = _get_grabix_index(in_file)
if gbi_file:
with... |
def enqueue(self, klass, *args):
"""Enqueue a job into a specific queue. Make sure the class you are
passing has **queue** attribute and a **perform** method on it.
"""
queue = getattr(klass,'queue', None)
if queue:
class_name = '%s.%s' % (klass.__module__, klass.__n... | Enqueue a job into a specific queue. Make sure the class you are
passing has **queue** attribute and a **perform** method on it. | Below is the the instruction that describes the task:
### Input:
Enqueue a job into a specific queue. Make sure the class you are
passing has **queue** attribute and a **perform** method on it.
### Response:
def enqueue(self, klass, *args):
"""Enqueue a job into a specific queue. Make sure the clas... |
def _load_permissions(campus, calendarid, resp_fragment, permission_list):
"""
:return: a list of sorted trumba.Permission objects
None if error, [] if not exists
"""
for record in resp_fragment:
if not _is_valid_email(record['Email']):
# skip the non UW users
... | :return: a list of sorted trumba.Permission objects
None if error, [] if not exists | Below is the the instruction that describes the task:
### Input:
:return: a list of sorted trumba.Permission objects
None if error, [] if not exists
### Response:
def _load_permissions(campus, calendarid, resp_fragment, permission_list):
"""
:return: a list of sorted trumba.Permission objects
... |
def process_lines( self, input_lines, **kwargs ):
''' Executes the pipeline of subsequent VISL_CG3 commands. The first process
in pipeline gets input_lines as an input, and each subsequent process gets
the output of the previous process as an input.
The idea of h... | Executes the pipeline of subsequent VISL_CG3 commands. The first process
in pipeline gets input_lines as an input, and each subsequent process gets
the output of the previous process as an input.
The idea of how to construct the pipeline borrows from:
https... | Below is the the instruction that describes the task:
### Input:
Executes the pipeline of subsequent VISL_CG3 commands. The first process
in pipeline gets input_lines as an input, and each subsequent process gets
the output of the previous process as an input.
The id... |
def _save_datasets_as_mitiff(self, datasets, image_description,
gen_filename, **kwargs):
"""Put all togehter and save as a tiff file with the special tag
making it a mitiff file.
"""
from libtiff import TIFF
tif = TIFF.open(gen_filename, mode=... | Put all togehter and save as a tiff file with the special tag
making it a mitiff file. | Below is the the instruction that describes the task:
### Input:
Put all togehter and save as a tiff file with the special tag
making it a mitiff file.
### Response:
def _save_datasets_as_mitiff(self, datasets, image_description,
gen_filename, **kwargs):
"""Put a... |
def unparse_flags(self):
"""Unparses all flags to the point before any FLAGS(argv) was called."""
for f in self._flags().values():
f.unparse()
# We log this message before marking flags as unparsed to avoid a
# problem when the logging library causes flags access.
logging.info('unparse_flags()... | Unparses all flags to the point before any FLAGS(argv) was called. | Below is the the instruction that describes the task:
### Input:
Unparses all flags to the point before any FLAGS(argv) was called.
### Response:
def unparse_flags(self):
"""Unparses all flags to the point before any FLAGS(argv) was called."""
for f in self._flags().values():
f.unparse()
# We log... |
def delete_client(self, identifier):
"""Delete client."""
params = {'id': identifier}
response = yield from self._transact(SERVER_DELETECLIENT, params)
self.synchronize(response) | Delete client. | Below is the the instruction that describes the task:
### Input:
Delete client.
### Response:
def delete_client(self, identifier):
"""Delete client."""
params = {'id': identifier}
response = yield from self._transact(SERVER_DELETECLIENT, params)
self.synchronize(response) |
def export_items(elastic_url, in_index, out_index, elastic_url_out=None,
search_after=False, search_after_value=None, limit=None,
copy=False):
""" Export items from in_index to out_index using the correct mapping """
if not limit:
limit = DEFAULT_LIMIT
if search_a... | Export items from in_index to out_index using the correct mapping | Below is the the instruction that describes the task:
### Input:
Export items from in_index to out_index using the correct mapping
### Response:
def export_items(elastic_url, in_index, out_index, elastic_url_out=None,
search_after=False, search_after_value=None, limit=None,
copy=F... |
def top_view(self):
"""Print packages status bar
"""
self.msg.template(78)
print("{0}{1}{2}{3}{4}{5}{6}{7}{8}{9}{10}".format(
"| Package", " " * 17,
"New Version", " " * 8,
"Arch", " " * 4,
"Build", " " * 2,
"Repos", " " * 10,
... | Print packages status bar | Below is the the instruction that describes the task:
### Input:
Print packages status bar
### Response:
def top_view(self):
"""Print packages status bar
"""
self.msg.template(78)
print("{0}{1}{2}{3}{4}{5}{6}{7}{8}{9}{10}".format(
"| Package", " " * 17,
"New ... |
def _map_or_starmap_async(function, iterable, args, kwargs, map_or_starmap):
"""
Shared function between parmap.map_async and parmap.starmap_async.
Refer to those functions for details.
"""
arg_newarg = (("parallel", "pm_parallel"), ("chunksize", "pm_chunksize"),
("pool", "pm_pool"... | Shared function between parmap.map_async and parmap.starmap_async.
Refer to those functions for details. | Below is the the instruction that describes the task:
### Input:
Shared function between parmap.map_async and parmap.starmap_async.
Refer to those functions for details.
### Response:
def _map_or_starmap_async(function, iterable, args, kwargs, map_or_starmap):
"""
Shared function between parmap.map_asy... |
def find_geo_coords(s):
"""Returns a list of lat/lons found by scanning the given text"""
coords = []
LOG.debug("Matching in text size %s", len(s))
for c in INFO_BOX_LAT_LON.findall(s):
try:
coord = (float(c[1]), float(c[2])) #, c[0])
coords.append(coord)
LOG... | Returns a list of lat/lons found by scanning the given text | Below is the the instruction that describes the task:
### Input:
Returns a list of lat/lons found by scanning the given text
### Response:
def find_geo_coords(s):
"""Returns a list of lat/lons found by scanning the given text"""
coords = []
LOG.debug("Matching in text size %s", len(s))
for c in INF... |
def write_byte_data(self, address, register, value):
"""Write a byte value to a device's register. """
LOGGER.debug("Writing byte data %s to register %s on device %s",
bin(value), hex(register), hex(address))
return self.driver.write_byte_data(address, register, value) | Write a byte value to a device's register. | Below is the the instruction that describes the task:
### Input:
Write a byte value to a device's register.
### Response:
def write_byte_data(self, address, register, value):
"""Write a byte value to a device's register. """
LOGGER.debug("Writing byte data %s to register %s on device %s",
... |
def return_selected_form_items(form_info):
"""
It returns chosen keys list from a given form.
Args:
form_info: serialized list of dict form data
Returns:
selected_keys(list): Chosen keys list
selected_names(list): Chosen channels' or subscribers' name... | It returns chosen keys list from a given form.
Args:
form_info: serialized list of dict form data
Returns:
selected_keys(list): Chosen keys list
selected_names(list): Chosen channels' or subscribers' names. | Below is the the instruction that describes the task:
### Input:
It returns chosen keys list from a given form.
Args:
form_info: serialized list of dict form data
Returns:
selected_keys(list): Chosen keys list
selected_names(list): Chosen channels' or subscribers... |
def list(self, **kwargs):
"""Retrieve a list of objects.
Args:
all (bool): If True, return all the items, without pagination
per_page (int): Number of items to retrieve per request
page (int): ID of the page to return (starts with page 1)
as_list (bool): ... | Retrieve a list of objects.
Args:
all (bool): If True, return all the items, without pagination
per_page (int): Number of items to retrieve per request
page (int): ID of the page to return (starts with page 1)
as_list (bool): If set to False and no pagination opt... | Below is the the instruction that describes the task:
### Input:
Retrieve a list of objects.
Args:
all (bool): If True, return all the items, without pagination
per_page (int): Number of items to retrieve per request
page (int): ID of the page to return (starts with page... |
def ParseContainersTable(
self, parser_mediator, database=None, table=None, **unused_kwargs):
"""Parses the Containers table.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
database (Optional[pyesedb.fil... | Parses the Containers table.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
database (Optional[pyesedb.file]): ESE database.
table (Optional[pyesedb.table]): table.
Raises:
ValueError: if the data... | Below is the the instruction that describes the task:
### Input:
Parses the Containers table.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
database (Optional[pyesedb.file]): ESE database.
table (Option... |
def match_index_versions(host=None, core_name=None):
'''
SLAVE CALL
Verifies that the master and the slave versions are in sync by
comparing the index version. If you are constantly pushing updates
the index the master and slave versions will seldom match. A solution
to this is pause indexing ev... | SLAVE CALL
Verifies that the master and the slave versions are in sync by
comparing the index version. If you are constantly pushing updates
the index the master and slave versions will seldom match. A solution
to this is pause indexing every so often to allow the slave to replicate
and then call th... | Below is the the instruction that describes the task:
### Input:
SLAVE CALL
Verifies that the master and the slave versions are in sync by
comparing the index version. If you are constantly pushing updates
the index the master and slave versions will seldom match. A solution
to this is pause indexin... |
def reset(self):
'''
Reset list of terms and y-variable.
'''
self.terms = OrderedDict()
self.y = None
self.backend = None
self.added_terms = []
self._added_priors = {}
self.completes = []
self.clean_data = None | Reset list of terms and y-variable. | Below is the the instruction that describes the task:
### Input:
Reset list of terms and y-variable.
### Response:
def reset(self):
'''
Reset list of terms and y-variable.
'''
self.terms = OrderedDict()
self.y = None
self.backend = None
self.added_terms = []
... |
def add_directory_digests_for_jars(self, targets_and_jars):
"""For each target, get DirectoryDigests for its jars and return them zipped with the jars.
:param targets_and_jars: List of tuples of the form (Target, [pants.java.jar.jar_dependency_utils.ResolveJar])
:return: list[tuple[(Target, list[pants.java... | For each target, get DirectoryDigests for its jars and return them zipped with the jars.
:param targets_and_jars: List of tuples of the form (Target, [pants.java.jar.jar_dependency_utils.ResolveJar])
:return: list[tuple[(Target, list[pants.java.jar.jar_dependency_utils.ResolveJar])] | Below is the the instruction that describes the task:
### Input:
For each target, get DirectoryDigests for its jars and return them zipped with the jars.
:param targets_and_jars: List of tuples of the form (Target, [pants.java.jar.jar_dependency_utils.ResolveJar])
:return: list[tuple[(Target, list[pants.ja... |
def simplified_solis(apparent_elevation, aod700=0.1, precipitable_water=1.,
pressure=101325., dni_extra=1364.):
"""
Calculate the clear sky GHI, DNI, and DHI according to the
simplified Solis model [1]_.
Reference [1]_ describes the accuracy of the model as being 15, 20,
and 18... | Calculate the clear sky GHI, DNI, and DHI according to the
simplified Solis model [1]_.
Reference [1]_ describes the accuracy of the model as being 15, 20,
and 18 W/m^2 for the beam, global, and diffuse components. Reference
[2]_ provides comparisons with other clear sky models.
Parameters
---... | Below is the the instruction that describes the task:
### Input:
Calculate the clear sky GHI, DNI, and DHI according to the
simplified Solis model [1]_.
Reference [1]_ describes the accuracy of the model as being 15, 20,
and 18 W/m^2 for the beam, global, and diffuse components. Reference
[2]_ prov... |
def get_num_columns_and_rows(widths, gap_width, term_width):
'''Given a list of string widths, a width of the minimum gap to place
between them, and the maximum width of the output (such as a terminal
width), calculate the number of columns and rows, and the width of each
column, for the optimal lay... | Given a list of string widths, a width of the minimum gap to place
between them, and the maximum width of the output (such as a terminal
width), calculate the number of columns and rows, and the width of each
column, for the optimal layout. | Below is the the instruction that describes the task:
### Input:
Given a list of string widths, a width of the minimum gap to place
between them, and the maximum width of the output (such as a terminal
width), calculate the number of columns and rows, and the width of each
column, for the optimal lay... |
def read_metadata(self, symbol, as_of=None, allow_secondary=None):
"""
Return the metadata saved for a symbol. This method is fast as it doesn't
actually load the data.
Parameters
----------
symbol : `str`
symbol name for the item
as_of : `str` or in... | Return the metadata saved for a symbol. This method is fast as it doesn't
actually load the data.
Parameters
----------
symbol : `str`
symbol name for the item
as_of : `str` or int or `datetime.datetime`
Return the data as it was as_of the point in time.... | Below is the the instruction that describes the task:
### Input:
Return the metadata saved for a symbol. This method is fast as it doesn't
actually load the data.
Parameters
----------
symbol : `str`
symbol name for the item
as_of : `str` or int or `datetime.dat... |
def deps_status(self):
"""Returns a list with the status of the dependencies."""
if not self.deps:
return [self.S_OK]
return [d.status for d in self.deps] | Returns a list with the status of the dependencies. | Below is the the instruction that describes the task:
### Input:
Returns a list with the status of the dependencies.
### Response:
def deps_status(self):
"""Returns a list with the status of the dependencies."""
if not self.deps:
return [self.S_OK]
return [d.status for d in sel... |
def all_continuous_indexes_slices(ol,value):
'''
from elist.elist import *
ol = [1,"a","a",2,3,"a",4,"a","a","a",5]
all_continuous_indexes_slices(ol,"a")
'''
rslt = []
length = ol.__len__()
cursor = 0
begin = None
slice = []
while(cursor < length):
cond1 =... | from elist.elist import *
ol = [1,"a","a",2,3,"a",4,"a","a","a",5]
all_continuous_indexes_slices(ol,"a") | Below is the the instruction that describes the task:
### Input:
from elist.elist import *
ol = [1,"a","a",2,3,"a",4,"a","a","a",5]
all_continuous_indexes_slices(ol,"a")
### Response:
def all_continuous_indexes_slices(ol,value):
'''
from elist.elist import *
ol = [1,"a","a",2,3,... |
def shift(self, periods, axis=0, fill_value=None):
""" shift the block by periods, possibly upcast """
# convert integer to float if necessary. need to do a lot more than
# that, handle boolean etc also
new_values, fill_value = maybe_upcast(self.values, fill_value)
# make sure ... | shift the block by periods, possibly upcast | Below is the the instruction that describes the task:
### Input:
shift the block by periods, possibly upcast
### Response:
def shift(self, periods, axis=0, fill_value=None):
""" shift the block by periods, possibly upcast """
# convert integer to float if necessary. need to do a lot more than
... |
def get_csv_col_headers(rows, row_headers_count_value=0):
"""
Retrieve csv column headers
"""
count = 0
if rows:
for row in rows:
if exclude_empty_values(row[:row_headers_count_value]):
break
count += 1
if len(rows) == count:
count = 1 #... | Retrieve csv column headers | Below is the the instruction that describes the task:
### Input:
Retrieve csv column headers
### Response:
def get_csv_col_headers(rows, row_headers_count_value=0):
"""
Retrieve csv column headers
"""
count = 0
if rows:
for row in rows:
if exclude_empty_values(row[:row_head... |
def _dirdiffandupdate(self, dir1, dir2):
"""
Private function which does directory diff & update
"""
self._dowork(dir1, dir2, None, self._update) | Private function which does directory diff & update | Below is the the instruction that describes the task:
### Input:
Private function which does directory diff & update
### Response:
def _dirdiffandupdate(self, dir1, dir2):
"""
Private function which does directory diff & update
"""
self._dowork(dir1, dir2, None, self._update) |
def build_hardware_simulator(
cls,
attached_instruments: Dict[top_types.Mount, Dict[str, Optional[str]]] = None, # noqa E501
attached_modules: List[str] = None,
config: robot_configs.robot_config = None,
loop: asyncio.AbstractEventLoop = None,
str... | Build a simulating hardware controller.
This method may be used both on a real robot and on dev machines.
Multiple simulating hardware controllers may be active at one time. | Below is the the instruction that describes the task:
### Input:
Build a simulating hardware controller.
This method may be used both on a real robot and on dev machines.
Multiple simulating hardware controllers may be active at one time.
### Response:
def build_hardware_simulator(
cls... |
def Y(self, value):
""" set phenotype """
self._N = value.shape[0]
self._P = value.shape[1]
self._Y = value
# missing data
self._Iok = ~sp.isnan(value)
self._veIok = vec(self._Iok)[:, 0]
self._miss = (~self._Iok).any()
# notify and clear_cached
... | set phenotype | Below is the the instruction that describes the task:
### Input:
set phenotype
### Response:
def Y(self, value):
""" set phenotype """
self._N = value.shape[0]
self._P = value.shape[1]
self._Y = value
# missing data
self._Iok = ~sp.isnan(value)
self._veIok = ... |
def get_feature(name):
"""Get an instance of a ``Features`` class by ``name`` (str)."""
if name == 'css':
return CSSFeatures()
elif name == 'kohlschuetter':
return KohlschuetterFeatures()
elif name == 'readability':
return ReadabilityFeatures()
elif name == 'weninger':
... | Get an instance of a ``Features`` class by ``name`` (str). | Below is the the instruction that describes the task:
### Input:
Get an instance of a ``Features`` class by ``name`` (str).
### Response:
def get_feature(name):
"""Get an instance of a ``Features`` class by ``name`` (str)."""
if name == 'css':
return CSSFeatures()
elif name == 'kohlschuetter':
... |
def normalize(rendered):
"""Return the input string without non-functional spaces or newlines."""
out = ''.join([line.strip()
for line in rendered.splitlines()
if line.strip()])
out = out.replace(', ', ',')
return out | Return the input string without non-functional spaces or newlines. | Below is the the instruction that describes the task:
### Input:
Return the input string without non-functional spaces or newlines.
### Response:
def normalize(rendered):
"""Return the input string without non-functional spaces or newlines."""
out = ''.join([line.strip()
for line in rend... |
def set_category(self, category):
"""Set package category
Args:
category: String of an existing category's name, or a
Category object.
"""
# For some reason, packages only have the category name, not the
# ID.
if isinstance(category, Category)... | Set package category
Args:
category: String of an existing category's name, or a
Category object. | Below is the the instruction that describes the task:
### Input:
Set package category
Args:
category: String of an existing category's name, or a
Category object.
### Response:
def set_category(self, category):
"""Set package category
Args:
category... |
def select(self, adjacentEdges=None, edgeList=None, extendEdges=None, firstNeighbors=None, \
invert=None, network=None, nodeList=None, verbose=False):
"""
Select nodes and/or edges in a network. This command provides options to
invert the selection, add first neighbors, add adjacent edge... | Select nodes and/or edges in a network. This command provides options to
invert the selection, add first neighbors, add adjacent edges of selected
nodes, and add adjacent nodes of selected edges
:param adjacentEdges (string, optional): If 'true', then select any edges
adjacent to an... | Below is the the instruction that describes the task:
### Input:
Select nodes and/or edges in a network. This command provides options to
invert the selection, add first neighbors, add adjacent edges of selected
nodes, and add adjacent nodes of selected edges
:param adjacentEdges (string, o... |
def weld_merge_join(arrays_self, weld_types_self, arrays_other, weld_types_other,
how, is_on_sorted, is_on_unique, readable_text):
"""Applies merge-join on the arrays returning indices from each to keep in the resulting
Parameters
----------
arrays_self : list of (numpy.ndarray or W... | Applies merge-join on the arrays returning indices from each to keep in the resulting
Parameters
----------
arrays_self : list of (numpy.ndarray or WeldObject)
Columns from the self DataFrame on which to join.
weld_types_self : list of WeldType
Corresponding Weld types.
arrays_other... | Below is the the instruction that describes the task:
### Input:
Applies merge-join on the arrays returning indices from each to keep in the resulting
Parameters
----------
arrays_self : list of (numpy.ndarray or WeldObject)
Columns from the self DataFrame on which to join.
weld_types_self ... |
def get_regulate_activities(self):
"""Get Activation/Inhibition INDRA Statements from the BioPAX model.
This method extracts Activation/Inhibition Statements and reuses the
structure of BioPAX Pattern's
org.biopax.paxtools.pattern.PatternBox.constrolsStateChange pattern
with add... | Get Activation/Inhibition INDRA Statements from the BioPAX model.
This method extracts Activation/Inhibition Statements and reuses the
structure of BioPAX Pattern's
org.biopax.paxtools.pattern.PatternBox.constrolsStateChange pattern
with additional constraints to specify the gain or los... | Below is the the instruction that describes the task:
### Input:
Get Activation/Inhibition INDRA Statements from the BioPAX model.
This method extracts Activation/Inhibition Statements and reuses the
structure of BioPAX Pattern's
org.biopax.paxtools.pattern.PatternBox.constrolsStateChange p... |
def uninstall(self, auto_confirm=False):
"""
Uninstall the distribution currently satisfying this requirement.
Prompts before removing or modifying files unless
``auto_confirm`` is True.
Refuses to delete or modify files outside of ``sys.prefix`` -
thus uninstallation w... | Uninstall the distribution currently satisfying this requirement.
Prompts before removing or modifying files unless
``auto_confirm`` is True.
Refuses to delete or modify files outside of ``sys.prefix`` -
thus uninstallation within a virtual environment can only
modify that virt... | Below is the the instruction that describes the task:
### Input:
Uninstall the distribution currently satisfying this requirement.
Prompts before removing or modifying files unless
``auto_confirm`` is True.
Refuses to delete or modify files outside of ``sys.prefix`` -
thus uninstal... |
def register_hooks(self, on_terminate=None, on_reload=None,
on_new_worker=None, on_dead_worker=None):
"""Register hook methods
This can be callable multiple times to add more hooks, hooks are
executed in added order. If a hook raised an exception, next hooks
will ... | Register hook methods
This can be callable multiple times to add more hooks, hooks are
executed in added order. If a hook raised an exception, next hooks
will be not executed.
:param on_terminate: method called on SIGTERM
:type on_terminate: callable()
:param on_reload:... | Below is the the instruction that describes the task:
### Input:
Register hook methods
This can be callable multiple times to add more hooks, hooks are
executed in added order. If a hook raised an exception, next hooks
will be not executed.
:param on_terminate: method called on SIG... |
def print_stats(self, clsname=None, limit=1.0):
"""
Write tracked objects to stdout. The output can be filtered and
pruned. Only objects are printed whose classname contain the substring
supplied by the `clsname` argument. The output can be pruned by
passing a `limit` value.
... | Write tracked objects to stdout. The output can be filtered and
pruned. Only objects are printed whose classname contain the substring
supplied by the `clsname` argument. The output can be pruned by
passing a `limit` value.
:param clsname: Only print objects whose classname contain t... | Below is the the instruction that describes the task:
### Input:
Write tracked objects to stdout. The output can be filtered and
pruned. Only objects are printed whose classname contain the substring
supplied by the `clsname` argument. The output can be pruned by
passing a `limit` value.
... |
def uploadStickerFile(self, user_id, png_sticker):
"""
See: https://core.telegram.org/bots/api#uploadstickerfile
"""
p = _strip(locals(), more=['png_sticker'])
return self._api_request_with_file('uploadStickerFile', _rectify(p), 'png_sticker', png_sticker) | See: https://core.telegram.org/bots/api#uploadstickerfile | Below is the the instruction that describes the task:
### Input:
See: https://core.telegram.org/bots/api#uploadstickerfile
### Response:
def uploadStickerFile(self, user_id, png_sticker):
"""
See: https://core.telegram.org/bots/api#uploadstickerfile
"""
p = _strip(locals(), more=['p... |
def parent_chain(self):
"""
Return the list of parents starting from this node. The chain ends
at the first node with no parents.
"""
chain = [self]
while True:
try:
parent = chain[-1].parent
except Exception:
break
... | Return the list of parents starting from this node. The chain ends
at the first node with no parents. | Below is the the instruction that describes the task:
### Input:
Return the list of parents starting from this node. The chain ends
at the first node with no parents.
### Response:
def parent_chain(self):
"""
Return the list of parents starting from this node. The chain ends
at the ... |
def _augment_book(self, uuid, event):
"""
Checks if the newly created object is a book and only has an ISBN.
If so, tries to fetch the book data off the internet.
:param uuid: uuid of book to augment
:param client: requesting client
"""
try:
if not is... | Checks if the newly created object is a book and only has an ISBN.
If so, tries to fetch the book data off the internet.
:param uuid: uuid of book to augment
:param client: requesting client | Below is the the instruction that describes the task:
### Input:
Checks if the newly created object is a book and only has an ISBN.
If so, tries to fetch the book data off the internet.
:param uuid: uuid of book to augment
:param client: requesting client
### Response:
def _augment_book(se... |
def relevant_kwargs(function, exclude_keys='self', exclude_values=None,
extra_values=None):
"""
This will return a dictionary of local variables that are parameters to the
function provided in the arg.
Example:
function(**relevant_kwargs(function))
:param function: f... | This will return a dictionary of local variables that are parameters to the
function provided in the arg.
Example:
function(**relevant_kwargs(function))
:param function: function to select parameters for
:param exclude_keys: str,list,func if not a function it will be converted
... | Below is the the instruction that describes the task:
### Input:
This will return a dictionary of local variables that are parameters to the
function provided in the arg.
Example:
function(**relevant_kwargs(function))
:param function: function to select parameters for
:param exclude_key... |
def expand(self, new_size):
""" expand the LUN to a new size
:param new_size: new size in bytes.
:return: the old size
"""
ret = self.size_total
resp = self.modify(size=new_size)
resp.raise_if_err()
return ret | expand the LUN to a new size
:param new_size: new size in bytes.
:return: the old size | Below is the the instruction that describes the task:
### Input:
expand the LUN to a new size
:param new_size: new size in bytes.
:return: the old size
### Response:
def expand(self, new_size):
""" expand the LUN to a new size
:param new_size: new size in bytes.
:return: t... |
def new_workunit_under_parent(self, name, parent, labels=None, cmd='', log_config=None):
"""Creates a (hierarchical) subunit of work for the purpose of timing and reporting.
- name: A short name for this work. E.g., 'resolve', 'compile', 'scala', 'zinc'.
- parent: The new workunit is created under this par... | Creates a (hierarchical) subunit of work for the purpose of timing and reporting.
- name: A short name for this work. E.g., 'resolve', 'compile', 'scala', 'zinc'.
- parent: The new workunit is created under this parent.
- labels: An optional iterable of labels. The reporters can use this to decide how to
... | Below is the the instruction that describes the task:
### Input:
Creates a (hierarchical) subunit of work for the purpose of timing and reporting.
- name: A short name for this work. E.g., 'resolve', 'compile', 'scala', 'zinc'.
- parent: The new workunit is created under this parent.
- labels: An optio... |
def _slice_weights(self, arr, li, lh):
"""slice fused rnn weights"""
args = {}
gate_names = self._gate_names
directions = self._directions
b = len(directions)
p = 0
for layer in range(self._num_layers):
for direction in directions:
for... | slice fused rnn weights | Below is the the instruction that describes the task:
### Input:
slice fused rnn weights
### Response:
def _slice_weights(self, arr, li, lh):
"""slice fused rnn weights"""
args = {}
gate_names = self._gate_names
directions = self._directions
b = len(directions)
p = ... |
def hsts_header(self):
"""Returns the proper HSTS policy."""
hsts_policy = 'max-age={0}'.format(self.hsts_age)
if self.hsts_include_subdomains:
hsts_policy += '; includeSubDomains'
return hsts_policy | Returns the proper HSTS policy. | Below is the the instruction that describes the task:
### Input:
Returns the proper HSTS policy.
### Response:
def hsts_header(self):
"""Returns the proper HSTS policy."""
hsts_policy = 'max-age={0}'.format(self.hsts_age)
if self.hsts_include_subdomains:
hsts_policy += '; inclu... |
def _n2deriv(self,l,n):
"""
NAME:
_n2deriv
PURPOSE:
evaluate the second derivative w.r.t. nu for this potential
INPUT:
l - prolate spheroidal coordinate lambda
n - prolate spheroidal coordinate nu
OUTPUT:
second derivati... | NAME:
_n2deriv
PURPOSE:
evaluate the second derivative w.r.t. nu for this potential
INPUT:
l - prolate spheroidal coordinate lambda
n - prolate spheroidal coordinate nu
OUTPUT:
second derivative w.r.t. nu
HISTORY:
20... | Below is the the instruction that describes the task:
### Input:
NAME:
_n2deriv
PURPOSE:
evaluate the second derivative w.r.t. nu for this potential
INPUT:
l - prolate spheroidal coordinate lambda
n - prolate spheroidal coordinate nu
OUTPUT:
... |
def mutagen_call(action, path, func, *args, **kwargs):
"""Call a Mutagen function with appropriate error handling.
`action` is a string describing what the function is trying to do,
and `path` is the relevant filename. The rest of the arguments
describe the callable to invoke.
We require at least ... | Call a Mutagen function with appropriate error handling.
`action` is a string describing what the function is trying to do,
and `path` is the relevant filename. The rest of the arguments
describe the callable to invoke.
We require at least Mutagen 1.33, where `IOError` is *never* used,
neither for... | Below is the the instruction that describes the task:
### Input:
Call a Mutagen function with appropriate error handling.
`action` is a string describing what the function is trying to do,
and `path` is the relevant filename. The rest of the arguments
describe the callable to invoke.
We require at... |
def get_oauth_request(self):
"""Return an OAuth Request object for the current request."""
try:
method = os.environ['REQUEST_METHOD']
except:
method = 'GET'
postdata = None
if method in ('POST', 'PUT'):
postdata = self.request.body
r... | Return an OAuth Request object for the current request. | Below is the the instruction that describes the task:
### Input:
Return an OAuth Request object for the current request.
### Response:
def get_oauth_request(self):
"""Return an OAuth Request object for the current request."""
try:
method = os.environ['REQUEST_METHOD']
except:
... |
def main():
"""The simplest usage of watershed delineation based on TauDEM."""
dem = '../tests/data/Jamaica_dem.tif'
num_proc = 2
wp = '../tests/data/tmp_results/wtsd_delineation'
TauDEMWorkflow.watershed_delineation(num_proc, dem, workingdir=wp) | The simplest usage of watershed delineation based on TauDEM. | Below is the the instruction that describes the task:
### Input:
The simplest usage of watershed delineation based on TauDEM.
### Response:
def main():
"""The simplest usage of watershed delineation based on TauDEM."""
dem = '../tests/data/Jamaica_dem.tif'
num_proc = 2
wp = '../tests/data/tmp_resul... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.