code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def remove_comments_and_docstrings(source):
"""
Returns *source* minus comments and docstrings.
.. note:: Uses Python's built-in tokenize module to great effect.
Example::
def noop(): # This is a comment
'''
Does nothing.
'''
pass # Don't do any... | Returns *source* minus comments and docstrings.
.. note:: Uses Python's built-in tokenize module to great effect.
Example::
def noop(): # This is a comment
'''
Does nothing.
'''
pass # Don't do anything
Will become::
def noop():
... | Below is the the instruction that describes the task:
### Input:
Returns *source* minus comments and docstrings.
.. note:: Uses Python's built-in tokenize module to great effect.
Example::
def noop(): # This is a comment
'''
Does nothing.
'''
pass #... |
def _ref(self, param, base_name=None):
"""
Store a parameter schema and return a reference to it.
:param schema:
Swagger parameter definition.
:param base_name:
Name that should be used for the reference.
:rtype: dict
:returns: JSON pointer to th... | Store a parameter schema and return a reference to it.
:param schema:
Swagger parameter definition.
:param base_name:
Name that should be used for the reference.
:rtype: dict
:returns: JSON pointer to the original parameter definition. | Below is the the instruction that describes the task:
### Input:
Store a parameter schema and return a reference to it.
:param schema:
Swagger parameter definition.
:param base_name:
Name that should be used for the reference.
:rtype: dict
:returns: JSON poi... |
def byte_to_bitstring(byte):
"""Convert one byte to a list of bits"""
assert 0 <= byte <= 0xff
bits = [int(x) for x in list(bin(byte + 0x100)[3:])]
return bits | Convert one byte to a list of bits | Below is the the instruction that describes the task:
### Input:
Convert one byte to a list of bits
### Response:
def byte_to_bitstring(byte):
"""Convert one byte to a list of bits"""
assert 0 <= byte <= 0xff
bits = [int(x) for x in list(bin(byte + 0x100)[3:])]
return bits |
def select_star_cb(self, widget, res_dict):
"""This method is called when the user selects a star from the table.
"""
keys = list(res_dict.keys())
if len(keys) == 0:
self.selected = []
self.replot_stars()
else:
idx = int(keys[0])
st... | This method is called when the user selects a star from the table. | Below is the the instruction that describes the task:
### Input:
This method is called when the user selects a star from the table.
### Response:
def select_star_cb(self, widget, res_dict):
"""This method is called when the user selects a star from the table.
"""
keys = list(res_dict.keys()... |
def get_factory_bundle(self, name):
# type: (str) -> Bundle
"""
Retrieves the Pelix Bundle object that registered the given factory
:param name: The name of a factory
:return: The Bundle that registered the given factory
:raise ValueError: Invalid factory
"""
... | Retrieves the Pelix Bundle object that registered the given factory
:param name: The name of a factory
:return: The Bundle that registered the given factory
:raise ValueError: Invalid factory | Below is the the instruction that describes the task:
### Input:
Retrieves the Pelix Bundle object that registered the given factory
:param name: The name of a factory
:return: The Bundle that registered the given factory
:raise ValueError: Invalid factory
### Response:
def get_factory_bun... |
def _combine_variants(in_vcfs, out_file, ref_file, config):
"""Combine variant files, writing the header from the first non-empty input.
in_vcfs is a list with each item starting with the chromosome regions,
and ending with the input file.
We sort by these regions to ensure the output file is in the ex... | Combine variant files, writing the header from the first non-empty input.
in_vcfs is a list with each item starting with the chromosome regions,
and ending with the input file.
We sort by these regions to ensure the output file is in the expected order. | Below is the the instruction that describes the task:
### Input:
Combine variant files, writing the header from the first non-empty input.
in_vcfs is a list with each item starting with the chromosome regions,
and ending with the input file.
We sort by these regions to ensure the output file is in the ... |
def print_treemap(self, format=None, output=sys.stdout, **kwargs):
"""
Print the matrix for self's nodes.
Args:
format (str): output format (csv, json or text).
output (file): file descriptor on which to write.
"""
treemap = self.as_treemap()
tree... | Print the matrix for self's nodes.
Args:
format (str): output format (csv, json or text).
output (file): file descriptor on which to write. | Below is the the instruction that describes the task:
### Input:
Print the matrix for self's nodes.
Args:
format (str): output format (csv, json or text).
output (file): file descriptor on which to write.
### Response:
def print_treemap(self, format=None, output=sys.stdout, **kwarg... |
def build(self, X, Y, w=None, edges=None):
""" Assigns data to this object and builds the Morse-Smale
Complex
@ In, X, an m-by-n array of values specifying m
n-dimensional samples
@ In, Y, a m vector of values specifying the output
responses correspond... | Assigns data to this object and builds the Morse-Smale
Complex
@ In, X, an m-by-n array of values specifying m
n-dimensional samples
@ In, Y, a m vector of values specifying the output
responses corresponding to the m samples specified by X
@ In, w... | Below is the the instruction that describes the task:
### Input:
Assigns data to this object and builds the Morse-Smale
Complex
@ In, X, an m-by-n array of values specifying m
n-dimensional samples
@ In, Y, a m vector of values specifying the output
respon... |
def set_policy(name, table='filter', family='ipv4', **kwargs):
'''
.. versionadded:: 2014.1.0
Sets the default policy for iptables firewall tables
table
The table that owns the chain that should be modified
family
Networking family, either ipv4 or ipv6
policy
The requ... | .. versionadded:: 2014.1.0
Sets the default policy for iptables firewall tables
table
The table that owns the chain that should be modified
family
Networking family, either ipv4 or ipv6
policy
The requested table policy | Below is the the instruction that describes the task:
### Input:
.. versionadded:: 2014.1.0
Sets the default policy for iptables firewall tables
table
The table that owns the chain that should be modified
family
Networking family, either ipv4 or ipv6
policy
The requested ... |
def get_children_to_delete(self):
"""Return all children that are not referenced
:returns: list or :class:`Reftrack`
:rtype: list
:raises: None
"""
refobjinter = self.get_refobjinter()
children = self.get_all_children()
todelete = []
for c in chi... | Return all children that are not referenced
:returns: list or :class:`Reftrack`
:rtype: list
:raises: None | Below is the the instruction that describes the task:
### Input:
Return all children that are not referenced
:returns: list or :class:`Reftrack`
:rtype: list
:raises: None
### Response:
def get_children_to_delete(self):
"""Return all children that are not referenced
:retur... |
def get_path(self, tile):
"""
Determine target file path.
Parameters
----------
tile : ``BufferedTile``
must be member of output ``TilePyramid``
Returns
-------
path : string
"""
return os.path.join(*[
self.path,
... | Determine target file path.
Parameters
----------
tile : ``BufferedTile``
must be member of output ``TilePyramid``
Returns
-------
path : string | Below is the the instruction that describes the task:
### Input:
Determine target file path.
Parameters
----------
tile : ``BufferedTile``
must be member of output ``TilePyramid``
Returns
-------
path : string
### Response:
def get_path(self, tile):
... |
def flipcheck(content):
"""Checks a string for anger and soothes said anger
Args:
content (str): The message to be flipchecked
Returns:
putitback (str): The righted table or text
"""
# Prevent tampering with flip
punct = """!"#$%&'*+,-./:;<=>?@[\]^_`{|}~ ━─"""
tamperdict =... | Checks a string for anger and soothes said anger
Args:
content (str): The message to be flipchecked
Returns:
putitback (str): The righted table or text | Below is the the instruction that describes the task:
### Input:
Checks a string for anger and soothes said anger
Args:
content (str): The message to be flipchecked
Returns:
putitback (str): The righted table or text
### Response:
def flipcheck(content):
"""Checks a string for anger a... |
def setup_sort_column(widget, column=0, attribute=None, model=None):
"""
*model* is the :class:`TreeModelSort` to act on. Defaults to what is
displayed. Pass this if you sort before filtering.
*widget* is a clickable :class:`TreeViewColumn`.
*column* is an integer addressing the column in *model* ... | *model* is the :class:`TreeModelSort` to act on. Defaults to what is
displayed. Pass this if you sort before filtering.
*widget* is a clickable :class:`TreeViewColumn`.
*column* is an integer addressing the column in *model* that holds your
objects.
*attribute* is a string naming an object attrib... | Below is the the instruction that describes the task:
### Input:
*model* is the :class:`TreeModelSort` to act on. Defaults to what is
displayed. Pass this if you sort before filtering.
*widget* is a clickable :class:`TreeViewColumn`.
*column* is an integer addressing the column in *model* that holds y... |
def hist2array(hist, include_overflow=False, copy=True, return_edges=False):
"""Convert a ROOT histogram into a NumPy array
Parameters
----------
hist : ROOT TH1, TH2, TH3, THn, or THnSparse
The ROOT histogram to convert into an array
include_overflow : bool, optional (default=False)
... | Convert a ROOT histogram into a NumPy array
Parameters
----------
hist : ROOT TH1, TH2, TH3, THn, or THnSparse
The ROOT histogram to convert into an array
include_overflow : bool, optional (default=False)
If True, the over- and underflow bins will be included in the
output numpy... | Below is the the instruction that describes the task:
### Input:
Convert a ROOT histogram into a NumPy array
Parameters
----------
hist : ROOT TH1, TH2, TH3, THn, or THnSparse
The ROOT histogram to convert into an array
include_overflow : bool, optional (default=False)
If True, the ... |
def load_header_chain( cls, chain_path ):
"""
Load the header chain from disk.
Each chain element will be a dictionary with:
*
"""
header_parser = BlockHeaderSerializer()
chain = []
height = 0
with open(chain_path, "rb") as f:
h = SP... | Load the header chain from disk.
Each chain element will be a dictionary with:
* | Below is the the instruction that describes the task:
### Input:
Load the header chain from disk.
Each chain element will be a dictionary with:
*
### Response:
def load_header_chain( cls, chain_path ):
"""
Load the header chain from disk.
Each chain element will be a diction... |
def validate_linux_host_name(namespace):
"""Validates a string as a legal host name component.
This validation will also occur server-side in the ARM API, but that may take
a minute or two before the user sees it. So it's more user-friendly to validate
in the CLI pre-flight.
"""
# https://stack... | Validates a string as a legal host name component.
This validation will also occur server-side in the ARM API, but that may take
a minute or two before the user sees it. So it's more user-friendly to validate
in the CLI pre-flight. | Below is the the instruction that describes the task:
### Input:
Validates a string as a legal host name component.
This validation will also occur server-side in the ARM API, but that may take
a minute or two before the user sees it. So it's more user-friendly to validate
in the CLI pre-flight.
### Re... |
def Logs(loggername, echo=True, debug=False, chatty=False, loglevel=logging.INFO, logfile=None, logpath=None, fileHandler=None):
"""Initialize logging
"""
log = logging.getLogger(loggername)
if fileHandler is None:
if logfile is None:
logFilename = _ourName
else:
... | Initialize logging | Below is the the instruction that describes the task:
### Input:
Initialize logging
### Response:
def Logs(loggername, echo=True, debug=False, chatty=False, loglevel=logging.INFO, logfile=None, logpath=None, fileHandler=None):
"""Initialize logging
"""
log = logging.getLogger(loggername)
if fileHa... |
def find_spelling(n):
"""
Finds d, r s.t. n-1 = 2^r * d
"""
r = 0
d = n - 1
# divmod used for large numbers
quotient, remainder = divmod(d, 2)
# while we can still divide 2's into n-1...
while remainder != 1:
r += 1
d = quotient # previous quotient before ... | Finds d, r s.t. n-1 = 2^r * d | Below is the the instruction that describes the task:
### Input:
Finds d, r s.t. n-1 = 2^r * d
### Response:
def find_spelling(n):
"""
Finds d, r s.t. n-1 = 2^r * d
"""
r = 0
d = n - 1
# divmod used for large numbers
quotient, remainder = divmod(d, 2)
# while we can still di... |
def removeJob(self, jobBatchSystemID):
"""Removes a job from the system."""
assert jobBatchSystemID in self.jobBatchSystemIDToIssuedJob
jobNode = self.jobBatchSystemIDToIssuedJob[jobBatchSystemID]
if jobNode.preemptable:
# len(jobBatchSystemIDToIssuedJob) should always be gre... | Removes a job from the system. | Below is the the instruction that describes the task:
### Input:
Removes a job from the system.
### Response:
def removeJob(self, jobBatchSystemID):
"""Removes a job from the system."""
assert jobBatchSystemID in self.jobBatchSystemIDToIssuedJob
jobNode = self.jobBatchSystemIDToIssuedJob[jo... |
def analysis(self):
"""The list of analysis of ``words`` layer elements."""
if not self.is_tagged(ANALYSIS):
self.tag_analysis()
return [word[ANALYSIS] for word in self.words] | The list of analysis of ``words`` layer elements. | Below is the the instruction that describes the task:
### Input:
The list of analysis of ``words`` layer elements.
### Response:
def analysis(self):
"""The list of analysis of ``words`` layer elements."""
if not self.is_tagged(ANALYSIS):
self.tag_analysis()
return [word[ANALYSIS... |
def chromiumContext(self, url, extra_tid=None):
'''
Return a active chromium context, useable for manual operations directly against
chromium.
The WebRequest user agent and other context is synchronized into the chromium
instance at startup, and changes are flushed back to the webrequest instance
from chro... | Return a active chromium context, useable for manual operations directly against
chromium.
The WebRequest user agent and other context is synchronized into the chromium
instance at startup, and changes are flushed back to the webrequest instance
from chromium at completion. | Below is the the instruction that describes the task:
### Input:
Return a active chromium context, useable for manual operations directly against
chromium.
The WebRequest user agent and other context is synchronized into the chromium
instance at startup, and changes are flushed back to the webrequest instanc... |
def parse_analyzer_arguments(arguments):
"""
Parse string in format `function_1:param1=value:param2 function_2:param` into array of FunctionArguments
"""
rets = []
for argument in arguments:
args = argument.split(argument_splitter)
# The first one is the function name
func... | Parse string in format `function_1:param1=value:param2 function_2:param` into array of FunctionArguments | Below is the the instruction that describes the task:
### Input:
Parse string in format `function_1:param1=value:param2 function_2:param` into array of FunctionArguments
### Response:
def parse_analyzer_arguments(arguments):
"""
Parse string in format `function_1:param1=value:param2 function_2:param` into ... |
def regenerate_models(self, propnames=None, exclude=[], deep=False):
r"""
Re-runs the specified model or models.
Parameters
----------
propnames : string or list of strings
The list of property names to be regenerated. If None are given
then ALL models a... | r"""
Re-runs the specified model or models.
Parameters
----------
propnames : string or list of strings
The list of property names to be regenerated. If None are given
then ALL models are re-run (except for those whose ``regen_mode``
is 'constant').
... | Below is the the instruction that describes the task:
### Input:
r"""
Re-runs the specified model or models.
Parameters
----------
propnames : string or list of strings
The list of property names to be regenerated. If None are given
then ALL models are re-ru... |
def _update_similarity_view(self):
"""Update the similarity view with matches for the specified
clusters."""
if not self.similarity:
return
selection = self.cluster_view.selected
if not len(selection):
return
cluster_id = selection[0]
clust... | Update the similarity view with matches for the specified
clusters. | Below is the the instruction that describes the task:
### Input:
Update the similarity view with matches for the specified
clusters.
### Response:
def _update_similarity_view(self):
"""Update the similarity view with matches for the specified
clusters."""
if not self.similarity:
... |
def _update_lock_icon(self):
"""Update locked state icon"""
icon = ima.icon('lock') if self.locked else ima.icon('lock_open')
self.locked_button.setIcon(icon)
tip = _("Unlock") if self.locked else _("Lock")
self.locked_button.setToolTip(tip) | Update locked state icon | Below is the the instruction that describes the task:
### Input:
Update locked state icon
### Response:
def _update_lock_icon(self):
"""Update locked state icon"""
icon = ima.icon('lock') if self.locked else ima.icon('lock_open')
self.locked_button.setIcon(icon)
tip = _("Unlock"... |
def bind_events(self, events):
'''Register all known events found in ``events`` key-valued parameters.
'''
evs = self._events
if evs and events:
for event in evs.values():
if event.name in events:
event.bind(events[event.name]) | Register all known events found in ``events`` key-valued parameters. | Below is the the instruction that describes the task:
### Input:
Register all known events found in ``events`` key-valued parameters.
### Response:
def bind_events(self, events):
'''Register all known events found in ``events`` key-valued parameters.
'''
evs = self._events
if evs an... |
def generate_mediation_matrix(dsm):
"""
Generate the mediation matrix of the given matrix.
Rules for mediation matrix generation:
Set -1 for items NOT to be considered
Set 0 for items which MUST NOT be present
Set 1 for items which MUST be present
Each module h... | Generate the mediation matrix of the given matrix.
Rules for mediation matrix generation:
Set -1 for items NOT to be considered
Set 0 for items which MUST NOT be present
Set 1 for items which MUST be present
Each module has optional dependencies to itself.
- Framework... | Below is the the instruction that describes the task:
### Input:
Generate the mediation matrix of the given matrix.
Rules for mediation matrix generation:
Set -1 for items NOT to be considered
Set 0 for items which MUST NOT be present
Set 1 for items which MUST be present
... |
def remove_capability(capability, image=None, restart=False):
'''
Uninstall a capability
Args:
capability(str): The capability to be removed
image (Optional[str]): The path to the root directory of an offline
Windows image. If `None` is passed, the running operating system is
... | Uninstall a capability
Args:
capability(str): The capability to be removed
image (Optional[str]): The path to the root directory of an offline
Windows image. If `None` is passed, the running operating system is
targeted. Default is None.
restart (Optional[bool]): Reb... | Below is the the instruction that describes the task:
### Input:
Uninstall a capability
Args:
capability(str): The capability to be removed
image (Optional[str]): The path to the root directory of an offline
Windows image. If `None` is passed, the running operating system is
... |
def xf2rav(xform):
"""
This routine determines the rotation matrix and angular velocity
of the rotation from a state transformation matrix.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/xf2rav_c.html
:param xform: state transformation matrix
:type xform: list[6][6]
:return:
... | This routine determines the rotation matrix and angular velocity
of the rotation from a state transformation matrix.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/xf2rav_c.html
:param xform: state transformation matrix
:type xform: list[6][6]
:return:
rotation associated with... | Below is the the instruction that describes the task:
### Input:
This routine determines the rotation matrix and angular velocity
of the rotation from a state transformation matrix.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/xf2rav_c.html
:param xform: state transformation matrix
:typ... |
def deserialize(cls, cls_target, obj_raw):
"""
:type cls_target: T|type
:type obj_raw: int|str|bool|float|list|dict|None
:rtype: T
"""
cls._initialize()
deserializer = cls._get_deserializer(cls_target)
if deserializer == cls:
return cls._des... | :type cls_target: T|type
:type obj_raw: int|str|bool|float|list|dict|None
:rtype: T | Below is the the instruction that describes the task:
### Input:
:type cls_target: T|type
:type obj_raw: int|str|bool|float|list|dict|None
:rtype: T
### Response:
def deserialize(cls, cls_target, obj_raw):
"""
:type cls_target: T|type
:type obj_raw: int|str|bool|float|list|... |
def construct_exc_class(cls):
"""Constructs proxy class for the exception."""
class ProxyException(cls, BaseException):
__pep3134__ = True
@property
def __traceback__(self):
if self.__fixed_traceback__:
return self.__fixed_traceback__
current_ex... | Constructs proxy class for the exception. | Below is the the instruction that describes the task:
### Input:
Constructs proxy class for the exception.
### Response:
def construct_exc_class(cls):
"""Constructs proxy class for the exception."""
class ProxyException(cls, BaseException):
__pep3134__ = True
@property
def __trace... |
def ColorfullyWrite(log: str, consoleColor: int = -1, writeToFile: bool = True, printToStdout: bool = True, logFile: str = None) -> None:
"""
log: str.
consoleColor: int, a value in class `ConsoleColor`, such as `ConsoleColor.DarkGreen`.
writeToFile: bool.
printToStdout: bool.
... | log: str.
consoleColor: int, a value in class `ConsoleColor`, such as `ConsoleColor.DarkGreen`.
writeToFile: bool.
printToStdout: bool.
logFile: str, log file path.
ColorfullyWrite('Hello <Color=Green>Green</Color> !!!'), color name must be in Logger.ColorNames. | Below is the the instruction that describes the task:
### Input:
log: str.
consoleColor: int, a value in class `ConsoleColor`, such as `ConsoleColor.DarkGreen`.
writeToFile: bool.
printToStdout: bool.
logFile: str, log file path.
ColorfullyWrite('Hello <Color=Green>Green</Col... |
def _post(self, url, data={}):
"""Wrapper around request.post() to use the API prefix. Returns a JSON response."""
r = requests.post(self._api_prefix + url,
data=json.dumps(data),
headers=self.headers,
auth=self.auth,
allow_redirects=False,
)
... | Wrapper around request.post() to use the API prefix. Returns a JSON response. | Below is the the instruction that describes the task:
### Input:
Wrapper around request.post() to use the API prefix. Returns a JSON response.
### Response:
def _post(self, url, data={}):
"""Wrapper around request.post() to use the API prefix. Returns a JSON response."""
r = requests.post(self._api... |
def Audio(self, run, tag):
"""Retrieve the audio events associated with a run and tag.
Args:
run: A string name of the run for which values are retrieved.
tag: A string name of the tag for which values are retrieved.
Raises:
KeyError: If the run is not found, or the tag is not available ... | Retrieve the audio events associated with a run and tag.
Args:
run: A string name of the run for which values are retrieved.
tag: A string name of the tag for which values are retrieved.
Raises:
KeyError: If the run is not found, or the tag is not available for
the given run.
Re... | Below is the the instruction that describes the task:
### Input:
Retrieve the audio events associated with a run and tag.
Args:
run: A string name of the run for which values are retrieved.
tag: A string name of the tag for which values are retrieved.
Raises:
KeyError: If the run is not ... |
def send_notification(self, user, sender=None, **kwargs):
"""
An intermediary function for sending an notification email informing
a pre-existing, active user that they have been added to a new
organization.
"""
if not user.is_active:
return False
self... | An intermediary function for sending an notification email informing
a pre-existing, active user that they have been added to a new
organization. | Below is the the instruction that describes the task:
### Input:
An intermediary function for sending an notification email informing
a pre-existing, active user that they have been added to a new
organization.
### Response:
def send_notification(self, user, sender=None, **kwargs):
"""
... |
def run(ctx, service, args, show_args, daemon, editable, integration):
"""Load and run a specific service."""
home = ctx.obj["HOME"]
service_path = plugin_utils.get_plugin_path(home, SERVICES, service, editable)
service_log_path = os.path.join(service_path, LOGS_DIR)
logger.debug("running command %... | Load and run a specific service. | Below is the the instruction that describes the task:
### Input:
Load and run a specific service.
### Response:
def run(ctx, service, args, show_args, daemon, editable, integration):
"""Load and run a specific service."""
home = ctx.obj["HOME"]
service_path = plugin_utils.get_plugin_path(home, SERVICES... |
def nacm_rule_list_rule_rule_type_notification_notification_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
nacm = ET.SubElement(config, "nacm", xmlns="urn:ietf:params:xml:ns:yang:ietf-netconf-acm")
rule_list = ET.SubElement(nacm, "rule-list")
... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def nacm_rule_list_rule_rule_type_notification_notification_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
nacm = ET.SubElement(config, "nacm", xmlns="u... |
def RV_timeseries(self,ts,recalc=False):
"""
Radial Velocity time series for star 1 at given times ts.
:param ts:
Times. If not ``Quantity``, assumed to be in days.
:type ts:
array-like or ``Quantity``
:param recalc: (optional)
If ``False``,... | Radial Velocity time series for star 1 at given times ts.
:param ts:
Times. If not ``Quantity``, assumed to be in days.
:type ts:
array-like or ``Quantity``
:param recalc: (optional)
If ``False``, then if called with the exact same ``ts``
as las... | Below is the the instruction that describes the task:
### Input:
Radial Velocity time series for star 1 at given times ts.
:param ts:
Times. If not ``Quantity``, assumed to be in days.
:type ts:
array-like or ``Quantity``
:param recalc: (optional)
If ``... |
def blurring_grid_from_mask_and_psf_shape(cls, mask, psf_shape):
"""Setup a blurring-grid from a mask, where a blurring grid consists of all pixels that are masked, but they \
are close enough to the unmasked pixels that a fraction of their light will be blurred into those pixels \
via PSF convo... | Setup a blurring-grid from a mask, where a blurring grid consists of all pixels that are masked, but they \
are close enough to the unmasked pixels that a fraction of their light will be blurred into those pixels \
via PSF convolution. For example, if our mask is as follows:
|x|x|x|x|x|... | Below is the the instruction that describes the task:
### Input:
Setup a blurring-grid from a mask, where a blurring grid consists of all pixels that are masked, but they \
are close enough to the unmasked pixels that a fraction of their light will be blurred into those pixels \
via PSF convolution.... |
def trial_end(self, trial_job_id, success):
"""trial_end
Parameters
----------
trial_job_id: int
trial job id
success: bool
True if succssfully finish the experiment, False otherwise
"""
if trial_job_id in self.running_history:
... | trial_end
Parameters
----------
trial_job_id: int
trial job id
success: bool
True if succssfully finish the experiment, False otherwise | Below is the the instruction that describes the task:
### Input:
trial_end
Parameters
----------
trial_job_id: int
trial job id
success: bool
True if succssfully finish the experiment, False otherwise
### Response:
def trial_end(self, trial_job_id, s... |
def load(self):
"""Load from a file and return an x509 object"""
private = self.is_private()
with open_tls_file(self.file_path, 'r', private=private) as fh:
if private:
self.x509 = crypto.load_privatekey(self.encoding, fh.read())
else:
sel... | Load from a file and return an x509 object | Below is the the instruction that describes the task:
### Input:
Load from a file and return an x509 object
### Response:
def load(self):
"""Load from a file and return an x509 object"""
private = self.is_private()
with open_tls_file(self.file_path, 'r', private=private) as fh:
... |
def update_editor(self):
"""
updates the logger and plot on the interpretation editor window
"""
self.fit_list = []
self.search_choices = []
for specimen in self.specimens_list:
if specimen not in self.parent.pmag_results_data['specimens']: continue
... | updates the logger and plot on the interpretation editor window | Below is the the instruction that describes the task:
### Input:
updates the logger and plot on the interpretation editor window
### Response:
def update_editor(self):
"""
updates the logger and plot on the interpretation editor window
"""
self.fit_list = []
self.search_cho... |
def getWorkingCollisionBoundsInfo(self):
"""
Returns the number of Quads if the buffer points to null. Otherwise it returns Quads
into the buffer up to the max specified from the working copy.
"""
fn = self.function_table.getWorkingCollisionBoundsInfo
pQuadsBuffer = Hmd... | Returns the number of Quads if the buffer points to null. Otherwise it returns Quads
into the buffer up to the max specified from the working copy. | Below is the the instruction that describes the task:
### Input:
Returns the number of Quads if the buffer points to null. Otherwise it returns Quads
into the buffer up to the max specified from the working copy.
### Response:
def getWorkingCollisionBoundsInfo(self):
"""
Returns the number... |
def action(self):
"""
This class overrides this method
"""
commandline = "{0} {1}".format(self.command, " ".join(self.arguments))
try:
completed_process = subprocess.run(commandline, shell=True)
self.exit_status = completed_process.returncode
excep... | This class overrides this method | Below is the the instruction that describes the task:
### Input:
This class overrides this method
### Response:
def action(self):
"""
This class overrides this method
"""
commandline = "{0} {1}".format(self.command, " ".join(self.arguments))
try:
completed_proces... |
def confirmations(self, txn_or_pmt):
"""
Returns the number of confirmations for given
:class:`Transaction <monero.transaction.Transaction>` or
:class:`Payment <monero.transaction.Payment>` object.
:rtype: int
"""
if isinstance(txn_or_pmt, Payment):
t... | Returns the number of confirmations for given
:class:`Transaction <monero.transaction.Transaction>` or
:class:`Payment <monero.transaction.Payment>` object.
:rtype: int | Below is the the instruction that describes the task:
### Input:
Returns the number of confirmations for given
:class:`Transaction <monero.transaction.Transaction>` or
:class:`Payment <monero.transaction.Payment>` object.
:rtype: int
### Response:
def confirmations(self, txn_or_pmt):
... |
def unstage_signature(vcs, signature):
"""Remove `signature` from the list of staged signatures
Args:
vcs (easyci.vcs.base.Vcs)
signature (basestring)
Raises:
NotStagedError
"""
evidence_path = _get_staged_history_path(vcs)
staged = get_staged_signatures(vcs)
if sig... | Remove `signature` from the list of staged signatures
Args:
vcs (easyci.vcs.base.Vcs)
signature (basestring)
Raises:
NotStagedError | Below is the the instruction that describes the task:
### Input:
Remove `signature` from the list of staged signatures
Args:
vcs (easyci.vcs.base.Vcs)
signature (basestring)
Raises:
NotStagedError
### Response:
def unstage_signature(vcs, signature):
"""Remove `signature` from ... |
def _precheck(self, curtailment_timeseries, feedin_df, curtailment_key):
"""
Raises an error if the curtailment at any time step exceeds the
total feed-in of all generators curtailment can be distributed among
at that time.
Parameters
-----------
curtailment_time... | Raises an error if the curtailment at any time step exceeds the
total feed-in of all generators curtailment can be distributed among
at that time.
Parameters
-----------
curtailment_timeseries : :pandas:`pandas.Series<series>`
Curtailment time series in kW for the te... | Below is the the instruction that describes the task:
### Input:
Raises an error if the curtailment at any time step exceeds the
total feed-in of all generators curtailment can be distributed among
at that time.
Parameters
-----------
curtailment_timeseries : :pandas:`pandas... |
def parse(text: str) -> Docstring:
"""
Parse the Google-style docstring into its components.
:returns: parsed docstring
"""
ret = Docstring()
if not text:
return ret
# Clean according to PEP-0257
text = inspect.cleandoc(text)
# Find first title and split on its position
... | Parse the Google-style docstring into its components.
:returns: parsed docstring | Below is the the instruction that describes the task:
### Input:
Parse the Google-style docstring into its components.
:returns: parsed docstring
### Response:
def parse(text: str) -> Docstring:
"""
Parse the Google-style docstring into its components.
:returns: parsed docstring
"""
ret =... |
def create_token(self,
token_name,
project_name,
dataset_name,
is_public):
"""
Creates a token with the given parameters.
Arguments:
project_name (str): Project name
dataset_name (str): Da... | Creates a token with the given parameters.
Arguments:
project_name (str): Project name
dataset_name (str): Dataset name project is based on
token_name (str): Token name
is_public (int): 1 is public. 0 is not public
Returns:
bool: True if projec... | Below is the the instruction that describes the task:
### Input:
Creates a token with the given parameters.
Arguments:
project_name (str): Project name
dataset_name (str): Dataset name project is based on
token_name (str): Token name
is_public (int): 1 is publ... |
def K(self):
"""Normalizing constant for wishart CDF."""
K1 = np.float_power(pi, 0.5 * self.n_min * self.n_min)
K1 /= (
np.float_power(2, 0.5 * self.n_min * self._n_max)
* self._mgamma(0.5 * self._n_max, self.n_min)
* self._mgamma(0.5 * self.n_min, self.n_min)... | Normalizing constant for wishart CDF. | Below is the the instruction that describes the task:
### Input:
Normalizing constant for wishart CDF.
### Response:
def K(self):
"""Normalizing constant for wishart CDF."""
K1 = np.float_power(pi, 0.5 * self.n_min * self.n_min)
K1 /= (
np.float_power(2, 0.5 * self.n_min * self.... |
def to_pfull_from_phalf(arr, pfull_coord):
"""Compute data at full pressure levels from values at half levels."""
phalf_top = arr.isel(**{internal_names.PHALF_STR: slice(1, None)})
phalf_top = replace_coord(phalf_top, internal_names.PHALF_STR,
internal_names.PFULL_STR, pfull_co... | Compute data at full pressure levels from values at half levels. | Below is the the instruction that describes the task:
### Input:
Compute data at full pressure levels from values at half levels.
### Response:
def to_pfull_from_phalf(arr, pfull_coord):
"""Compute data at full pressure levels from values at half levels."""
phalf_top = arr.isel(**{internal_names.PHALF_STR:... |
def compose_view(bg_svgs, fg_svgs, ref=0, out_file='report.svg'):
"""
Composes the input svgs into one standalone svg and inserts
the CSS code for the flickering animation
"""
import svgutils.transform as svgt
if fg_svgs is None:
fg_svgs = []
# Merge SVGs and get roots
svgs = b... | Composes the input svgs into one standalone svg and inserts
the CSS code for the flickering animation | Below is the the instruction that describes the task:
### Input:
Composes the input svgs into one standalone svg and inserts
the CSS code for the flickering animation
### Response:
def compose_view(bg_svgs, fg_svgs, ref=0, out_file='report.svg'):
"""
Composes the input svgs into one standalone svg and ... |
def api_version(created_ver, last_changed_ver, return_value_ver):
"""Version check decorator. Currently only checks Bigger Than."""
def api_min_version_decorator(function):
def wrapper(function, self, *args, **kwargs):
if not self.version_check_mode == "none":
if self.v... | Version check decorator. Currently only checks Bigger Than. | Below is the the instruction that describes the task:
### Input:
Version check decorator. Currently only checks Bigger Than.
### Response:
def api_version(created_ver, last_changed_ver, return_value_ver):
"""Version check decorator. Currently only checks Bigger Than."""
def api_min_version_decorator(functi... |
def BARzero(w_F, w_R, DeltaF):
"""A function that when zeroed is equivalent to the solution of
the Bennett acceptance ratio.
from http://journals.aps.org/prl/pdf/10.1103/PhysRevLett.91.140601
D_F = M + w_F - Delta F
D_R = M + w_R - Delta F
we want:
\sum_N_F (1+exp(D_F))^-1 = \sum N_R N_R <... | A function that when zeroed is equivalent to the solution of
the Bennett acceptance ratio.
from http://journals.aps.org/prl/pdf/10.1103/PhysRevLett.91.140601
D_F = M + w_F - Delta F
D_R = M + w_R - Delta F
we want:
\sum_N_F (1+exp(D_F))^-1 = \sum N_R N_R <(1+exp(-D_R))^-1>
ln \sum N_F (1+e... | Below is the the instruction that describes the task:
### Input:
A function that when zeroed is equivalent to the solution of
the Bennett acceptance ratio.
from http://journals.aps.org/prl/pdf/10.1103/PhysRevLett.91.140601
D_F = M + w_F - Delta F
D_R = M + w_R - Delta F
we want:
\sum_N_F (... |
def _inv_cls(cls):
"""The inverse of this bidict type, i.e. one with *_fwdm_cls* and *_invm_cls* swapped."""
if cls._fwdm_cls is cls._invm_cls:
return cls
if not getattr(cls, '_inv_cls_', None):
class _Inv(cls):
_fwdm_cls = cls._invm_cls
_i... | The inverse of this bidict type, i.e. one with *_fwdm_cls* and *_invm_cls* swapped. | Below is the the instruction that describes the task:
### Input:
The inverse of this bidict type, i.e. one with *_fwdm_cls* and *_invm_cls* swapped.
### Response:
def _inv_cls(cls):
"""The inverse of this bidict type, i.e. one with *_fwdm_cls* and *_invm_cls* swapped."""
if cls._fwdm_cls is cls._in... |
def stop(self, timeout: int = 5) -> None:
"""
Try to stop the transaction store in the given timeout or raise an
exception.
"""
self.running = False
start = time.perf_counter()
while True:
if self.getsCounter == 0:
return True
... | Try to stop the transaction store in the given timeout or raise an
exception. | Below is the the instruction that describes the task:
### Input:
Try to stop the transaction store in the given timeout or raise an
exception.
### Response:
def stop(self, timeout: int = 5) -> None:
"""
Try to stop the transaction store in the given timeout or raise an
exception.
... |
def is_nsphere(points):
"""
Check if a list of points is an nsphere.
Parameters
-----------
points : (n, dimension) float
Points in space
Returns
-----------
check : bool
True if input points are on an nsphere
"""
center, radius, error = fit_nsphere(points)
chec... | Check if a list of points is an nsphere.
Parameters
-----------
points : (n, dimension) float
Points in space
Returns
-----------
check : bool
True if input points are on an nsphere | Below is the the instruction that describes the task:
### Input:
Check if a list of points is an nsphere.
Parameters
-----------
points : (n, dimension) float
Points in space
Returns
-----------
check : bool
True if input points are on an nsphere
### Response:
def is_nsphere(p... |
def spawn_program(self, name, arguments=[], timeout=30, exclusive=False):
"""Spawns a program in the working directory.
This method allows the interaction with the running program,
based on the returned RunningProgram object.
Args:
name (str): The name of the program... | Spawns a program in the working directory.
This method allows the interaction with the running program,
based on the returned RunningProgram object.
Args:
name (str): The name of the program to be executed.
arguments (tuple): Command-line arguments for the progra... | Below is the the instruction that describes the task:
### Input:
Spawns a program in the working directory.
This method allows the interaction with the running program,
based on the returned RunningProgram object.
Args:
name (str): The name of the program to be executed.... |
def posterior_mode(self, observations, name=None):
"""Compute maximum likelihood sequence of hidden states.
When this function is provided with a sequence of observations
`x[0], ..., x[num_steps - 1]`, it returns the sequence of hidden
states `z[0], ..., z[num_steps - 1]`, drawn from the underlying
... | Compute maximum likelihood sequence of hidden states.
When this function is provided with a sequence of observations
`x[0], ..., x[num_steps - 1]`, it returns the sequence of hidden
states `z[0], ..., z[num_steps - 1]`, drawn from the underlying
Markov chain, that is most likely to yield those observat... | Below is the the instruction that describes the task:
### Input:
Compute maximum likelihood sequence of hidden states.
When this function is provided with a sequence of observations
`x[0], ..., x[num_steps - 1]`, it returns the sequence of hidden
states `z[0], ..., z[num_steps - 1]`, drawn from the und... |
def get_ga_client_id(self):
"""
Retrieve the client ID from the Google Analytics cookie, if available,
and save in the current session
"""
request = self.get_ga_request()
if not request or not hasattr(request, 'session'):
return super(GARequestErrorReportingMi... | Retrieve the client ID from the Google Analytics cookie, if available,
and save in the current session | Below is the the instruction that describes the task:
### Input:
Retrieve the client ID from the Google Analytics cookie, if available,
and save in the current session
### Response:
def get_ga_client_id(self):
"""
Retrieve the client ID from the Google Analytics cookie, if available,
... |
def send_messages(self, messages):
"""Send one or more EmailMessage objects.
Returns:
int: Number of email messages sent.
"""
if not messages:
return
new_conn_created = self.open()
if not self.connection:
# We failed silentl... | Send one or more EmailMessage objects.
Returns:
int: Number of email messages sent. | Below is the the instruction that describes the task:
### Input:
Send one or more EmailMessage objects.
Returns:
int: Number of email messages sent.
### Response:
def send_messages(self, messages):
"""Send one or more EmailMessage objects.
Returns:
int: Nu... |
def name_inner_event(cls):
"""Decorator to rename cls.Event 'Event' as 'cls.Event'"""
if hasattr(cls, 'Event'):
cls.Event._event_name = '{}.Event'.format(cls.__name__)
else:
warnings.warn('Class {} does not have a inner Event'.format(cls))
return cls | Decorator to rename cls.Event 'Event' as 'cls.Event | Below is the the instruction that describes the task:
### Input:
Decorator to rename cls.Event 'Event' as 'cls.Event
### Response:
def name_inner_event(cls):
"""Decorator to rename cls.Event 'Event' as 'cls.Event'"""
if hasattr(cls, 'Event'):
cls.Event._event_name = '{}.Event'.format(cls.__name__)
... |
def set(self, instance, value, **kwargs):
"""
Check if value is an actual date/time value. If not, attempt
to convert it to one; otherwise, set to None. Assign all
properties passed as kwargs to object.
"""
val = get_date(instance, value)
super(DateTimeField, self... | Check if value is an actual date/time value. If not, attempt
to convert it to one; otherwise, set to None. Assign all
properties passed as kwargs to object. | Below is the the instruction that describes the task:
### Input:
Check if value is an actual date/time value. If not, attempt
to convert it to one; otherwise, set to None. Assign all
properties passed as kwargs to object.
### Response:
def set(self, instance, value, **kwargs):
"""
C... |
def call(self, file_, mode='r', buffering=-1, encoding=None,
errors=None, newline=None, closefd=True, opener=None,
open_modes=None):
"""Return a file-like object with the contents of the target
file object.
Args:
file_: Path to target file or a file descrip... | Return a file-like object with the contents of the target
file object.
Args:
file_: Path to target file or a file descriptor.
mode: Additional file modes (all modes in `open()` are supported).
buffering: ignored. (Used for signature compliance with
__... | Below is the the instruction that describes the task:
### Input:
Return a file-like object with the contents of the target
file object.
Args:
file_: Path to target file or a file descriptor.
mode: Additional file modes (all modes in `open()` are supported).
buffe... |
def get_and_alter(self, function):
"""
Alters the currently stored value by applying a function on it on and gets the old value.
:param function: (Function), A stateful serializable object which represents the Function defined on
server side.
This object must have a seri... | Alters the currently stored value by applying a function on it on and gets the old value.
:param function: (Function), A stateful serializable object which represents the Function defined on
server side.
This object must have a serializable Function counter part registered on server sid... | Below is the the instruction that describes the task:
### Input:
Alters the currently stored value by applying a function on it on and gets the old value.
:param function: (Function), A stateful serializable object which represents the Function defined on
server side.
This object mu... |
def get_instance(self, payload):
"""
Build an instance of UserBindingInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.chat.v2.service.user.user_binding.UserBindingInstance
:rtype: twilio.rest.chat.v2.service.user.user_binding.UserBindingInstance... | Build an instance of UserBindingInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.chat.v2.service.user.user_binding.UserBindingInstance
:rtype: twilio.rest.chat.v2.service.user.user_binding.UserBindingInstance | Below is the the instruction that describes the task:
### Input:
Build an instance of UserBindingInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.chat.v2.service.user.user_binding.UserBindingInstance
:rtype: twilio.rest.chat.v2.service.user.user_binding.Use... |
def login(self, username, password=None, email=None, registry=None,
reauth=False, dockercfg_path=None):
"""
Authenticate with a registry. Similar to the ``docker login`` command.
Args:
username (str): The registry username
password (str): The plaintext pass... | Authenticate with a registry. Similar to the ``docker login`` command.
Args:
username (str): The registry username
password (str): The plaintext password
email (str): The email for the registry account
registry (str): URL to the registry. E.g.
``... | Below is the the instruction that describes the task:
### Input:
Authenticate with a registry. Similar to the ``docker login`` command.
Args:
username (str): The registry username
password (str): The plaintext password
email (str): The email for the registry account
... |
def extract_exposure_metadata(dstore, what):
"""
Extract the loss categories and the tags of the exposure.
Use it as /extract/exposure_metadata
"""
dic = {}
dic1, dic2 = dstore['assetcol/tagcol'].__toh5__()
dic.update(dic1)
dic.update(dic2)
if 'asset_risk' in dstore:
dic['mul... | Extract the loss categories and the tags of the exposure.
Use it as /extract/exposure_metadata | Below is the the instruction that describes the task:
### Input:
Extract the loss categories and the tags of the exposure.
Use it as /extract/exposure_metadata
### Response:
def extract_exposure_metadata(dstore, what):
"""
Extract the loss categories and the tags of the exposure.
Use it as /extract... |
def show_bare_metal_state_output_bare_metal_state(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_bare_metal_state = ET.Element("show_bare_metal_state")
config = show_bare_metal_state
output = ET.SubElement(show_bare_metal_state, "output")
... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def show_bare_metal_state_output_bare_metal_state(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_bare_metal_state = ET.Element("show_bare_metal_state")
... |
def subject_areas(self):
"""List of tuples of author subject areas in the form
(area, frequency, abbreviation, code), where frequency is the
number of publications in this subject area.
"""
areas = self.xml.findall('subject-areas/subject-area')
freqs = self.xml.findall('a... | List of tuples of author subject areas in the form
(area, frequency, abbreviation, code), where frequency is the
number of publications in this subject area. | Below is the the instruction that describes the task:
### Input:
List of tuples of author subject areas in the form
(area, frequency, abbreviation, code), where frequency is the
number of publications in this subject area.
### Response:
def subject_areas(self):
"""List of tuples of author s... |
def hcenter_blit(target, source, dest = (0, 0), area=None, special_flags=0):
'''
The same as center_blit(), but only centers horizontally.
'''
loc = lambda d, s: (_vec(d.get_width() / 2, 0) -
_vec(s.get_width() / 2, 0))
_blitter(loc, target, source, dest, area, special_flags) | The same as center_blit(), but only centers horizontally. | Below is the the instruction that describes the task:
### Input:
The same as center_blit(), but only centers horizontally.
### Response:
def hcenter_blit(target, source, dest = (0, 0), area=None, special_flags=0):
'''
The same as center_blit(), but only centers horizontally.
'''
loc = lambda d, s: ... |
def gmv(a, b):
"""Geometric mean variance
"""
return np.exp(np.square(np.log(a) - np.log(b)).mean()) | Geometric mean variance | Below is the the instruction that describes the task:
### Input:
Geometric mean variance
### Response:
def gmv(a, b):
"""Geometric mean variance
"""
return np.exp(np.square(np.log(a) - np.log(b)).mean()) |
def setrange(self, name, offset, value):
"""
Overwrite bytes in the value of ``name`` starting at ``offset`` with
``value``. If ``offset`` plus the length of ``value`` exceeds the
length of the original value, the new value will be larger
than before.
If ``offset`` exceed... | Overwrite bytes in the value of ``name`` starting at ``offset`` with
``value``. If ``offset`` plus the length of ``value`` exceeds the
length of the original value, the new value will be larger
than before.
If ``offset`` exceeds the length of the original value, null bytes
will b... | Below is the the instruction that describes the task:
### Input:
Overwrite bytes in the value of ``name`` starting at ``offset`` with
``value``. If ``offset`` plus the length of ``value`` exceeds the
length of the original value, the new value will be larger
than before.
If ``offset`... |
def get_ceph_df(self, sentry_unit):
"""Return dict of ceph df json output, including ceph pool state.
:param sentry_unit: Pointer to amulet sentry instance (juju unit)
:returns: Dict of ceph df output
"""
cmd = 'sudo ceph df --format=json'
output, code = sentry_unit.run(... | Return dict of ceph df json output, including ceph pool state.
:param sentry_unit: Pointer to amulet sentry instance (juju unit)
:returns: Dict of ceph df output | Below is the the instruction that describes the task:
### Input:
Return dict of ceph df json output, including ceph pool state.
:param sentry_unit: Pointer to amulet sentry instance (juju unit)
:returns: Dict of ceph df output
### Response:
def get_ceph_df(self, sentry_unit):
"""Return dic... |
def data(self):
"""return stored data
Returns:
unpickled data
"""
try:
bytestream = super(MimeData, self).data(self._mimeType).data()
return pickle.loads(bytestream)
except:
raise | return stored data
Returns:
unpickled data | Below is the the instruction that describes the task:
### Input:
return stored data
Returns:
unpickled data
### Response:
def data(self):
"""return stored data
Returns:
unpickled data
"""
try:
bytestream = super(MimeData,... |
def handle_exception (self):
"""
An exception occurred. Log it and set the cache flag.
"""
etype, evalue = sys.exc_info()[:2]
log.debug(LOG_CHECK, "Error in %s: %s %s", self.url, etype, evalue, exception=True)
# note: etype must be the exact class, not a subclass
... | An exception occurred. Log it and set the cache flag. | Below is the the instruction that describes the task:
### Input:
An exception occurred. Log it and set the cache flag.
### Response:
def handle_exception (self):
"""
An exception occurred. Log it and set the cache flag.
"""
etype, evalue = sys.exc_info()[:2]
log.debug(LOG_CH... |
def run(toolkit_name, options, verbose=True, show_progress=False):
"""
Internal function to execute toolkit on the turicreate server.
Parameters
----------
toolkit_name : string
The name of the toolkit.
options : dict
A map containing the required input for the toolkit function... | Internal function to execute toolkit on the turicreate server.
Parameters
----------
toolkit_name : string
The name of the toolkit.
options : dict
A map containing the required input for the toolkit function,
for example: {'graph': g, 'reset_prob': 0.15}.
verbose : bool
... | Below is the the instruction that describes the task:
### Input:
Internal function to execute toolkit on the turicreate server.
Parameters
----------
toolkit_name : string
The name of the toolkit.
options : dict
A map containing the required input for the toolkit function,
... |
def simple_paths_by_name(self, start_name, end_name):
"""Return a list of paths between start and end functions.
"""
cfg_start = self.find_function_by_name(start_name)
cfg_end = self.find_function_by_name(end_name)
if not cfg_start or not cfg_end:
raise Exception("St... | Return a list of paths between start and end functions. | Below is the the instruction that describes the task:
### Input:
Return a list of paths between start and end functions.
### Response:
def simple_paths_by_name(self, start_name, end_name):
"""Return a list of paths between start and end functions.
"""
cfg_start = self.find_function_by_name(... |
def validate_config(self, values, argv=None, strict=False):
"""Validate all config values through the command-line parser.
This takes all supplied options (which could have been retrieved from a
number of sources (such as CLI, env vars, etc...) and then validates
them by running them th... | Validate all config values through the command-line parser.
This takes all supplied options (which could have been retrieved from a
number of sources (such as CLI, env vars, etc...) and then validates
them by running them through argparser (and raises SystemExit on
failure).
:r... | Below is the the instruction that describes the task:
### Input:
Validate all config values through the command-line parser.
This takes all supplied options (which could have been retrieved from a
number of sources (such as CLI, env vars, etc...) and then validates
them by running them thro... |
def write_text(_command, txt_file):
"""Dump SQL command to a text file."""
command = _command.strip()
with open(txt_file, 'w') as txt:
txt.writelines(command) | Dump SQL command to a text file. | Below is the the instruction that describes the task:
### Input:
Dump SQL command to a text file.
### Response:
def write_text(_command, txt_file):
"""Dump SQL command to a text file."""
command = _command.strip()
with open(txt_file, 'w') as txt:
txt.writelines(command) |
def allowed(self):
'''
Check to see if the pop request is allowed
@return: True means the maximum was not been reached for the current
time window, thus allowing what ever operation follows
'''
# Expire old keys (hits)
expires = time.time() - self.window
... | Check to see if the pop request is allowed
@return: True means the maximum was not been reached for the current
time window, thus allowing what ever operation follows | Below is the the instruction that describes the task:
### Input:
Check to see if the pop request is allowed
@return: True means the maximum was not been reached for the current
time window, thus allowing what ever operation follows
### Response:
def allowed(self):
'''
Check to ... |
def build_event_handler(self, runnable, regime, event_handler):
"""
Build event handler code.
@param event_handler: Event handler object
@type event_handler: lems.model.dynamics.EventHandler
@return: Generated event handler code.
@rtype: list(string)
"""
... | Build event handler code.
@param event_handler: Event handler object
@type event_handler: lems.model.dynamics.EventHandler
@return: Generated event handler code.
@rtype: list(string) | Below is the the instruction that describes the task:
### Input:
Build event handler code.
@param event_handler: Event handler object
@type event_handler: lems.model.dynamics.EventHandler
@return: Generated event handler code.
@rtype: list(string)
### Response:
def build_event_han... |
def _distance(self, x0, y0, x1, y1):
"""Utitlity function to compute distance between points."""
dx = x1-x0
dy = y1-y0
# roll displacements across the borders
if self.pix:
dx[ dx > self.Lx/2 ] -= self.Lx
dx[ dx < -self.Lx/2 ] += self.Lx
if self.piy... | Utitlity function to compute distance between points. | Below is the the instruction that describes the task:
### Input:
Utitlity function to compute distance between points.
### Response:
def _distance(self, x0, y0, x1, y1):
"""Utitlity function to compute distance between points."""
dx = x1-x0
dy = y1-y0
# roll displacements across the... |
def predict_density(self, Xnew, Ynew):
"""
Compute the (log) density of the data Ynew at the points Xnew
Note that this computes the log density of the data individually,
ignoring correlations between them. The result is a matrix the same
shape as Ynew containing the log densiti... | Compute the (log) density of the data Ynew at the points Xnew
Note that this computes the log density of the data individually,
ignoring correlations between them. The result is a matrix the same
shape as Ynew containing the log densities. | Below is the the instruction that describes the task:
### Input:
Compute the (log) density of the data Ynew at the points Xnew
Note that this computes the log density of the data individually,
ignoring correlations between them. The result is a matrix the same
shape as Ynew containing the l... |
def variant_case(store, case_obj, variant_obj):
"""Pre-process case for the variant view.
Adds information about files from case obj to variant
Args:
store(scout.adapter.MongoAdapter)
case_obj(scout.models.Case)
variant_obj(scout.models.Variant)
"""
case_obj['bam_files'] = ... | Pre-process case for the variant view.
Adds information about files from case obj to variant
Args:
store(scout.adapter.MongoAdapter)
case_obj(scout.models.Case)
variant_obj(scout.models.Variant) | Below is the the instruction that describes the task:
### Input:
Pre-process case for the variant view.
Adds information about files from case obj to variant
Args:
store(scout.adapter.MongoAdapter)
case_obj(scout.models.Case)
variant_obj(scout.models.Variant)
### Response:
def var... |
def main(argv=None):
"""Run Tika from command line according to USAGE."""
global Verbose
global EncodeUtf8
global csvOutput
if argv is None:
argv = sys.argv
if (len(argv) < 3 and not (('-h' in argv) or ('--help' in argv))):
log.exception('Bad args')
raise TikaException('... | Run Tika from command line according to USAGE. | Below is the the instruction that describes the task:
### Input:
Run Tika from command line according to USAGE.
### Response:
def main(argv=None):
"""Run Tika from command line according to USAGE."""
global Verbose
global EncodeUtf8
global csvOutput
if argv is None:
argv = sys.argv
... |
def validate_profile_exists(self):
"""Validate the provided profiles name exists."""
if self.args.profile_name not in self.profiles:
self.handle_error('Could not find profile "{}"'.format(self.args.profile_name)) | Validate the provided profiles name exists. | Below is the the instruction that describes the task:
### Input:
Validate the provided profiles name exists.
### Response:
def validate_profile_exists(self):
"""Validate the provided profiles name exists."""
if self.args.profile_name not in self.profiles:
self.handle_error('Could not f... |
def _async_call(self, uri, body=None, method="GET", error_class=None,
has_response=True, *args, **kwargs):
"""
Handles asynchronous call/responses for the DNS API.
Returns the response headers and body if the call was successful.
If an error status is returned, and the 'erro... | Handles asynchronous call/responses for the DNS API.
Returns the response headers and body if the call was successful.
If an error status is returned, and the 'error_class' parameter is
specified, that class of error will be raised with the details from
the response. If no error class i... | Below is the the instruction that describes the task:
### Input:
Handles asynchronous call/responses for the DNS API.
Returns the response headers and body if the call was successful.
If an error status is returned, and the 'error_class' parameter is
specified, that class of error will be r... |
def activate_left(self, token):
"""Make a copy of the received token and call `_activate_left`."""
watchers.MATCHER.debug(
"Node <%s> activated left with token %r", self, token)
return self._activate_left(token.copy()) | Make a copy of the received token and call `_activate_left`. | Below is the the instruction that describes the task:
### Input:
Make a copy of the received token and call `_activate_left`.
### Response:
def activate_left(self, token):
"""Make a copy of the received token and call `_activate_left`."""
watchers.MATCHER.debug(
"Node <%s> activated lef... |
def _kwargs_from_dict(cls, a_dict: dict) -> dict:
"""Modify __init__ arguments from an external dictionary.
Template method for from dict.
Override if necessary (like it's done in Histogram1D).
"""
from .binnings import BinningBase
kwargs = {
"binnings": [Bin... | Modify __init__ arguments from an external dictionary.
Template method for from dict.
Override if necessary (like it's done in Histogram1D). | Below is the the instruction that describes the task:
### Input:
Modify __init__ arguments from an external dictionary.
Template method for from dict.
Override if necessary (like it's done in Histogram1D).
### Response:
def _kwargs_from_dict(cls, a_dict: dict) -> dict:
"""Modify __init__ a... |
def main(host='localhost', port=8086, nb_day=15):
"""Instantiate a connection to the backend."""
nb_day = 15 # number of day to generate time series
timeinterval_min = 5 # create an event every x minutes
total_minutes = 1440 * nb_day
total_records = int(total_minutes / timeinterval_min)
now = ... | Instantiate a connection to the backend. | Below is the the instruction that describes the task:
### Input:
Instantiate a connection to the backend.
### Response:
def main(host='localhost', port=8086, nb_day=15):
"""Instantiate a connection to the backend."""
nb_day = 15 # number of day to generate time series
timeinterval_min = 5 # create an... |
def add_private_note(self, private_notes, source=None):
"""Add private notes.
:param private_notes: hidden notes for the current document
:type private_notes: string
:param source: source for the given private notes
:type source: string
"""
self._append_to('_pri... | Add private notes.
:param private_notes: hidden notes for the current document
:type private_notes: string
:param source: source for the given private notes
:type source: string | Below is the the instruction that describes the task:
### Input:
Add private notes.
:param private_notes: hidden notes for the current document
:type private_notes: string
:param source: source for the given private notes
:type source: string
### Response:
def add_private_note(sel... |
def _set_lsp_secpath_autobw_template(self, v, load=False):
"""
Setter method for lsp_secpath_autobw_template, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/lsp/secondary_path/lsp_secpath_auto_bandwidth/lsp_secpath_autobw_template (leafref)
If this variable is read-only (config: false) ... | Setter method for lsp_secpath_autobw_template, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/lsp/secondary_path/lsp_secpath_auto_bandwidth/lsp_secpath_autobw_template (leafref)
If this variable is read-only (config: false) in the
source YANG file, then _set_lsp_secpath_autobw_template is c... | Below is the the instruction that describes the task:
### Input:
Setter method for lsp_secpath_autobw_template, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/lsp/secondary_path/lsp_secpath_auto_bandwidth/lsp_secpath_autobw_template (leafref)
If this variable is read-only (config: false) in... |
def import_smesh(file):
""" Generates NURBS surface(s) from surface mesh (smesh) file(s).
*smesh* files are some text files which contain a set of NURBS surfaces. Each file in the set corresponds to one
NURBS surface. Most of the time, you receive multiple *smesh* files corresponding to an complete object ... | Generates NURBS surface(s) from surface mesh (smesh) file(s).
*smesh* files are some text files which contain a set of NURBS surfaces. Each file in the set corresponds to one
NURBS surface. Most of the time, you receive multiple *smesh* files corresponding to an complete object composed of
several NURBS su... | Below is the the instruction that describes the task:
### Input:
Generates NURBS surface(s) from surface mesh (smesh) file(s).
*smesh* files are some text files which contain a set of NURBS surfaces. Each file in the set corresponds to one
NURBS surface. Most of the time, you receive multiple *smesh* files... |
def translate(self, desired_locale=None):
"""Translate this message to the desired locale.
:param desired_locale: The desired locale to translate the message to,
if no locale is provided the message will be
translated to the system's default... | Translate this message to the desired locale.
:param desired_locale: The desired locale to translate the message to,
if no locale is provided the message will be
translated to the system's default locale.
:returns: the translated message in... | Below is the the instruction that describes the task:
### Input:
Translate this message to the desired locale.
:param desired_locale: The desired locale to translate the message to,
if no locale is provided the message will be
translated to the ... |
def _get_qsize(tuning, width):
"""Return a reasonable quarter note size for 'tuning' and 'width'."""
names = [x.to_shorthand() for x in tuning.tuning]
basesize = len(max(names)) + 3
barsize = ((width - basesize) - 2) - 1
# x * 4 + 0.5x - barsize = 0 4.5x = barsize x = barsize / 4.5
return max(0... | Return a reasonable quarter note size for 'tuning' and 'width'. | Below is the the instruction that describes the task:
### Input:
Return a reasonable quarter note size for 'tuning' and 'width'.
### Response:
def _get_qsize(tuning, width):
"""Return a reasonable quarter note size for 'tuning' and 'width'."""
names = [x.to_shorthand() for x in tuning.tuning]
basesize ... |
def draw_rubberband(self, event, x0, y0, x1, y1):
'adapted from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/189744'
canvas = self.canvas
dc =wx.ClientDC(canvas)
# Set logical function to XOR for rubberbanding
dc.SetLogicalFunction(wx.XOR)
# Set dc brush and ... | adapted from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/189744 | Below is the the instruction that describes the task:
### Input:
adapted from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/189744
### Response:
def draw_rubberband(self, event, x0, y0, x1, y1):
'adapted from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/189744'
canvas = self.ca... |
def get_family_lookup_session(self, proxy):
"""Gets the ``OsidSession`` associated with the family lookup service.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.relationship.FamilyLookupSession) - a
``FamilyLookupSession``
raise: NullArgument - ``proxy`` is ``... | Gets the ``OsidSession`` associated with the family lookup service.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.relationship.FamilyLookupSession) - a
``FamilyLookupSession``
raise: NullArgument - ``proxy`` is ``null``
raise: OperationFailed - unable to comp... | Below is the the instruction that describes the task:
### Input:
Gets the ``OsidSession`` associated with the family lookup service.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.relationship.FamilyLookupSession) - a
``FamilyLookupSession``
raise: NullArgument - `... |
def _send(self, message, fail_silently=False):
"""Save message to a file for debugging
"""
seeds = '1234567890qwertyuiopasdfghjklzxcvbnm'
file_part1 = datetime.now().strftime('%Y%m%d%H%M%S')
file_part2 = ''.join(sample(seeds, 4))
filename = join(self.tld, '%s_%s.msg' % (f... | Save message to a file for debugging | Below is the the instruction that describes the task:
### Input:
Save message to a file for debugging
### Response:
def _send(self, message, fail_silently=False):
"""Save message to a file for debugging
"""
seeds = '1234567890qwertyuiopasdfghjklzxcvbnm'
file_part1 = datetime.now().s... |
def evaluate(self, brain_info):
"""
Evaluates policy for the agent experiences provided.
:param brain_info: BrainInfo object containing inputs.
:return: Outputs from network as defined by self.inference_dict.
"""
feed_dict = {self.model.batch_size: len(brain_info.vector_o... | Evaluates policy for the agent experiences provided.
:param brain_info: BrainInfo object containing inputs.
:return: Outputs from network as defined by self.inference_dict. | Below is the the instruction that describes the task:
### Input:
Evaluates policy for the agent experiences provided.
:param brain_info: BrainInfo object containing inputs.
:return: Outputs from network as defined by self.inference_dict.
### Response:
def evaluate(self, brain_info):
"""
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.