code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def _remove_strings(code) :
""" Remove strings in code
"""
removed_string = ""
is_string_now = None
for i in range(0, len(code)-1) :
append_this_turn = False
if code[i] == "'" and (i == 0 or code[i-1] != '\\') :
if is_string_now == "'" :
is_string_now = None
elif is_string_now == None ... | Remove strings in code | Below is the the instruction that describes the task:
### Input:
Remove strings in code
### Response:
def _remove_strings(code) :
""" Remove strings in code
"""
removed_string = ""
is_string_now = None
for i in range(0, len(code)-1) :
append_this_turn = False
if code[i] == "'" and (i == 0 or co... |
def angular_crossmatch_against_catalogue(
self,
objectList,
searchPara={},
search_name="",
brightnessFilter=False,
physicalSearch=False,
classificationType=False
):
"""*perform an angular separation crossmatch against a given catalogue in the database ... | *perform an angular separation crossmatch against a given catalogue in the database and annotate the crossmatch with some value added parameters (distances, physical separations, sub-type of transient etc)*
**Key Arguments:**
- ``objectList`` -- the list of transient locations to match against the ... | Below is the the instruction that describes the task:
### Input:
*perform an angular separation crossmatch against a given catalogue in the database and annotate the crossmatch with some value added parameters (distances, physical separations, sub-type of transient etc)*
**Key Arguments:**
- ``... |
def _software_params_to_argparse(parameters):
"""
Converts a SoftwareParameterCollection into an ArgumentParser object.
Parameters
----------
parameters: SoftwareParameterCollection
The software parameters
Returns
-------
argparse: ArgumentParser
An initialized argument ... | Converts a SoftwareParameterCollection into an ArgumentParser object.
Parameters
----------
parameters: SoftwareParameterCollection
The software parameters
Returns
-------
argparse: ArgumentParser
An initialized argument parser | Below is the the instruction that describes the task:
### Input:
Converts a SoftwareParameterCollection into an ArgumentParser object.
Parameters
----------
parameters: SoftwareParameterCollection
The software parameters
Returns
-------
argparse: ArgumentParser
An initialize... |
def add_transition_view_for_model(self, transition_m, parent_state_m):
"""Creates a `TransitionView` and adds it to the canvas
The method creates a`TransitionView` from the given `TransitionModel `transition_m` and adds it to the canvas.
:param TransitionModel transition_m: The transition for ... | Creates a `TransitionView` and adds it to the canvas
The method creates a`TransitionView` from the given `TransitionModel `transition_m` and adds it to the canvas.
:param TransitionModel transition_m: The transition for which a view is to be created
:param ContainerStateModel parent_state_m: ... | Below is the the instruction that describes the task:
### Input:
Creates a `TransitionView` and adds it to the canvas
The method creates a`TransitionView` from the given `TransitionModel `transition_m` and adds it to the canvas.
:param TransitionModel transition_m: The transition for which a view ... |
def asDict(self, recursive=False):
"""
Return as an dict
:param recursive: turns the nested Row as dict (default: False).
>>> Row(name="Alice", age=11).asDict() == {'name': 'Alice', 'age': 11}
True
>>> row = Row(key=1, value=Row(name='a', age=2))
>>> row.asDict(... | Return as an dict
:param recursive: turns the nested Row as dict (default: False).
>>> Row(name="Alice", age=11).asDict() == {'name': 'Alice', 'age': 11}
True
>>> row = Row(key=1, value=Row(name='a', age=2))
>>> row.asDict() == {'key': 1, 'value': Row(age=2, name='a')}
... | Below is the the instruction that describes the task:
### Input:
Return as an dict
:param recursive: turns the nested Row as dict (default: False).
>>> Row(name="Alice", age=11).asDict() == {'name': 'Alice', 'age': 11}
True
>>> row = Row(key=1, value=Row(name='a', age=2))
>... |
def is_valid_mac(addr):
"""Check the syntax of a given mac address.
The acceptable format is xx:xx:xx:xx:xx:xx
"""
addrs = addr.split(':')
if len(addrs) != 6:
return False
for m in addrs:
try:
if int(m, 16) > 255:
return False
except ValueErro... | Check the syntax of a given mac address.
The acceptable format is xx:xx:xx:xx:xx:xx | Below is the the instruction that describes the task:
### Input:
Check the syntax of a given mac address.
The acceptable format is xx:xx:xx:xx:xx:xx
### Response:
def is_valid_mac(addr):
"""Check the syntax of a given mac address.
The acceptable format is xx:xx:xx:xx:xx:xx
"""
addrs = addr.sp... |
def get_metric(self, reset: bool) -> Union[float, Tuple[float, ...], Dict[str, float], Dict[str, List[float]]]:
"""
Compute and return the metric. Optionally also call :func:`self.reset`.
"""
raise NotImplementedError | Compute and return the metric. Optionally also call :func:`self.reset`. | Below is the the instruction that describes the task:
### Input:
Compute and return the metric. Optionally also call :func:`self.reset`.
### Response:
def get_metric(self, reset: bool) -> Union[float, Tuple[float, ...], Dict[str, float], Dict[str, List[float]]]:
"""
Compute and return the metric. O... |
def set_value(self, *args, **kwargs):
"""
Quickly set single value at (item, major, minor) location.
.. deprecated:: 0.21.0
Please use .at[] or .iat[] accessors.
Parameters
----------
item : item label (panel item)
major : major axis label (panel item r... | Quickly set single value at (item, major, minor) location.
.. deprecated:: 0.21.0
Please use .at[] or .iat[] accessors.
Parameters
----------
item : item label (panel item)
major : major axis label (panel item row)
minor : minor axis label (panel item column)
... | Below is the the instruction that describes the task:
### Input:
Quickly set single value at (item, major, minor) location.
.. deprecated:: 0.21.0
Please use .at[] or .iat[] accessors.
Parameters
----------
item : item label (panel item)
major : major axis label (p... |
def relative_time_to_text(l10n=locales.get(_default), **kwargs):
"""
Return an aproximate textual representation of the provioded duration of
time.
Examples:
relative_time_to_text(hours=6, minutes=34) -> "six and a half hours"
relative_time_to_text(years=5, months=8, days=5) -> "less than six y... | Return an aproximate textual representation of the provioded duration of
time.
Examples:
relative_time_to_text(hours=6, minutes=34) -> "six and a half hours"
relative_time_to_text(years=5, months=8, days=5) -> "less than six years"
Keyword arguments:
l10n -- The locale of the language for the ... | Below is the the instruction that describes the task:
### Input:
Return an aproximate textual representation of the provioded duration of
time.
Examples:
relative_time_to_text(hours=6, minutes=34) -> "six and a half hours"
relative_time_to_text(years=5, months=8, days=5) -> "less than six years"
... |
def set_inteface_down(devid, ifindex):
"""
function takest devid and ifindex of specific device and interface and issues a RESTFUL call to " shut" the specifie
d interface on the target device.
:param devid: int or str value of the target device
:param ifindex: int or str value of the target interfa... | function takest devid and ifindex of specific device and interface and issues a RESTFUL call to " shut" the specifie
d interface on the target device.
:param devid: int or str value of the target device
:param ifindex: int or str value of the target interface
:return: HTTP status code 204 with no values... | Below is the the instruction that describes the task:
### Input:
function takest devid and ifindex of specific device and interface and issues a RESTFUL call to " shut" the specifie
d interface on the target device.
:param devid: int or str value of the target device
:param ifindex: int or str value of ... |
def _async_open(self, session_id, proto_version):
''' Perform the specific steps needed to open a connection to a Bokeh session
Specifically, this method coordinates:
* Getting a session for a session ID (creating a new one if needed)
* Creating a protocol receiver and hander
*... | Perform the specific steps needed to open a connection to a Bokeh session
Specifically, this method coordinates:
* Getting a session for a session ID (creating a new one if needed)
* Creating a protocol receiver and hander
* Opening a new ServerConnection and sending it an ACK
... | Below is the the instruction that describes the task:
### Input:
Perform the specific steps needed to open a connection to a Bokeh session
Specifically, this method coordinates:
* Getting a session for a session ID (creating a new one if needed)
* Creating a protocol receiver and hander
... |
def hook_focus_events(self):
""" Install the hooks for focus events.
This method may be overridden by subclasses as needed.
"""
widget = self.widget
widget.focusInEvent = self.focusInEvent
widget.focusOutEvent = self.focusOutEvent | Install the hooks for focus events.
This method may be overridden by subclasses as needed. | Below is the the instruction that describes the task:
### Input:
Install the hooks for focus events.
This method may be overridden by subclasses as needed.
### Response:
def hook_focus_events(self):
""" Install the hooks for focus events.
This method may be overridden by subclasses as nee... |
def __expr_str(cls, expr, level):
'''Returns string representing the expression.'''
ident = ' ' * level * 4
if isinstance(expr, tuple):
return '{}{}'.format(ident, str(expr))
if expr.etype[0] in ['pvar', 'constant']:
return '{}Expression(etype={}, args={})'.form... | Returns string representing the expression. | Below is the the instruction that describes the task:
### Input:
Returns string representing the expression.
### Response:
def __expr_str(cls, expr, level):
'''Returns string representing the expression.'''
ident = ' ' * level * 4
if isinstance(expr, tuple):
return '{}{}'.forma... |
def _list_selection_changed(self):
"""Selection has changed in the list."""
items = self.list_layers_in_map_report.selectedItems()
self.remove_layer.setEnabled(len(items) >= 1)
if len(items) == 1 and self.list_layers_in_map_report.count() >= 2:
index = self.list_layers_in_map... | Selection has changed in the list. | Below is the the instruction that describes the task:
### Input:
Selection has changed in the list.
### Response:
def _list_selection_changed(self):
"""Selection has changed in the list."""
items = self.list_layers_in_map_report.selectedItems()
self.remove_layer.setEnabled(len(items) >= 1)
... |
def _apply_prefix(prefix, model):
"""
Prefix all path entries in model with the given prefix.
"""
if not isinstance(model, dict):
raise TypeError("Expected dict for model, got %s" % type(model))
# We get unwanted leading/trailing slashes if prefix or model['path'] are
# '', both of whic... | Prefix all path entries in model with the given prefix. | Below is the the instruction that describes the task:
### Input:
Prefix all path entries in model with the given prefix.
### Response:
def _apply_prefix(prefix, model):
"""
Prefix all path entries in model with the given prefix.
"""
if not isinstance(model, dict):
raise TypeError("Expected ... |
def structure_dir(self):
"""str: Directory where structure related files are stored"""
if self.root_dir:
return op.join(self.protein_dir, 'structures')
else:
log.debug('Root directory not set')
return None | str: Directory where structure related files are stored | Below is the the instruction that describes the task:
### Input:
str: Directory where structure related files are stored
### Response:
def structure_dir(self):
"""str: Directory where structure related files are stored"""
if self.root_dir:
return op.join(self.protein_dir, 'structures')
... |
def calculate_signature(key, data, timestamp=None):
"""
Calculates the signature for the given request data.
"""
# Create a timestamp if one was not given
if timestamp is None:
timestamp = int(time.time())
# Construct the message from the timestamp and the data in the request
messag... | Calculates the signature for the given request data. | Below is the the instruction that describes the task:
### Input:
Calculates the signature for the given request data.
### Response:
def calculate_signature(key, data, timestamp=None):
"""
Calculates the signature for the given request data.
"""
# Create a timestamp if one was not given
if times... |
def _kill_process(self, pid, sig=signal.SIGKILL):
"""Try to send signal to given process."""
try:
os.kill(pid, sig)
except OSError as e:
if e.errno == errno.ESRCH: # process itself returned and exited before killing
logging.debug("Failure %s while killing ... | Try to send signal to given process. | Below is the the instruction that describes the task:
### Input:
Try to send signal to given process.
### Response:
def _kill_process(self, pid, sig=signal.SIGKILL):
"""Try to send signal to given process."""
try:
os.kill(pid, sig)
except OSError as e:
if e.errno == ... |
def _is_request_in_include_path(self, request):
"""Check if the request path is in the `_include_paths` list.
If no specific include paths are given then we assume that
authentication is required for all paths.
"""
if self._include_paths:
for path in self._include_p... | Check if the request path is in the `_include_paths` list.
If no specific include paths are given then we assume that
authentication is required for all paths. | Below is the the instruction that describes the task:
### Input:
Check if the request path is in the `_include_paths` list.
If no specific include paths are given then we assume that
authentication is required for all paths.
### Response:
def _is_request_in_include_path(self, request):
"""... |
def L2S(lunarD, lunarM, lunarY, lunarLeap, tZ=7):
'''def L2S(lunarD, lunarM, lunarY, lunarLeap, tZ = 7): Convert a lunar date
to the corresponding solar date.'''
if (lunarM < 11):
a11 = getLunarMonth11(lunarY - 1, tZ)
b11 = getLunarMonth11(lunarY, tZ)
else:
a11 = getLunarMonth11(... | def L2S(lunarD, lunarM, lunarY, lunarLeap, tZ = 7): Convert a lunar date
to the corresponding solar date. | Below is the the instruction that describes the task:
### Input:
def L2S(lunarD, lunarM, lunarY, lunarLeap, tZ = 7): Convert a lunar date
to the corresponding solar date.
### Response:
def L2S(lunarD, lunarM, lunarY, lunarLeap, tZ=7):
'''def L2S(lunarD, lunarM, lunarY, lunarLeap, tZ = 7): Convert a lunar d... |
def appname(path=None):
"""
Return a useful application name based on the program argument.
A special case maps 'mod_wsgi' to a more appropriate name so
web applications show up as our own.
"""
if path is None:
path = sys.argv[0]
name = os.path.basename(os.path.splitext(path)[0])
if name == 'mod... | Return a useful application name based on the program argument.
A special case maps 'mod_wsgi' to a more appropriate name so
web applications show up as our own. | Below is the the instruction that describes the task:
### Input:
Return a useful application name based on the program argument.
A special case maps 'mod_wsgi' to a more appropriate name so
web applications show up as our own.
### Response:
def appname(path=None):
"""
Return a useful application name based on ... |
def _get_connected_subgraphs(vertices, vertices_neighbours):
"""Break a graph containing unconnected subgraphs into a list of connected
subgraphs.
Returns
-------
[set([vertex, ...]), ...]
"""
remaining_vertices = set(vertices)
subgraphs = []
while remaining_vertices:
subgra... | Break a graph containing unconnected subgraphs into a list of connected
subgraphs.
Returns
-------
[set([vertex, ...]), ...] | Below is the the instruction that describes the task:
### Input:
Break a graph containing unconnected subgraphs into a list of connected
subgraphs.
Returns
-------
[set([vertex, ...]), ...]
### Response:
def _get_connected_subgraphs(vertices, vertices_neighbours):
"""Break a graph containing u... |
def get_queryset(self):
"""
Retrieve the category by his path and
build a queryset of her published entries.
"""
self.category = get_category_or_404(self.kwargs['path'])
return self.category.entries_published() | Retrieve the category by his path and
build a queryset of her published entries. | Below is the the instruction that describes the task:
### Input:
Retrieve the category by his path and
build a queryset of her published entries.
### Response:
def get_queryset(self):
"""
Retrieve the category by his path and
build a queryset of her published entries.
"""
... |
def _get_type(self, values):
""":return: the type of a knitting pattern set."""
if TYPE not in values:
self._error("No pattern type given but should be "
"\"{}\"".format(KNITTING_PATTERN_TYPE))
type_ = values[TYPE]
if type_ != KNITTING_PATTERN_TYPE:
... | :return: the type of a knitting pattern set. | Below is the the instruction that describes the task:
### Input:
:return: the type of a knitting pattern set.
### Response:
def _get_type(self, values):
""":return: the type of a knitting pattern set."""
if TYPE not in values:
self._error("No pattern type given but should be "
... |
def verification_check(self, phone_number, country_code, verification_code):
"""
:param phone_number:
:param country_code:
:param verification_code:
:return:
"""
options = {
'phone_number': phone_number,
'country_code': country_code,
... | :param phone_number:
:param country_code:
:param verification_code:
:return: | Below is the the instruction that describes the task:
### Input:
:param phone_number:
:param country_code:
:param verification_code:
:return:
### Response:
def verification_check(self, phone_number, country_code, verification_code):
"""
:param phone_number:
:param co... |
def set_goid2color_pval(self, goid2color):
"""Fill missing colors based on p-value of an enriched GO term."""
alpha2col = self.alpha2col
if self.pval_name is not None:
pval_name = self.pval_name
for goid, res in self.go2res.items():
pval = getattr(res, pva... | Fill missing colors based on p-value of an enriched GO term. | Below is the the instruction that describes the task:
### Input:
Fill missing colors based on p-value of an enriched GO term.
### Response:
def set_goid2color_pval(self, goid2color):
"""Fill missing colors based on p-value of an enriched GO term."""
alpha2col = self.alpha2col
if self.pval_n... |
def tuplesorted(items, *keys):
"""Sort by tuples with a different key for each item.
Args:
items: An iterable series of sequences (typically tuples)
*keys: Key objects which transform individual elements of
each tuple into sort keys. The zeroth object
transforms the zerot... | Sort by tuples with a different key for each item.
Args:
items: An iterable series of sequences (typically tuples)
*keys: Key objects which transform individual elements of
each tuple into sort keys. The zeroth object
transforms the zeroth element of each tuple, the first
... | Below is the the instruction that describes the task:
### Input:
Sort by tuples with a different key for each item.
Args:
items: An iterable series of sequences (typically tuples)
*keys: Key objects which transform individual elements of
each tuple into sort keys. The zeroth object
... |
def get_valid_times_for_job_legacy(self, num_job):
""" Get the times for which the job num_job will be valid, using the method
use in inspiral hipe.
"""
# All of this should be integers, so no rounding factors needed.
shift_dur = self.curr_seg[0] + int(self.job_time_shift * num_j... | Get the times for which the job num_job will be valid, using the method
use in inspiral hipe. | Below is the the instruction that describes the task:
### Input:
Get the times for which the job num_job will be valid, using the method
use in inspiral hipe.
### Response:
def get_valid_times_for_job_legacy(self, num_job):
""" Get the times for which the job num_job will be valid, using the method... |
def keep_negative_impute(X, y, model_generator, method_name, num_fcounts=11):
""" Keep Negative (impute)
xlabel = "Max fraction of features kept"
ylabel = "Negative mean model output"
transform = "negate"
sort_order = 17
"""
return __run_measure(measures.keep_impute, X, y, model_generator, m... | Keep Negative (impute)
xlabel = "Max fraction of features kept"
ylabel = "Negative mean model output"
transform = "negate"
sort_order = 17 | Below is the the instruction that describes the task:
### Input:
Keep Negative (impute)
xlabel = "Max fraction of features kept"
ylabel = "Negative mean model output"
transform = "negate"
sort_order = 17
### Response:
def keep_negative_impute(X, y, model_generator, method_name, num_fcounts=11):
... |
def _init(self, formula):
"""
SAT oracle initialization. The method creates a new SAT oracle and
feeds it with the formula's hard clauses. Afterwards, all soft
clauses of the formula are augmented with selector literals and
also added to the solver. The list of al... | SAT oracle initialization. The method creates a new SAT oracle and
feeds it with the formula's hard clauses. Afterwards, all soft
clauses of the formula are augmented with selector literals and
also added to the solver. The list of all introduced selectors is
stored in va... | Below is the the instruction that describes the task:
### Input:
SAT oracle initialization. The method creates a new SAT oracle and
feeds it with the formula's hard clauses. Afterwards, all soft
clauses of the formula are augmented with selector literals and
also added to the sol... |
def _call_connection_lost(self, error):
"""Finalize closing."""
try:
self._protocol.connection_lost(error)
finally:
os.close(self._fileno)
self._fileno = None
self._protocol = None
self._loop = None | Finalize closing. | Below is the the instruction that describes the task:
### Input:
Finalize closing.
### Response:
def _call_connection_lost(self, error):
"""Finalize closing."""
try:
self._protocol.connection_lost(error)
finally:
os.close(self._fileno)
self._fileno = None... |
def build_homogeneisation_vehicules(temporary_store = None, year = None):
assert temporary_store is not None
"""Compute vehicule numbers by type"""
assert year is not None
# Load data
bdf_survey_collection = SurveyCollection.load(
collection = 'budget_des_familles', config_files_directory =... | Compute vehicule numbers by type | Below is the the instruction that describes the task:
### Input:
Compute vehicule numbers by type
### Response:
def build_homogeneisation_vehicules(temporary_store = None, year = None):
assert temporary_store is not None
"""Compute vehicule numbers by type"""
assert year is not None
# Load data
... |
def _set_mep_id(self, v, load=False):
"""
Setter method for mep_id, mapped from YANG variable /protocol/cfm/domain_name/ma_name/cfm_ma_sub_commands/mep/mep_id (uint32)
If this variable is read-only (config: false) in the
source YANG file, then _set_mep_id is considered as a private
method. Backends ... | Setter method for mep_id, mapped from YANG variable /protocol/cfm/domain_name/ma_name/cfm_ma_sub_commands/mep/mep_id (uint32)
If this variable is read-only (config: false) in the
source YANG file, then _set_mep_id is considered as a private
method. Backends looking to populate this variable should
do so... | Below is the the instruction that describes the task:
### Input:
Setter method for mep_id, mapped from YANG variable /protocol/cfm/domain_name/ma_name/cfm_ma_sub_commands/mep/mep_id (uint32)
If this variable is read-only (config: false) in the
source YANG file, then _set_mep_id is considered as a private
... |
def nodes_touching_tile(tile_id):
"""
Get a list of node coordinates touching the given tile.
:param tile_id: tile identifier, Tile.tile_id
:return: list of node coordinates touching the given tile, list(int)
"""
coord = tile_id_to_coord(tile_id)
nodes = []
for offset in _tile_node_offs... | Get a list of node coordinates touching the given tile.
:param tile_id: tile identifier, Tile.tile_id
:return: list of node coordinates touching the given tile, list(int) | Below is the the instruction that describes the task:
### Input:
Get a list of node coordinates touching the given tile.
:param tile_id: tile identifier, Tile.tile_id
:return: list of node coordinates touching the given tile, list(int)
### Response:
def nodes_touching_tile(tile_id):
"""
Get a list... |
def draw_polygon(
self,
*pts,
close_path=True,
stroke=None,
stroke_width=1,
stroke_dash=None,
fill=None
) -> None:
"""Draws the given polygon."""
c = self.c
c.save()
c.new_path()
for x... | Draws the given polygon. | Below is the the instruction that describes the task:
### Input:
Draws the given polygon.
### Response:
def draw_polygon(
self,
*pts,
close_path=True,
stroke=None,
stroke_width=1,
stroke_dash=None,
fill=None
) -> None:
... |
def get_queries(self, project, expand=None, depth=None, include_deleted=None):
"""GetQueries.
[Preview API] Gets the root queries and their children
:param str project: Project ID or project name
:param str expand: Include the query string (wiql), clauses, query result columns, and sort ... | GetQueries.
[Preview API] Gets the root queries and their children
:param str project: Project ID or project name
:param str expand: Include the query string (wiql), clauses, query result columns, and sort options in the results.
:param int depth: In the folder of queries, return child q... | Below is the the instruction that describes the task:
### Input:
GetQueries.
[Preview API] Gets the root queries and their children
:param str project: Project ID or project name
:param str expand: Include the query string (wiql), clauses, query result columns, and sort options in the result... |
def find_time_base(self, gps, first_ms_stamp):
'''work out time basis for the log - new style'''
t = self._gpsTimeToTime(gps.Week, gps.TimeMS)
self.set_timebase(t - gps.T*0.001)
self.timestamp = self.timebase + first_ms_stamp*0.001 | work out time basis for the log - new style | Below is the the instruction that describes the task:
### Input:
work out time basis for the log - new style
### Response:
def find_time_base(self, gps, first_ms_stamp):
'''work out time basis for the log - new style'''
t = self._gpsTimeToTime(gps.Week, gps.TimeMS)
self.set_timebase(t - gps... |
def make_processor(self, name, mappings, processor_type, **kwargs):
"""
Instantiates a RmlProcessor and registers it in the manager
Args:
-----
name: the name to register the processor
mappings: the list RML mapping definitions to use
processor_type: ... | Instantiates a RmlProcessor and registers it in the manager
Args:
-----
name: the name to register the processor
mappings: the list RML mapping definitions to use
processor_type: the name of the RML processor to use | Below is the the instruction that describes the task:
### Input:
Instantiates a RmlProcessor and registers it in the manager
Args:
-----
name: the name to register the processor
mappings: the list RML mapping definitions to use
processor_type: the name of the RML... |
def Email(v):
"""Verify that the value is an Email or not.
>>> s = Schema(Email())
>>> with raises(MultipleInvalid, 'expected an Email'):
... s("a.com")
>>> with raises(MultipleInvalid, 'expected an Email'):
... s("a@.com")
>>> with raises(MultipleInvalid, 'expected an Email'):
... ... | Verify that the value is an Email or not.
>>> s = Schema(Email())
>>> with raises(MultipleInvalid, 'expected an Email'):
... s("a.com")
>>> with raises(MultipleInvalid, 'expected an Email'):
... s("a@.com")
>>> with raises(MultipleInvalid, 'expected an Email'):
... s("a@.com")
>>>... | Below is the the instruction that describes the task:
### Input:
Verify that the value is an Email or not.
>>> s = Schema(Email())
>>> with raises(MultipleInvalid, 'expected an Email'):
... s("a.com")
>>> with raises(MultipleInvalid, 'expected an Email'):
... s("a@.com")
>>> with raises... |
def smoothing_cross_entropy_factored_grad(op, dy):
"""Gradient function for smoothing_cross_entropy_factored."""
a = op.inputs[0]
b = op.inputs[1]
labels = op.inputs[2]
confidence = op.inputs[3]
num_splits = 16
vocab_size = shape_list(b)[0]
labels = approximate_split(labels, num_splits)
a = approximat... | Gradient function for smoothing_cross_entropy_factored. | Below is the the instruction that describes the task:
### Input:
Gradient function for smoothing_cross_entropy_factored.
### Response:
def smoothing_cross_entropy_factored_grad(op, dy):
"""Gradient function for smoothing_cross_entropy_factored."""
a = op.inputs[0]
b = op.inputs[1]
labels = op.inputs[2]
c... |
def get_unused_list_annotation_values(graph) -> Mapping[str, Set[str]]:
"""Get all of the unused values for list annotations.
:param pybel.BELGraph graph: A BEL graph
:return: A dictionary of {str annotation: set of str values that aren't used}
"""
result = {}
for annotation, values in graph.an... | Get all of the unused values for list annotations.
:param pybel.BELGraph graph: A BEL graph
:return: A dictionary of {str annotation: set of str values that aren't used} | Below is the the instruction that describes the task:
### Input:
Get all of the unused values for list annotations.
:param pybel.BELGraph graph: A BEL graph
:return: A dictionary of {str annotation: set of str values that aren't used}
### Response:
def get_unused_list_annotation_values(graph) -> Mapping[s... |
def _getMostActiveCells(self):
"""
Gets the most active cells in the Union SDR having at least non-zero
activation in sorted order.
@return: a list of cell indices
"""
poolingActivation = self._poolingActivation
nonZeroCells = numpy.argwhere(poolingActivation > 0)[:,0]
# include a tie-b... | Gets the most active cells in the Union SDR having at least non-zero
activation in sorted order.
@return: a list of cell indices | Below is the the instruction that describes the task:
### Input:
Gets the most active cells in the Union SDR having at least non-zero
activation in sorted order.
@return: a list of cell indices
### Response:
def _getMostActiveCells(self):
"""
Gets the most active cells in the Union SDR having at le... |
def _hangul_char_to_jamo(syllable):
"""Return a 3-tuple of lead, vowel, and tail jamo characters.
Note: Non-Hangul characters are echoed back.
"""
if is_hangul_char(syllable):
rem = ord(syllable) - _JAMO_OFFSET
tail = rem % 28
vowel = 1 + ((rem - tail) % 588) // 28
lead =... | Return a 3-tuple of lead, vowel, and tail jamo characters.
Note: Non-Hangul characters are echoed back. | Below is the the instruction that describes the task:
### Input:
Return a 3-tuple of lead, vowel, and tail jamo characters.
Note: Non-Hangul characters are echoed back.
### Response:
def _hangul_char_to_jamo(syllable):
"""Return a 3-tuple of lead, vowel, and tail jamo characters.
Note: Non-Hangul chara... |
def _isInt(x, precision = 0.0001):
"""
Return (isInt, intValue) for a given floating point number.
Parameters:
----------------------------------------------------------------------
x: floating point number to evaluate
precision: desired precision
retval: (isInt, intValue)
isInt: True if x... | Return (isInt, intValue) for a given floating point number.
Parameters:
----------------------------------------------------------------------
x: floating point number to evaluate
precision: desired precision
retval: (isInt, intValue)
isInt: True if x is close enough to an integer value
... | Below is the the instruction that describes the task:
### Input:
Return (isInt, intValue) for a given floating point number.
Parameters:
----------------------------------------------------------------------
x: floating point number to evaluate
precision: desired precision
retval: (isInt, intValue)
... |
def ReadGRRUser(self, username, cursor=None):
"""Reads a user object corresponding to a given name."""
cursor.execute(
"SELECT username, password, ui_mode, canary_mode, user_type "
"FROM grr_users WHERE username_hash = %s", [mysql_utils.Hash(username)])
row = cursor.fetchone()
if row is... | Reads a user object corresponding to a given name. | Below is the the instruction that describes the task:
### Input:
Reads a user object corresponding to a given name.
### Response:
def ReadGRRUser(self, username, cursor=None):
"""Reads a user object corresponding to a given name."""
cursor.execute(
"SELECT username, password, ui_mode, canary_mode, ... |
def post(self, data):
"""
Posts message with payload formatted in accordance with
this documentation https://api.slack.com/incoming-webhooks
"""
if not self.url:
raise Error('URL for incoming webhook is undefined')
return requests.post(self.url, data=json.dum... | Posts message with payload formatted in accordance with
this documentation https://api.slack.com/incoming-webhooks | Below is the the instruction that describes the task:
### Input:
Posts message with payload formatted in accordance with
this documentation https://api.slack.com/incoming-webhooks
### Response:
def post(self, data):
"""
Posts message with payload formatted in accordance with
this do... |
def Approval(self, username, approval_id):
"""Returns a reference to an approval."""
return ClientApprovalRef(
client_id=self.client_id,
username=username,
approval_id=approval_id,
context=self._context) | Returns a reference to an approval. | Below is the the instruction that describes the task:
### Input:
Returns a reference to an approval.
### Response:
def Approval(self, username, approval_id):
"""Returns a reference to an approval."""
return ClientApprovalRef(
client_id=self.client_id,
username=username,
approval_id... |
def main():
"""Main method for running upsidedown.py from the command line."""
import sys
output = []
line = sys.stdin.readline()
while line:
line = line.strip("\n")
output.append(transform(line))
line = sys.stdin.readline()
output.reverse()
print("\n".join(output)... | Main method for running upsidedown.py from the command line. | Below is the the instruction that describes the task:
### Input:
Main method for running upsidedown.py from the command line.
### Response:
def main():
"""Main method for running upsidedown.py from the command line."""
import sys
output = []
line = sys.stdin.readline()
while line:
lin... |
def get_event(self, timeout=None, block=True):
"""
Fetch the next available :class:`Event` from any source, or raise
:class:`mitogen.core.TimeoutError` if no value is available within
`timeout` seconds.
On success, the message's :attr:`receiver
<mitogen.core.Message.rece... | Fetch the next available :class:`Event` from any source, or raise
:class:`mitogen.core.TimeoutError` if no value is available within
`timeout` seconds.
On success, the message's :attr:`receiver
<mitogen.core.Message.receiver>` attribute is set to the receiver.
:param float time... | Below is the the instruction that describes the task:
### Input:
Fetch the next available :class:`Event` from any source, or raise
:class:`mitogen.core.TimeoutError` if no value is available within
`timeout` seconds.
On success, the message's :attr:`receiver
<mitogen.core.Message.re... |
def elem_find(self, field, value):
"""
Return the indices of elements whose field first satisfies the given values
``value`` should be unique in self.field.
This function does not check the uniqueness.
:param field: name of the supplied field
:param value: value of fiel... | Return the indices of elements whose field first satisfies the given values
``value`` should be unique in self.field.
This function does not check the uniqueness.
:param field: name of the supplied field
:param value: value of field of the elemtn to find
:return: idx of the ele... | Below is the the instruction that describes the task:
### Input:
Return the indices of elements whose field first satisfies the given values
``value`` should be unique in self.field.
This function does not check the uniqueness.
:param field: name of the supplied field
:param value:... |
def get_balance(self, asset_hash, id=None, endpoint=None):
"""
Get balance by asset hash
Args:
asset_hash: (str) asset to lookup, example would be 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b'
id: (int, optional) id to use for response tracking
... | Get balance by asset hash
Args:
asset_hash: (str) asset to lookup, example would be 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b'
id: (int, optional) id to use for response tracking
endpoint: (RPCEndpoint, optional) endpoint to specify to use
Ret... | Below is the the instruction that describes the task:
### Input:
Get balance by asset hash
Args:
asset_hash: (str) asset to lookup, example would be 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b'
id: (int, optional) id to use for response tracking
endp... |
def write(self, *text, sep=' '):
"""
Write text to response
:param text:
:param sep:
:return:
"""
self.text += markdown.text(*text, sep)
return self | Write text to response
:param text:
:param sep:
:return: | Below is the the instruction that describes the task:
### Input:
Write text to response
:param text:
:param sep:
:return:
### Response:
def write(self, *text, sep=' '):
"""
Write text to response
:param text:
:param sep:
:return:
"""
... |
def _prepare_dict_inputs(inputs, tensor_info_map):
"""Converts inputs to a dict of inputs and checks extra/missing args.
Args:
inputs: inputs fed to Module.__call__().
tensor_info_map: A map from string to `tensor_info.ParsedTensorInfo`
describing the signature inputs.
Returns:
A dict of value... | Converts inputs to a dict of inputs and checks extra/missing args.
Args:
inputs: inputs fed to Module.__call__().
tensor_info_map: A map from string to `tensor_info.ParsedTensorInfo`
describing the signature inputs.
Returns:
A dict of values with the same keys as tensor_info_map.
Raises:
... | Below is the the instruction that describes the task:
### Input:
Converts inputs to a dict of inputs and checks extra/missing args.
Args:
inputs: inputs fed to Module.__call__().
tensor_info_map: A map from string to `tensor_info.ParsedTensorInfo`
describing the signature inputs.
Returns:
A ... |
def _page_gen(self):
"""
Generates The String for pages
"""
track = ""
for page in self.__pages__:
track += "/{page}".format(page=page)
return track | Generates The String for pages | Below is the the instruction that describes the task:
### Input:
Generates The String for pages
### Response:
def _page_gen(self):
"""
Generates The String for pages
"""
track = ""
for page in self.__pages__:
track += "/{page}".format(page=page)
return tr... |
def set_xattr(self, path, xattr_name, xattr_value, flag, **kwargs):
"""Set an xattr of a file or directory.
:param xattr_name: The name must be prefixed with the namespace followed by ``.``. For
example, ``user.attr``.
:param flag: ``CREATE`` or ``REPLACE``
"""
kwarg... | Set an xattr of a file or directory.
:param xattr_name: The name must be prefixed with the namespace followed by ``.``. For
example, ``user.attr``.
:param flag: ``CREATE`` or ``REPLACE`` | Below is the the instruction that describes the task:
### Input:
Set an xattr of a file or directory.
:param xattr_name: The name must be prefixed with the namespace followed by ``.``. For
example, ``user.attr``.
:param flag: ``CREATE`` or ``REPLACE``
### Response:
def set_xattr(self, ... |
def filterResults(allResults, reportKeys, optimizeKey=None):
""" Given the complete set of results generated by an experiment (passed in
'results'), filter out and return only the ones the caller wants, as
specified through 'reportKeys' and 'optimizeKey'.
A report key is a string of key names separated by colo... | Given the complete set of results generated by an experiment (passed in
'results'), filter out and return only the ones the caller wants, as
specified through 'reportKeys' and 'optimizeKey'.
A report key is a string of key names separated by colons, each key being one
level deeper into the experiment results d... | Below is the the instruction that describes the task:
### Input:
Given the complete set of results generated by an experiment (passed in
'results'), filter out and return only the ones the caller wants, as
specified through 'reportKeys' and 'optimizeKey'.
A report key is a string of key names separated by co... |
def _echo_method(self, method):
"""Given a method, return a method that runs the internal
method and echos the result.
"""
@functools.wraps(method)
def func(*args, **kwargs):
# Echo warning if this method is deprecated.
if getattr(method, 'deprecated', Fal... | Given a method, return a method that runs the internal
method and echos the result. | Below is the the instruction that describes the task:
### Input:
Given a method, return a method that runs the internal
method and echos the result.
### Response:
def _echo_method(self, method):
"""Given a method, return a method that runs the internal
method and echos the result.
"... |
def run(self, sensor_graph, model):
"""Run this optimization pass on the sensor graph
If necessary, information on the device model being targeted
can be found in the associated model argument.
Args:
sensor_graph (SensorGraph): The sensor graph to optimize
model... | Run this optimization pass on the sensor graph
If necessary, information on the device model being targeted
can be found in the associated model argument.
Args:
sensor_graph (SensorGraph): The sensor graph to optimize
model (DeviceModel): The device model we're using | Below is the the instruction that describes the task:
### Input:
Run this optimization pass on the sensor graph
If necessary, information on the device model being targeted
can be found in the associated model argument.
Args:
sensor_graph (SensorGraph): The sensor graph to opti... |
def get_localhost():
'''
Should return 127.0.0.1 in ipv4 and ::1 in ipv6
localhost is not used because on windows vista/windows 7, there can be issues where the resolving doesn't work
properly and takes a lot of time (had this issue on the pyunit server).
Using the IP directly solves the problem.
... | Should return 127.0.0.1 in ipv4 and ::1 in ipv6
localhost is not used because on windows vista/windows 7, there can be issues where the resolving doesn't work
properly and takes a lot of time (had this issue on the pyunit server).
Using the IP directly solves the problem. | Below is the the instruction that describes the task:
### Input:
Should return 127.0.0.1 in ipv4 and ::1 in ipv6
localhost is not used because on windows vista/windows 7, there can be issues where the resolving doesn't work
properly and takes a lot of time (had this issue on the pyunit server).
Using ... |
def get_variables(self):
"""
Returns a list of variables.
Each variable is represented by an index of list.
For example if the no of variables are 4 then the list will be
[var_0, var_1, var_2, var_3]
Returns
-------
list: list of variables
Exampl... | Returns a list of variables.
Each variable is represented by an index of list.
For example if the no of variables are 4 then the list will be
[var_0, var_1, var_2, var_3]
Returns
-------
list: list of variables
Example
-------
>>> reader = UAIRea... | Below is the the instruction that describes the task:
### Input:
Returns a list of variables.
Each variable is represented by an index of list.
For example if the no of variables are 4 then the list will be
[var_0, var_1, var_2, var_3]
Returns
-------
list: list of v... |
def checkUser(self, user):
"""
Query a username or email address to see if a corresponding Microsoft account exists.
Args:
user (str): username or email address of an account
Returns:
bool: whether the account exists
"""
return not self.conn("POS... | Query a username or email address to see if a corresponding Microsoft account exists.
Args:
user (str): username or email address of an account
Returns:
bool: whether the account exists | Below is the the instruction that describes the task:
### Input:
Query a username or email address to see if a corresponding Microsoft account exists.
Args:
user (str): username or email address of an account
Returns:
bool: whether the account exists
### Response:
def chec... |
def get(self, host, files_count, path="/", ssl=False, external=None):
"""
Send get request to a url and wrap the results
:param host (str): the host name of the url
:param path (str): the path of the url (start with "/")
:return (dict): the result of the test url
"""
... | Send get request to a url and wrap the results
:param host (str): the host name of the url
:param path (str): the path of the url (start with "/")
:return (dict): the result of the test url | Below is the the instruction that describes the task:
### Input:
Send get request to a url and wrap the results
:param host (str): the host name of the url
:param path (str): the path of the url (start with "/")
:return (dict): the result of the test url
### Response:
def get(self, host, fi... |
def list_datasets(
self,
project=None,
include_all=False,
filter=None,
max_results=None,
page_token=None,
retry=DEFAULT_RETRY,
):
"""List datasets for the project associated with this client.
See
https://cloud.google.com/bigquery/docs/... | List datasets for the project associated with this client.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/datasets/list
Args:
project (str):
Optional. Project ID to use for retreiving datasets. Defaults
to the client's project.
... | Below is the the instruction that describes the task:
### Input:
List datasets for the project associated with this client.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/datasets/list
Args:
project (str):
Optional. Project ID to use for retreiving... |
def parse(self):
"""
Parse the vmstat file
:return: status of the metric parse
"""
file_status = True
for input_file in self.infile_list:
file_status = file_status and naarad.utils.is_valid_file(input_file)
if not file_status:
return False
status = True
cur_zone = No... | Parse the vmstat file
:return: status of the metric parse | Below is the the instruction that describes the task:
### Input:
Parse the vmstat file
:return: status of the metric parse
### Response:
def parse(self):
"""
Parse the vmstat file
:return: status of the metric parse
"""
file_status = True
for input_file in self.infile_list:
file_s... |
def shorten(string, length=140, ellipsis=None):
'''
Shorten a string to 140 characters without breaking words.
Optionally add an ellipsis character: '…' if ellipsis=True, or a given string
e.g. ellipsis=' (cut)'
'''
string = string.strip()
if len(string) > length:
if ellipsis is Tru... | Shorten a string to 140 characters without breaking words.
Optionally add an ellipsis character: '…' if ellipsis=True, or a given string
e.g. ellipsis=' (cut)' | Below is the the instruction that describes the task:
### Input:
Shorten a string to 140 characters without breaking words.
Optionally add an ellipsis character: '…' if ellipsis=True, or a given string
e.g. ellipsis=' (cut)'
### Response:
def shorten(string, length=140, ellipsis=None):
'''
Shorten ... |
def cross_v3(vec_a, vec_b):
"""Return the crossproduct between vec_a and vec_b."""
return Vec3(vec_a.y * vec_b.z - vec_a.z * vec_b.y,
vec_a.z * vec_b.x - vec_a.x * vec_b.z,
vec_a.x * vec_b.y - vec_a.y * vec_b.x) | Return the crossproduct between vec_a and vec_b. | Below is the the instruction that describes the task:
### Input:
Return the crossproduct between vec_a and vec_b.
### Response:
def cross_v3(vec_a, vec_b):
"""Return the crossproduct between vec_a and vec_b."""
return Vec3(vec_a.y * vec_b.z - vec_a.z * vec_b.y,
vec_a.z * vec_b.x - vec_a.x ... |
def namedspace(typename, required_fields=(), optional_fields=(), mutable_fields=(),
default_values=frozendict(), default_value_factories=frozendict(),
return_none=False):
"""Builds a new class that encapsulates a namespace and provides
various ways to access it.
The typename argument is re... | Builds a new class that encapsulates a namespace and provides
various ways to access it.
The typename argument is required and is the name of the
namedspace class that will be generated.
The required_fields and optional_fields arguments can be a string
or sequence of strings and together specify ... | Below is the the instruction that describes the task:
### Input:
Builds a new class that encapsulates a namespace and provides
various ways to access it.
The typename argument is required and is the name of the
namedspace class that will be generated.
The required_fields and optional_fields argum... |
def visit_ifexp(self, node, parent):
"""visit a IfExp node by returning a fresh instance of it"""
newnode = nodes.IfExp(node.lineno, node.col_offset, parent)
newnode.postinit(
self.visit(node.test, newnode),
self.visit(node.body, newnode),
self.visit(node.orel... | visit a IfExp node by returning a fresh instance of it | Below is the the instruction that describes the task:
### Input:
visit a IfExp node by returning a fresh instance of it
### Response:
def visit_ifexp(self, node, parent):
"""visit a IfExp node by returning a fresh instance of it"""
newnode = nodes.IfExp(node.lineno, node.col_offset, parent)
... |
def send(self, message, json=False, callback=None):
"""Use send to send a simple string message.
If ``json`` is True, the message will be encoded as a JSON object
on the wire, and decoded on the other side.
This is mostly for backwards compatibility. ``emit()`` is more fun.
:... | Use send to send a simple string message.
If ``json`` is True, the message will be encoded as a JSON object
on the wire, and decoded on the other side.
This is mostly for backwards compatibility. ``emit()`` is more fun.
:param callback: This is a callback function that will be
... | Below is the the instruction that describes the task:
### Input:
Use send to send a simple string message.
If ``json`` is True, the message will be encoded as a JSON object
on the wire, and decoded on the other side.
This is mostly for backwards compatibility. ``emit()`` is more fun.
... |
def absorb(self, other):
"""
For attributes of others that value is not None, assign it to self.
**中文文档**
将另一个文档中的数据更新到本条文档。当且仅当数据值不为None时。
"""
if not isinstance(other, self.__class__):
raise TypeError("`other` has to be a instance of %s!" %
... | For attributes of others that value is not None, assign it to self.
**中文文档**
将另一个文档中的数据更新到本条文档。当且仅当数据值不为None时。 | Below is the the instruction that describes the task:
### Input:
For attributes of others that value is not None, assign it to self.
**中文文档**
将另一个文档中的数据更新到本条文档。当且仅当数据值不为None时。
### Response:
def absorb(self, other):
"""
For attributes of others that value is not None, assign it to ... |
def set_project_path(self, path):
"""
Sets the project path and disables the project search in the combobox
if the value of path is None.
"""
if path is None:
self.project_path = None
self.model().item(PROJECT, 0).setEnabled(False)
if s... | Sets the project path and disables the project search in the combobox
if the value of path is None. | Below is the the instruction that describes the task:
### Input:
Sets the project path and disables the project search in the combobox
if the value of path is None.
### Response:
def set_project_path(self, path):
"""
Sets the project path and disables the project search in the combobox
... |
def model_resource(self, resource_name):
""" Details of a specific model resource. """
resource = first(
[resource for resource in self.api._registry.values()
if resource.get_api_name() == resource_name])
data = {
'apiVersion': '0.1',
'swaggerVe... | Details of a specific model resource. | Below is the the instruction that describes the task:
### Input:
Details of a specific model resource.
### Response:
def model_resource(self, resource_name):
""" Details of a specific model resource. """
resource = first(
[resource for resource in self.api._registry.values()
... |
def get_all_kernels(self, kernel_ids=None, owners=None):
"""
Retrieve all the EC2 kernels available on your account.
Constructs a filter to allow the processing to happen server side.
:type kernel_ids: list
:param kernel_ids: A list of strings with the image IDs wanted
... | Retrieve all the EC2 kernels available on your account.
Constructs a filter to allow the processing to happen server side.
:type kernel_ids: list
:param kernel_ids: A list of strings with the image IDs wanted
:type owners: list
:param owners: A list of owner IDs
:rtype... | Below is the the instruction that describes the task:
### Input:
Retrieve all the EC2 kernels available on your account.
Constructs a filter to allow the processing to happen server side.
:type kernel_ids: list
:param kernel_ids: A list of strings with the image IDs wanted
:type ow... |
def get_items(self, project=None, scope_path=None, recursion_level=None, include_links=None, version_descriptor=None):
"""GetItems.
Get a list of Tfvc items
:param str project: Project ID or project name
:param str scope_path: Version control path of a folder to return multiple items.
... | GetItems.
Get a list of Tfvc items
:param str project: Project ID or project name
:param str scope_path: Version control path of a folder to return multiple items.
:param str recursion_level: None (just the item), or OneLevel (contents of a folder).
:param bool include_links: Tru... | Below is the the instruction that describes the task:
### Input:
GetItems.
Get a list of Tfvc items
:param str project: Project ID or project name
:param str scope_path: Version control path of a folder to return multiple items.
:param str recursion_level: None (just the item), or On... |
def smtp_connection(c):
"""Create an SMTP connection from a Config object"""
if c.smtp_ssl:
klass = smtplib.SMTP_SSL
else:
klass = smtplib.SMTP
conn = klass(c.smtp_host, c.smtp_port, timeout=c.smtp_timeout)
if not c.smtp_ssl:
conn.ehlo()
conn.starttls()
conn.e... | Create an SMTP connection from a Config object | Below is the the instruction that describes the task:
### Input:
Create an SMTP connection from a Config object
### Response:
def smtp_connection(c):
"""Create an SMTP connection from a Config object"""
if c.smtp_ssl:
klass = smtplib.SMTP_SSL
else:
klass = smtplib.SMTP
conn = klass(... |
def is_owner():
"""A :func:`.check` that checks if the person invoking this command is the
owner of the bot.
This is powered by :meth:`.Bot.is_owner`.
This check raises a special exception, :exc:`.NotOwner` that is derived
from :exc:`.CheckFailure`.
"""
async def predicate(ctx):
i... | A :func:`.check` that checks if the person invoking this command is the
owner of the bot.
This is powered by :meth:`.Bot.is_owner`.
This check raises a special exception, :exc:`.NotOwner` that is derived
from :exc:`.CheckFailure`. | Below is the the instruction that describes the task:
### Input:
A :func:`.check` that checks if the person invoking this command is the
owner of the bot.
This is powered by :meth:`.Bot.is_owner`.
This check raises a special exception, :exc:`.NotOwner` that is derived
from :exc:`.CheckFailure`.
##... |
def _has_role(self, role_name_or_list):
"""
Whether the user has this role name
"""
if not isinstance(role_name_or_list, list):
role_name_or_list = [role_name_or_list]
return any(
[r.name in role_name_or_list for r in self.get_user_roles()]) | Whether the user has this role name | Below is the the instruction that describes the task:
### Input:
Whether the user has this role name
### Response:
def _has_role(self, role_name_or_list):
"""
Whether the user has this role name
"""
if not isinstance(role_name_or_list, list):
role_name_or_list = [role_na... |
def abspath(myPath):
import sys, os
""" Get absolute path to resource, works for dev and for PyInstaller """
try:
# PyInstaller creates a temp folder and stores path in _MEIPASS
base_path = sys._MEIPASS
return os.path.join(base_path, os.path.basename(myPath))
except Exception:
... | Get absolute path to resource, works for dev and for PyInstaller | Below is the the instruction that describes the task:
### Input:
Get absolute path to resource, works for dev and for PyInstaller
### Response:
def abspath(myPath):
import sys, os
""" Get absolute path to resource, works for dev and for PyInstaller """
try:
# PyInstaller creates a temp folder a... |
def decorator(caller, _func=None):
"""decorator(caller) converts a caller function into a decorator"""
if _func is not None: # return a decorated function
# this is obsolete behavior; you should use decorate instead
return decorate(_func, caller)
# else return a decorator function
if in... | decorator(caller) converts a caller function into a decorator | Below is the the instruction that describes the task:
### Input:
decorator(caller) converts a caller function into a decorator
### Response:
def decorator(caller, _func=None):
"""decorator(caller) converts a caller function into a decorator"""
if _func is not None: # return a decorated function
# ... |
def matches_key_in_query(self, key, query_key, query):
"""
增加查询条件,限制查询结果对象指定字段的值,与另外一个查询对象的返回结果指定的值相同。
:param key: 查询条件字段名
:param query_key: 查询对象返回结果的字段名
:param query: 查询对象
:type query: Query
:rtype: Query
"""
dumped = query.dump()
dumped[... | 增加查询条件,限制查询结果对象指定字段的值,与另外一个查询对象的返回结果指定的值相同。
:param key: 查询条件字段名
:param query_key: 查询对象返回结果的字段名
:param query: 查询对象
:type query: Query
:rtype: Query | Below is the the instruction that describes the task:
### Input:
增加查询条件,限制查询结果对象指定字段的值,与另外一个查询对象的返回结果指定的值相同。
:param key: 查询条件字段名
:param query_key: 查询对象返回结果的字段名
:param query: 查询对象
:type query: Query
:rtype: Query
### Response:
def matches_key_in_query(self, key, query_key, q... |
def _fake_referencenames(self, namespace, **params):
"""
Implements a mock WBEM server responder for
:meth:`~pywbem.WBEMConnection.ReferenceNames`
"""
assert params['ResultClass'] is None or \
isinstance(params['ResultClass'], CIMClassName)
rc = None if param... | Implements a mock WBEM server responder for
:meth:`~pywbem.WBEMConnection.ReferenceNames` | Below is the the instruction that describes the task:
### Input:
Implements a mock WBEM server responder for
:meth:`~pywbem.WBEMConnection.ReferenceNames`
### Response:
def _fake_referencenames(self, namespace, **params):
"""
Implements a mock WBEM server responder for
:meth:`~pywbe... |
def _doCommandCompletion(self):
""" Command-completion method """
prefix = ''.join(self.inputBuffer).strip().upper()
matches = self.completion.keys(prefix)
matchLen = len(matches)
if matchLen == 0 and prefix[-1] == '=':
try:
... | Command-completion method | Below is the the instruction that describes the task:
### Input:
Command-completion method
### Response:
def _doCommandCompletion(self):
""" Command-completion method """
prefix = ''.join(self.inputBuffer).strip().upper()
matches = self.completion.keys(prefix)
matchLen = le... |
def parse_args(*args, **kwargs):
"""
Parse the args for the command.
It should be possible for one to specify '--ns', '-x', and '--rename'
multiple times:
>>> args = parse_args(['--ns', 'foo', 'bar', '--ns', 'baz'])
>>> args.ns
['foo', 'bar', 'baz']
>>> parse_args(['-x', '--exclude'])... | Parse the args for the command.
It should be possible for one to specify '--ns', '-x', and '--rename'
multiple times:
>>> args = parse_args(['--ns', 'foo', 'bar', '--ns', 'baz'])
>>> args.ns
['foo', 'bar', 'baz']
>>> parse_args(['-x', '--exclude']).exclude
[]
>>> renames = parse_args... | Below is the the instruction that describes the task:
### Input:
Parse the args for the command.
It should be possible for one to specify '--ns', '-x', and '--rename'
multiple times:
>>> args = parse_args(['--ns', 'foo', 'bar', '--ns', 'baz'])
>>> args.ns
['foo', 'bar', 'baz']
>>> parse_a... |
def get_digests(self):
'''return a list of layers from a manifest.
The function is intended to work with both version
1 and 2 of the schema. All layers (including redundant)
are returned. By default, we try version 2 first,
then fall back to version 1.
For version 1 manifests: ex... | return a list of layers from a manifest.
The function is intended to work with both version
1 and 2 of the schema. All layers (including redundant)
are returned. By default, we try version 2 first,
then fall back to version 1.
For version 1 manifests: extraction is reversed
P... | Below is the the instruction that describes the task:
### Input:
return a list of layers from a manifest.
The function is intended to work with both version
1 and 2 of the schema. All layers (including redundant)
are returned. By default, we try version 2 first,
then fall back to version... |
def is_log(value):
"""
This function checks whether file path
that is specified at "log_file" option exists,
whether write permission to the file path.
Return the following value:
case1: exists path and write permission
is_log('/tmp')
'/tmp/hogehoge.log'
case2: non-exis... | This function checks whether file path
that is specified at "log_file" option exists,
whether write permission to the file path.
Return the following value:
case1: exists path and write permission
is_log('/tmp')
'/tmp/hogehoge.log'
case2: non-exists path and write permission
... | Below is the the instruction that describes the task:
### Input:
This function checks whether file path
that is specified at "log_file" option exists,
whether write permission to the file path.
Return the following value:
case1: exists path and write permission
is_log('/tmp')
'/... |
def fake_shell(self, func, stdout=False):
"""
Execute a function and decorate its return value in the style of
_low_level_execute_command(). This produces a return value that looks
like some shell command was run, when really func() was implemented
entirely in Python.
If... | Execute a function and decorate its return value in the style of
_low_level_execute_command(). This produces a return value that looks
like some shell command was run, when really func() was implemented
entirely in Python.
If the function raises :py:class:`mitogen.core.CallError`, this ... | Below is the the instruction that describes the task:
### Input:
Execute a function and decorate its return value in the style of
_low_level_execute_command(). This produces a return value that looks
like some shell command was run, when really func() was implemented
entirely in Python.
... |
def write_zip(self, resources=None, dumpfile=None):
"""Write a ZIP format dump file.
Writes a ZIP file containing the resources in the iterable resources along with
a manifest file manifest.xml (written first). No checks on the size of files
or total size are performed, this is expected... | Write a ZIP format dump file.
Writes a ZIP file containing the resources in the iterable resources along with
a manifest file manifest.xml (written first). No checks on the size of files
or total size are performed, this is expected to have been done beforehand. | Below is the the instruction that describes the task:
### Input:
Write a ZIP format dump file.
Writes a ZIP file containing the resources in the iterable resources along with
a manifest file manifest.xml (written first). No checks on the size of files
or total size are performed, this is ex... |
def Reverse(self, y):
"""Looks up y and returns the corresponding value of x."""
return self._Bisect(y, self.ys, self.xs) | Looks up y and returns the corresponding value of x. | Below is the the instruction that describes the task:
### Input:
Looks up y and returns the corresponding value of x.
### Response:
def Reverse(self, y):
"""Looks up y and returns the corresponding value of x."""
return self._Bisect(y, self.ys, self.xs) |
def get_messages(user):
"""
Fetch messages for given user. Returns None if no such message exists.
:param user: User instance
"""
key = _user_key(user)
result = cache.get(key)
if result:
cache.delete(key)
return result
return None | Fetch messages for given user. Returns None if no such message exists.
:param user: User instance | Below is the the instruction that describes the task:
### Input:
Fetch messages for given user. Returns None if no such message exists.
:param user: User instance
### Response:
def get_messages(user):
"""
Fetch messages for given user. Returns None if no such message exists.
:param user: User i... |
def clean_up_auth_url(auth_url):
"""Clean up the auth url to extract the exact Keystone URL"""
# NOTE(mnaser): This drops the query and fragment because we're only
# trying to extract the Keystone URL.
scheme, netloc, path, query, fragment = urlparse.urlsplit(auth_url)
return urlparse... | Clean up the auth url to extract the exact Keystone URL | Below is the the instruction that describes the task:
### Input:
Clean up the auth url to extract the exact Keystone URL
### Response:
def clean_up_auth_url(auth_url):
"""Clean up the auth url to extract the exact Keystone URL"""
# NOTE(mnaser): This drops the query and fragment because we're only
# ... |
def gevent_run(app, monkey_patch=True, start=True, debug=False,
**kwargs): # pragma: no cover
"""Run your app in gevent.spawn, run simple loop if start == True
:param app: queues.Microservice instance
:param monkey_patch: boolean, use gevent.monkey.patch_all() for patching standard modules,... | Run your app in gevent.spawn, run simple loop if start == True
:param app: queues.Microservice instance
:param monkey_patch: boolean, use gevent.monkey.patch_all() for patching standard modules, default: True
:param start: boolean, if True, server will be start (simple loop)
:param kwargs: other params... | Below is the the instruction that describes the task:
### Input:
Run your app in gevent.spawn, run simple loop if start == True
:param app: queues.Microservice instance
:param monkey_patch: boolean, use gevent.monkey.patch_all() for patching standard modules, default: True
:param start: boolean, if Tru... |
def count_frames(frame, count_start=0):
"Return a count of the number of frames"
count = -count_start
while frame:
count += 1
frame = frame.f_back
return count | Return a count of the number of frames | Below is the the instruction that describes the task:
### Input:
Return a count of the number of frames
### Response:
def count_frames(frame, count_start=0):
"Return a count of the number of frames"
count = -count_start
while frame:
count += 1
frame = frame.f_back
return count |
def sample_stats_prior_to_xarray(self):
"""Extract sample_stats from fit."""
dtypes = {"divergent__": bool, "n_leapfrog__": np.int64, "treedepth__": np.int64}
# copy dims and coords
dims = deepcopy(self.dims) if self.dims is not None else {}
coords = deepcopy(self.coords) if sel... | Extract sample_stats from fit. | Below is the the instruction that describes the task:
### Input:
Extract sample_stats from fit.
### Response:
def sample_stats_prior_to_xarray(self):
"""Extract sample_stats from fit."""
dtypes = {"divergent__": bool, "n_leapfrog__": np.int64, "treedepth__": np.int64}
# copy dims and coord... |
def match(self, *args, **kwargs):
"""
Check the if these args match this expectation.
"""
return self._any_args or \
self._arguments_rule.validate(*args, **kwargs) | Check the if these args match this expectation. | Below is the the instruction that describes the task:
### Input:
Check the if these args match this expectation.
### Response:
def match(self, *args, **kwargs):
"""
Check the if these args match this expectation.
"""
return self._any_args or \
self._arguments_rule.valida... |
def decode_rfc2231(s):
"""Decode string according to RFC 2231"""
parts = s.split(TICK, 2)
if len(parts) <= 2:
return None, None, s
return parts | Decode string according to RFC 2231 | Below is the the instruction that describes the task:
### Input:
Decode string according to RFC 2231
### Response:
def decode_rfc2231(s):
"""Decode string according to RFC 2231"""
parts = s.split(TICK, 2)
if len(parts) <= 2:
return None, None, s
return parts |
def eventdata(payload):
"""
Parse a Supervisor event.
"""
headerinfo, data = payload.split('\n', 1)
headers = get_headers(headerinfo)
return headers, data | Parse a Supervisor event. | Below is the the instruction that describes the task:
### Input:
Parse a Supervisor event.
### Response:
def eventdata(payload):
"""
Parse a Supervisor event.
"""
headerinfo, data = payload.split('\n', 1)
headers = get_headers(headerinfo)
return headers, data |
def html_state(self):
"""Display state in HTML format for the admin form."""
ret = ""
state = json.loads(self.state)
for (app, appstate) in state.items():
for (model, modelstate) in appstate.items():
ret += "<p>%s.models.%s</p>" % (app, model,)
... | Display state in HTML format for the admin form. | Below is the the instruction that describes the task:
### Input:
Display state in HTML format for the admin form.
### Response:
def html_state(self):
"""Display state in HTML format for the admin form."""
ret = ""
state = json.loads(self.state)
for (app, appstate) in state.items():
... |
def url_for(self, *args: str, **kwargs: str) -> URL:
"""Construct url for route with additional params."""
return self._resource.url_for(*args, **kwargs) | Construct url for route with additional params. | Below is the the instruction that describes the task:
### Input:
Construct url for route with additional params.
### Response:
def url_for(self, *args: str, **kwargs: str) -> URL:
"""Construct url for route with additional params."""
return self._resource.url_for(*args, **kwargs) |
def iteration(self, node_status=True):
"""
Execute a single model iteration
:return: Iteration_id, Incremental node status (dictionary node->status)
"""
self.clean_initial_status(self.available_statuses.values())
actual_status = {node: nstatus for node, nstatus in future... | Execute a single model iteration
:return: Iteration_id, Incremental node status (dictionary node->status) | Below is the the instruction that describes the task:
### Input:
Execute a single model iteration
:return: Iteration_id, Incremental node status (dictionary node->status)
### Response:
def iteration(self, node_status=True):
"""
Execute a single model iteration
:return: Iteration_i... |
def eigen(matrix):
""" Calculates the eigenvalues and eigenvectors of the input matrix.
Returns a tuple of (eigenvalues, eigenvectors, cumulative percentage of
variance explained). Eigenvalues and eigenvectors are sorted in order of
eigenvalue magnitude, high to low """
(vals, vecs) = np.linalg.eig... | Calculates the eigenvalues and eigenvectors of the input matrix.
Returns a tuple of (eigenvalues, eigenvectors, cumulative percentage of
variance explained). Eigenvalues and eigenvectors are sorted in order of
eigenvalue magnitude, high to low | Below is the the instruction that describes the task:
### Input:
Calculates the eigenvalues and eigenvectors of the input matrix.
Returns a tuple of (eigenvalues, eigenvectors, cumulative percentage of
variance explained). Eigenvalues and eigenvectors are sorted in order of
eigenvalue magnitude, high to... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.