code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def is_descendant_of_bin(self, id_, bin_id):
"""Tests if an ``Id`` is a descendant of a bin.
arg: id (osid.id.Id): an ``Id``
arg: bin_id (osid.id.Id): the ``Id`` of a bin
return: (boolean) - ``true`` if the ``id`` is a descendant of
the ``bin_id,`` ``false`` other... | Tests if an ``Id`` is a descendant of a bin.
arg: id (osid.id.Id): an ``Id``
arg: bin_id (osid.id.Id): the ``Id`` of a bin
return: (boolean) - ``true`` if the ``id`` is a descendant of
the ``bin_id,`` ``false`` otherwise
raise: NotFound - ``bin_id`` is not found
... | Below is the the instruction that describes the task:
### Input:
Tests if an ``Id`` is a descendant of a bin.
arg: id (osid.id.Id): an ``Id``
arg: bin_id (osid.id.Id): the ``Id`` of a bin
return: (boolean) - ``true`` if the ``id`` is a descendant of
the ``bin_id,`` ``... |
def folderitems(self):
"""XXX refactor if possible to non-classic mode
"""
items = super(AnalysisRequestAnalysesView, self).folderitems()
self.categories.sort()
return items | XXX refactor if possible to non-classic mode | Below is the the instruction that describes the task:
### Input:
XXX refactor if possible to non-classic mode
### Response:
def folderitems(self):
"""XXX refactor if possible to non-classic mode
"""
items = super(AnalysisRequestAnalysesView, self).folderitems()
self.categories.sort(... |
def _add_membership_multicast_socket(self):
"""
Make membership request to multicast
:rtype: None
"""
self._membership_request = socket.inet_aton(self._multicast_group) \
+ socket.inet_aton(self._multicast_ip)
# Send add membership request to socket
... | Make membership request to multicast
:rtype: None | Below is the the instruction that describes the task:
### Input:
Make membership request to multicast
:rtype: None
### Response:
def _add_membership_multicast_socket(self):
"""
Make membership request to multicast
:rtype: None
"""
self._membership_request = socket.... |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self,
'credential_type') and self.credential_type is not None:
_dict['credential_type'] = self.credential_type
if hasattr(self, 'client_id') and self.client_id... | Return a json dictionary representing this model. | Below is the the instruction that describes the task:
### Input:
Return a json dictionary representing this model.
### Response:
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self,
'credential_type') and self.credential_... |
def dump(data, stream=None, Dumper=Dumper, **kwds):
"""
Serialize a Python object into a YAML stream.
If stream is None, return the produced string instead.
"""
return dump_all([data], stream, Dumper=Dumper, **kwds) | Serialize a Python object into a YAML stream.
If stream is None, return the produced string instead. | Below is the the instruction that describes the task:
### Input:
Serialize a Python object into a YAML stream.
If stream is None, return the produced string instead.
### Response:
def dump(data, stream=None, Dumper=Dumper, **kwds):
"""
Serialize a Python object into a YAML stream.
If stream is None... |
def summarise( self, results ):
"""Generate a summary of results from a list of result dicts
returned by running the underlying experiment. By default we generate
mean, median, variance, and extrema for each value recorded.
Override this method to create different or extra summary stati... | Generate a summary of results from a list of result dicts
returned by running the underlying experiment. By default we generate
mean, median, variance, and extrema for each value recorded.
Override this method to create different or extra summary statistics.
:param results: an array of... | Below is the the instruction that describes the task:
### Input:
Generate a summary of results from a list of result dicts
returned by running the underlying experiment. By default we generate
mean, median, variance, and extrema for each value recorded.
Override this method to create differ... |
def restart_complete(self, state, new_address):
'''
Called when we get notified that the restart has been completed by
some agent who has volontureed to do so.
'''
if state.timeout_call_id:
state.agent.cancel_delayed_call(state.timeout_call_id)
state.timeo... | Called when we get notified that the restart has been completed by
some agent who has volontureed to do so. | Below is the the instruction that describes the task:
### Input:
Called when we get notified that the restart has been completed by
some agent who has volontureed to do so.
### Response:
def restart_complete(self, state, new_address):
'''
Called when we get notified that the restart has bee... |
def get_all_tags(image_name, branch=None):
"""
GET /v1/repositories/<namespace>/<repository_name>/tags
:param image_name: The docker image name
:param branch: The branch to filter by
:return: A list of Version instances, latest first
"""
try:
return get_all_tags_no_auth(image_name, ... | GET /v1/repositories/<namespace>/<repository_name>/tags
:param image_name: The docker image name
:param branch: The branch to filter by
:return: A list of Version instances, latest first | Below is the the instruction that describes the task:
### Input:
GET /v1/repositories/<namespace>/<repository_name>/tags
:param image_name: The docker image name
:param branch: The branch to filter by
:return: A list of Version instances, latest first
### Response:
def get_all_tags(image_name, branch=... |
def get(self):
"""
method to fetch all contents as a list
:return: list
"""
ret_list = []
if hasattr(self, "font"):
ret_list.append(self.font)
if hasattr(self, "size"):
ret_list.append(self.size)
if hasattr(self, "text"):
... | method to fetch all contents as a list
:return: list | Below is the the instruction that describes the task:
### Input:
method to fetch all contents as a list
:return: list
### Response:
def get(self):
"""
method to fetch all contents as a list
:return: list
"""
ret_list = []
if hasattr(self, "font"):
... |
def play(self, sox_effects=()):
""" Play the segment. """
audio_data = self.getAudioData()
logging.getLogger().info("Playing speech segment (%s): '%s'" % (self.lang, self))
cmd = ["sox", "-q", "-t", "mp3", "-"]
if sys.platform.startswith("win32"):
cmd.extend(("-t", "waveaudio"))
cmd.extend... | Play the segment. | Below is the the instruction that describes the task:
### Input:
Play the segment.
### Response:
def play(self, sox_effects=()):
""" Play the segment. """
audio_data = self.getAudioData()
logging.getLogger().info("Playing speech segment (%s): '%s'" % (self.lang, self))
cmd = ["sox", "-q", "-t", "mp... |
def get_experiment_summ_ids( self, coinc_event_id ):
"""
Gets all the experiment_summ_ids that map to a given coinc_event_id.
"""
experiment_summ_ids = []
for row in self:
if row.coinc_event_id == coinc_event_id:
experiment_summ_ids.append(row.experiment_summ_id)
if len(experiment_summ_ids) == 0:
... | Gets all the experiment_summ_ids that map to a given coinc_event_id. | Below is the the instruction that describes the task:
### Input:
Gets all the experiment_summ_ids that map to a given coinc_event_id.
### Response:
def get_experiment_summ_ids( self, coinc_event_id ):
"""
Gets all the experiment_summ_ids that map to a given coinc_event_id.
"""
experiment_summ_ids = []
fo... |
def FindSourceFiles(self, node='.'):
""" returns a list of all source files.
"""
node = self.arg2nodes(node, self.fs.Entry)[0]
sources = []
def build_source(ss):
for s in ss:
if isinstance(s, SCons.Node.FS.Dir):
build_source(s.all_... | returns a list of all source files. | Below is the the instruction that describes the task:
### Input:
returns a list of all source files.
### Response:
def FindSourceFiles(self, node='.'):
""" returns a list of all source files.
"""
node = self.arg2nodes(node, self.fs.Entry)[0]
sources = []
def build_source(ss... |
def _dedent(text, tabsize=8, skip_first_line=False):
"""_dedent(text, tabsize=8, skip_first_line=False) -> dedented text
"text" is the text to dedent.
"tabsize" is the tab width to use for indent width calculations.
"skip_first_line" is a boolean indicating if the first line should
... | _dedent(text, tabsize=8, skip_first_line=False) -> dedented text
"text" is the text to dedent.
"tabsize" is the tab width to use for indent width calculations.
"skip_first_line" is a boolean indicating if the first line should
be skipped for calculating the indent width and for dede... | Below is the the instruction that describes the task:
### Input:
_dedent(text, tabsize=8, skip_first_line=False) -> dedented text
"text" is the text to dedent.
"tabsize" is the tab width to use for indent width calculations.
"skip_first_line" is a boolean indicating if the first line should... |
def order(self, field, order=None):
"""
Set field and order set by arguments
"""
if not order:
order = ORDER.DESC
self.url.order = (field, order)
self.url.set_page(1)
return self | Set field and order set by arguments | Below is the the instruction that describes the task:
### Input:
Set field and order set by arguments
### Response:
def order(self, field, order=None):
"""
Set field and order set by arguments
"""
if not order:
order = ORDER.DESC
self.url.order = (field, order)
... |
def get_process_rca(self, pid=None):
'''
get_process_rca(self, pid=None)
Get the RCA tree of a given failed process. The RCA tree contains all failed child processes that caused the failure of the given process.
:Parameters:
* *pid* (`string`) -- Identifier of an existing proce... | get_process_rca(self, pid=None)
Get the RCA tree of a given failed process. The RCA tree contains all failed child processes that caused the failure of the given process.
:Parameters:
* *pid* (`string`) -- Identifier of an existing process | Below is the the instruction that describes the task:
### Input:
get_process_rca(self, pid=None)
Get the RCA tree of a given failed process. The RCA tree contains all failed child processes that caused the failure of the given process.
:Parameters:
* *pid* (`string`) -- Identifier of an ex... |
def resolve_function(slither, contract_name, function_name):
"""
Resolves a function instance, given a contract name and function.
:param contract_name: The name of the contract the function is declared in.
:param function_name: The name of the function to resolve.
:return: Returns the resolved func... | Resolves a function instance, given a contract name and function.
:param contract_name: The name of the contract the function is declared in.
:param function_name: The name of the function to resolve.
:return: Returns the resolved function, raises an exception otherwise. | Below is the the instruction that describes the task:
### Input:
Resolves a function instance, given a contract name and function.
:param contract_name: The name of the contract the function is declared in.
:param function_name: The name of the function to resolve.
:return: Returns the resolved function... |
def process(self):
""" Collects, processes & reports metrics """
if self.agent.machine.fsm.current is "wait4init":
# Test the host agent if we're ready to send data
if self.agent.is_agent_ready():
self.agent.machine.fsm.ready()
else:
re... | Collects, processes & reports metrics | Below is the the instruction that describes the task:
### Input:
Collects, processes & reports metrics
### Response:
def process(self):
""" Collects, processes & reports metrics """
if self.agent.machine.fsm.current is "wait4init":
# Test the host agent if we're ready to send data
... |
def Weber_saltation(mp, rhop, dp, rhog, D, Vterminal=4):
r'''Calculates saltation velocity of the gas for pneumatic conveying,
according to [1]_ as described in [2]_, [3]_, [4]_, and [5]_.
If Vterminal is under 3 m/s, use equation 1; otherwise, equation 2.
.. math::
Fr_s = \left(7 + \frac{8}{3... | r'''Calculates saltation velocity of the gas for pneumatic conveying,
according to [1]_ as described in [2]_, [3]_, [4]_, and [5]_.
If Vterminal is under 3 m/s, use equation 1; otherwise, equation 2.
.. math::
Fr_s = \left(7 + \frac{8}{3}V_{terminal}\right)\mu^{0.25}
\left(\frac{d_p}{D}\ri... | Below is the the instruction that describes the task:
### Input:
r'''Calculates saltation velocity of the gas for pneumatic conveying,
according to [1]_ as described in [2]_, [3]_, [4]_, and [5]_.
If Vterminal is under 3 m/s, use equation 1; otherwise, equation 2.
.. math::
Fr_s = \left(7 + \f... |
def write(self, output_filepath):
"""
serialize the ExmaraldaFile instance and write it to a file.
Parameters
----------
output_filepath : str
relative or absolute path to the Exmaralda file to be created
"""
with open(output_filepath, 'w') as out_fil... | serialize the ExmaraldaFile instance and write it to a file.
Parameters
----------
output_filepath : str
relative or absolute path to the Exmaralda file to be created | Below is the the instruction that describes the task:
### Input:
serialize the ExmaraldaFile instance and write it to a file.
Parameters
----------
output_filepath : str
relative or absolute path to the Exmaralda file to be created
### Response:
def write(self, output_filepath)... |
def get_attributes(self, obj):
""" Get all object's attributes.
Sends multi-parameter info/config queries and returns the result as dictionary.
:param obj: requested object.
:returns: dictionary of <name, value> of all attributes returned by the query.
:rtype: dict of (str, str... | Get all object's attributes.
Sends multi-parameter info/config queries and returns the result as dictionary.
:param obj: requested object.
:returns: dictionary of <name, value> of all attributes returned by the query.
:rtype: dict of (str, str) | Below is the the instruction that describes the task:
### Input:
Get all object's attributes.
Sends multi-parameter info/config queries and returns the result as dictionary.
:param obj: requested object.
:returns: dictionary of <name, value> of all attributes returned by the query.
... |
def default_formats(self, path):
"""Return the default formats, if they apply to the current path #157"""
formats = long_form_multiple_formats(self.default_jupytext_formats)
for fmt in formats:
try:
base_path(path, fmt)
return self.default_jupytext_for... | Return the default formats, if they apply to the current path #157 | Below is the the instruction that describes the task:
### Input:
Return the default formats, if they apply to the current path #157
### Response:
def default_formats(self, path):
"""Return the default formats, if they apply to the current path #157"""
formats = long_form_multiple_formats(self.defau... |
def main():
'''Calculate the distance of an object in inches using a HCSR04 sensor
and a Raspberry Pi'''
trig_pin = 17
echo_pin = 27
# Default values
# unit = 'metric'
# temperature = 20
# round_to = 1
# Create a distance reading with the hcsr04 sensor module
# and overide ... | Calculate the distance of an object in inches using a HCSR04 sensor
and a Raspberry Pi | Below is the the instruction that describes the task:
### Input:
Calculate the distance of an object in inches using a HCSR04 sensor
and a Raspberry Pi
### Response:
def main():
'''Calculate the distance of an object in inches using a HCSR04 sensor
and a Raspberry Pi'''
trig_pin = 17
ech... |
def conv2d(self, filter_size, output_channels, stride=1, padding='SAME', bn=True, activation_fn=tf.nn.relu,
b_value=0.0, s_value=1.0, trainable=True):
"""
2D Convolutional Layer.
:param filter_size: int. assumes square filter
:param output_channels: int
:param stri... | 2D Convolutional Layer.
:param filter_size: int. assumes square filter
:param output_channels: int
:param stride: int
:param padding: 'VALID' or 'SAME'
:param activation_fn: tf.nn function
:param b_value: float
:param s_value: float | Below is the the instruction that describes the task:
### Input:
2D Convolutional Layer.
:param filter_size: int. assumes square filter
:param output_channels: int
:param stride: int
:param padding: 'VALID' or 'SAME'
:param activation_fn: tf.nn function
:param b_value... |
def console_set_default_background(
con: tcod.console.Console, col: Tuple[int, int, int]
) -> None:
"""Change the default background color for a console.
Args:
con (Console): Any Console instance.
col (Union[Tuple[int, int, int], Sequence[int]]):
An (r, g, b) sequence or Color i... | Change the default background color for a console.
Args:
con (Console): Any Console instance.
col (Union[Tuple[int, int, int], Sequence[int]]):
An (r, g, b) sequence or Color instance.
.. deprecated:: 8.5
Use :any:`Console.default_bg` instead. | Below is the the instruction that describes the task:
### Input:
Change the default background color for a console.
Args:
con (Console): Any Console instance.
col (Union[Tuple[int, int, int], Sequence[int]]):
An (r, g, b) sequence or Color instance.
.. deprecated:: 8.5
... |
def from_app(cls, app, environ, buffered=False):
"""Create a new response object from an application output. This
works best if you pass it an application that returns a generator all
the time. Sometimes applications may use the `write()` callable
returned by the `start_response` funct... | Create a new response object from an application output. This
works best if you pass it an application that returns a generator all
the time. Sometimes applications may use the `write()` callable
returned by the `start_response` function. This tries to resolve such
edge cases automati... | Below is the the instruction that describes the task:
### Input:
Create a new response object from an application output. This
works best if you pass it an application that returns a generator all
the time. Sometimes applications may use the `write()` callable
returned by the `start_respon... |
def random_bytes(n):
"""Returns n random bytes generated with given seed
---
tags:
- Dynamic data
parameters:
- in: path
name: n
type: int
produces:
- application/octet-stream
responses:
200:
description: Bytes.
"""
n = min(n, 100 * 1024) ... | Returns n random bytes generated with given seed
---
tags:
- Dynamic data
parameters:
- in: path
name: n
type: int
produces:
- application/octet-stream
responses:
200:
description: Bytes. | Below is the the instruction that describes the task:
### Input:
Returns n random bytes generated with given seed
---
tags:
- Dynamic data
parameters:
- in: path
name: n
type: int
produces:
- application/octet-stream
responses:
200:
description: By... |
def _select_options(pat):
"""returns a list of keys matching `pat`
if pat=="all", returns all registered options
"""
# short-circuit for exact key
if pat in _registered_options:
return [pat]
# else look through all of them
keys = sorted(_registered_options.keys())
if pat == 'a... | returns a list of keys matching `pat`
if pat=="all", returns all registered options | Below is the the instruction that describes the task:
### Input:
returns a list of keys matching `pat`
if pat=="all", returns all registered options
### Response:
def _select_options(pat):
"""returns a list of keys matching `pat`
if pat=="all", returns all registered options
"""
# short-circ... |
def byaxis_out(self):
"""Object to index along output dimensions.
This is only valid for non-trivial `out_shape`.
Examples
--------
Indexing with integers or slices:
>>> domain = odl.IntervalProd(0, 1)
>>> fspace = odl.FunctionSpace(domain, out_dtype=(float, (2... | Object to index along output dimensions.
This is only valid for non-trivial `out_shape`.
Examples
--------
Indexing with integers or slices:
>>> domain = odl.IntervalProd(0, 1)
>>> fspace = odl.FunctionSpace(domain, out_dtype=(float, (2, 3, 4)))
>>> fspace.byax... | Below is the the instruction that describes the task:
### Input:
Object to index along output dimensions.
This is only valid for non-trivial `out_shape`.
Examples
--------
Indexing with integers or slices:
>>> domain = odl.IntervalProd(0, 1)
>>> fspace = odl.Functi... |
def url_input(url_string, download=True):
"""
This method expects a direct URL link to an xml file. It will apply no
modifications to the received URL string, so ensure good input.
"""
log.debug('URL Input - {0}'.format(url_string))
try:
open_xml = urllib.request.urlopen(url_string)
... | This method expects a direct URL link to an xml file. It will apply no
modifications to the received URL string, so ensure good input. | Below is the the instruction that describes the task:
### Input:
This method expects a direct URL link to an xml file. It will apply no
modifications to the received URL string, so ensure good input.
### Response:
def url_input(url_string, download=True):
"""
This method expects a direct URL link to an... |
def _parse_float_vec(vec):
"""
Parse a vector of float values representing IBM 8 byte floats into
native 8 byte floats.
"""
dtype = np.dtype('>u4,>u4')
vec1 = vec.view(dtype=dtype)
xport1 = vec1['f0']
xport2 = vec1['f1']
# Start by setting first half of ieee number to first half of... | Parse a vector of float values representing IBM 8 byte floats into
native 8 byte floats. | Below is the the instruction that describes the task:
### Input:
Parse a vector of float values representing IBM 8 byte floats into
native 8 byte floats.
### Response:
def _parse_float_vec(vec):
"""
Parse a vector of float values representing IBM 8 byte floats into
native 8 byte floats.
"""
... |
def read_int(self):
"""
Reads an integer. The size depends on the architecture.
Reads a 4 byte small-endian singed int on 32 bit arch
Reads an 8 byte small-endian singed int on 64 bit arch
"""
if self.reader.sysinfo.ProcessorArchitecture == PROCESSOR_ARCHITECTURE.AMD64:
return int.from_bytes(self.read(8... | Reads an integer. The size depends on the architecture.
Reads a 4 byte small-endian singed int on 32 bit arch
Reads an 8 byte small-endian singed int on 64 bit arch | Below is the the instruction that describes the task:
### Input:
Reads an integer. The size depends on the architecture.
Reads a 4 byte small-endian singed int on 32 bit arch
Reads an 8 byte small-endian singed int on 64 bit arch
### Response:
def read_int(self):
"""
Reads an integer. The size depends on ... |
def find_parameter(self, name):
"""Find parameter by name or normalized arg name."""
name = self.normalize_name(name)
arg = self.args.get(name)
return None if arg is None else arg.parameter | Find parameter by name or normalized arg name. | Below is the the instruction that describes the task:
### Input:
Find parameter by name or normalized arg name.
### Response:
def find_parameter(self, name):
"""Find parameter by name or normalized arg name."""
name = self.normalize_name(name)
arg = self.args.get(name)
return None i... |
def getdomain(self):
"""Get the complete domain name from an address."""
sdlist = []
while self.pos < len(self.field):
if self.field[self.pos] in self.LWS:
self.pos += 1
elif self.field[self.pos] == '(':
self.commentlist.append(self.getcomm... | Get the complete domain name from an address. | Below is the the instruction that describes the task:
### Input:
Get the complete domain name from an address.
### Response:
def getdomain(self):
"""Get the complete domain name from an address."""
sdlist = []
while self.pos < len(self.field):
if self.field[self.pos] in self.LWS... |
def real_main(new_url=None,
baseline_url=None,
upload_build_id=None,
upload_release_name=None):
"""Runs the ur_pair_diff."""
coordinator = workers.get_coordinator()
fetch_worker.register(coordinator)
coordinator.start()
item = UrlPairDiff(
new_url,
... | Runs the ur_pair_diff. | Below is the the instruction that describes the task:
### Input:
Runs the ur_pair_diff.
### Response:
def real_main(new_url=None,
baseline_url=None,
upload_build_id=None,
upload_release_name=None):
"""Runs the ur_pair_diff."""
coordinator = workers.get_coordinator(... |
def NRM(f,a,b,best):
WARN = True # Warn, rather than stop if I encounter a NaN...
"""
Calculate NRM expected lab field and estimated ancient field
NRM(blab,best)= (best/blab)*TRM(blab)
"""
if float(f)==0:
print('ERROR: NRM: f==0.')
if not WARN : sys.exit()
m = (old_div(float(... | Calculate NRM expected lab field and estimated ancient field
NRM(blab,best)= (best/blab)*TRM(blab) | Below is the the instruction that describes the task:
### Input:
Calculate NRM expected lab field and estimated ancient field
NRM(blab,best)= (best/blab)*TRM(blab)
### Response:
def NRM(f,a,b,best):
WARN = True # Warn, rather than stop if I encounter a NaN...
"""
Calculate NRM expected lab fiel... |
def get_channels(self):
"""Get the selected channel(s in order). """
selectedItems = self.idx_chan.selectedItems()
selected_chan = [x.text() for x in selectedItems]
chan_in_order = []
for chan in self.chan:
if chan in selected_chan:
chan_in_order.appen... | Get the selected channel(s in order). | Below is the the instruction that describes the task:
### Input:
Get the selected channel(s in order).
### Response:
def get_channels(self):
"""Get the selected channel(s in order). """
selectedItems = self.idx_chan.selectedItems()
selected_chan = [x.text() for x in selectedItems]
c... |
def get_coh_PTF_files(cp, ifos, run_dir, bank_veto=False, summary_files=False):
"""
Retrieve files needed to run coh_PTF jobs within a PyGRB workflow
Parameters
----------
cp : pycbc.workflow.configuration.WorkflowConfigParser object
The parsed configuration options of a pycbc.workflow.core.Wor... | Retrieve files needed to run coh_PTF jobs within a PyGRB workflow
Parameters
----------
cp : pycbc.workflow.configuration.WorkflowConfigParser object
The parsed configuration options of a pycbc.workflow.core.Workflow.
ifos : str
String containing the analysis interferometer IDs.
run_dir :... | Below is the the instruction that describes the task:
### Input:
Retrieve files needed to run coh_PTF jobs within a PyGRB workflow
Parameters
----------
cp : pycbc.workflow.configuration.WorkflowConfigParser object
The parsed configuration options of a pycbc.workflow.core.Workflow.
ifos : str
... |
def _expire_data(self):
"""
Remove all expired entries.
"""
expire_time_stamp = time.time() - self.expire_time
self.timed_data = {d: t for d, t in self.timed_data.items()
if t > expire_time_stamp} | Remove all expired entries. | Below is the the instruction that describes the task:
### Input:
Remove all expired entries.
### Response:
def _expire_data(self):
"""
Remove all expired entries.
"""
expire_time_stamp = time.time() - self.expire_time
self.timed_data = {d: t for d, t in self.timed_data.it... |
def checkForSpiceError(f):
"""
Internal function to check
:param f:
:raise stypes.SpiceyError:
"""
if failed():
errorparts = {
"tkvsn": tkvrsn("TOOLKIT").replace("CSPICE_", ""),
"short": getmsg("SHORT", 26),
"explain": getmsg("EXPLAIN", 100).strip(),
... | Internal function to check
:param f:
:raise stypes.SpiceyError: | Below is the the instruction that describes the task:
### Input:
Internal function to check
:param f:
:raise stypes.SpiceyError:
### Response:
def checkForSpiceError(f):
"""
Internal function to check
:param f:
:raise stypes.SpiceyError:
"""
if failed():
errorparts = {
... |
def basic_consume(self, queue='', consumer_tag='', no_local=False,
no_ack=False, exclusive=False, nowait=False,
callback=None, ticket=None):
"""
start a queue consumer
This method asks the server to start a "consumer", which is a
transient request for messages from a spe... | start a queue consumer
This method asks the server to start a "consumer", which is a
transient request for messages from a specific queue.
Consumers last as long as the channel they were created on, or
until the client cancels them.
RULE:
The server SHOULD support ... | Below is the the instruction that describes the task:
### Input:
start a queue consumer
This method asks the server to start a "consumer", which is a
transient request for messages from a specific queue.
Consumers last as long as the channel they were created on, or
until the client... |
def do_imports(self):
"""
Import all importable options
"""
self.do_import('worker_class', Worker)
self.do_import('queue_model', self.options.worker_class.queue_model)
self.do_import('error_model', self.options.worker_class.error_model)
self.do_import('callback', ... | Import all importable options | Below is the the instruction that describes the task:
### Input:
Import all importable options
### Response:
def do_imports(self):
"""
Import all importable options
"""
self.do_import('worker_class', Worker)
self.do_import('queue_model', self.options.worker_class.queue_model... |
def rename(self, target):
"""
Rename this path to the given path.
"""
if self._closed:
self._raise_closed()
self._accessor.rename(self, target) | Rename this path to the given path. | Below is the the instruction that describes the task:
### Input:
Rename this path to the given path.
### Response:
def rename(self, target):
"""
Rename this path to the given path.
"""
if self._closed:
self._raise_closed()
self._accessor.rename(self, target) |
def update_credentials(self, key, secret):
''' Update credentials '''
self.access_key = key
self.secret_key = secret | Update credentials | Below is the the instruction that describes the task:
### Input:
Update credentials
### Response:
def update_credentials(self, key, secret):
''' Update credentials '''
self.access_key = key
self.secret_key = secret |
def calculate(self, T, P, zs, ws, method):
r'''Method to calculate thermal conductivity of a liquid mixture at
temperature `T`, pressure `P`, mole fractions `zs` and weight fractions
`ws` with a given method.
This method has no exception handling; see `mixture_property`
for tha... | r'''Method to calculate thermal conductivity of a liquid mixture at
temperature `T`, pressure `P`, mole fractions `zs` and weight fractions
`ws` with a given method.
This method has no exception handling; see `mixture_property`
for that.
Parameters
----------
T... | Below is the the instruction that describes the task:
### Input:
r'''Method to calculate thermal conductivity of a liquid mixture at
temperature `T`, pressure `P`, mole fractions `zs` and weight fractions
`ws` with a given method.
This method has no exception handling; see `mixture_propert... |
def find_visible_elements(driver, selector, by=By.CSS_SELECTOR):
"""
Finds all WebElements that match a selector and are visible.
Similar to webdriver.find_elements.
@Params
driver - the webdriver object (required)
selector - the locator that is used to search the DOM (required)
by - the met... | Finds all WebElements that match a selector and are visible.
Similar to webdriver.find_elements.
@Params
driver - the webdriver object (required)
selector - the locator that is used to search the DOM (required)
by - the method to search for the locator (Default: By.CSS_SELECTOR) | Below is the the instruction that describes the task:
### Input:
Finds all WebElements that match a selector and are visible.
Similar to webdriver.find_elements.
@Params
driver - the webdriver object (required)
selector - the locator that is used to search the DOM (required)
by - the method to s... |
def transformer_moe_base():
"""Set of hyperparameters."""
hparams = common_hparams.basic_params1()
hparams.norm_type = "layer"
hparams.hidden_size = 512
hparams.batch_size = 4096
hparams.max_length = 2001
hparams.max_input_seq_length = 2000
hparams.max_target_seq_length = 2000
hparams.dropout = 0.0
... | Set of hyperparameters. | Below is the the instruction that describes the task:
### Input:
Set of hyperparameters.
### Response:
def transformer_moe_base():
"""Set of hyperparameters."""
hparams = common_hparams.basic_params1()
hparams.norm_type = "layer"
hparams.hidden_size = 512
hparams.batch_size = 4096
hparams.max_length = ... |
def date_factory(value, datatype_cls, validation_level=None):
"""
Creates a :class:`DT <hl7apy.base_datatypes.DT>` object
The value in input must be a string parsable with :meth:`datetime.strptime`.
The date format is chosen according to the length of the value as stated in this table:
+-------+--... | Creates a :class:`DT <hl7apy.base_datatypes.DT>` object
The value in input must be a string parsable with :meth:`datetime.strptime`.
The date format is chosen according to the length of the value as stated in this table:
+-------+-----------+
|Length |Format |
+=======+===========+
|4 ... | Below is the the instruction that describes the task:
### Input:
Creates a :class:`DT <hl7apy.base_datatypes.DT>` object
The value in input must be a string parsable with :meth:`datetime.strptime`.
The date format is chosen according to the length of the value as stated in this table:
+-------+-------... |
def hide_busy(self):
"""Unlock buttons A helper function to indicate processing is done."""
self.progress_bar.hide()
self.parent.pbnNext.setEnabled(True)
self.parent.pbnBack.setEnabled(True)
self.parent.pbnCancel.setEnabled(True)
self.parent.repaint()
disable_busy... | Unlock buttons A helper function to indicate processing is done. | Below is the the instruction that describes the task:
### Input:
Unlock buttons A helper function to indicate processing is done.
### Response:
def hide_busy(self):
"""Unlock buttons A helper function to indicate processing is done."""
self.progress_bar.hide()
self.parent.pbnNext.setEnabled... |
def nn_setsockopt(socket, level, option, value):
"""set a socket option
socket - socket number
level - option level
option - option
value - a readable byte buffer (not a Unicode string) containing the value
returns - 0 on success or < 0 on error
"""
try:
return _nn_setsockopt(s... | set a socket option
socket - socket number
level - option level
option - option
value - a readable byte buffer (not a Unicode string) containing the value
returns - 0 on success or < 0 on error | Below is the the instruction that describes the task:
### Input:
set a socket option
socket - socket number
level - option level
option - option
value - a readable byte buffer (not a Unicode string) containing the value
returns - 0 on success or < 0 on error
### Response:
def nn_setsockopt(soc... |
def __get_securities(self, currency: str, agent: str, symbol: str,
namespace: str) -> List[dal.Security]:
""" Fetches the securities that match the given filters """
repo = self.get_security_repository()
query = repo.query
if currency is not None:
qu... | Fetches the securities that match the given filters | Below is the the instruction that describes the task:
### Input:
Fetches the securities that match the given filters
### Response:
def __get_securities(self, currency: str, agent: str, symbol: str,
namespace: str) -> List[dal.Security]:
""" Fetches the securities that match the giv... |
def workflow(ctx, client):
"""List or manage workflows with subcommands."""
if ctx.invoked_subcommand is None:
from renku.models.refs import LinkReference
names = defaultdict(list)
for ref in LinkReference.iter_items(client, common_path='workflows'):
names[ref.reference.name... | List or manage workflows with subcommands. | Below is the the instruction that describes the task:
### Input:
List or manage workflows with subcommands.
### Response:
def workflow(ctx, client):
"""List or manage workflows with subcommands."""
if ctx.invoked_subcommand is None:
from renku.models.refs import LinkReference
names = defau... |
def main():
""" Start the DQL client. """
parse = argparse.ArgumentParser(description=main.__doc__)
parse.add_argument("-c", "--command", help="Run this command and exit")
region = os.environ.get("AWS_REGION", "us-west-1")
parse.add_argument(
"-r",
"--region",
default=region,... | Start the DQL client. | Below is the the instruction that describes the task:
### Input:
Start the DQL client.
### Response:
def main():
""" Start the DQL client. """
parse = argparse.ArgumentParser(description=main.__doc__)
parse.add_argument("-c", "--command", help="Run this command and exit")
region = os.environ.get("A... |
def _sin_to_angle(result, deriv, side=1):
"""Convert a sine and its derivatives to an angle and its derivatives"""
v = np.arcsin(np.clip(result[0], -1, 1))
sign = side
if sign == -1:
if v < 0:
offset = -np.pi
else:
offset = np.pi
else:
offset = 0.0
... | Convert a sine and its derivatives to an angle and its derivatives | Below is the the instruction that describes the task:
### Input:
Convert a sine and its derivatives to an angle and its derivatives
### Response:
def _sin_to_angle(result, deriv, side=1):
"""Convert a sine and its derivatives to an angle and its derivatives"""
v = np.arcsin(np.clip(result[0], -1, 1))
s... |
def validate_wavetable(self):
"""Enforce monotonic, ascending wavelength array with no zero or
negative values.
Raises
------
pysynphot.exceptions.DuplicateWavelength
Wavelength array contains duplicate entries.
pysynphot.exceptions.UnsortedWavelength
... | Enforce monotonic, ascending wavelength array with no zero or
negative values.
Raises
------
pysynphot.exceptions.DuplicateWavelength
Wavelength array contains duplicate entries.
pysynphot.exceptions.UnsortedWavelength
Wavelength array is not monotonic a... | Below is the the instruction that describes the task:
### Input:
Enforce monotonic, ascending wavelength array with no zero or
negative values.
Raises
------
pysynphot.exceptions.DuplicateWavelength
Wavelength array contains duplicate entries.
pysynphot.exceptio... |
def target_doc(self):
"""Returns resource doc as at the target, when the posting was already created \
at the target. This property normally contains the **target_doc** data from \
the livebrigde storage item, saved in a syndication earlier.
:returns: dict"""
if not hasatt... | Returns resource doc as at the target, when the posting was already created \
at the target. This property normally contains the **target_doc** data from \
the livebrigde storage item, saved in a syndication earlier.
:returns: dict | Below is the the instruction that describes the task:
### Input:
Returns resource doc as at the target, when the posting was already created \
at the target. This property normally contains the **target_doc** data from \
the livebrigde storage item, saved in a syndication earlier.
:re... |
def add_node(self, node):
"""Link the agent to a random member of the previous generation."""
nodes = [n for n in self.nodes() if not isinstance(n, Source)]
num_agents = len(nodes)
curr_generation = int((num_agents - 1) / float(self.generation_size))
node.generation = curr_genera... | Link the agent to a random member of the previous generation. | Below is the the instruction that describes the task:
### Input:
Link the agent to a random member of the previous generation.
### Response:
def add_node(self, node):
"""Link the agent to a random member of the previous generation."""
nodes = [n for n in self.nodes() if not isinstance(n, Source)]
... |
def _send_live_report(self, report_id):
"""Sends a PUT request with the report JSON files currently in the
report_queue attribute.
Parameters
----------
report_id : str
Hash of the report JSON as retrieved from :func:`~_get_report_hash`
"""
# Determi... | Sends a PUT request with the report JSON files currently in the
report_queue attribute.
Parameters
----------
report_id : str
Hash of the report JSON as retrieved from :func:`~_get_report_hash` | Below is the the instruction that describes the task:
### Input:
Sends a PUT request with the report JSON files currently in the
report_queue attribute.
Parameters
----------
report_id : str
Hash of the report JSON as retrieved from :func:`~_get_report_hash`
### Response... |
def manual_invoice(cls, user, due_delta, description_price_pairs):
''' Generates an invoice for arbitrary items, not held in a user's
cart.
Arguments:
user (User): The user the invoice is being generated for.
due_delta (datetime.timedelta): The length until the invoice i... | Generates an invoice for arbitrary items, not held in a user's
cart.
Arguments:
user (User): The user the invoice is being generated for.
due_delta (datetime.timedelta): The length until the invoice is
due.
description_price_pairs ([(str, long or Deci... | Below is the the instruction that describes the task:
### Input:
Generates an invoice for arbitrary items, not held in a user's
cart.
Arguments:
user (User): The user the invoice is being generated for.
due_delta (datetime.timedelta): The length until the invoice is
... |
def is_varchar(self):
"""Determine if a data record is of the type VARCHAR."""
dt = DATA_TYPES['varchar']
if type(self.data) is dt['type'] and len(self.data) < dt['max']:
self.type = 'VARCHAR'
self.len = len(self.data)
return True | Determine if a data record is of the type VARCHAR. | Below is the the instruction that describes the task:
### Input:
Determine if a data record is of the type VARCHAR.
### Response:
def is_varchar(self):
"""Determine if a data record is of the type VARCHAR."""
dt = DATA_TYPES['varchar']
if type(self.data) is dt['type'] and len(self.data) < d... |
def dateAt(self, x):
"""
Returns the date at the inputed x position.
:return <QDate>
"""
gantt = self.ganttWidget()
dstart = gantt.dateStart()
days = int(x / float(gantt.cellWidth()))
return dstart.addDays(... | Returns the date at the inputed x position.
:return <QDate> | Below is the the instruction that describes the task:
### Input:
Returns the date at the inputed x position.
:return <QDate>
### Response:
def dateAt(self, x):
"""
Returns the date at the inputed x position.
:return <QDate>
"""
gantt... |
def begin_y(self):
"""
Return the Y-position of the begin point of this connector, in
English Metric Units (as a |Length| object).
"""
cxnSp = self._element
y, cy, flipV = cxnSp.y, cxnSp.cy, cxnSp.flipV
begin_y = y+cy if flipV else y
return Emu(begin_y) | Return the Y-position of the begin point of this connector, in
English Metric Units (as a |Length| object). | Below is the the instruction that describes the task:
### Input:
Return the Y-position of the begin point of this connector, in
English Metric Units (as a |Length| object).
### Response:
def begin_y(self):
"""
Return the Y-position of the begin point of this connector, in
English Me... |
def drawdaisy(x, y, color='#fefefe'):
"""
Draw a daisy at x, y
"""
# save location, size etc
_ctx.push()
# save fill and stroke
_fill =_ctx.fill()
_stroke = _ctx.stroke()
sc = (1.0 / _ctx.HEIGHT) * float(y * 0.5) * 4.0
# draw stalk
_ctx.strokewidth(sc * 2.0)
_ctx.s... | Draw a daisy at x, y | Below is the the instruction that describes the task:
### Input:
Draw a daisy at x, y
### Response:
def drawdaisy(x, y, color='#fefefe'):
"""
Draw a daisy at x, y
"""
# save location, size etc
_ctx.push()
# save fill and stroke
_fill =_ctx.fill()
_stroke = _ctx.stroke()
sc... |
def list2pd(all_data, subjindex=None, listindex=None):
"""
Makes multi-indexed dataframe of subject data
Parameters
----------
all_data : list of lists of strings
strings are either all presented or all recalled items, in the order of presentation or recall
*should also work for pre... | Makes multi-indexed dataframe of subject data
Parameters
----------
all_data : list of lists of strings
strings are either all presented or all recalled items, in the order of presentation or recall
*should also work for presented / recalled ints and floats, if desired
Returns
---... | Below is the the instruction that describes the task:
### Input:
Makes multi-indexed dataframe of subject data
Parameters
----------
all_data : list of lists of strings
strings are either all presented or all recalled items, in the order of presentation or recall
*should also work for p... |
def set_values(self,x):
""" Updates self.theta parameter. No returns values"""
x = numpy.atleast_2d(x)
x = x.real # ahem
C_inv = self.__C_inv__
theta = numpy.dot( x, C_inv )
self.theta = theta
return theta | Updates self.theta parameter. No returns values | Below is the the instruction that describes the task:
### Input:
Updates self.theta parameter. No returns values
### Response:
def set_values(self,x):
""" Updates self.theta parameter. No returns values"""
x = numpy.atleast_2d(x)
x = x.real # ahem
C_inv = self.__C_inv__
t... |
def dependency_map(self):
r"""
Create a graph of the dependency graph in a decent format
See Also
--------
dependency_graph
dependency_list
"""
dtree = self.dependency_graph()
fig = nx.draw_spectral(dtree,
with_labe... | r"""
Create a graph of the dependency graph in a decent format
See Also
--------
dependency_graph
dependency_list | Below is the the instruction that describes the task:
### Input:
r"""
Create a graph of the dependency graph in a decent format
See Also
--------
dependency_graph
dependency_list
### Response:
def dependency_map(self):
r"""
Create a graph of the dependency g... |
def strict(*types):
"""Decorator, type check production rule output"""
def decorate(func):
@wraps(func)
def wrapper(self, p):
func(self, p)
if not isinstance(p[0], types):
raise YAMLStrictTypeError(p[0], types, func)
wrapper.co_firstlineno = func... | Decorator, type check production rule output | Below is the the instruction that describes the task:
### Input:
Decorator, type check production rule output
### Response:
def strict(*types):
"""Decorator, type check production rule output"""
def decorate(func):
@wraps(func)
def wrapper(self, p):
func(self, p)
if... |
def register(cls, config_type: Type[DecoderConfig], suffix: str):
"""
Registers decoder type for configuration. Suffix is appended to decoder prefix.
:param config_type: Configuration type for decoder.
:param suffix: String to append to decoder prefix.
:return: Class decorator.... | Registers decoder type for configuration. Suffix is appended to decoder prefix.
:param config_type: Configuration type for decoder.
:param suffix: String to append to decoder prefix.
:return: Class decorator. | Below is the the instruction that describes the task:
### Input:
Registers decoder type for configuration. Suffix is appended to decoder prefix.
:param config_type: Configuration type for decoder.
:param suffix: String to append to decoder prefix.
:return: Class decorator.
### Response:
d... |
def inverse(self):
"""
Retrieves the inverse of a G1 element.
"""
result = G1Element()
librelic.g1_neg_abi(byref(result), byref(self))
return result | Retrieves the inverse of a G1 element. | Below is the the instruction that describes the task:
### Input:
Retrieves the inverse of a G1 element.
### Response:
def inverse(self):
"""
Retrieves the inverse of a G1 element.
"""
result = G1Element()
librelic.g1_neg_abi(byref(result), byref(self))
return result |
def settings_view_decorator(function):
"""Insert decorator from settings, if any.
.. note:: Decorator in ``CLOUD_BROWSER_VIEW_DECORATOR`` can be either a
callable or a fully-qualified string path (the latter, which we'll
lazy import).
"""
dec = settings.CLOUD_BROWSER_VIEW_DECORATOR
... | Insert decorator from settings, if any.
.. note:: Decorator in ``CLOUD_BROWSER_VIEW_DECORATOR`` can be either a
callable or a fully-qualified string path (the latter, which we'll
lazy import). | Below is the the instruction that describes the task:
### Input:
Insert decorator from settings, if any.
.. note:: Decorator in ``CLOUD_BROWSER_VIEW_DECORATOR`` can be either a
callable or a fully-qualified string path (the latter, which we'll
lazy import).
### Response:
def settings_view_deco... |
def block_events(self):
"""
Special version of block_events that loops over all tree elements.
"""
# block events in the usual way
BaseObject.block_events(self)
# loop over all top level parameters
for i in range(self._widget.topLevelItemCount()):
... | Special version of block_events that loops over all tree elements. | Below is the the instruction that describes the task:
### Input:
Special version of block_events that loops over all tree elements.
### Response:
def block_events(self):
"""
Special version of block_events that loops over all tree elements.
"""
# block events in the usual way
... |
def get_parameter_diff(awsclient, config):
"""get differences between local config and currently active config
"""
client_cf = awsclient.get_client('cloudformation')
try:
stack_name = config['stack']['StackName']
if stack_name:
response = client_cf.describe_stacks(StackName=s... | get differences between local config and currently active config | Below is the the instruction that describes the task:
### Input:
get differences between local config and currently active config
### Response:
def get_parameter_diff(awsclient, config):
"""get differences between local config and currently active config
"""
client_cf = awsclient.get_client('cloudforma... |
def raw(self, module, method='GET', data=None):
'''
Submits or requsts raw input
'''
request = self.session
url = 'http://%s:%s/%s' % (self.host, self.port, module)
if self.verbose:
print data
if method=='GET':
response = request.get(url)
... | Submits or requsts raw input | Below is the the instruction that describes the task:
### Input:
Submits or requsts raw input
### Response:
def raw(self, module, method='GET', data=None):
'''
Submits or requsts raw input
'''
request = self.session
url = 'http://%s:%s/%s' % (self.host, self.port, module)
... |
def save_datasets(self, writer="geotiff", datasets=None, compute=True, **kwargs):
"""Save all the datasets present in a scene to disk using *writer*."""
if datasets is not None:
datasets = [self[ds] for ds in datasets]
else:
datasets = [self.datasets.get(ds) for ds in sel... | Save all the datasets present in a scene to disk using *writer*. | Below is the the instruction that describes the task:
### Input:
Save all the datasets present in a scene to disk using *writer*.
### Response:
def save_datasets(self, writer="geotiff", datasets=None, compute=True, **kwargs):
"""Save all the datasets present in a scene to disk using *writer*."""
if... |
def has_permission(self, request, *args, **kwargs):
"""
Figures out if the current user has permissions for this view.
"""
self.kwargs = kwargs
self.args = args
self.request = request
self.org = self.derive_org()
if self.get_user().is_superuser:
... | Figures out if the current user has permissions for this view. | Below is the the instruction that describes the task:
### Input:
Figures out if the current user has permissions for this view.
### Response:
def has_permission(self, request, *args, **kwargs):
"""
Figures out if the current user has permissions for this view.
"""
self.kwargs = kwar... |
def CheckCronJobAccess(self, username, cron_job_id):
"""Checks whether a given user can access given cron job."""
self._CheckAccess(
username, str(cron_job_id),
rdf_objects.ApprovalRequest.ApprovalType.APPROVAL_TYPE_CRON_JOB) | Checks whether a given user can access given cron job. | Below is the the instruction that describes the task:
### Input:
Checks whether a given user can access given cron job.
### Response:
def CheckCronJobAccess(self, username, cron_job_id):
"""Checks whether a given user can access given cron job."""
self._CheckAccess(
username, str(cron_job_id),
... |
def estimate_mutual_information(x, y):
"""Estimate the mutual information of two datasets.
Mutual information is a measure of dependence between
two datasets and is calculated as:
$I(x;y) = H(x) + H(y) - H(x,y)$
Where H(x) is the Shannon entropy of x. For continuous datasets,
adapts the K... | Estimate the mutual information of two datasets.
Mutual information is a measure of dependence between
two datasets and is calculated as:
$I(x;y) = H(x) + H(y) - H(x,y)$
Where H(x) is the Shannon entropy of x. For continuous datasets,
adapts the Kraskov Estimator [1] for mutual information.
... | Below is the the instruction that describes the task:
### Input:
Estimate the mutual information of two datasets.
Mutual information is a measure of dependence between
two datasets and is calculated as:
$I(x;y) = H(x) + H(y) - H(x,y)$
Where H(x) is the Shannon entropy of x. For continuous dat... |
def ximshow_unrectified(self, slitlet2d):
"""Display unrectified image with spectrails and frontiers.
Parameters
----------
slitlet2d : numpy array
Array containing the unrectified slitlet image.
"""
title = "Slitlet#" + str(self.islitlet)
ax = xims... | Display unrectified image with spectrails and frontiers.
Parameters
----------
slitlet2d : numpy array
Array containing the unrectified slitlet image. | Below is the the instruction that describes the task:
### Input:
Display unrectified image with spectrails and frontiers.
Parameters
----------
slitlet2d : numpy array
Array containing the unrectified slitlet image.
### Response:
def ximshow_unrectified(self, slitlet2d):
... |
def _projection(self, a, b, c):
"""Return projection of (a,b) onto (a,c)
Arguments are point locations, not indexes.
"""
ab = b - a
ac = c - a
return a + ((ab*ac).sum() / (ac*ac).sum()) * ac | Return projection of (a,b) onto (a,c)
Arguments are point locations, not indexes. | Below is the the instruction that describes the task:
### Input:
Return projection of (a,b) onto (a,c)
Arguments are point locations, not indexes.
### Response:
def _projection(self, a, b, c):
"""Return projection of (a,b) onto (a,c)
Arguments are point locations, not indexes.
"""
... |
def convert_table(self, markup):
""" Subtitutes <table> content to Wikipedia markup.
"""
for table in re.findall(self.re["html-table"], markup):
wiki = table
wiki = re.sub(r"<table(.*?)>", "{|\\1", wiki)
wiki = re.sub(r"<tr(.*?)>", "|-\\1", w... | Subtitutes <table> content to Wikipedia markup. | Below is the the instruction that describes the task:
### Input:
Subtitutes <table> content to Wikipedia markup.
### Response:
def convert_table(self, markup):
""" Subtitutes <table> content to Wikipedia markup.
"""
for table in re.findall(self.re["html-table"], markup):
... |
def _from_dict(self, obj_dict):
"""
Initialize a model from the dictionary
"""
self._n_folds = obj_dict["param"]["n_folds"]
self._n_rows = obj_dict["param"]["n_rows"]
self._use_stored_folds = obj_dict["param"]["use_stored_folds"]
self._concise_model = Concise.fro... | Initialize a model from the dictionary | Below is the the instruction that describes the task:
### Input:
Initialize a model from the dictionary
### Response:
def _from_dict(self, obj_dict):
"""
Initialize a model from the dictionary
"""
self._n_folds = obj_dict["param"]["n_folds"]
self._n_rows = obj_dict["param"][... |
def layers(self, rev=True):
"""
Get list of DockerImage for every layer in image
:param rev: get layers rev
:return: list of DockerImages
"""
image_layers = [
DockerImage(None, identifier=x, pull_policy=DockerImagePullPolicy.NEVER)
for x in self.g... | Get list of DockerImage for every layer in image
:param rev: get layers rev
:return: list of DockerImages | Below is the the instruction that describes the task:
### Input:
Get list of DockerImage for every layer in image
:param rev: get layers rev
:return: list of DockerImages
### Response:
def layers(self, rev=True):
"""
Get list of DockerImage for every layer in image
:param ... |
def marker_for_line(self, line):
"""
Returns the marker that is displayed at the specified line number if
any.
:param line: The marker line.
:return: Marker of None
:rtype: pyqode.core.Marker
"""
markers = []
for marker in self._markers:
... | Returns the marker that is displayed at the specified line number if
any.
:param line: The marker line.
:return: Marker of None
:rtype: pyqode.core.Marker | Below is the the instruction that describes the task:
### Input:
Returns the marker that is displayed at the specified line number if
any.
:param line: The marker line.
:return: Marker of None
:rtype: pyqode.core.Marker
### Response:
def marker_for_line(self, line):
"""
... |
def push_results(self, results, scheduler_name):
"""Send a HTTP request to the satellite (POST /put_results)
Send actions results to the satellite
:param results: Results list to send
:type results: list
:param scheduler_name: Scheduler name
:type scheduler_name: uuid
... | Send a HTTP request to the satellite (POST /put_results)
Send actions results to the satellite
:param results: Results list to send
:type results: list
:param scheduler_name: Scheduler name
:type scheduler_name: uuid
:return: True on success, False on failure
:rt... | Below is the the instruction that describes the task:
### Input:
Send a HTTP request to the satellite (POST /put_results)
Send actions results to the satellite
:param results: Results list to send
:type results: list
:param scheduler_name: Scheduler name
:type scheduler_name... |
def output_path(self, path_name):
""" Modify a path so it fits expectations.
Avoid returning relative paths that start with '../' and possibly
return relative paths when output and cache directories match.
"""
# make sure it is a valid posix format
... | Modify a path so it fits expectations.
Avoid returning relative paths that start with '../' and possibly
return relative paths when output and cache directories match. | Below is the the instruction that describes the task:
### Input:
Modify a path so it fits expectations.
Avoid returning relative paths that start with '../' and possibly
return relative paths when output and cache directories match.
### Response:
def output_path(self, path_name):
... |
def _get_admin_info(command, host=None, core_name=None):
'''
PRIVATE METHOD
Calls the _http_request method and passes the admin command to execute
and stores the data. This data is fairly static but should be refreshed
periodically to make sure everything this OK. The data object will contain
th... | PRIVATE METHOD
Calls the _http_request method and passes the admin command to execute
and stores the data. This data is fairly static but should be refreshed
periodically to make sure everything this OK. The data object will contain
the JSON response.
command : str
The admin command to exec... | Below is the the instruction that describes the task:
### Input:
PRIVATE METHOD
Calls the _http_request method and passes the admin command to execute
and stores the data. This data is fairly static but should be refreshed
periodically to make sure everything this OK. The data object will contain
th... |
def verifyArguments(self, arg):
"""
Verifies that arguments to setInputs and setTargets are appropriately formatted.
"""
for l in arg:
if not type(l) == list and \
not type(l) == type(Numeric.array([0.0])) and \
not type(l) == tuple and \
... | Verifies that arguments to setInputs and setTargets are appropriately formatted. | Below is the the instruction that describes the task:
### Input:
Verifies that arguments to setInputs and setTargets are appropriately formatted.
### Response:
def verifyArguments(self, arg):
"""
Verifies that arguments to setInputs and setTargets are appropriately formatted.
"""
fo... |
def capabilities(self, keyword=None):
"""CAPABILITIES command.
Determines the capabilities of the server.
Although RFC3977 states that this is a required command for servers to
implement not all servers do, so expect that NNTPPermanentError may be
raised when this command is is... | CAPABILITIES command.
Determines the capabilities of the server.
Although RFC3977 states that this is a required command for servers to
implement not all servers do, so expect that NNTPPermanentError may be
raised when this command is issued.
See <http://tools.ietf.org/html/rf... | Below is the the instruction that describes the task:
### Input:
CAPABILITIES command.
Determines the capabilities of the server.
Although RFC3977 states that this is a required command for servers to
implement not all servers do, so expect that NNTPPermanentError may be
raised whe... |
def _loadedges(self) -> typing.Tuple[np.ndarray, np.ndarray, np.ndarray, float, np.ndarray]:
"""
Attempts to intelligently load the .mat file and take average of left and right edges
:return: left and right averages
:return: times for each column
:return: accept/reject for each ... | Attempts to intelligently load the .mat file and take average of left and right edges
:return: left and right averages
:return: times for each column
:return: accept/reject for each column
:return: pixel-inch ratio | Below is the the instruction that describes the task:
### Input:
Attempts to intelligently load the .mat file and take average of left and right edges
:return: left and right averages
:return: times for each column
:return: accept/reject for each column
:return: pixel-inch ratio
###... |
def pause(message='Press any key to continue . . . '):
"""
Prints the specified message if it's not None and waits for a keypress.
"""
if message is not None:
print(message, end='')
sys.stdout.flush()
getch()
print() | Prints the specified message if it's not None and waits for a keypress. | Below is the the instruction that describes the task:
### Input:
Prints the specified message if it's not None and waits for a keypress.
### Response:
def pause(message='Press any key to continue . . . '):
"""
Prints the specified message if it's not None and waits for a keypress.
"""
if message is... |
def colormesh(X, Y):
"""
Generates line paths for a quadmesh given 2D arrays of X and Y
coordinates.
"""
X1 = X[0:-1, 0:-1].ravel()
Y1 = Y[0:-1, 0:-1].ravel()
X2 = X[1:, 0:-1].ravel()
Y2 = Y[1:, 0:-1].ravel()
X3 = X[1:, 1:].ravel()
Y3 = Y[1:, 1:].ravel()
X4 = X[0:-1, 1:].rave... | Generates line paths for a quadmesh given 2D arrays of X and Y
coordinates. | Below is the the instruction that describes the task:
### Input:
Generates line paths for a quadmesh given 2D arrays of X and Y
coordinates.
### Response:
def colormesh(X, Y):
"""
Generates line paths for a quadmesh given 2D arrays of X and Y
coordinates.
"""
X1 = X[0:-1, 0:-1].ravel()
... |
def get_item_notification_session(self, item_receiver):
"""Gets the notification session for notifications pertaining to item changes.
arg: item_receiver (osid.assessment.ItemReceiver): the item
receiver interface
return: (osid.assessment.ItemNotificationSession) - an
... | Gets the notification session for notifications pertaining to item changes.
arg: item_receiver (osid.assessment.ItemReceiver): the item
receiver interface
return: (osid.assessment.ItemNotificationSession) - an
``ItemNotificationSession``
raise: NullArgument -... | Below is the the instruction that describes the task:
### Input:
Gets the notification session for notifications pertaining to item changes.
arg: item_receiver (osid.assessment.ItemReceiver): the item
receiver interface
return: (osid.assessment.ItemNotificationSession) - an
... |
def parse_host_address(addr):
"""
parse host address to get domain name or ipv4/v6 address,
cidr prefix and net mask code string if given a subnet address
:param addr:
:type addr: str
:return: parsed domain name/ipv4 address/ipv6 address,
cidr prefix if there is,
net m... | parse host address to get domain name or ipv4/v6 address,
cidr prefix and net mask code string if given a subnet address
:param addr:
:type addr: str
:return: parsed domain name/ipv4 address/ipv6 address,
cidr prefix if there is,
net mask code string if there is
:rtype: (s... | Below is the the instruction that describes the task:
### Input:
parse host address to get domain name or ipv4/v6 address,
cidr prefix and net mask code string if given a subnet address
:param addr:
:type addr: str
:return: parsed domain name/ipv4 address/ipv6 address,
cidr prefix if t... |
def get_volumes_for_container(self, container_id, skip_empty_source=True):
"""
get a list of volumes mounter in a container
:param container_id: str
:param skip_empty_source: bool, don't list volumes which are not created on FS
:return: list, a list of volume names
"""
... | get a list of volumes mounter in a container
:param container_id: str
:param skip_empty_source: bool, don't list volumes which are not created on FS
:return: list, a list of volume names | Below is the the instruction that describes the task:
### Input:
get a list of volumes mounter in a container
:param container_id: str
:param skip_empty_source: bool, don't list volumes which are not created on FS
:return: list, a list of volume names
### Response:
def get_volumes_for_cont... |
def get_context_data(self, **kwargs):
"""This add in the context of list_type and returns this as Alive."""
context = super(AnimalListAlive, self).get_context_data(**kwargs)
context['list_type'] = 'Alive'
return context | This add in the context of list_type and returns this as Alive. | Below is the the instruction that describes the task:
### Input:
This add in the context of list_type and returns this as Alive.
### Response:
def get_context_data(self, **kwargs):
"""This add in the context of list_type and returns this as Alive."""
context = super(AnimalListAlive, self).... |
def _convert_to_db_tc_metadata(tc_metadata):
"""
Convert tc_metadata to match Opentmi metadata format
:param tc_metadata: metadata as dict
:return: converted metadata
"""
db_meta = copy.deepcopy(tc_metadata)
# tcid is a mandatory field, it should throw an error i... | Convert tc_metadata to match Opentmi metadata format
:param tc_metadata: metadata as dict
:return: converted metadata | Below is the the instruction that describes the task:
### Input:
Convert tc_metadata to match Opentmi metadata format
:param tc_metadata: metadata as dict
:return: converted metadata
### Response:
def _convert_to_db_tc_metadata(tc_metadata):
"""
Convert tc_metadata to match Opentmi ... |
def token(self, id, **kwargs):
"""
Retrieve a service request ID from a token.
>>> Three('api.city.gov').token('12345')
{'service_request_id': {'for': {'token': '12345'}}}
"""
data = self.get('tokens', id, **kwargs)
return data | Retrieve a service request ID from a token.
>>> Three('api.city.gov').token('12345')
{'service_request_id': {'for': {'token': '12345'}}} | Below is the the instruction that describes the task:
### Input:
Retrieve a service request ID from a token.
>>> Three('api.city.gov').token('12345')
{'service_request_id': {'for': {'token': '12345'}}}
### Response:
def token(self, id, **kwargs):
"""
Retrieve a service request ID f... |
def set_engine(cls, neweng):
''' Sets the given coralillo engine so the model uses it to communicate
with the redis database '''
assert isinstance(neweng, Engine), 'Provided object must be of class Engine'
if hasattr(cls, 'Meta'):
cls.Meta.engine = neweng
else:
... | Sets the given coralillo engine so the model uses it to communicate
with the redis database | Below is the the instruction that describes the task:
### Input:
Sets the given coralillo engine so the model uses it to communicate
with the redis database
### Response:
def set_engine(cls, neweng):
''' Sets the given coralillo engine so the model uses it to communicate
with the redis data... |
def _request(self, method, url, **kwargs):
# type: (str, str, **Any) -> requests.Response
"""Perform the request on the API."""
self.last_request = None
self.last_response = self.session.request(method, url, auth=self.auth, headers=self.headers, **kwargs)
self.last_request = self... | Perform the request on the API. | Below is the the instruction that describes the task:
### Input:
Perform the request on the API.
### Response:
def _request(self, method, url, **kwargs):
# type: (str, str, **Any) -> requests.Response
"""Perform the request on the API."""
self.last_request = None
self.last_response ... |
def fit(self,y_true_cal=None, y_prob_cal=None):
""" If calibration, then train the calibration of probabilities
Parameters
----------
y_true_cal : array-like of shape = [n_samples], optional default = None
True class to be used for calibrating the probabilities
y_pr... | If calibration, then train the calibration of probabilities
Parameters
----------
y_true_cal : array-like of shape = [n_samples], optional default = None
True class to be used for calibrating the probabilities
y_prob_cal : array-like of shape = [n_samples, 2], optional defa... | Below is the the instruction that describes the task:
### Input:
If calibration, then train the calibration of probabilities
Parameters
----------
y_true_cal : array-like of shape = [n_samples], optional default = None
True class to be used for calibrating the probabilities
... |
def upgrade(name=None,
pkgs=None,
**kwargs):
'''
Run a full package upgrade (``pkg_add -u``), or upgrade a specific package
if ``name`` or ``pkgs`` is provided.
``name`` is ignored when ``pkgs`` is specified.
Returns a dictionary containing the changes:
.. versionadded:... | Run a full package upgrade (``pkg_add -u``), or upgrade a specific package
if ``name`` or ``pkgs`` is provided.
``name`` is ignored when ``pkgs`` is specified.
Returns a dictionary containing the changes:
.. versionadded:: 2019.2.0
.. code-block:: python
{'<package>': {'old': '<old-versi... | Below is the the instruction that describes the task:
### Input:
Run a full package upgrade (``pkg_add -u``), or upgrade a specific package
if ``name`` or ``pkgs`` is provided.
``name`` is ignored when ``pkgs`` is specified.
Returns a dictionary containing the changes:
.. versionadded:: 2019.2.0
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.