code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def _on_process_error(self, error):
""" Logs process error """
if self is None:
return
if error not in PROCESS_ERROR_STRING:
error = -1
if not self._prevent_logs:
_logger().warning(PROCESS_ERROR_STRING[error]) | Logs process error | Below is the the instruction that describes the task:
### Input:
Logs process error
### Response:
def _on_process_error(self, error):
""" Logs process error """
if self is None:
return
if error not in PROCESS_ERROR_STRING:
error = -1
if not self._prevent_logs... |
def get_adapter(self, model):
"""Returns the adapter associated with the given model."""
if not self.is_registered(model):
raise RegistrationError(
'{} is not registered with Algolia engine'.format(model))
return self.__registered_models[model] | Returns the adapter associated with the given model. | Below is the the instruction that describes the task:
### Input:
Returns the adapter associated with the given model.
### Response:
def get_adapter(self, model):
"""Returns the adapter associated with the given model."""
if not self.is_registered(model):
raise RegistrationError(
... |
def no_ssl_verification(self):
""" Requests module fails due to lets encrypt ssl encryption. Will be fixed in the future release."""
try:
from functools import partialmethod
except ImportError:
# Python 2 fallback: https://gist.github.com/carymrobbins/8940382
... | Requests module fails due to lets encrypt ssl encryption. Will be fixed in the future release. | Below is the the instruction that describes the task:
### Input:
Requests module fails due to lets encrypt ssl encryption. Will be fixed in the future release.
### Response:
def no_ssl_verification(self):
""" Requests module fails due to lets encrypt ssl encryption. Will be fixed in the future release."""
... |
def reset(self):
"""
Reset all statistics and clear any statistic names.
All statistics must be inactive before a reset will execute
Returns: True if reset, False if not
"""
# Test for any stats being currently timed.
for stat in six.itervalues(self._op_stats):
... | Reset all statistics and clear any statistic names.
All statistics must be inactive before a reset will execute
Returns: True if reset, False if not | Below is the the instruction that describes the task:
### Input:
Reset all statistics and clear any statistic names.
All statistics must be inactive before a reset will execute
Returns: True if reset, False if not
### Response:
def reset(self):
"""
Reset all statistics and clear an... |
def run_shell(cmd: str,
out: Optional[Union[TeeCapture, IO[str]]] = sys.stdout,
err: Optional[Union[TeeCapture, IO[str]]] = sys.stderr,
raise_on_fail: bool = True,
log_run_to_stderr: bool = True,
**kwargs
) -> CommandOutput:
"""Invo... | Invokes a shell command and waits for it to finish.
Args:
cmd: The command line string to execute, e.g. "echo dog | cat > file".
out: Where to write the process' stdout. Defaults to sys.stdout. Can be
anything accepted by print's 'file' parameter, or None if the
output shoul... | Below is the the instruction that describes the task:
### Input:
Invokes a shell command and waits for it to finish.
Args:
cmd: The command line string to execute, e.g. "echo dog | cat > file".
out: Where to write the process' stdout. Defaults to sys.stdout. Can be
anything accepted... |
def http_post_request(url, params, add_to_headers=None, _async=False):
"""
from 火币demo, post方法
:param url:
:param params:
:param add_to_headers:
:return:
"""
headers = {
"Accept": "application/json",
'Content-Type': 'application/json'
}
if add_to_headers:
... | from 火币demo, post方法
:param url:
:param params:
:param add_to_headers:
:return: | Below is the the instruction that describes the task:
### Input:
from 火币demo, post方法
:param url:
:param params:
:param add_to_headers:
:return:
### Response:
def http_post_request(url, params, add_to_headers=None, _async=False):
"""
from 火币demo, post方法
:param url:
:param params:
... |
def _http_headers(self):
"""Return dictionary of http headers necessary for making an http
connection to the endpoint of this Connection.
:return: Dictionary of headers
"""
if not self.usertag:
return {}
creds = u'{}:{}'.format(
self.usertag,
... | Return dictionary of http headers necessary for making an http
connection to the endpoint of this Connection.
:return: Dictionary of headers | Below is the the instruction that describes the task:
### Input:
Return dictionary of http headers necessary for making an http
connection to the endpoint of this Connection.
:return: Dictionary of headers
### Response:
def _http_headers(self):
"""Return dictionary of http headers necessar... |
def play_move(self, c):
"""Notable side effects:
- finalizes the probability distribution according to
this roots visit counts into the class' running tally, `searches_pi`
- Makes the node associated with this move the root, for future
`inject_noise` calls.
"""
... | Notable side effects:
- finalizes the probability distribution according to
this roots visit counts into the class' running tally, `searches_pi`
- Makes the node associated with this move the root, for future
`inject_noise` calls. | Below is the the instruction that describes the task:
### Input:
Notable side effects:
- finalizes the probability distribution according to
this roots visit counts into the class' running tally, `searches_pi`
- Makes the node associated with this move the root, for future
... |
def summarize_classes(self):
"""
Summary of classes: names, numeric labels and sizes
Returns
-------
tuple : class_set, label_set, class_sizes
class_set : list
List of names of all the classes
label_set : list
Label for each class in clas... | Summary of classes: names, numeric labels and sizes
Returns
-------
tuple : class_set, label_set, class_sizes
class_set : list
List of names of all the classes
label_set : list
Label for each class in class_set
class_sizes : list
Size... | Below is the the instruction that describes the task:
### Input:
Summary of classes: names, numeric labels and sizes
Returns
-------
tuple : class_set, label_set, class_sizes
class_set : list
List of names of all the classes
label_set : list
Label fo... |
def from_array(array):
"""
Deserialize a new InlineQuery from a given dictionary.
:return: new InlineQuery instance.
:rtype: InlineQuery
"""
if array is None or not array:
return None
# end if
assert_type_or_raise(array, dict, parameter_name="... | Deserialize a new InlineQuery from a given dictionary.
:return: new InlineQuery instance.
:rtype: InlineQuery | Below is the the instruction that describes the task:
### Input:
Deserialize a new InlineQuery from a given dictionary.
:return: new InlineQuery instance.
:rtype: InlineQuery
### Response:
def from_array(array):
"""
Deserialize a new InlineQuery from a given dictionary.
:r... |
def check_structure(filepath):
"""Returns False if the file is okay, None if file format is unsupported by PIL/PILLOW, or returns an error string if the file is corrupt."""
#http://stackoverflow.com/questions/1401527/how-do-i-programmatically-check-whether-an-image-png-jpeg-or-gif-is-corrupted/1401565#1401565
... | Returns False if the file is okay, None if file format is unsupported by PIL/PILLOW, or returns an error string if the file is corrupt. | Below is the the instruction that describes the task:
### Input:
Returns False if the file is okay, None if file format is unsupported by PIL/PILLOW, or returns an error string if the file is corrupt.
### Response:
def check_structure(filepath):
"""Returns False if the file is okay, None if file format is unsu... |
def Run(self):
"""Run it and collect output.
Returns:
1 (true) If everything went well.
0 (false) If there were problems.
"""
if not self.executable:
logging.error('Could not locate "%s"' % self.long_name)
return 0
finfo = os.stat(self.executable)
self.date = time.lo... | Run it and collect output.
Returns:
1 (true) If everything went well.
0 (false) If there were problems. | Below is the the instruction that describes the task:
### Input:
Run it and collect output.
Returns:
1 (true) If everything went well.
0 (false) If there were problems.
### Response:
def Run(self):
"""Run it and collect output.
Returns:
1 (true) If everything went well.
0... |
def split_pair(pair_string, separator, nullable_idx=1):
"""Split a string into a pair, which can have one empty value.
Args:
pair_string: The string to be split.
separator: The separator to be used for splitting.
nullable_idx: The location to be set to null if the separator is not in the
... | Split a string into a pair, which can have one empty value.
Args:
pair_string: The string to be split.
separator: The separator to be used for splitting.
nullable_idx: The location to be set to null if the separator is not in the
input string. Should be either 0 or 1.
Returns:
A ... | Below is the the instruction that describes the task:
### Input:
Split a string into a pair, which can have one empty value.
Args:
pair_string: The string to be split.
separator: The separator to be used for splitting.
nullable_idx: The location to be set to null if the separator is not in the
... |
def _ast_op_repeat_to_code(self, opr, ignore_whitespace=False, **kwargs):
"""Convert an AST repeat op to python source code."""
lines = ["one_or_more("]
lines.extend(self._indent(self._ast_to_code(opr.operands[0])))
lines[-1] += ","
lines.append(self._indent("ignore_whitespace={}".format(bool(ignore... | Convert an AST repeat op to python source code. | Below is the the instruction that describes the task:
### Input:
Convert an AST repeat op to python source code.
### Response:
def _ast_op_repeat_to_code(self, opr, ignore_whitespace=False, **kwargs):
"""Convert an AST repeat op to python source code."""
lines = ["one_or_more("]
lines.extend(self._inde... |
def load(self, reload=False):
"""
Load the config and defaults from files.
"""
if reload or not self._loaded:
# load defaults
if self._defaults_file and type(self._defaults_file) == str:
self._defaults_file = File(self._defaults_file, parent=self._... | Load the config and defaults from files. | Below is the the instruction that describes the task:
### Input:
Load the config and defaults from files.
### Response:
def load(self, reload=False):
"""
Load the config and defaults from files.
"""
if reload or not self._loaded:
# load defaults
if self._defa... |
def scale_image(self):
"""Scale the image size."""
new_width = int(self.figcanvas.fwidth *
self._scalestep ** self._scalefactor)
new_height = int(self.figcanvas.fheight *
self._scalestep ** self._scalefactor)
self.figcanvas.setFixedSize(ne... | Scale the image size. | Below is the the instruction that describes the task:
### Input:
Scale the image size.
### Response:
def scale_image(self):
"""Scale the image size."""
new_width = int(self.figcanvas.fwidth *
self._scalestep ** self._scalefactor)
new_height = int(self.figcanvas.fheig... |
def niceString2uri(aUriString, namespaces=None):
"""
From a string representing a URI possibly with the namespace qname, returns a URI instance.
gold:Citation ==> rdflib.term.URIRef(u'http://purl.org/linguistics/gold/Citation')
Namespaces are a list
[('xml', rdflib.URIRef('http://www.w3.org/XML/... | From a string representing a URI possibly with the namespace qname, returns a URI instance.
gold:Citation ==> rdflib.term.URIRef(u'http://purl.org/linguistics/gold/Citation')
Namespaces are a list
[('xml', rdflib.URIRef('http://www.w3.org/XML/1998/namespace'))
('', rdflib.URIRef('http://cohereweb.ne... | Below is the the instruction that describes the task:
### Input:
From a string representing a URI possibly with the namespace qname, returns a URI instance.
gold:Citation ==> rdflib.term.URIRef(u'http://purl.org/linguistics/gold/Citation')
Namespaces are a list
[('xml', rdflib.URIRef('http://www.w3.... |
def send(self, destination, body, content_type=None, headers=None, **keyword_headers):
"""
Send a message to a destination.
:param str destination: the destination of the message (e.g. queue or topic name)
:param body: the content of the message
:param str content_type: the cont... | Send a message to a destination.
:param str destination: the destination of the message (e.g. queue or topic name)
:param body: the content of the message
:param str content_type: the content type of the message
:param dict headers: a map of any additional headers the broker requires
... | Below is the the instruction that describes the task:
### Input:
Send a message to a destination.
:param str destination: the destination of the message (e.g. queue or topic name)
:param body: the content of the message
:param str content_type: the content type of the message
:param... |
def submission(self):
"""Return the Submission object this comment belongs to."""
if not self._submission: # Comment not from submission
self._submission = self.reddit_session.get_submission(
url=self._fast_permalink)
return self._submission | Return the Submission object this comment belongs to. | Below is the the instruction that describes the task:
### Input:
Return the Submission object this comment belongs to.
### Response:
def submission(self):
"""Return the Submission object this comment belongs to."""
if not self._submission: # Comment not from submission
self._submission... |
def toUnicode(data, encoding=DEFAULT_ENCODING):
"""
Converts the inputted data to unicode format.
:param data | <str> || <unicode> || <iterable>
:return <unicode> || <iterable>
"""
if isinstance(data, unicode_type):
return data
if isinstance(data, bytes_type):
... | Converts the inputted data to unicode format.
:param data | <str> || <unicode> || <iterable>
:return <unicode> || <iterable> | Below is the the instruction that describes the task:
### Input:
Converts the inputted data to unicode format.
:param data | <str> || <unicode> || <iterable>
:return <unicode> || <iterable>
### Response:
def toUnicode(data, encoding=DEFAULT_ENCODING):
"""
Converts the inputted da... |
def nside2pixarea(nside, degrees=False):
"""Drop-in replacement for healpy `~healpy.pixelfunc.nside2pixarea`."""
area = nside_to_pixel_area(nside)
if degrees:
return area.to(u.deg ** 2).value
else:
return area.to(u.sr).value | Drop-in replacement for healpy `~healpy.pixelfunc.nside2pixarea`. | Below is the the instruction that describes the task:
### Input:
Drop-in replacement for healpy `~healpy.pixelfunc.nside2pixarea`.
### Response:
def nside2pixarea(nside, degrees=False):
"""Drop-in replacement for healpy `~healpy.pixelfunc.nside2pixarea`."""
area = nside_to_pixel_area(nside)
if degrees:... |
def title_line(text):
"""Returns a string that represents the
text as a title blurb
"""
columns = shutil.get_terminal_size()[0]
start = columns // 2 - len(text) // 2
output = '='*columns + '\n\n' + \
' ' * start + str(text) + "\n\n" + \
'='*columns + '\n'
return outpu... | Returns a string that represents the
text as a title blurb | Below is the the instruction that describes the task:
### Input:
Returns a string that represents the
text as a title blurb
### Response:
def title_line(text):
"""Returns a string that represents the
text as a title blurb
"""
columns = shutil.get_terminal_size()[0]
start = columns // 2 - le... |
def _get_lantern_format(self, df):
""" Feature slice view browser expects data in the format of:
{"metricValues": {"count": 12, "accuracy": 1.0}, "feature": "species:Iris-setosa"}
{"metricValues": {"count": 11, "accuracy": 0.72}, "feature": "species:Iris-versicolor"}
...
This f... | Feature slice view browser expects data in the format of:
{"metricValues": {"count": 12, "accuracy": 1.0}, "feature": "species:Iris-setosa"}
{"metricValues": {"count": 11, "accuracy": 0.72}, "feature": "species:Iris-versicolor"}
...
This function converts a DataFrame to such format... | Below is the the instruction that describes the task:
### Input:
Feature slice view browser expects data in the format of:
{"metricValues": {"count": 12, "accuracy": 1.0}, "feature": "species:Iris-setosa"}
{"metricValues": {"count": 11, "accuracy": 0.72}, "feature": "species:Iris-versicolor"}
... |
def figure_grid(figures_grid,
row_heights=None,
column_widths=None,
row_spacing=0.15,
column_spacing=0.15,
share_xaxis=False,
share_yaxis=False):
"""
Construct a figure from a 2D grid of sub-figures
Parameters
... | Construct a figure from a 2D grid of sub-figures
Parameters
----------
figures_grid: list of list of (dict or None)
2D list of plotly figure dicts that will be combined in a grid to
produce the resulting figure. None values maybe used to leave empty
grid cells
row_heights: list... | Below is the the instruction that describes the task:
### Input:
Construct a figure from a 2D grid of sub-figures
Parameters
----------
figures_grid: list of list of (dict or None)
2D list of plotly figure dicts that will be combined in a grid to
produce the resulting figure. None valu... |
def process_file(self, path, dryrun):
"""
Add header to all files.
"""
if dryrun:
return path
# get file's current header
with open(path, "r") as infile:
head = infile.read(len(self.__header))
# normalize line breaks
if self.__nor... | Add header to all files. | Below is the the instruction that describes the task:
### Input:
Add header to all files.
### Response:
def process_file(self, path, dryrun):
"""
Add header to all files.
"""
if dryrun:
return path
# get file's current header
with open(path, "r") as infi... |
def emit_children(self, node):
"""Emit all the children of a node."""
return "".join([self.emit_node(child) for child in node.children]) | Emit all the children of a node. | Below is the the instruction that describes the task:
### Input:
Emit all the children of a node.
### Response:
def emit_children(self, node):
"""Emit all the children of a node."""
return "".join([self.emit_node(child) for child in node.children]) |
def __execute_kadmin(cmd):
'''
Execute kadmin commands
'''
ret = {}
auth_keytab = __opts__.get('auth_keytab', None)
auth_principal = __opts__.get('auth_principal', None)
if __salt__['file.file_exists'](auth_keytab) and auth_principal:
return __salt__['cmd.run_all'](
'ka... | Execute kadmin commands | Below is the the instruction that describes the task:
### Input:
Execute kadmin commands
### Response:
def __execute_kadmin(cmd):
'''
Execute kadmin commands
'''
ret = {}
auth_keytab = __opts__.get('auth_keytab', None)
auth_principal = __opts__.get('auth_principal', None)
if __salt__[... |
def list_all_after(self, message_id, limit=None):
"""Return all group messages created after a message.
:param str message_id: the ID of a message
:param int limit: maximum number of messages per page
:return: group messages
:rtype: generator
"""
return self.list... | Return all group messages created after a message.
:param str message_id: the ID of a message
:param int limit: maximum number of messages per page
:return: group messages
:rtype: generator | Below is the the instruction that describes the task:
### Input:
Return all group messages created after a message.
:param str message_id: the ID of a message
:param int limit: maximum number of messages per page
:return: group messages
:rtype: generator
### Response:
def list_all_... |
async def handleAll(self, deq: deque, limit=None) -> int:
"""
Handle all items in a deque. Can call asynchronous handlers.
:param deq: a deque of items to be handled by this router
:param limit: the number of items in the deque to the handled
:return: the number of items handled... | Handle all items in a deque. Can call asynchronous handlers.
:param deq: a deque of items to be handled by this router
:param limit: the number of items in the deque to the handled
:return: the number of items handled successfully | Below is the the instruction that describes the task:
### Input:
Handle all items in a deque. Can call asynchronous handlers.
:param deq: a deque of items to be handled by this router
:param limit: the number of items in the deque to the handled
:return: the number of items handled successf... |
def _get_dependencies_from_cache(ireq):
"""Retrieves dependencies for the requirement from the dependency cache.
"""
if os.environ.get("PASSA_IGNORE_LOCAL_CACHE"):
return
if ireq.editable:
return
try:
deps = DEPENDENCY_CACHE[ireq]
pyrq = REQUIRES_PYTHON_CACHE[ireq]
... | Retrieves dependencies for the requirement from the dependency cache. | Below is the the instruction that describes the task:
### Input:
Retrieves dependencies for the requirement from the dependency cache.
### Response:
def _get_dependencies_from_cache(ireq):
"""Retrieves dependencies for the requirement from the dependency cache.
"""
if os.environ.get("PASSA_IGNORE_LOCAL... |
def choices(self):
""" Retrieve choices from API if possible"""
if not self._choices:
gandi = self.gandi or GandiContextHelper()
self._choices = self._get_choices(gandi)
if not self._choices:
api = gandi.get_api_connector()
gandi.echo('... | Retrieve choices from API if possible | Below is the the instruction that describes the task:
### Input:
Retrieve choices from API if possible
### Response:
def choices(self):
""" Retrieve choices from API if possible"""
if not self._choices:
gandi = self.gandi or GandiContextHelper()
self._choices = self._get_cho... |
def QA_util_make_hour_index(day, type_='1h'):
"""创建股票的小时线的index
Arguments:
day {[type]} -- [description]
Returns:
[type] -- [description]
"""
if QA_util_if_trade(day) is True:
return pd.date_range(
str(day) + ' 09:30:00',
str(day) + ' 11:30:00',
... | 创建股票的小时线的index
Arguments:
day {[type]} -- [description]
Returns:
[type] -- [description] | Below is the the instruction that describes the task:
### Input:
创建股票的小时线的index
Arguments:
day {[type]} -- [description]
Returns:
[type] -- [description]
### Response:
def QA_util_make_hour_index(day, type_='1h'):
"""创建股票的小时线的index
Arguments:
day {[type]} -- [description]... |
def stddev(self):
"""Return the sample standard deviation."""
if len(self) < 2:
return float('NaN')
# The stupidest algorithm, but it works fine.
try:
arr = self.samples()
mean = sum(arr) / len(arr)
bigsum = 0.0
for x in arr:
bigsum += (x - mean)**2
return sqr... | Return the sample standard deviation. | Below is the the instruction that describes the task:
### Input:
Return the sample standard deviation.
### Response:
def stddev(self):
"""Return the sample standard deviation."""
if len(self) < 2:
return float('NaN')
# The stupidest algorithm, but it works fine.
try:
arr = self.samples(... |
def get_local_urls(port):
'''get urls of local machine'''
url_list = []
for name, info in psutil.net_if_addrs().items():
for addr in info:
if AddressFamily.AF_INET == addr.family:
url_list.append('http://{}:{}'.format(addr.address, port))
return url_list | get urls of local machine | Below is the the instruction that describes the task:
### Input:
get urls of local machine
### Response:
def get_local_urls(port):
'''get urls of local machine'''
url_list = []
for name, info in psutil.net_if_addrs().items():
for addr in info:
if AddressFamily.AF_INET == addr.family... |
def create_slab_label(self):
"""
Returns a label (str) for this particular slab based
on composition, coverage and Miller index.
"""
if "label" in self.data.keys():
return self.data["label"]
label = str(self.miller_index)
ads_strs = list(self.ads... | Returns a label (str) for this particular slab based
on composition, coverage and Miller index. | Below is the the instruction that describes the task:
### Input:
Returns a label (str) for this particular slab based
on composition, coverage and Miller index.
### Response:
def create_slab_label(self):
"""
Returns a label (str) for this particular slab based
on composition... |
def upsert(self, rows, unique_fields, update_fields, return_rows=False, return_models=False):
"""
Performs an upsert with the set of models defined in rows. If the unique field which is meant
to cause a conflict is an auto increment field, then the field should be excluded when its value is null... | Performs an upsert with the set of models defined in rows. If the unique field which is meant
to cause a conflict is an auto increment field, then the field should be excluded when its value is null.
In this case, an upsert will be performed followed by a bulk_create | Below is the the instruction that describes the task:
### Input:
Performs an upsert with the set of models defined in rows. If the unique field which is meant
to cause a conflict is an auto increment field, then the field should be excluded when its value is null.
In this case, an upsert will be per... |
def parse_transcript(gene_obj, tx_obj, build=None):
"""Parse variant gene transcript (VEP)."""
build = build or 37
add_tx_links(tx_obj, build)
if tx_obj.get('refseq_id'):
gene_name = (gene_obj['common']['hgnc_symbol'] if gene_obj['common'] else
gene_obj['hgnc_id'])
... | Parse variant gene transcript (VEP). | Below is the the instruction that describes the task:
### Input:
Parse variant gene transcript (VEP).
### Response:
def parse_transcript(gene_obj, tx_obj, build=None):
"""Parse variant gene transcript (VEP)."""
build = build or 37
add_tx_links(tx_obj, build)
if tx_obj.get('refseq_id'):
gen... |
def get_value_display(self):
"""Human friendly value output"""
if self.display_as == 'percentage':
return '{0}%'.format(self.latest_value)
if self.display_as == 'boolean':
return bool(self.latest_value)
if self.display_as == 'byte':
return defaultfilte... | Human friendly value output | Below is the the instruction that describes the task:
### Input:
Human friendly value output
### Response:
def get_value_display(self):
"""Human friendly value output"""
if self.display_as == 'percentage':
return '{0}%'.format(self.latest_value)
if self.display_as == 'boolean':
... |
def format_table(table,
align='<',
format='{:.3g}',
colwidth=None,
maxwidth=None,
spacing=2,
truncate=0,
suffix="..."
):
"""
Formats a table represented as an iterable of iterab... | Formats a table represented as an iterable of iterable into a nice big string
suitable for printing.
Parameters:
-----------
align : string or list of strings
Alignment of cell contents. Each character in a string specifies
the alignment of one column.
* ``<`` - Le... | Below is the the instruction that describes the task:
### Input:
Formats a table represented as an iterable of iterable into a nice big string
suitable for printing.
Parameters:
-----------
align : string or list of strings
Alignment of cell contents. Each character in a string specifi... |
def clear_choice_texts(self, choice_id):
"""stub"""
if self.get_choices_metadata().is_read_only():
raise NoAccess()
updated_choices = []
for current_choice in self.my_osid_object_form._my_map['choices']:
if current_choice['id'] != choice_id:
update... | stub | Below is the the instruction that describes the task:
### Input:
stub
### Response:
def clear_choice_texts(self, choice_id):
"""stub"""
if self.get_choices_metadata().is_read_only():
raise NoAccess()
updated_choices = []
for current_choice in self.my_osid_object_form._my... |
def get_pairs(self, base=None, show_details=False):
"""
Function to fetch a list of trading pairs offered on the Switcheo decentralized exchange.
Execution of this function is as follows::
get_pairs() # Fetch all pairs
get_pairs(base="SWTH") # Fetc... | Function to fetch a list of trading pairs offered on the Switcheo decentralized exchange.
Execution of this function is as follows::
get_pairs() # Fetch all pairs
get_pairs(base="SWTH") # Fetch only SWTH base pairs
get_pairs(show_details=True) # Fetch ... | Below is the the instruction that describes the task:
### Input:
Function to fetch a list of trading pairs offered on the Switcheo decentralized exchange.
Execution of this function is as follows::
get_pairs() # Fetch all pairs
get_pairs(base="SWTH") # Fetch o... |
def getBottomRight(self):
""" Return the ``Location`` of the bottom right corner of this region """
return Location(self.x+self.w, self.y+self.h) | Return the ``Location`` of the bottom right corner of this region | Below is the the instruction that describes the task:
### Input:
Return the ``Location`` of the bottom right corner of this region
### Response:
def getBottomRight(self):
""" Return the ``Location`` of the bottom right corner of this region """
return Location(self.x+self.w, self.y+self.h) |
def create_table(self, name, *columns, **kwargs):
"""Create a new table with the same metadata and info
"""
targs = table_args(**kwargs)
args, kwargs = targs[:-1], targs[-1]
return Table(name, self.metadata, *columns, *args, **kwargs) | Create a new table with the same metadata and info | Below is the the instruction that describes the task:
### Input:
Create a new table with the same metadata and info
### Response:
def create_table(self, name, *columns, **kwargs):
"""Create a new table with the same metadata and info
"""
targs = table_args(**kwargs)
args, kwargs = t... |
def filter_304_headers(headers):
"""Filter a list of headers to include in a "304 Not Modified" response."""
return [(k, v) for k, v in headers if k.lower() not in _filter_from_304] | Filter a list of headers to include in a "304 Not Modified" response. | Below is the the instruction that describes the task:
### Input:
Filter a list of headers to include in a "304 Not Modified" response.
### Response:
def filter_304_headers(headers):
"""Filter a list of headers to include in a "304 Not Modified" response."""
return [(k, v) for k, v in headers if k.lower() n... |
def add_data_to_df(self, data: np.array):
"""Build Pandas Dataframe in memory"""
col_names = ['high_p', 'low_p', 'open_p', 'close_p', 'volume', 'oi']
data = np.array(data).reshape(-1, len(col_names) + 1)
df = pd.DataFrame(data=data[:, 1:], index=data[:, 0],
co... | Build Pandas Dataframe in memory | Below is the the instruction that describes the task:
### Input:
Build Pandas Dataframe in memory
### Response:
def add_data_to_df(self, data: np.array):
"""Build Pandas Dataframe in memory"""
col_names = ['high_p', 'low_p', 'open_p', 'close_p', 'volume', 'oi']
data = np.array(data).resha... |
def avail_images(call=None):
'''
Return a dict of all available VM images on the cloud provider.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
ret = ... | Return a dict of all available VM images on the cloud provider. | Below is the the instruction that describes the task:
### Input:
Return a dict of all available VM images on the cloud provider.
### Response:
def avail_images(call=None):
'''
Return a dict of all available VM images on the cloud provider.
'''
if call == 'action':
raise SaltCloudSystemExit(... |
def load_file(self, filepath, **kwargs):
""" loads a file into the defintion triplestore
args:
filepath: the path to the file
"""
log.setLevel(kwargs.get("log_level", self.log_level))
filename = os.path.split(filepath)[-1]
if filename in self.loaded:
... | loads a file into the defintion triplestore
args:
filepath: the path to the file | Below is the the instruction that describes the task:
### Input:
loads a file into the defintion triplestore
args:
filepath: the path to the file
### Response:
def load_file(self, filepath, **kwargs):
""" loads a file into the defintion triplestore
args:
filepath: ... |
def _encodeTimestamp(timestamp):
""" Encodes a 7-octet timestamp from the specified date
Note: the specified timestamp must have a UTC offset set; you can use gsmmodem.util.SimpleOffsetTzInfo for simple cases
:param timestamp: The timestamp to encode
:type timestamp: datetime.datetime
... | Encodes a 7-octet timestamp from the specified date
Note: the specified timestamp must have a UTC offset set; you can use gsmmodem.util.SimpleOffsetTzInfo for simple cases
:param timestamp: The timestamp to encode
:type timestamp: datetime.datetime
:return: The encoded timestamp
:rtyp... | Below is the the instruction that describes the task:
### Input:
Encodes a 7-octet timestamp from the specified date
Note: the specified timestamp must have a UTC offset set; you can use gsmmodem.util.SimpleOffsetTzInfo for simple cases
:param timestamp: The timestamp to encode
:type timestamp... |
def postproc (stats_result):
"""Simple helper to postprocess angular outputs from StatsCollectors in the
way we want.
"""
n, mean, scat = stats_result
mean *= 180 / np.pi # rad => deg
scat /= n # variance-of-samples => variance-of-mean
scat **= 0.5 # variance => stddev
scat *= 180 / np.... | Simple helper to postprocess angular outputs from StatsCollectors in the
way we want. | Below is the the instruction that describes the task:
### Input:
Simple helper to postprocess angular outputs from StatsCollectors in the
way we want.
### Response:
def postproc (stats_result):
"""Simple helper to postprocess angular outputs from StatsCollectors in the
way we want.
"""
n, mean... |
def get_num_sequenced(study_id):
"""Return number of sequenced tumors for given study.
This is useful for calculating mutation statistics in terms of the
prevalence of certain mutations within a type of cancer.
Parameters
----------
study_id : str
The ID of the cBio study.
Exam... | Return number of sequenced tumors for given study.
This is useful for calculating mutation statistics in terms of the
prevalence of certain mutations within a type of cancer.
Parameters
----------
study_id : str
The ID of the cBio study.
Example: 'paad_icgc'
Returns
------... | Below is the the instruction that describes the task:
### Input:
Return number of sequenced tumors for given study.
This is useful for calculating mutation statistics in terms of the
prevalence of certain mutations within a type of cancer.
Parameters
----------
study_id : str
The ID of... |
def delete_vector(self, hash_name, bucket_keys, data):
"""
Deletes vector and JSON-serializable data in buckets with specified keys.
"""
with self.redis_object.pipeline() as pipeline:
for key in bucket_keys:
redis_key = self._format_redis_key(hash_name, key)
... | Deletes vector and JSON-serializable data in buckets with specified keys. | Below is the the instruction that describes the task:
### Input:
Deletes vector and JSON-serializable data in buckets with specified keys.
### Response:
def delete_vector(self, hash_name, bucket_keys, data):
"""
Deletes vector and JSON-serializable data in buckets with specified keys.
"""
... |
def process_in_out_queues(func, q_in, q_out):
"""Iterate through a Queue, call, ``func`, and Queue the result
Parameters
----------
func : `callable`
any function that can take an element of the input `Queue` as
the only argument
q_in : `multiprocessing.queue.Queue`
the inp... | Iterate through a Queue, call, ``func`, and Queue the result
Parameters
----------
func : `callable`
any function that can take an element of the input `Queue` as
the only argument
q_in : `multiprocessing.queue.Queue`
the input `Queue`
q_out : `multiprocessing.queue.Queue`... | Below is the the instruction that describes the task:
### Input:
Iterate through a Queue, call, ``func`, and Queue the result
Parameters
----------
func : `callable`
any function that can take an element of the input `Queue` as
the only argument
q_in : `multiprocessing.queue.Queue`... |
def _delegate(self, path):
# type: (Text) -> Optional[FS]
"""Get a filesystem which has a given path.
"""
for _name, fs in self.iterate_fs():
if fs.exists(path):
return fs
return None | Get a filesystem which has a given path. | Below is the the instruction that describes the task:
### Input:
Get a filesystem which has a given path.
### Response:
def _delegate(self, path):
# type: (Text) -> Optional[FS]
"""Get a filesystem which has a given path.
"""
for _name, fs in self.iterate_fs():
if fs.exi... |
def parse(self):
"""Parse pattern list."""
result = ['']
negative = False
p = util.norm_pattern(self.pattern, not self.unix, self.raw_chars)
p = p.decode('latin-1') if self.is_bytes else p
if is_negative(p, self.flags):
negative = True
p = p[1:]... | Parse pattern list. | Below is the the instruction that describes the task:
### Input:
Parse pattern list.
### Response:
def parse(self):
"""Parse pattern list."""
result = ['']
negative = False
p = util.norm_pattern(self.pattern, not self.unix, self.raw_chars)
p = p.decode('latin-1') if self.... |
def get_netconf_client_capabilities_output_session_af_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_netconf_client_capabilities = ET.Element("get_netconf_client_capabilities")
config = get_netconf_client_capabilities
output = ET.SubEle... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def get_netconf_client_capabilities_output_session_af_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_netconf_client_capabilities = ET.Element("get_n... |
def get_place_details(api_key, place_id, **kwargs):
"""
sends request to detail to get a search string and uses standard proto buffer to get additional information
on the current status of popular times
:return: json details
"""
params = {
'placeid': place_id,
'key': api_key,
... | sends request to detail to get a search string and uses standard proto buffer to get additional information
on the current status of popular times
:return: json details | Below is the the instruction that describes the task:
### Input:
sends request to detail to get a search string and uses standard proto buffer to get additional information
on the current status of popular times
:return: json details
### Response:
def get_place_details(api_key, place_id, **kwargs):
"""... |
def bin_up_array_2d_using_mean(array_2d, bin_up_factor):
"""Bin up an array to coarser resolution, by binning up groups of pixels and using their mean value to determine \
the value of the new pixel.
If an array of shape (8,8) is input and the bin up size is 2, this would return a new array of size (4,4) ... | Bin up an array to coarser resolution, by binning up groups of pixels and using their mean value to determine \
the value of the new pixel.
If an array of shape (8,8) is input and the bin up size is 2, this would return a new array of size (4,4) where \
every pixel was the mean of each collection of 2x2 p... | Below is the the instruction that describes the task:
### Input:
Bin up an array to coarser resolution, by binning up groups of pixels and using their mean value to determine \
the value of the new pixel.
If an array of shape (8,8) is input and the bin up size is 2, this would return a new array of size (... |
def serialize(self, image):
"""Turn a Image into a base64 encoded FLAC picture block.
"""
pic = mutagen.flac.Picture()
pic.data = image.data
pic.type = image.type_index
pic.mime = image.mime_type
pic.desc = image.desc or u''
# Encoding with base64 returns... | Turn a Image into a base64 encoded FLAC picture block. | Below is the the instruction that describes the task:
### Input:
Turn a Image into a base64 encoded FLAC picture block.
### Response:
def serialize(self, image):
"""Turn a Image into a base64 encoded FLAC picture block.
"""
pic = mutagen.flac.Picture()
pic.data = image.data
... |
def set(self, key: str, value: str, opt: dict = None) -> None:
"""
设置 cookie.value 并设置属性
"""
self[key] = value
if opt is not None:
self[key].update(opt) | 设置 cookie.value 并设置属性 | Below is the the instruction that describes the task:
### Input:
设置 cookie.value 并设置属性
### Response:
def set(self, key: str, value: str, opt: dict = None) -> None:
"""
设置 cookie.value 并设置属性
"""
self[key] = value
if opt is not None:
self[key].update(opt) |
def _general_multithread(func):
""" return the general multithreading function using func """
def multithread(templates, stream, *args, **kwargs):
with pool_boy(ThreadPool, len(stream), **kwargs) as pool:
return _pool_normxcorr(templates, stream, pool=pool, func=func)
return multithrea... | return the general multithreading function using func | Below is the the instruction that describes the task:
### Input:
return the general multithreading function using func
### Response:
def _general_multithread(func):
""" return the general multithreading function using func """
def multithread(templates, stream, *args, **kwargs):
with pool_boy(Thre... |
def clip_and_copy_attack_outputs(self, attack_name, is_targeted):
"""Clips results of attack and copy it to directory with all images.
Args:
attack_name: name of the attack.
is_targeted: if True then attack is targeted, otherwise non-targeted.
"""
if is_targeted:
self._targeted_attack... | Clips results of attack and copy it to directory with all images.
Args:
attack_name: name of the attack.
is_targeted: if True then attack is targeted, otherwise non-targeted. | Below is the the instruction that describes the task:
### Input:
Clips results of attack and copy it to directory with all images.
Args:
attack_name: name of the attack.
is_targeted: if True then attack is targeted, otherwise non-targeted.
### Response:
def clip_and_copy_attack_outputs(self, attac... |
def sign(self, secret_exponent, val, gen_k=None):
"""
:param: secret_exponent: a :class:`Point <pycoin.ecdsa.Point.Point>` on the curve
:param: val: an integer value
:param: gen_k: a function generating __k values__
:returns: a pair of integers ``(r, s)`` represents an ecdsa sig... | :param: secret_exponent: a :class:`Point <pycoin.ecdsa.Point.Point>` on the curve
:param: val: an integer value
:param: gen_k: a function generating __k values__
:returns: a pair of integers ``(r, s)`` represents an ecdsa signature of ``val``
with public key ``self * secret_exponent... | Below is the the instruction that describes the task:
### Input:
:param: secret_exponent: a :class:`Point <pycoin.ecdsa.Point.Point>` on the curve
:param: val: an integer value
:param: gen_k: a function generating __k values__
:returns: a pair of integers ``(r, s)`` represents an ecdsa sign... |
def reverse(
self,
query,
radius=None,
exactly_one=True,
maxresults=None,
pageinformation=None,
language=None,
mode='retrieveAddresses',
timeout=DEFAULT_SENTINEL
):
"""
Return an address by lo... | Return an address by location point.
This implementation supports only a subset of all available parameters.
A list of all parameters of the pure REST API is available here:
https://developer.here.com/documentation/geocoder/topics/resource-reverse-geocode.html
:param query: The coordin... | Below is the the instruction that describes the task:
### Input:
Return an address by location point.
This implementation supports only a subset of all available parameters.
A list of all parameters of the pure REST API is available here:
https://developer.here.com/documentation/geocoder/to... |
async def observation(self):
"""Retrieve current weather observation."""
try:
observations = await self.api.observations()
except:
return self._last_observation
closest = self._filter_closest(self.station.latitude,
self.sta... | Retrieve current weather observation. | Below is the the instruction that describes the task:
### Input:
Retrieve current weather observation.
### Response:
async def observation(self):
"""Retrieve current weather observation."""
try:
observations = await self.api.observations()
except:
return self._last_... |
def within(self, x, j=None):
"""Checks which ellipsoid(s) `x` falls within, skipping the `j`-th
ellipsoid."""
# Loop through distance calculations if there aren't too many.
idxs = np.where([self.ells[i].contains(x) if i != j else True
for i in range(self.nells)]... | Checks which ellipsoid(s) `x` falls within, skipping the `j`-th
ellipsoid. | Below is the the instruction that describes the task:
### Input:
Checks which ellipsoid(s) `x` falls within, skipping the `j`-th
ellipsoid.
### Response:
def within(self, x, j=None):
"""Checks which ellipsoid(s) `x` falls within, skipping the `j`-th
ellipsoid."""
# Loop through dis... |
def remove_from_pythonpath(self, path):
"""Remove path from project's PYTHONPATH
Return True if path was removed, False if it was not found"""
pathlist = self.get_pythonpath()
if path in pathlist:
pathlist.pop(pathlist.index(path))
self.set_pythonpath(pathli... | Remove path from project's PYTHONPATH
Return True if path was removed, False if it was not found | Below is the the instruction that describes the task:
### Input:
Remove path from project's PYTHONPATH
Return True if path was removed, False if it was not found
### Response:
def remove_from_pythonpath(self, path):
"""Remove path from project's PYTHONPATH
Return True if path was removed... |
def decamel(string):
""""Split CamelCased words.
CamelCase -> Camel Case, dromedaryCase -> dromedary Case.
"""
regex = re.compile(r'(\B[A-Z][a-z]*)')
return regex.sub(r' \1', string) | Split CamelCased words.
CamelCase -> Camel Case, dromedaryCase -> dromedary Case. | Below is the the instruction that describes the task:
### Input:
Split CamelCased words.
CamelCase -> Camel Case, dromedaryCase -> dromedary Case.
### Response:
def decamel(string):
""""Split CamelCased words.
CamelCase -> Camel Case, dromedaryCase -> dromedary Case.
"""
regex = re.compile(r'... |
def parse_http_header(header_line):
"""Parse an HTTP header from a string, and return an ``HttpHeader``.
``header_line`` should only contain one line.
``BadHttpHeaderError`` is raised if the string is an invalid header line.
"""
header_line = header_line.decode().strip()
col_idx = header_line.... | Parse an HTTP header from a string, and return an ``HttpHeader``.
``header_line`` should only contain one line.
``BadHttpHeaderError`` is raised if the string is an invalid header line. | Below is the the instruction that describes the task:
### Input:
Parse an HTTP header from a string, and return an ``HttpHeader``.
``header_line`` should only contain one line.
``BadHttpHeaderError`` is raised if the string is an invalid header line.
### Response:
def parse_http_header(header_line):
"... |
def t_CONSTANT(tok): # pylint: disable=locally-disabled,invalid-name
r'"([^"]+)"|\'([^\']+)\''
tok.value = (tok.type, re.sub('["\']', '', tok.value))
return tok | r'"([^"]+)"|\'([^\']+)\ | Below is the the instruction that describes the task:
### Input:
r'"([^"]+)"|\'([^\']+)\
### Response:
def t_CONSTANT(tok): # pylint: disable=locally-disabled,invalid-name
r'"([^"]+)"|\'([^\']+)\''
tok.value = (tok.type, re.sub('["\']', '', tok.value))
return tok |
def _load(self, scale=0.001):
"""Load the VIIRS RSR data for the band requested"""
if self.bandname == 'DNB':
header_lines_to_skip = N_HEADER_LINES_DNB[self.platform_name]
else:
header_lines_to_skip = N_HEADER_LINES[self.platform_name]
try:
data = np.... | Load the VIIRS RSR data for the band requested | Below is the the instruction that describes the task:
### Input:
Load the VIIRS RSR data for the band requested
### Response:
def _load(self, scale=0.001):
"""Load the VIIRS RSR data for the band requested"""
if self.bandname == 'DNB':
header_lines_to_skip = N_HEADER_LINES_DNB[self.plat... |
def to_dict(self, field=None, **kwargs):
"""
Convert the ParameterSet to a structured (nested) dictionary
to allow traversing the structure from the bottom up
:parameter str field: (optional) build the dictionary with keys at
a given level/field. Can be any of the keys in
... | Convert the ParameterSet to a structured (nested) dictionary
to allow traversing the structure from the bottom up
:parameter str field: (optional) build the dictionary with keys at
a given level/field. Can be any of the keys in
:func:`meta`. If None, the keys will be the lowes... | Below is the the instruction that describes the task:
### Input:
Convert the ParameterSet to a structured (nested) dictionary
to allow traversing the structure from the bottom up
:parameter str field: (optional) build the dictionary with keys at
a given level/field. Can be any of the k... |
def add_omim_info(genes, alias_genes, genemap_lines, mim2gene_lines):
"""Add omim information
We collect information on what phenotypes that are associated with a gene,
what inheritance models that are associated and the correct omim id.
Args:
genes(dict): Dictionary with all genes
... | Add omim information
We collect information on what phenotypes that are associated with a gene,
what inheritance models that are associated and the correct omim id.
Args:
genes(dict): Dictionary with all genes
alias_genes(dict): Genes mapped to all aliases
genemap_lines(ite... | Below is the the instruction that describes the task:
### Input:
Add omim information
We collect information on what phenotypes that are associated with a gene,
what inheritance models that are associated and the correct omim id.
Args:
genes(dict): Dictionary with all genes
ali... |
def addNodeLabelPrefix(self, prefix=None, copy=False):
'''
Rename all nodes in the network from x to prefix_x. If no prefix
is given, use the name of the graph as the prefix.
The purpose of this method is to make node names unique so that
composing two graphs is well-de... | Rename all nodes in the network from x to prefix_x. If no prefix
is given, use the name of the graph as the prefix.
The purpose of this method is to make node names unique so that
composing two graphs is well-defined. | Below is the the instruction that describes the task:
### Input:
Rename all nodes in the network from x to prefix_x. If no prefix
is given, use the name of the graph as the prefix.
The purpose of this method is to make node names unique so that
composing two graphs is well-defined.... |
def get_desired():
"""Populate ``DESIRED_TEMPLATE`` with public members.
If there are no members, does nothing.
Returns:
str: The "desired" contents of ``bezier.rst``.
"""
public_members = get_public_members()
if public_members:
members = "\n :members: {}".format(", ".join(p... | Populate ``DESIRED_TEMPLATE`` with public members.
If there are no members, does nothing.
Returns:
str: The "desired" contents of ``bezier.rst``. | Below is the the instruction that describes the task:
### Input:
Populate ``DESIRED_TEMPLATE`` with public members.
If there are no members, does nothing.
Returns:
str: The "desired" contents of ``bezier.rst``.
### Response:
def get_desired():
"""Populate ``DESIRED_TEMPLATE`` with public memb... |
def getStatus(self) :
"""returns a word describing the status of the collection (loaded, loading, deleted, unloaded, newborn) instead of a number, if you prefer the number it's in self.status"""
if self.status == CONST.COLLECTION_LOADING_STATUS :
return "loading"
elif self.status == ... | returns a word describing the status of the collection (loaded, loading, deleted, unloaded, newborn) instead of a number, if you prefer the number it's in self.status | Below is the the instruction that describes the task:
### Input:
returns a word describing the status of the collection (loaded, loading, deleted, unloaded, newborn) instead of a number, if you prefer the number it's in self.status
### Response:
def getStatus(self) :
"""returns a word describing the status... |
def get_last_failed_access_attempt(cls, **kwargs):
"""
Return Failed access attempt of Client
:param ip_adress: String
:return:
"""
try:
lockout = cls.objects.get(
**kwargs
)
except cls.DoesNotExist:
lockout = No... | Return Failed access attempt of Client
:param ip_adress: String
:return: | Below is the the instruction that describes the task:
### Input:
Return Failed access attempt of Client
:param ip_adress: String
:return:
### Response:
def get_last_failed_access_attempt(cls, **kwargs):
"""
Return Failed access attempt of Client
:param ip_adress: String
... |
def get_nearest_observation_site(self, latitude=None, longitude=None):
"""
This function returns the nearest Site to the specified
coordinates that supports observations
"""
if longitude is None:
print('ERROR: No longitude given.')
return False
if... | This function returns the nearest Site to the specified
coordinates that supports observations | Below is the the instruction that describes the task:
### Input:
This function returns the nearest Site to the specified
coordinates that supports observations
### Response:
def get_nearest_observation_site(self, latitude=None, longitude=None):
"""
This function returns the nearest Site to ... |
def async_call(self, fn, *args, **kwargs):
"""Schedule `fn` to be called by the event loop soon.
This function is thread-safe, and is the only way code not
on the main thread could interact with nvim api objects.
This function can also be called in a synchronous
event handler, ... | Schedule `fn` to be called by the event loop soon.
This function is thread-safe, and is the only way code not
on the main thread could interact with nvim api objects.
This function can also be called in a synchronous
event handler, just before it returns, to defer execution
tha... | Below is the the instruction that describes the task:
### Input:
Schedule `fn` to be called by the event loop soon.
This function is thread-safe, and is the only way code not
on the main thread could interact with nvim api objects.
This function can also be called in a synchronous
... |
def apply_template_on_contents(
contents,
template,
context,
defaults,
saltenv):
'''
Return the contents after applying the templating engine
contents
template string
template
template format
context
Overrides default context variabl... | Return the contents after applying the templating engine
contents
template string
template
template format
context
Overrides default context variables passed to the template.
defaults
Default context passed to the template.
CLI Example:
.. code-block:: bash
... | Below is the the instruction that describes the task:
### Input:
Return the contents after applying the templating engine
contents
template string
template
template format
context
Overrides default context variables passed to the template.
defaults
Default context... |
def _pad(self, b):
"""
Will padd the param to be of the correct length for the encryption alg.
:type b: bytes
:rtype: bytes
"""
return b + (self.bs - len(b) % self.bs) * chr(self.bs - len(b) % self.bs).encode("UTF-8") | Will padd the param to be of the correct length for the encryption alg.
:type b: bytes
:rtype: bytes | Below is the the instruction that describes the task:
### Input:
Will padd the param to be of the correct length for the encryption alg.
:type b: bytes
:rtype: bytes
### Response:
def _pad(self, b):
"""
Will padd the param to be of the correct length for the encryption alg.
... |
def connect(self):
"Initiate the connection to a proxying hub"
log.info("connecting")
# don't have the connection attempt reconnects, because when it goes
# down we are going to cycle to the next potential peer from the Client
self._peer = connection.Peer(
None, ... | Initiate the connection to a proxying hub | Below is the the instruction that describes the task:
### Input:
Initiate the connection to a proxying hub
### Response:
def connect(self):
"Initiate the connection to a proxying hub"
log.info("connecting")
# don't have the connection attempt reconnects, because when it goes
# down... |
def parse_ip(text):
"""Extract an IPv4 IP from a text string
Uses an IP Address Regex: http://www.regular-expressions.info/examples.html
"""
ip_matches = re.findall(r'\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b', text)
ip = ip_matches[0] if ip_matches else None
return ip | Extract an IPv4 IP from a text string
Uses an IP Address Regex: http://www.regular-expressions.info/examples.html | Below is the the instruction that describes the task:
### Input:
Extract an IPv4 IP from a text string
Uses an IP Address Regex: http://www.regular-expressions.info/examples.html
### Response:
def parse_ip(text):
"""Extract an IPv4 IP from a text string
Uses an IP Address Regex: http://www.regular-expr... |
def GetSyncMoConfig(ConfigDoc):
""" Internal support method for SyncManagedObject. """
moConfigMap = {}
configList = ConfigDoc.getElementsByTagName("mo")
for moConfigNode in configList:
classId = None
noun = None
version = None
actionVersion = None
action = None
ignoreReason = None
status ... | Internal support method for SyncManagedObject. | Below is the the instruction that describes the task:
### Input:
Internal support method for SyncManagedObject.
### Response:
def GetSyncMoConfig(ConfigDoc):
""" Internal support method for SyncManagedObject. """
moConfigMap = {}
configList = ConfigDoc.getElementsByTagName("mo")
for moConfigNode in config... |
def _remove_summary(self):
"""Removed packge size summary
"""
if self.size > 0:
print("\nRemoved summary")
print("=" * 79)
print("{0}Size of removed packages {1} {2}.{3}".format(
self.meta.color["GREY"], round(self.size, 2), self.unit,
... | Removed packge size summary | Below is the the instruction that describes the task:
### Input:
Removed packge size summary
### Response:
def _remove_summary(self):
"""Removed packge size summary
"""
if self.size > 0:
print("\nRemoved summary")
print("=" * 79)
print("{0}Size of removed... |
def create_enum(enum_type, help_string=NO_HELP, default=NO_DEFAULT):
# type: (Type[Enum], str, Union[Any, NO_DEFAULT_TYPE]) -> Type[Enum]
"""
Create an enum config
:param enum_type:
:param help_string:
:param default:
:return:
"""
# noinspection Py... | Create an enum config
:param enum_type:
:param help_string:
:param default:
:return: | Below is the the instruction that describes the task:
### Input:
Create an enum config
:param enum_type:
:param help_string:
:param default:
:return:
### Response:
def create_enum(enum_type, help_string=NO_HELP, default=NO_DEFAULT):
# type: (Type[Enum], str, Union[Any, NO_DE... |
def _generate_address(self, key_iterator):
# type: (KeyIterator) -> Address
"""
Generates a new address.
Used in the event of a cache miss.
"""
if self.checksum:
return (
self.address_from_digest(
digest=self._get_digest(ke... | Generates a new address.
Used in the event of a cache miss. | Below is the the instruction that describes the task:
### Input:
Generates a new address.
Used in the event of a cache miss.
### Response:
def _generate_address(self, key_iterator):
# type: (KeyIterator) -> Address
"""
Generates a new address.
Used in the event of a cache ... |
def create_random(magf, magf_params, errf, errf_params,
timef=np.linspace, timef_params=None, size=DEFAULT_SIZE,
id=None, ds_name=DS_NAME, description=DESCRIPTION,
bands=BANDS, metadata=METADATA):
"""Generate a data with any given random function.
Parameter... | Generate a data with any given random function.
Parameters
----------
magf : callable
Function to generate the magnitudes.
magf_params : dict-like
Parameters to feed the `magf` function.
errf : callable
Function to generate the magnitudes.
errf_params : dict-like
... | Below is the the instruction that describes the task:
### Input:
Generate a data with any given random function.
Parameters
----------
magf : callable
Function to generate the magnitudes.
magf_params : dict-like
Parameters to feed the `magf` function.
errf : callable
Fu... |
def httpretty_callback(request, uri, headers):
"""httpretty request handler.
converts a call intercepted by httpretty to
the stack-in-a-box infrastructure
:param request: request object
:param uri: the uri of the request
:param headers: headers for the response
:returns: tuple - (int, dic... | httpretty request handler.
converts a call intercepted by httpretty to
the stack-in-a-box infrastructure
:param request: request object
:param uri: the uri of the request
:param headers: headers for the response
:returns: tuple - (int, dict, string) containing:
int - the... | Below is the the instruction that describes the task:
### Input:
httpretty request handler.
converts a call intercepted by httpretty to
the stack-in-a-box infrastructure
:param request: request object
:param uri: the uri of the request
:param headers: headers for the response
:returns: tu... |
def get_app_keys(self, app_uri):
"""获得账号下应用的密钥
列出指定应用的密钥,仅当访问者对指定应用有管理权限时有效:
用户对创建的应用有管理权限。
用户对使用的第三方应用没有管理权限,第三方应用的运维方有管理权限。
Args:
- app_uri: 应用的完整标识
Returns:
返回一个tuple对象,其格式为(<result>, <ResponseInfo>)
- result 成功返回... | 获得账号下应用的密钥
列出指定应用的密钥,仅当访问者对指定应用有管理权限时有效:
用户对创建的应用有管理权限。
用户对使用的第三方应用没有管理权限,第三方应用的运维方有管理权限。
Args:
- app_uri: 应用的完整标识
Returns:
返回一个tuple对象,其格式为(<result>, <ResponseInfo>)
- result 成功返回秘钥列表,失败返回None
- ResponseInfo ... | Below is the the instruction that describes the task:
### Input:
获得账号下应用的密钥
列出指定应用的密钥,仅当访问者对指定应用有管理权限时有效:
用户对创建的应用有管理权限。
用户对使用的第三方应用没有管理权限,第三方应用的运维方有管理权限。
Args:
- app_uri: 应用的完整标识
Returns:
返回一个tuple对象,其格式为(<result>, <ResponseInfo>)
... |
def listFields(self, template):
"""List all the attributes to be rendered from the template file
:param template: The template to render.
The template is actually a file, which is usually generated
by :class:`rtcclient.template.Templater.getTemplate` and can also
be ... | List all the attributes to be rendered from the template file
:param template: The template to render.
The template is actually a file, which is usually generated
by :class:`rtcclient.template.Templater.getTemplate` and can also
be modified by user accordingly.
:retu... | Below is the the instruction that describes the task:
### Input:
List all the attributes to be rendered from the template file
:param template: The template to render.
The template is actually a file, which is usually generated
by :class:`rtcclient.template.Templater.getTemplate` an... |
def encrypt_password(self, raw_password):
"""
Encrypts a plaintext password using the stored passlib password context
"""
PraetorianError.require_condition(
self.pwd_ctx is not None,
"Praetorian must be initialized before this method is available",
)
... | Encrypts a plaintext password using the stored passlib password context | Below is the the instruction that describes the task:
### Input:
Encrypts a plaintext password using the stored passlib password context
### Response:
def encrypt_password(self, raw_password):
"""
Encrypts a plaintext password using the stored passlib password context
"""
Praetorian... |
def state_to_cookie(state, name, path, encryption_key):
"""
Saves a state to a cookie
:type state: satosa.state.State
:type name: str
:type path: str
:type encryption_key: str
:rtype: http.cookies.SimpleCookie
:param state: The state to save
:param name: Name identifier of the cook... | Saves a state to a cookie
:type state: satosa.state.State
:type name: str
:type path: str
:type encryption_key: str
:rtype: http.cookies.SimpleCookie
:param state: The state to save
:param name: Name identifier of the cookie
:param path: Endpoint path the cookie will be associated to
... | Below is the the instruction that describes the task:
### Input:
Saves a state to a cookie
:type state: satosa.state.State
:type name: str
:type path: str
:type encryption_key: str
:rtype: http.cookies.SimpleCookie
:param state: The state to save
:param name: Name identifier of the coo... |
def build_penalties(self):
"""
builds the GAM block-diagonal penalty matrix in quadratic form
out of penalty matrices specified for each feature.
each feature penalty matrix is multiplied by a lambda for that feature.
so for m features:
P = block_diag[lam0 * P0, lam1 * ... | builds the GAM block-diagonal penalty matrix in quadratic form
out of penalty matrices specified for each feature.
each feature penalty matrix is multiplied by a lambda for that feature.
so for m features:
P = block_diag[lam0 * P0, lam1 * P1, lam2 * P2, ... , lamm * Pm]
Param... | Below is the the instruction that describes the task:
### Input:
builds the GAM block-diagonal penalty matrix in quadratic form
out of penalty matrices specified for each feature.
each feature penalty matrix is multiplied by a lambda for that feature.
so for m features:
P = block_d... |
def vrrp_vip(self, **kwargs):
"""Set VRRP VIP.
Args:
int_type (str): Type of interface. (gigabitethernet,
tengigabitethernet, etc).
name (str): Name of interface. (1/0/5, 1/0/10, etc).
vrid (str): VRRPv3 ID.
vip (str): IPv4/IPv6 Virtual IP ... | Set VRRP VIP.
Args:
int_type (str): Type of interface. (gigabitethernet,
tengigabitethernet, etc).
name (str): Name of interface. (1/0/5, 1/0/10, etc).
vrid (str): VRRPv3 ID.
vip (str): IPv4/IPv6 Virtual IP Address.
rbridge_id (str): rb... | Below is the the instruction that describes the task:
### Input:
Set VRRP VIP.
Args:
int_type (str): Type of interface. (gigabitethernet,
tengigabitethernet, etc).
name (str): Name of interface. (1/0/5, 1/0/10, etc).
vrid (str): VRRPv3 ID.
vip ... |
def distinct_by_t(func):
"""
Transformation for Sequence.distinct_by
:param func: distinct_by function
:return: transformation
"""
def distinct_by(sequence):
distinct_lookup = {}
for element in sequence:
key = func(element)
if key not in distinct_lookup:
... | Transformation for Sequence.distinct_by
:param func: distinct_by function
:return: transformation | Below is the the instruction that describes the task:
### Input:
Transformation for Sequence.distinct_by
:param func: distinct_by function
:return: transformation
### Response:
def distinct_by_t(func):
"""
Transformation for Sequence.distinct_by
:param func: distinct_by function
:return: tr... |
def add(self, name, parents=None):
"""
add a node to the graph.
Raises an exception if the node cannot be added (i.e., if a node
that name already exists, or if it would create a cycle.
NOTE: A node can be added before its parents are added.
name: The name of the node ... | add a node to the graph.
Raises an exception if the node cannot be added (i.e., if a node
that name already exists, or if it would create a cycle.
NOTE: A node can be added before its parents are added.
name: The name of the node to add to the graph. Name can be any
unique... | Below is the the instruction that describes the task:
### Input:
add a node to the graph.
Raises an exception if the node cannot be added (i.e., if a node
that name already exists, or if it would create a cycle.
NOTE: A node can be added before its parents are added.
name: The nam... |
def get(self, name_or_id):
"""
Get alert by name or id
:param name_or_id: The alert's name or id
:type name_or_id: str
:return: A list of matching tags. An empty list is returned if there are
not any matches
:rtype: list of dict
:raises: This will r... | Get alert by name or id
:param name_or_id: The alert's name or id
:type name_or_id: str
:return: A list of matching tags. An empty list is returned if there are
not any matches
:rtype: list of dict
:raises: This will raise a
:class:`ServerException<loge... | Below is the the instruction that describes the task:
### Input:
Get alert by name or id
:param name_or_id: The alert's name or id
:type name_or_id: str
:return: A list of matching tags. An empty list is returned if there are
not any matches
:rtype: list of dict
... |
def getcandsfile(d, segment=-1, domock=False):
""" Return name of candsfile for a given dictionary. Must have d['segment'] defined.
domock is option to save simulated cands.
"""
if domock:
prefix = 'candsmock_'
else:
prefix= 'cands_'
if d.has_key('segment'):
return os.pa... | Return name of candsfile for a given dictionary. Must have d['segment'] defined.
domock is option to save simulated cands. | Below is the the instruction that describes the task:
### Input:
Return name of candsfile for a given dictionary. Must have d['segment'] defined.
domock is option to save simulated cands.
### Response:
def getcandsfile(d, segment=-1, domock=False):
""" Return name of candsfile for a given dictionary. Must ... |
def _set_mac_address(self, v, load=False):
"""
Setter method for mac_address, mapped from YANG variable /bridge_domain/mac_address (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_mac_address is considered as a private
method. Backends looking to populate ... | Setter method for mac_address, mapped from YANG variable /bridge_domain/mac_address (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_mac_address is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set... | Below is the the instruction that describes the task:
### Input:
Setter method for mac_address, mapped from YANG variable /bridge_domain/mac_address (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_mac_address is considered as a private
method. Backends lookin... |
def cancel_bundle_task(self, bundle_id):
"""
Cancel a previously submitted bundle task
:type bundle_id: string
:param bundle_id: The identifier of the bundle task to cancel.
"""
params = {'BundleId' : bundle_id}
return self.get_object('CancelBundleTask', params,... | Cancel a previously submitted bundle task
:type bundle_id: string
:param bundle_id: The identifier of the bundle task to cancel. | Below is the the instruction that describes the task:
### Input:
Cancel a previously submitted bundle task
:type bundle_id: string
:param bundle_id: The identifier of the bundle task to cancel.
### Response:
def cancel_bundle_task(self, bundle_id):
"""
Cancel a previously submitted... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.