code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def _command(self, commands):
"""!
\~english
Send command to ssd1306, DC pin need set to LOW
@param commands: an byte or array of bytes
\~chinese
发送命令给 SSD1306,DC 需要设定为低电平 LOW
@param commands: 一个字节或字节数组
"""
if self._spi == None: raise "Do not set... | !
\~english
Send command to ssd1306, DC pin need set to LOW
@param commands: an byte or array of bytes
\~chinese
发送命令给 SSD1306,DC 需要设定为低电平 LOW
@param commands: 一个字节或字节数组 | Below is the the instruction that describes the task:
### Input:
!
\~english
Send command to ssd1306, DC pin need set to LOW
@param commands: an byte or array of bytes
\~chinese
发送命令给 SSD1306,DC 需要设定为低电平 LOW
@param commands: 一个字节或字节数组
### Response:
def _command(sel... |
def p_declassign(self, p):
'declassign : sigtypes declassign_element SEMICOLON'
decllist = self.create_declassign(
p[1], p[2][0], p[2][1], lineno=p.lineno(2))
p[0] = Decl(decllist, lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | declassign : sigtypes declassign_element SEMICOLON | Below is the the instruction that describes the task:
### Input:
declassign : sigtypes declassign_element SEMICOLON
### Response:
def p_declassign(self, p):
'declassign : sigtypes declassign_element SEMICOLON'
decllist = self.create_declassign(
p[1], p[2][0], p[2][1], lineno=p.lineno(2)... |
def show_clusters(sample, clusters, representatives, **kwargs):
"""!
@brief Display BSAS clustering results.
@param[in] sample (list): Dataset that was used for clustering.
@param[in] clusters (array_like): Clusters that were allocated by the algorithm.
@param[in] representative... | !
@brief Display BSAS clustering results.
@param[in] sample (list): Dataset that was used for clustering.
@param[in] clusters (array_like): Clusters that were allocated by the algorithm.
@param[in] representatives (array_like): Allocated representatives correspond to clusters.
@... | Below is the the instruction that describes the task:
### Input:
!
@brief Display BSAS clustering results.
@param[in] sample (list): Dataset that was used for clustering.
@param[in] clusters (array_like): Clusters that were allocated by the algorithm.
@param[in] representatives (arr... |
def list_vcls(self, service_id, version_number):
"""List the uploaded VCLs for a particular service and version."""
content = self._fetch("/service/%s/version/%d/vcl" % (service_id, version_number))
return map(lambda x: FastlyVCL(self, x), content) | List the uploaded VCLs for a particular service and version. | Below is the the instruction that describes the task:
### Input:
List the uploaded VCLs for a particular service and version.
### Response:
def list_vcls(self, service_id, version_number):
"""List the uploaded VCLs for a particular service and version."""
content = self._fetch("/service/%s/version/%d/vcl" % (s... |
def canonical(self):
"""
Compute canonical preference representation
Uses auxiliary problem of 9.4.2, with the preference shock process reintroduced
Calculates pihat, llambdahat and ubhat for the equivalent canonical household technology
"""
Ac1 = np.hstack((self.deltah,... | Compute canonical preference representation
Uses auxiliary problem of 9.4.2, with the preference shock process reintroduced
Calculates pihat, llambdahat and ubhat for the equivalent canonical household technology | Below is the the instruction that describes the task:
### Input:
Compute canonical preference representation
Uses auxiliary problem of 9.4.2, with the preference shock process reintroduced
Calculates pihat, llambdahat and ubhat for the equivalent canonical household technology
### Response:
def can... |
def capability_installed(name,
source=None,
limit_access=False,
image=None,
restart=False):
'''
Install a DISM capability
Args:
name (str): The capability to install
source (str): The optiona... | Install a DISM capability
Args:
name (str): The capability to install
source (str): The optional source of the capability
limit_access (bool): Prevent DISM from contacting Windows Update for
online images
image (Optional[str]): The path to the root directory of an offlin... | Below is the the instruction that describes the task:
### Input:
Install a DISM capability
Args:
name (str): The capability to install
source (str): The optional source of the capability
limit_access (bool): Prevent DISM from contacting Windows Update for
online images
... |
def system_switch_attributes_rbridge_id_host_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
system = ET.SubElement(config, "system", xmlns="urn:brocade.com:mgmt:brocade-ras")
switch_attributes = ET.SubElement(system, "switch-attributes")
rb... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def system_switch_attributes_rbridge_id_host_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
system = ET.SubElement(config, "system", xmlns="urn:brocade.... |
def aliasSub(requestContext, seriesList, search, replace):
"""
Runs series names through a regex search/replace.
Example::
&target=aliasSub(ip.*TCP*,"^.*TCP(\d+)","\\1")
"""
try:
seriesList.name = re.sub(search, replace, seriesList.name)
except AttributeError:
for series... | Runs series names through a regex search/replace.
Example::
&target=aliasSub(ip.*TCP*,"^.*TCP(\d+)","\\1") | Below is the the instruction that describes the task:
### Input:
Runs series names through a regex search/replace.
Example::
&target=aliasSub(ip.*TCP*,"^.*TCP(\d+)","\\1")
### Response:
def aliasSub(requestContext, seriesList, search, replace):
"""
Runs series names through a regex search/repl... |
def get_password_authentication_key(self, username, password, server_b_value, salt):
"""
Calculates the final hkdf based on computed S value, and computed U value and the key
:param {String} username Username.
:param {String} password Password.
:param {Long integer} server_b_valu... | Calculates the final hkdf based on computed S value, and computed U value and the key
:param {String} username Username.
:param {String} password Password.
:param {Long integer} server_b_value Server B value.
:param {Long integer} salt Generated salt.
:return {Buffer} Computed HK... | Below is the the instruction that describes the task:
### Input:
Calculates the final hkdf based on computed S value, and computed U value and the key
:param {String} username Username.
:param {String} password Password.
:param {Long integer} server_b_value Server B value.
:param {Lo... |
def plot_distance_landscape_projection(self, x_axis, y_axis, ax=None, *args, **kwargs):
"""
Plots the distance landscape jointly-generated from all the results
:param x_axis: symbol to plot on x axis
:param y_axis: symbol to plot on y axis
:param ax: axis object to plot onto
... | Plots the distance landscape jointly-generated from all the results
:param x_axis: symbol to plot on x axis
:param y_axis: symbol to plot on y axis
:param ax: axis object to plot onto
:param args: arguments to pass to :func:`matplotlib.pyplot.contourf`
:param kwargs: keyword arg... | Below is the the instruction that describes the task:
### Input:
Plots the distance landscape jointly-generated from all the results
:param x_axis: symbol to plot on x axis
:param y_axis: symbol to plot on y axis
:param ax: axis object to plot onto
:param args: arguments to pass to ... |
def fulltext_search(self, transport, index, query, **params):
"""
fulltext_search(index, query, **params)
Performs a full-text search query.
.. note:: This request is automatically retried :attr:`retries`
times if it fails due to network error.
:param index: the buc... | fulltext_search(index, query, **params)
Performs a full-text search query.
.. note:: This request is automatically retried :attr:`retries`
times if it fails due to network error.
:param index: the bucket/index to search over
:type index: string
:param query: the sea... | Below is the the instruction that describes the task:
### Input:
fulltext_search(index, query, **params)
Performs a full-text search query.
.. note:: This request is automatically retried :attr:`retries`
times if it fails due to network error.
:param index: the bucket/index to ... |
def run_genesippr(self):
"""
Run GeneSippr on each of the samples
"""
from pathlib import Path
home = str(Path.home())
logging.info('GeneSippr')
# These unfortunate hard coded paths appear to be necessary
miniconda_path = os.path.join(home, 'miniconda3')
... | Run GeneSippr on each of the samples | Below is the the instruction that describes the task:
### Input:
Run GeneSippr on each of the samples
### Response:
def run_genesippr(self):
"""
Run GeneSippr on each of the samples
"""
from pathlib import Path
home = str(Path.home())
logging.info('GeneSippr')
... |
def timeseries(self):
"""Simulated time series"""
if self._timeseries is None:
self.compute()
if isinstance(self.system, NetworkModel):
return self.system._reshape_timeseries(self._timeseries)
else:
return self._timeseries | Simulated time series | Below is the the instruction that describes the task:
### Input:
Simulated time series
### Response:
def timeseries(self):
"""Simulated time series"""
if self._timeseries is None:
self.compute()
if isinstance(self.system, NetworkModel):
return self.system._reshape_ti... |
def set_char(key, value):
""" Updates charters used to render components.
"""
global _chars
category = _get_char_category(key)
if not category:
raise KeyError
_chars[category][key] = value | Updates charters used to render components. | Below is the the instruction that describes the task:
### Input:
Updates charters used to render components.
### Response:
def set_char(key, value):
""" Updates charters used to render components.
"""
global _chars
category = _get_char_category(key)
if not category:
raise KeyError
_... |
def account_unblock(self, id):
"""
Unblock a user.
Returns a `relationship dict`_ containing the updated relationship to the user.
"""
id = self.__unpack_id(id)
url = '/api/v1/accounts/{0}/unblock'.format(str(id))
return self.__api_request('POST', url) | Unblock a user.
Returns a `relationship dict`_ containing the updated relationship to the user. | Below is the the instruction that describes the task:
### Input:
Unblock a user.
Returns a `relationship dict`_ containing the updated relationship to the user.
### Response:
def account_unblock(self, id):
"""
Unblock a user.
Returns a `relationship dict`_ containing the updated r... |
def set_pipeline(filename, scan, fileroot='', paramfile='', **kwargs):
""" Function defines pipeline state for search. Takes data/scan as input.
fileroot is base name for associated products (cal files, noise, cands). if blank, it is set to filename.
paramfile is name of file that defines all pipeline param... | Function defines pipeline state for search. Takes data/scan as input.
fileroot is base name for associated products (cal files, noise, cands). if blank, it is set to filename.
paramfile is name of file that defines all pipeline parameters (python-like syntax).
kwargs used to overload paramfile definitions.
... | Below is the the instruction that describes the task:
### Input:
Function defines pipeline state for search. Takes data/scan as input.
fileroot is base name for associated products (cal files, noise, cands). if blank, it is set to filename.
paramfile is name of file that defines all pipeline parameters (pyt... |
def filteritems(predicate, dict_):
"""Return a new dictionary comprising of items
for which ``predicate`` returns True.
:param predicate: Predicate taking a key-value pair, or None
.. versionchanged: 0.0.2
``predicate`` is now taking a key-value pair as a single argument.
"""
predicate ... | Return a new dictionary comprising of items
for which ``predicate`` returns True.
:param predicate: Predicate taking a key-value pair, or None
.. versionchanged: 0.0.2
``predicate`` is now taking a key-value pair as a single argument. | Below is the the instruction that describes the task:
### Input:
Return a new dictionary comprising of items
for which ``predicate`` returns True.
:param predicate: Predicate taking a key-value pair, or None
.. versionchanged: 0.0.2
``predicate`` is now taking a key-value pair as a single argum... |
def _buckets(data, bucket_count=None):
"""Create a TensorFlow op to group data into histogram buckets.
Arguments:
data: A `Tensor` of any shape. Must be castable to `float64`.
bucket_count: Optional positive `int` or scalar `int32` `Tensor`.
Returns:
A `Tensor` of shape `[k, 3]` and type `float64`. T... | Create a TensorFlow op to group data into histogram buckets.
Arguments:
data: A `Tensor` of any shape. Must be castable to `float64`.
bucket_count: Optional positive `int` or scalar `int32` `Tensor`.
Returns:
A `Tensor` of shape `[k, 3]` and type `float64`. The `i`th row is
a triple `[left_edge, ri... | Below is the the instruction that describes the task:
### Input:
Create a TensorFlow op to group data into histogram buckets.
Arguments:
data: A `Tensor` of any shape. Must be castable to `float64`.
bucket_count: Optional positive `int` or scalar `int32` `Tensor`.
Returns:
A `Tensor` of shape `[k, ... |
def _get_table(self):
"""Gets report as table (with columns)
:return: column names and data
"""
data = get_inner_data(self.report)
labels = data.keys()
row = [
data[key]
for key in labels
]
return list(labels), [row] | Gets report as table (with columns)
:return: column names and data | Below is the the instruction that describes the task:
### Input:
Gets report as table (with columns)
:return: column names and data
### Response:
def _get_table(self):
"""Gets report as table (with columns)
:return: column names and data
"""
data = get_inner_data(self.repo... |
def bipartite_vertex_cover(bigraph):
"""Bipartite minimum vertex cover by Koenig's theorem
:param bigraph: adjacency list, index = vertex in U,
value = neighbor list in V
:assumption: U = V = {0, 1, 2, ..., n - 1} for n = len(bigraph)
:returns: boolean table for U, b... | Bipartite minimum vertex cover by Koenig's theorem
:param bigraph: adjacency list, index = vertex in U,
value = neighbor list in V
:assumption: U = V = {0, 1, 2, ..., n - 1} for n = len(bigraph)
:returns: boolean table for U, boolean table for V
:comment: selected ve... | Below is the the instruction that describes the task:
### Input:
Bipartite minimum vertex cover by Koenig's theorem
:param bigraph: adjacency list, index = vertex in U,
value = neighbor list in V
:assumption: U = V = {0, 1, 2, ..., n - 1} for n = len(bigraph)
:return... |
def lcsseq(self, src, tar):
"""Return the longest common subsequence of two strings.
Based on the dynamic programming algorithm from
http://rosettacode.org/wiki/Longest_common_subsequence
:cite:`rosettacode:2018b`. This is licensed GFDL 1.2.
Modifications include:
c... | Return the longest common subsequence of two strings.
Based on the dynamic programming algorithm from
http://rosettacode.org/wiki/Longest_common_subsequence
:cite:`rosettacode:2018b`. This is licensed GFDL 1.2.
Modifications include:
conversion to a numpy array in place of ... | Below is the the instruction that describes the task:
### Input:
Return the longest common subsequence of two strings.
Based on the dynamic programming algorithm from
http://rosettacode.org/wiki/Longest_common_subsequence
:cite:`rosettacode:2018b`. This is licensed GFDL 1.2.
Modifi... |
def set_text(self, point, text):
"""Set a text value in the screen canvas."""
if not self.option.legend:
return
if not isinstance(point, Point):
point = Point(point)
for offset, char in enumerate(str(text)):
self.screen.canvas[point.y][point.x + offs... | Set a text value in the screen canvas. | Below is the the instruction that describes the task:
### Input:
Set a text value in the screen canvas.
### Response:
def set_text(self, point, text):
"""Set a text value in the screen canvas."""
if not self.option.legend:
return
if not isinstance(point, Point):
poi... |
def select_record(self, table, where=None, values=None, orderby=None, limit=None, columns=None):
''' Support these keywords where, values, orderby, limit and columns'''
query = self.schema.query_builder.build_select(table, where, orderby, limit, columns)
return table.to_table(self.execute(query,... | Support these keywords where, values, orderby, limit and columns | Below is the the instruction that describes the task:
### Input:
Support these keywords where, values, orderby, limit and columns
### Response:
def select_record(self, table, where=None, values=None, orderby=None, limit=None, columns=None):
''' Support these keywords where, values, orderby, limit and colum... |
def macontrol(self, data: ['SASdata', str] = None,
ewmachart: str = None,
machart: str = None,
procopts: str = None,
stmtpassthrough: str = None,
**kwargs: dict) -> 'SASresults':
"""
Python method to call the MACON... | Python method to call the MACONTROL procedure
Documentation link:
https://go.documentation.sas.com/?cdcId=pgmsascdc&cdcVersion=9.4_3.4&docsetId=qcug&docsetTarget=qcug_macontrol_toc.htm&locale=en
:param data: SASdata object or string. This parameter is required.
:parm ewmachart: The ewm... | Below is the the instruction that describes the task:
### Input:
Python method to call the MACONTROL procedure
Documentation link:
https://go.documentation.sas.com/?cdcId=pgmsascdc&cdcVersion=9.4_3.4&docsetId=qcug&docsetTarget=qcug_macontrol_toc.htm&locale=en
:param data: SASdata object or... |
def process(self, request_adu):
""" Process request ADU and return response.
:param request_adu: A bytearray containing the ADU request.
:return: A bytearray containing the response of the ADU request.
"""
meta_data = self.get_meta_data(request_adu)
request_pdu = self.ge... | Process request ADU and return response.
:param request_adu: A bytearray containing the ADU request.
:return: A bytearray containing the response of the ADU request. | Below is the the instruction that describes the task:
### Input:
Process request ADU and return response.
:param request_adu: A bytearray containing the ADU request.
:return: A bytearray containing the response of the ADU request.
### Response:
def process(self, request_adu):
""" Process r... |
def to_fp(self, file_pointer, comments=None):
"""
The method can be used to save a WCNF formula into a file pointer.
The file pointer is expected as an argument. Additionally,
supplementary comment lines can be specified in the ``comments``
parameter.
... | The method can be used to save a WCNF formula into a file pointer.
The file pointer is expected as an argument. Additionally,
supplementary comment lines can be specified in the ``comments``
parameter.
:param fname: a file name where to store the formula.
:pa... | Below is the the instruction that describes the task:
### Input:
The method can be used to save a WCNF formula into a file pointer.
The file pointer is expected as an argument. Additionally,
supplementary comment lines can be specified in the ``comments``
parameter.
... |
def wait(self, timeout=None):
"""
Calls following snippet so you don't have to remember what import. See
:py:obj:`WebDriverWait <selenium.webdriver.support.wait.WebDriverWait>` for more
information. Detault timeout is `~.default_wait_timeout`.
.. code-block:: python
... | Calls following snippet so you don't have to remember what import. See
:py:obj:`WebDriverWait <selenium.webdriver.support.wait.WebDriverWait>` for more
information. Detault timeout is `~.default_wait_timeout`.
.. code-block:: python
selenium.webdriver.support.wait.WebDriverWait(dri... | Below is the the instruction that describes the task:
### Input:
Calls following snippet so you don't have to remember what import. See
:py:obj:`WebDriverWait <selenium.webdriver.support.wait.WebDriverWait>` for more
information. Detault timeout is `~.default_wait_timeout`.
.. code-block:: ... |
def encrypt_item(table_name, aws_cmk_id):
"""Demonstrate use of EncryptedClient to transparently encrypt an item."""
index_key = {"partition_attribute": {"S": "is this"}, "sort_attribute": {"N": "55"}}
plaintext_item = {
"example": {"S": "data"},
"some numbers": {"N": "99"},
"and som... | Demonstrate use of EncryptedClient to transparently encrypt an item. | Below is the the instruction that describes the task:
### Input:
Demonstrate use of EncryptedClient to transparently encrypt an item.
### Response:
def encrypt_item(table_name, aws_cmk_id):
"""Demonstrate use of EncryptedClient to transparently encrypt an item."""
index_key = {"partition_attribute": {"S": ... |
def parse(path):
"""Parse an ``.ensime`` config file from S-expressions.
Args:
path (str): Path of an ``.ensime`` file to parse.
Returns:
dict: Configuration values with string keys.
"""
def paired(iterable):
"""s -> (s0, s1), (s2, s3), (s4,... | Parse an ``.ensime`` config file from S-expressions.
Args:
path (str): Path of an ``.ensime`` file to parse.
Returns:
dict: Configuration values with string keys. | Below is the the instruction that describes the task:
### Input:
Parse an ``.ensime`` config file from S-expressions.
Args:
path (str): Path of an ``.ensime`` file to parse.
Returns:
dict: Configuration values with string keys.
### Response:
def parse(path):
"""Par... |
def execute_return_result(cmd):
'''
Executes the passed command. Returns the standard out if successful
:param str cmd: The command to run
:return: The standard out of the command if successful, otherwise returns
an error
:rtype: str
:raises: Error if command fails or is not supported
... | Executes the passed command. Returns the standard out if successful
:param str cmd: The command to run
:return: The standard out of the command if successful, otherwise returns
an error
:rtype: str
:raises: Error if command fails or is not supported | Below is the the instruction that describes the task:
### Input:
Executes the passed command. Returns the standard out if successful
:param str cmd: The command to run
:return: The standard out of the command if successful, otherwise returns
an error
:rtype: str
:raises: Error if command fail... |
def RemoveManagedObject(self, inMo=None, classId=None, params=None, dumpXml=None):
"""
Removes Managed Object in UCS.
- inMo, if provided, it acts as the target object for the present operation. It should be None unless a user wants to provide an
inMo. It can be a single MO or a list containing multiple m... | Removes Managed Object in UCS.
- inMo, if provided, it acts as the target object for the present operation. It should be None unless a user wants to provide an
inMo. It can be a single MO or a list containing multiple managed objects.
- classId of the managed object/s to be removed.
- params contains semi... | Below is the the instruction that describes the task:
### Input:
Removes Managed Object in UCS.
- inMo, if provided, it acts as the target object for the present operation. It should be None unless a user wants to provide an
inMo. It can be a single MO or a list containing multiple managed objects.
- cl... |
def minimize(value_and_gradients_function,
initial_position,
tolerance=1e-8,
x_tolerance=0,
f_relative_tolerance=0,
initial_inverse_hessian_estimate=None,
max_iterations=50,
parallel_iterations=1,
stopping_condition=... | Applies the BFGS algorithm to minimize a differentiable function.
Performs unconstrained minimization of a differentiable function using the
BFGS scheme. For details of the algorithm, see [Nocedal and Wright(2006)][1].
### Usage:
The following example demonstrates the BFGS optimizer attempting to find the
... | Below is the the instruction that describes the task:
### Input:
Applies the BFGS algorithm to minimize a differentiable function.
Performs unconstrained minimization of a differentiable function using the
BFGS scheme. For details of the algorithm, see [Nocedal and Wright(2006)][1].
### Usage:
The follow... |
def peering_connection_pending_from_vpc(conn_id=None, conn_name=None, vpc_id=None,
vpc_name=None, region=None, key=None,
keyid=None, profile=None):
'''
Check if a VPC peering connection is in the pending state, and requested from th... | Check if a VPC peering connection is in the pending state, and requested from the given VPC.
.. versionadded:: 2016.11.0
conn_id
The connection ID to check. Exclusive with conn_name.
conn_name
The connection name to check. Exclusive with conn_id.
vpc_id
Is this the ID of th... | Below is the the instruction that describes the task:
### Input:
Check if a VPC peering connection is in the pending state, and requested from the given VPC.
.. versionadded:: 2016.11.0
conn_id
The connection ID to check. Exclusive with conn_name.
conn_name
The connection name to che... |
def get_instance(self, payload):
"""
Build an instance of FunctionInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.serverless.v1.service.function.FunctionInstance
:rtype: twilio.rest.serverless.v1.service.function.FunctionInstance
"""
... | Build an instance of FunctionInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.serverless.v1.service.function.FunctionInstance
:rtype: twilio.rest.serverless.v1.service.function.FunctionInstance | Below is the the instruction that describes the task:
### Input:
Build an instance of FunctionInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.serverless.v1.service.function.FunctionInstance
:rtype: twilio.rest.serverless.v1.service.function.FunctionInstanc... |
def get_ZXY_freqs(Data, zfreq, xfreq, yfreq, bandwidth=5000):
"""
Determines the exact z, x and y peak frequencies from approximate
frequencies by finding the highest peak in the PSD "close to" the
approximate peak frequency. By "close to" I mean within the range:
approxFreq - bandwidth/2 to approxF... | Determines the exact z, x and y peak frequencies from approximate
frequencies by finding the highest peak in the PSD "close to" the
approximate peak frequency. By "close to" I mean within the range:
approxFreq - bandwidth/2 to approxFreq + bandwidth/2
Parameters
----------
Data : DataObject
... | Below is the the instruction that describes the task:
### Input:
Determines the exact z, x and y peak frequencies from approximate
frequencies by finding the highest peak in the PSD "close to" the
approximate peak frequency. By "close to" I mean within the range:
approxFreq - bandwidth/2 to approxFreq +... |
def delete(self):
"""
Deletes the object
:return:
:rtype: None
"""
return self._delete_request(endpoint=self.ENDPOINT + '/' + str(self.id)) | Deletes the object
:return:
:rtype: None | Below is the the instruction that describes the task:
### Input:
Deletes the object
:return:
:rtype: None
### Response:
def delete(self):
"""
Deletes the object
:return:
:rtype: None
"""
return self._delete_request(endpoint=self.ENDPOINT + '/' + str... |
def UsesArtifact(self, artifacts):
"""Determines if the check uses the specified artifact.
Args:
artifacts: Either a single artifact name, or a list of artifact names
Returns:
True if the check uses a specific artifact.
"""
# If artifact is a single string, see if it is in the list of ... | Determines if the check uses the specified artifact.
Args:
artifacts: Either a single artifact name, or a list of artifact names
Returns:
True if the check uses a specific artifact. | Below is the the instruction that describes the task:
### Input:
Determines if the check uses the specified artifact.
Args:
artifacts: Either a single artifact name, or a list of artifact names
Returns:
True if the check uses a specific artifact.
### Response:
def UsesArtifact(self, artifacts... |
def cell_value(self, column_family_id, column, index=0):
"""Get a single cell value stored on this instance.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_row_cell_value]
:end-before: [END bigtable_row_cell_value]
Args:
... | Get a single cell value stored on this instance.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_row_cell_value]
:end-before: [END bigtable_row_cell_value]
Args:
column_family_id (str): The ID of the column family. Must be o... | Below is the the instruction that describes the task:
### Input:
Get a single cell value stored on this instance.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_row_cell_value]
:end-before: [END bigtable_row_cell_value]
Args:
... |
def binaryEntropy(x):
"""
Calculate entropy for a list of binary random variables
:param x: (torch tensor) the probability of the variable to be 1.
:return: entropy: (torch tensor) entropy, sum(entropy)
"""
entropy = - x*x.log2() - (1-x)*(1-x).log2()
entropy[x*(1 - x) == 0] = 0
return entropy, entropy.... | Calculate entropy for a list of binary random variables
:param x: (torch tensor) the probability of the variable to be 1.
:return: entropy: (torch tensor) entropy, sum(entropy) | Below is the the instruction that describes the task:
### Input:
Calculate entropy for a list of binary random variables
:param x: (torch tensor) the probability of the variable to be 1.
:return: entropy: (torch tensor) entropy, sum(entropy)
### Response:
def binaryEntropy(x):
"""
Calculate entropy for a ... |
def _get_factor(self, belief_prop, evidence):
"""
Extracts the required factor from the junction tree.
Parameters:
----------
belief_prop: Belief Propagation
Belief Propagation which needs to be updated.
evidence: dict
a dict key, value pair as {... | Extracts the required factor from the junction tree.
Parameters:
----------
belief_prop: Belief Propagation
Belief Propagation which needs to be updated.
evidence: dict
a dict key, value pair as {var: state_of_var_observed} | Below is the the instruction that describes the task:
### Input:
Extracts the required factor from the junction tree.
Parameters:
----------
belief_prop: Belief Propagation
Belief Propagation which needs to be updated.
evidence: dict
a dict key, value pair a... |
def get_size(fileobj):
"""Returns the size of the file.
The position when passed in will be preserved if no error occurs.
Args:
fileobj (fileobj)
Returns:
int: The size of the file
Raises:
IOError
"""
old_pos = fileobj.tell()
try:
fileobj.seek(0, 2)
... | Returns the size of the file.
The position when passed in will be preserved if no error occurs.
Args:
fileobj (fileobj)
Returns:
int: The size of the file
Raises:
IOError | Below is the the instruction that describes the task:
### Input:
Returns the size of the file.
The position when passed in will be preserved if no error occurs.
Args:
fileobj (fileobj)
Returns:
int: The size of the file
Raises:
IOError
### Response:
def get_size(fileobj):
... |
def wraplet(cls, *cls_args, **cls_kwargs):
"""
Create a factory to produce a Wrapper from a slave factory
:param cls_args: positional arguments to provide to the Wrapper class
:param cls_kwargs: keyword arguments to provide to the Wrapper class
:return:
.. code:: python... | Create a factory to produce a Wrapper from a slave factory
:param cls_args: positional arguments to provide to the Wrapper class
:param cls_kwargs: keyword arguments to provide to the Wrapper class
:return:
.. code:: python
cls_wrapper_factory = cls.wraplet(*cls_args, **cl... | Below is the the instruction that describes the task:
### Input:
Create a factory to produce a Wrapper from a slave factory
:param cls_args: positional arguments to provide to the Wrapper class
:param cls_kwargs: keyword arguments to provide to the Wrapper class
:return:
.. code:: ... |
def search_records(self, **kwargs):
"""
rq Search Query in iDigBio Query Format, using Record Query Fields
sort field to sort on, pick from Record Query Fields
fields a list of fields to return, specified using the fieldName parameter from Fields with type records
... | rq Search Query in iDigBio Query Format, using Record Query Fields
sort field to sort on, pick from Record Query Fields
fields a list of fields to return, specified using the fieldName parameter from Fields with type records
fields_exclude a list of fields to exclude, specified... | Below is the the instruction that describes the task:
### Input:
rq Search Query in iDigBio Query Format, using Record Query Fields
sort field to sort on, pick from Record Query Fields
fields a list of fields to return, specified using the fieldName parameter from Fields with type recor... |
def login(
self):
"""login"""
auth_url = self.api_urls["login"]
if self.verbose:
log.info(("log in user={} url={} ca_dir={} cert={}")
.format(
self.user,
auth_url,
self.ca_dir,
... | login | Below is the the instruction that describes the task:
### Input:
login
### Response:
def login(
self):
"""login"""
auth_url = self.api_urls["login"]
if self.verbose:
log.info(("log in user={} url={} ca_dir={} cert={}")
.format(
... |
def get_xlmhg_pval2(N, K, X, L, stat, tol=DEFAULT_TOL):
"""Calculate the XL-mHG p-value using "Algorithm 2".
Parameters
----------
N: int
The length of the list.
K: int
The number of 1's in the list.
X: int
The XL-mHG ``X`` parameter.
L: int
The XL-mHG ``L`` ... | Calculate the XL-mHG p-value using "Algorithm 2".
Parameters
----------
N: int
The length of the list.
K: int
The number of 1's in the list.
X: int
The XL-mHG ``X`` parameter.
L: int
The XL-mHG ``L`` parameter.
stat: float
The XL-mHG test statistic.
... | Below is the the instruction that describes the task:
### Input:
Calculate the XL-mHG p-value using "Algorithm 2".
Parameters
----------
N: int
The length of the list.
K: int
The number of 1's in the list.
X: int
The XL-mHG ``X`` parameter.
L: int
The XL-mHG ... |
def centralize(data, time=False, units=False):
"""
Function to subtract the mean across time and/or across units from data
Parameters
----------
data : numpy.ndarray
1D or 2D array containing time series, 1st index: unit, 2nd index: time
time : bool
True: subtract mea... | Function to subtract the mean across time and/or across units from data
Parameters
----------
data : numpy.ndarray
1D or 2D array containing time series, 1st index: unit, 2nd index: time
time : bool
True: subtract mean across time.
units : bool
True: subtract mean... | Below is the the instruction that describes the task:
### Input:
Function to subtract the mean across time and/or across units from data
Parameters
----------
data : numpy.ndarray
1D or 2D array containing time series, 1st index: unit, 2nd index: time
time : bool
True: su... |
def remove_entities(status, entitylist):
'''Remove entities for a list of items.'''
try:
entities = status.entities
text = status.text
except AttributeError:
entities = status.get('entities', dict())
text = status['text']
indices = [ent['indices'] for etype, entval in li... | Remove entities for a list of items. | Below is the the instruction that describes the task:
### Input:
Remove entities for a list of items.
### Response:
def remove_entities(status, entitylist):
'''Remove entities for a list of items.'''
try:
entities = status.entities
text = status.text
except AttributeError:
entit... |
def find_top_level_complex(gpr):
"""
Find unique elements of both branches of the top level logical AND.
Parameters
----------
gpr : str
The gene-protein-reaction association as a string.
Returns
-------
int
The size of the symmetric difference between the set of elemen... | Find unique elements of both branches of the top level logical AND.
Parameters
----------
gpr : str
The gene-protein-reaction association as a string.
Returns
-------
int
The size of the symmetric difference between the set of elements to
the left of the top level logic... | Below is the the instruction that describes the task:
### Input:
Find unique elements of both branches of the top level logical AND.
Parameters
----------
gpr : str
The gene-protein-reaction association as a string.
Returns
-------
int
The size of the symmetric difference b... |
def expected_counts(T, p0, N):
r"""Compute expected transition counts for Markov chain with n steps.
Parameters
----------
T : (M, M) ndarray or sparse matrix
Transition matrix
p0 : (M,) ndarray
Initial (probability) vector
N : int
Number of steps to take
Returns
... | r"""Compute expected transition counts for Markov chain with n steps.
Parameters
----------
T : (M, M) ndarray or sparse matrix
Transition matrix
p0 : (M,) ndarray
Initial (probability) vector
N : int
Number of steps to take
Returns
--------
EC : (M, M) ndarray ... | Below is the the instruction that describes the task:
### Input:
r"""Compute expected transition counts for Markov chain with n steps.
Parameters
----------
T : (M, M) ndarray or sparse matrix
Transition matrix
p0 : (M,) ndarray
Initial (probability) vector
N : int
Numbe... |
def client_authentication(self, request, auth=None, **kwargs):
"""
Do client authentication
:param endpoint_context: A
:py:class:`oidcendpoint.endpoint_context.SrvInfo` instance
:param request: Parsed request, a self.request_cls class instance
:param authn: Authoriza... | Do client authentication
:param endpoint_context: A
:py:class:`oidcendpoint.endpoint_context.SrvInfo` instance
:param request: Parsed request, a self.request_cls class instance
:param authn: Authorization info
:return: client_id or raise and exception | Below is the the instruction that describes the task:
### Input:
Do client authentication
:param endpoint_context: A
:py:class:`oidcendpoint.endpoint_context.SrvInfo` instance
:param request: Parsed request, a self.request_cls class instance
:param authn: Authorization info
... |
def tokenize_words(string):
"""
Tokenize input text to words.
:param string: Text to tokenize
:type string: str or unicode
:return: words
:rtype: list of strings
"""
string = six.text_type(string)
return re.findall(WORD_TOKENIZATION_RULES, string) | Tokenize input text to words.
:param string: Text to tokenize
:type string: str or unicode
:return: words
:rtype: list of strings | Below is the the instruction that describes the task:
### Input:
Tokenize input text to words.
:param string: Text to tokenize
:type string: str or unicode
:return: words
:rtype: list of strings
### Response:
def tokenize_words(string):
"""
Tokenize input text to words.
:param string:... |
def proxy(host='localhost', port=4304, flags=0, persistent=False,
verbose=False, ):
"""factory function that returns a proxy object for an owserver at
host, port.
"""
# resolve host name/port
try:
gai = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM,
... | factory function that returns a proxy object for an owserver at
host, port. | Below is the the instruction that describes the task:
### Input:
factory function that returns a proxy object for an owserver at
host, port.
### Response:
def proxy(host='localhost', port=4304, flags=0, persistent=False,
verbose=False, ):
"""factory function that returns a proxy object for an ows... |
def file_list(self):
"""
Lists all files in the working directory.
"""
blacklist = ['.git', 'aetros']
working_tree = self.git.work_tree
def recursive(path='.'):
if os.path.basename(path) in blacklist:
return 0, 0
if os.path.isdir(... | Lists all files in the working directory. | Below is the the instruction that describes the task:
### Input:
Lists all files in the working directory.
### Response:
def file_list(self):
"""
Lists all files in the working directory.
"""
blacklist = ['.git', 'aetros']
working_tree = self.git.work_tree
def recur... |
def get_bitmap(self, time=None, size=32, store_path=None):
"""
Get a bitmap of the object at a given instance of time. If time is
`None`,`then the bitmap is generated for the last point in time.
Parameters
----------
time : int or None
size : int
Size... | Get a bitmap of the object at a given instance of time. If time is
`None`,`then the bitmap is generated for the last point in time.
Parameters
----------
time : int or None
size : int
Size in pixels. The resulting bitmap will be (size x size).
store_path : No... | Below is the the instruction that describes the task:
### Input:
Get a bitmap of the object at a given instance of time. If time is
`None`,`then the bitmap is generated for the last point in time.
Parameters
----------
time : int or None
size : int
Size in pixels... |
def get_partitions_by_names(self, db_name, tbl_name, names):
"""
Parameters:
- db_name
- tbl_name
- names
"""
self.send_get_partitions_by_names(db_name, tbl_name, names)
return self.recv_get_partitions_by_names() | Parameters:
- db_name
- tbl_name
- names | Below is the the instruction that describes the task:
### Input:
Parameters:
- db_name
- tbl_name
- names
### Response:
def get_partitions_by_names(self, db_name, tbl_name, names):
"""
Parameters:
- db_name
- tbl_name
- names
"""
self.send_get_partitions_by_names(db_na... |
def _parse_spacy_kwargs(**kwargs):
"""Supported args include:
Args:
n_threads/num_threads: Number of threads to use. Uses num_cpus - 1 by default.
batch_size: The number of texts to accumulate into a common working set before processing.
(Default value: 1000)
"""
n_threads =... | Supported args include:
Args:
n_threads/num_threads: Number of threads to use. Uses num_cpus - 1 by default.
batch_size: The number of texts to accumulate into a common working set before processing.
(Default value: 1000) | Below is the the instruction that describes the task:
### Input:
Supported args include:
Args:
n_threads/num_threads: Number of threads to use. Uses num_cpus - 1 by default.
batch_size: The number of texts to accumulate into a common working set before processing.
(Default value: 10... |
def list_alignment(list1, list2, missing=False):
"""
Assumes list items are unique
Args:
list1 (list): a list of unique items to be aligned
list2 (list): a list of unique items in a desired ordering
missing (bool): True if list2 can contain items not in list1
Returns:
l... | Assumes list items are unique
Args:
list1 (list): a list of unique items to be aligned
list2 (list): a list of unique items in a desired ordering
missing (bool): True if list2 can contain items not in list1
Returns:
list: sorting that will map list1 onto list2
CommandLine:... | Below is the the instruction that describes the task:
### Input:
Assumes list items are unique
Args:
list1 (list): a list of unique items to be aligned
list2 (list): a list of unique items in a desired ordering
missing (bool): True if list2 can contain items not in list1
Returns:
... |
def nth(self, n, dropna=None):
"""
Take the nth row from each group if n is an int, or a subset of rows
if n is a list of ints.
If dropna, will take the nth non-null row, dropna is either
Truthy (if a Series) or 'all', 'any' (if a DataFrame);
this is equivalent to callin... | Take the nth row from each group if n is an int, or a subset of rows
if n is a list of ints.
If dropna, will take the nth non-null row, dropna is either
Truthy (if a Series) or 'all', 'any' (if a DataFrame);
this is equivalent to calling dropna(how=dropna) before the
groupby.
... | Below is the the instruction that describes the task:
### Input:
Take the nth row from each group if n is an int, or a subset of rows
if n is a list of ints.
If dropna, will take the nth non-null row, dropna is either
Truthy (if a Series) or 'all', 'any' (if a DataFrame);
this is eq... |
def make_processitem_sectionlist_memorysection_peinfo_exports_exportedfunctions_string(export_function, condition='is',
negate=False,
preserve_cas... | Create a node for ProcessItem/SectionList/MemorySection/PEInfo/Exports/ExportedFunctions/string
:return: A IndicatorItem represented as an Element node | Below is the the instruction that describes the task:
### Input:
Create a node for ProcessItem/SectionList/MemorySection/PEInfo/Exports/ExportedFunctions/string
:return: A IndicatorItem represented as an Element node
### Response:
def make_processitem_sectionlist_memorysection_peinfo_exports_exportedfunct... |
def main():
"""
NAME
thellier_magic.py
DESCRIPTION
plots Thellier-Thellier data in version 3.0 format
Reads saved interpretations from a specimen formatted table, default: specimens.txt
SYNTAX
thellier_magic.py [command line options]
OPTIONS
-h prints help ... | NAME
thellier_magic.py
DESCRIPTION
plots Thellier-Thellier data in version 3.0 format
Reads saved interpretations from a specimen formatted table, default: specimens.txt
SYNTAX
thellier_magic.py [command line options]
OPTIONS
-h prints help message and quits
... | Below is the the instruction that describes the task:
### Input:
NAME
thellier_magic.py
DESCRIPTION
plots Thellier-Thellier data in version 3.0 format
Reads saved interpretations from a specimen formatted table, default: specimens.txt
SYNTAX
thellier_magic.py [command line ... |
def _relay(self, **kwargs):
"""Send the request through the server and return the HTTP response."""
retval = None
delay_time = 2 # For connection retries
read_attempts = 0 # For reading from socket
while retval is None: # Evict can return False
sock = socket.socket... | Send the request through the server and return the HTTP response. | Below is the the instruction that describes the task:
### Input:
Send the request through the server and return the HTTP response.
### Response:
def _relay(self, **kwargs):
"""Send the request through the server and return the HTTP response."""
retval = None
delay_time = 2 # For connection... |
def get_pcfg():
'''
sets up the config options by reading globals saved in peasoup/global.py
as self.pcfg
'''
path = os.path.dirname(AppBuilder.main_file)
file = os.path.join(path,
PEASOUP_USER_DIR,
PEASOUP_CONFIG_FI... | sets up the config options by reading globals saved in peasoup/global.py
as self.pcfg | Below is the the instruction that describes the task:
### Input:
sets up the config options by reading globals saved in peasoup/global.py
as self.pcfg
### Response:
def get_pcfg():
'''
sets up the config options by reading globals saved in peasoup/global.py
as self.pcfg
'''
... |
def convert(self, caffemodel_path, outmodel_path):
"""Convert a Caffe .caffemodel file to MXNet .params file"""
net_param = caffe_pb2.NetParameter()
with open(caffemodel_path, 'rb') as caffe_model_file:
net_param.ParseFromString(caffe_model_file.read())
layers = net_param.la... | Convert a Caffe .caffemodel file to MXNet .params file | Below is the the instruction that describes the task:
### Input:
Convert a Caffe .caffemodel file to MXNet .params file
### Response:
def convert(self, caffemodel_path, outmodel_path):
"""Convert a Caffe .caffemodel file to MXNet .params file"""
net_param = caffe_pb2.NetParameter()
with ope... |
def get_arguments(self, name: str, strip: bool = True) -> List[str]:
"""Returns a list of the arguments with the given name.
If the argument is not present, returns an empty list.
This method searches both the query and body arguments.
"""
# Make sure `get_arguments` isn't acc... | Returns a list of the arguments with the given name.
If the argument is not present, returns an empty list.
This method searches both the query and body arguments. | Below is the the instruction that describes the task:
### Input:
Returns a list of the arguments with the given name.
If the argument is not present, returns an empty list.
This method searches both the query and body arguments.
### Response:
def get_arguments(self, name: str, strip: bool = True)... |
def mult_inv(a, b):
"""
Calculate the multiplicative inverse a**-1 % b.
This function works for n >= 5 where n is prime.
"""
# in addition to the normal setup, we also remember b
last_b, x, last_x, y, last_y = b, 0, 1, 1, 0
while b != 0:
q = a // b
a, b = b, a % b
x,... | Calculate the multiplicative inverse a**-1 % b.
This function works for n >= 5 where n is prime. | Below is the the instruction that describes the task:
### Input:
Calculate the multiplicative inverse a**-1 % b.
This function works for n >= 5 where n is prime.
### Response:
def mult_inv(a, b):
"""
Calculate the multiplicative inverse a**-1 % b.
This function works for n >= 5 where n is prime.
... |
def _validate( # pylint: disable=too-many-arguments
cls,
sign,
integer_part,
non_repeating_part,
repeating_part,
base
):
"""
Check if radix is valid.
:param int sign: -1, 0, or 1 as appropriate
:param integer_part: the part on the left... | Check if radix is valid.
:param int sign: -1, 0, or 1 as appropriate
:param integer_part: the part on the left side of the radix
:type integer_part: list of int
:param non_repeating_part: non repeating part on left side
:type non_repeating_part: list of int
:param repeat... | Below is the the instruction that describes the task:
### Input:
Check if radix is valid.
:param int sign: -1, 0, or 1 as appropriate
:param integer_part: the part on the left side of the radix
:type integer_part: list of int
:param non_repeating_part: non repeating part on left sid... |
def resample_to_delta_t(timeseries, delta_t, method='butterworth'):
"""Resmple the time_series to delta_t
Resamples the TimeSeries instance time_series to the given time step,
delta_t. Only powers of two and real valued time series are supported
at this time. Additional restrictions may apply to partic... | Resmple the time_series to delta_t
Resamples the TimeSeries instance time_series to the given time step,
delta_t. Only powers of two and real valued time series are supported
at this time. Additional restrictions may apply to particular filter
methods.
Parameters
----------
time_series: Ti... | Below is the the instruction that describes the task:
### Input:
Resmple the time_series to delta_t
Resamples the TimeSeries instance time_series to the given time step,
delta_t. Only powers of two and real valued time series are supported
at this time. Additional restrictions may apply to particular f... |
def get(self, name):
"""Get the parameter whose name is *name*.
The returned object is a :class:`.Parameter` instance. Raises
:exc:`ValueError` if no parameter has this name. Since multiple
parameters can have the same name, we'll return the last match, since
the last parameter ... | Get the parameter whose name is *name*.
The returned object is a :class:`.Parameter` instance. Raises
:exc:`ValueError` if no parameter has this name. Since multiple
parameters can have the same name, we'll return the last match, since
the last parameter is the only one read by the Medi... | Below is the the instruction that describes the task:
### Input:
Get the parameter whose name is *name*.
The returned object is a :class:`.Parameter` instance. Raises
:exc:`ValueError` if no parameter has this name. Since multiple
parameters can have the same name, we'll return the last mat... |
def stop(self):
"""
Stops the ``Pipers`` according to pipeline topology.
"""
self.log.debug('%s begins stopping routine' % repr(self))
self.log.debug('%s triggers stopping in input pipers' % repr(self))
inputs = self.get_inputs()
for piper in inputs:
... | Stops the ``Pipers`` according to pipeline topology. | Below is the the instruction that describes the task:
### Input:
Stops the ``Pipers`` according to pipeline topology.
### Response:
def stop(self):
"""
Stops the ``Pipers`` according to pipeline topology.
"""
self.log.debug('%s begins stopping routine' % repr(self))
... |
def pack_bot_file_id(file):
"""
Inverse operation for `resolve_bot_file_id`.
The only parameters this method will accept are :tl:`Document` and
:tl:`Photo`, and it will return a variable-length ``file_id`` string.
If an invalid parameter is given, it will ``return None``.
"""
if isinstance... | Inverse operation for `resolve_bot_file_id`.
The only parameters this method will accept are :tl:`Document` and
:tl:`Photo`, and it will return a variable-length ``file_id`` string.
If an invalid parameter is given, it will ``return None``. | Below is the the instruction that describes the task:
### Input:
Inverse operation for `resolve_bot_file_id`.
The only parameters this method will accept are :tl:`Document` and
:tl:`Photo`, and it will return a variable-length ``file_id`` string.
If an invalid parameter is given, it will ``return None... |
def add_external_reference_to_term(self,term_id, external_ref):
"""
Adds an external reference to the given term identifier
@type term_id: string
@param term_id: the term identifier
@param external_ref: an external reference object
@type external_ref: L{CexternalReference... | Adds an external reference to the given term identifier
@type term_id: string
@param term_id: the term identifier
@param external_ref: an external reference object
@type external_ref: L{CexternalReference} | Below is the the instruction that describes the task:
### Input:
Adds an external reference to the given term identifier
@type term_id: string
@param term_id: the term identifier
@param external_ref: an external reference object
@type external_ref: L{CexternalReference}
### Response:... |
def _check_position(self, feature, info):
"""
Takes the featur and the info dict and checks for the forced position
:param feature:
:param info:
:return:
"""
pos = info.get('position')
if pos is not None:
feature_pos = self.get_feature_position... | Takes the featur and the info dict and checks for the forced position
:param feature:
:param info:
:return: | Below is the the instruction that describes the task:
### Input:
Takes the featur and the info dict and checks for the forced position
:param feature:
:param info:
:return:
### Response:
def _check_position(self, feature, info):
"""
Takes the featur and the info dict and che... |
def ip_info(self, vuln_name=None, vuln_id=None, ip_list_only=True, hostfilter=None):
"""
List of all IP Addresses with a vulnerability
:param vuln_name: t_vulndata.f_vulnid
:param vuln_id: t_vulndata.id
:param ip_list_only: IP List only (default) or rest of t_hosts fields
... | List of all IP Addresses with a vulnerability
:param vuln_name: t_vulndata.f_vulnid
:param vuln_id: t_vulndata.id
:param ip_list_only: IP List only (default) or rest of t_hosts fields
:param hostfilter: Valid hostfilter or none
:return: [(ip, hostname) ...] or [(ip, hostname, t_... | Below is the the instruction that describes the task:
### Input:
List of all IP Addresses with a vulnerability
:param vuln_name: t_vulndata.f_vulnid
:param vuln_id: t_vulndata.id
:param ip_list_only: IP List only (default) or rest of t_hosts fields
:param hostfilter: Valid hostfilte... |
def set_state(name, backend, state, socket=DEFAULT_SOCKET_URL):
'''
Force a server's administrative state to a new state. This can be useful to
disable load balancing and/or any traffic to a server. Setting the state to
"ready" puts the server in normal mode, and the command is the equivalent of
the... | Force a server's administrative state to a new state. This can be useful to
disable load balancing and/or any traffic to a server. Setting the state to
"ready" puts the server in normal mode, and the command is the equivalent of
the "enable server" command. Setting the state to "maint" disables any traffic
... | Below is the the instruction that describes the task:
### Input:
Force a server's administrative state to a new state. This can be useful to
disable load balancing and/or any traffic to a server. Setting the state to
"ready" puts the server in normal mode, and the command is the equivalent of
the "enabl... |
async def uv_protection_window(
self, low: float = 3.5, high: float = 3.5) -> dict:
"""Get data on when a UV protection window is."""
return await self.request(
'get', 'protection', params={
'from': str(low),
'to': str(high)
}) | Get data on when a UV protection window is. | Below is the the instruction that describes the task:
### Input:
Get data on when a UV protection window is.
### Response:
async def uv_protection_window(
self, low: float = 3.5, high: float = 3.5) -> dict:
"""Get data on when a UV protection window is."""
return await self.request(
... |
def params_to_dict(params, dct):
"""
Updates the 'dct' dictionary with the 'params' dictionary, filtering out
all those whose param value is None.
"""
for param, val in params.items():
if val is None:
continue
dct[param] = val
return dct | Updates the 'dct' dictionary with the 'params' dictionary, filtering out
all those whose param value is None. | Below is the the instruction that describes the task:
### Input:
Updates the 'dct' dictionary with the 'params' dictionary, filtering out
all those whose param value is None.
### Response:
def params_to_dict(params, dct):
"""
Updates the 'dct' dictionary with the 'params' dictionary, filtering out
... |
def to_excel(self, filename, recommended_only=False, include_io=True):
"""
Return an Excel file for each model and dataset.
Parameters
----------
filename : str or ExcelWriter object
Either the file name (string) or an ExcelWriter object.
recommended_only : b... | Return an Excel file for each model and dataset.
Parameters
----------
filename : str or ExcelWriter object
Either the file name (string) or an ExcelWriter object.
recommended_only : bool, optional
If True, only recommended models for each session are included. I... | Below is the the instruction that describes the task:
### Input:
Return an Excel file for each model and dataset.
Parameters
----------
filename : str or ExcelWriter object
Either the file name (string) or an ExcelWriter object.
recommended_only : bool, optional
... |
def call_many(self, callback, args):
"""callback is run with each arg but run a call per second"""
if isinstance(callback, str):
callback = getattr(self, callback)
f = None
for arg in args:
f = callback(*arg)
return f | callback is run with each arg but run a call per second | Below is the the instruction that describes the task:
### Input:
callback is run with each arg but run a call per second
### Response:
def call_many(self, callback, args):
"""callback is run with each arg but run a call per second"""
if isinstance(callback, str):
callback = getattr(self... |
def pack_images(images, rows, cols):
"""Helper utility to make a field of images."""
shape = tf.shape(input=images)
width = shape[-3]
height = shape[-2]
depth = shape[-1]
images = tf.reshape(images, (-1, width, height, depth))
batch = tf.shape(input=images)[0]
rows = tf.minimum(rows, batch)
cols = tf.... | Helper utility to make a field of images. | Below is the the instruction that describes the task:
### Input:
Helper utility to make a field of images.
### Response:
def pack_images(images, rows, cols):
"""Helper utility to make a field of images."""
shape = tf.shape(input=images)
width = shape[-3]
height = shape[-2]
depth = shape[-1]
images = tf... |
def project_point(p, permutation=None):
"""
Maps (x,y,z) coordinates to planar simplex.
Parameters
----------
p: 3-tuple
The point to be projected p = (x, y, z)
permutation: string, None, equivalent to "012"
The order of the coordinates, counterclockwise from the origin
"""
... | Maps (x,y,z) coordinates to planar simplex.
Parameters
----------
p: 3-tuple
The point to be projected p = (x, y, z)
permutation: string, None, equivalent to "012"
The order of the coordinates, counterclockwise from the origin | Below is the the instruction that describes the task:
### Input:
Maps (x,y,z) coordinates to planar simplex.
Parameters
----------
p: 3-tuple
The point to be projected p = (x, y, z)
permutation: string, None, equivalent to "012"
The order of the coordinates, counterclockwise from th... |
def create_mysql(username, password, host, port, database, **kwargs): # pragma: no cover
"""
create an engine connected to a mysql database using mysqldb.
"""
return create_engine(
_create_mysql(username, password, host, port, database),
**kwargs
) | create an engine connected to a mysql database using mysqldb. | Below is the the instruction that describes the task:
### Input:
create an engine connected to a mysql database using mysqldb.
### Response:
def create_mysql(username, password, host, port, database, **kwargs): # pragma: no cover
"""
create an engine connected to a mysql database using mysqldb.
"""
... |
def read_uint16(self):
"""Read 2 bytes."""
if self.pos + 2 > self.remaining_length:
return NC.ERR_PROTOCOL
msb = self.payload[self.pos]
self.pos += 1
lsb = self.payload[self.pos]
self.pos += 1
word = (msb << 8) + lsb
return NC... | Read 2 bytes. | Below is the the instruction that describes the task:
### Input:
Read 2 bytes.
### Response:
def read_uint16(self):
"""Read 2 bytes."""
if self.pos + 2 > self.remaining_length:
return NC.ERR_PROTOCOL
msb = self.payload[self.pos]
self.pos += 1
lsb = self.payload[s... |
def main():
"""Destroy any ELB related Resources."""
logging.basicConfig(format=LOGGING_FORMAT)
parser = argparse.ArgumentParser(description=main.__doc__)
add_debug(parser)
add_app(parser)
add_env(parser)
add_region(parser)
args = parser.parse_args()
logging.getLogger(__package__.s... | Destroy any ELB related Resources. | Below is the the instruction that describes the task:
### Input:
Destroy any ELB related Resources.
### Response:
def main():
"""Destroy any ELB related Resources."""
logging.basicConfig(format=LOGGING_FORMAT)
parser = argparse.ArgumentParser(description=main.__doc__)
add_debug(parser)
add_app... |
def _asynciostacks(*args, **kwargs): # pragma: no cover
'''
A signal handler used to print asyncio task stacks and thread stacks.
'''
print(80 * '*')
print('Asyncio tasks stacks:')
tasks = asyncio.all_tasks(_glob_loop)
for task in tasks:
task.print_stack()
print(80 * '*')
pr... | A signal handler used to print asyncio task stacks and thread stacks. | Below is the the instruction that describes the task:
### Input:
A signal handler used to print asyncio task stacks and thread stacks.
### Response:
def _asynciostacks(*args, **kwargs): # pragma: no cover
'''
A signal handler used to print asyncio task stacks and thread stacks.
'''
print(80 * '*')... |
def contains(self, other):
"""
Return True if this contains other. Other may be either range of same
type or scalar of same type as the boundaries.
>>> intrange(1, 10).contains(intrange(1, 5))
True
>>> intrange(1, 10).contains(intrange(5, 10))
Tru... | Return True if this contains other. Other may be either range of same
type or scalar of same type as the boundaries.
>>> intrange(1, 10).contains(intrange(1, 5))
True
>>> intrange(1, 10).contains(intrange(5, 10))
True
>>> intrange(1, 10).contains(intr... | Below is the the instruction that describes the task:
### Input:
Return True if this contains other. Other may be either range of same
type or scalar of same type as the boundaries.
>>> intrange(1, 10).contains(intrange(1, 5))
True
>>> intrange(1, 10).contains(intrange(5... |
def _get_stats_from_socket(self, name):
"""Return the parsed JSON data returned when ceph is told to
dump the stats from the named socket.
In the event of an error error, the exception is logged, and
an empty result set is returned.
"""
try:
json_blob = subpr... | Return the parsed JSON data returned when ceph is told to
dump the stats from the named socket.
In the event of an error error, the exception is logged, and
an empty result set is returned. | Below is the the instruction that describes the task:
### Input:
Return the parsed JSON data returned when ceph is told to
dump the stats from the named socket.
In the event of an error error, the exception is logged, and
an empty result set is returned.
### Response:
def _get_stats_from_s... |
def _carregar(self):
"""Carrega (ou recarrega) a biblioteca SAT. Se a convenção de chamada
ainda não tiver sido definida, será determinada pela extensão do
arquivo da biblioteca.
:raises ValueError: Se a convenção de chamada não puder ser determinada
ou se não for um valor v... | Carrega (ou recarrega) a biblioteca SAT. Se a convenção de chamada
ainda não tiver sido definida, será determinada pela extensão do
arquivo da biblioteca.
:raises ValueError: Se a convenção de chamada não puder ser determinada
ou se não for um valor válido. | Below is the the instruction that describes the task:
### Input:
Carrega (ou recarrega) a biblioteca SAT. Se a convenção de chamada
ainda não tiver sido definida, será determinada pela extensão do
arquivo da biblioteca.
:raises ValueError: Se a convenção de chamada não puder ser determinada... |
def calc_check_digit(digits):
"""Calculate and return the GS1 check digit."""
ints = [int(d) for d in digits]
l = len(ints)
odds = slice((l - 1) % 2, l, 2)
even = slice(l % 2, l, 2)
checksum = 3 * sum(ints[odds]) + sum(ints[even])
return str(-checksum % 10) | Calculate and return the GS1 check digit. | Below is the the instruction that describes the task:
### Input:
Calculate and return the GS1 check digit.
### Response:
def calc_check_digit(digits):
"""Calculate and return the GS1 check digit."""
ints = [int(d) for d in digits]
l = len(ints)
odds = slice((l - 1) % 2, l, 2)
... |
def base_prompt(self, prompt):
"""Extract the base prompt pattern."""
if prompt is None:
return None
if not self.device.is_target:
return prompt
pattern = pattern_manager.pattern(self.platform, "prompt_dynamic", compiled=False)
pattern = pattern.format(pro... | Extract the base prompt pattern. | Below is the the instruction that describes the task:
### Input:
Extract the base prompt pattern.
### Response:
def base_prompt(self, prompt):
"""Extract the base prompt pattern."""
if prompt is None:
return None
if not self.device.is_target:
return prompt
pa... |
def get_institute_usage(institute, start, end):
"""Return a tuple of cpu hours and number of jobs for an institute
for a given period
Keyword arguments:
institute --
start -- start date
end -- end date
"""
try:
cache = InstituteCache.objects.get(
institute=institute,... | Return a tuple of cpu hours and number of jobs for an institute
for a given period
Keyword arguments:
institute --
start -- start date
end -- end date | Below is the the instruction that describes the task:
### Input:
Return a tuple of cpu hours and number of jobs for an institute
for a given period
Keyword arguments:
institute --
start -- start date
end -- end date
### Response:
def get_institute_usage(institute, start, end):
"""Return a ... |
def is_request_complete_for_rid(request, rid):
"""Check if a given request has been completed on the given relation
@param request: A CephBrokerRq object
@param rid: Relation ID
"""
broker_key = get_broker_rsp_key()
for unit in related_units(rid):
rdata = relation_get(rid=rid, unit=unit... | Check if a given request has been completed on the given relation
@param request: A CephBrokerRq object
@param rid: Relation ID | Below is the the instruction that describes the task:
### Input:
Check if a given request has been completed on the given relation
@param request: A CephBrokerRq object
@param rid: Relation ID
### Response:
def is_request_complete_for_rid(request, rid):
"""Check if a given request has been completed o... |
def replace_values(in_m, out_m, map_from=(), map_to=()):
'''
Make a copy of a model with one value replaced with another
'''
for link in in_m.match():
new_link = list(link)
if map_from:
if link[ORIGIN] in map_from: new_link[ORIGIN] = map_to[map_from.index(link[ORIGIN])]
... | Make a copy of a model with one value replaced with another | Below is the the instruction that describes the task:
### Input:
Make a copy of a model with one value replaced with another
### Response:
def replace_values(in_m, out_m, map_from=(), map_to=()):
'''
Make a copy of a model with one value replaced with another
'''
for link in in_m.match():
n... |
def file_id_to_name(self, file_id):
"""Convert a file id to the file name."""
sql = 'select name from files where id = ?'
logging.debug('%s %s', sql, (file_id,))
self.cursor.execute(sql, (file_id,))
name = self.cursor.fetchone()
if name:
return name[0]
... | Convert a file id to the file name. | Below is the the instruction that describes the task:
### Input:
Convert a file id to the file name.
### Response:
def file_id_to_name(self, file_id):
"""Convert a file id to the file name."""
sql = 'select name from files where id = ?'
logging.debug('%s %s', sql, (file_id,))
self.c... |
def integerbox(msg=""
, title=" "
, default=""
, lowerbound=0
, upperbound=99
, image = None
, root = None
, **invalidKeywordArguments
):
"""
Show a box in which a user can enter an integer.
In addition to arguments for msg and title, this function accepts
integer argum... | Show a box in which a user can enter an integer.
In addition to arguments for msg and title, this function accepts
integer arguments for "default", "lowerbound", and "upperbound".
The default argument may be None.
When the user enters some text, the text is checked to verify that it
can be conver... | Below is the the instruction that describes the task:
### Input:
Show a box in which a user can enter an integer.
In addition to arguments for msg and title, this function accepts
integer arguments for "default", "lowerbound", and "upperbound".
The default argument may be None.
When the user ente... |
def artist(self, spotify_id):
"""Get a spotify artist by their ID.
Parameters
----------
spotify_id : str
The spotify_id to search by.
"""
route = Route('GET', '/artists/{spotify_id}', spotify_id=spotify_id)
return self.request(route) | Get a spotify artist by their ID.
Parameters
----------
spotify_id : str
The spotify_id to search by. | Below is the the instruction that describes the task:
### Input:
Get a spotify artist by their ID.
Parameters
----------
spotify_id : str
The spotify_id to search by.
### Response:
def artist(self, spotify_id):
"""Get a spotify artist by their ID.
Parameters
... |
def deploy(provider=None):
"""
Deploys your project
"""
if os.path.exists(DEPLOY_YAML):
site = yaml.safe_load(_read_file(DEPLOY_YAML))
provider_class = PROVIDERS[site['provider']]
provider_class.deploy() | Deploys your project | Below is the the instruction that describes the task:
### Input:
Deploys your project
### Response:
def deploy(provider=None):
"""
Deploys your project
"""
if os.path.exists(DEPLOY_YAML):
site = yaml.safe_load(_read_file(DEPLOY_YAML))
provider_class = PROVIDERS[site['provider']]
pr... |
def describe_volumes(kwargs=None, call=None):
'''
Describe a volume (or volumes)
volume_id
One or more volume IDs. Multiple IDs must be separated by ",".
TODO: Add all of the filters.
'''
if call != 'function':
log.error(
'The describe_volumes function must be calle... | Describe a volume (or volumes)
volume_id
One or more volume IDs. Multiple IDs must be separated by ",".
TODO: Add all of the filters. | Below is the the instruction that describes the task:
### Input:
Describe a volume (or volumes)
volume_id
One or more volume IDs. Multiple IDs must be separated by ",".
TODO: Add all of the filters.
### Response:
def describe_volumes(kwargs=None, call=None):
'''
Describe a volume (or volu... |
def consultar_sat(self):
"""Sobrepõe :meth:`~satcfe.base.FuncoesSAT.consultar_sat`.
:return: Uma resposta SAT padrão.
:rtype: satcfe.resposta.padrao.RespostaSAT
"""
retorno = super(ClienteSATLocal, self).consultar_sat()
return RespostaSAT.consultar_sat(retorno) | Sobrepõe :meth:`~satcfe.base.FuncoesSAT.consultar_sat`.
:return: Uma resposta SAT padrão.
:rtype: satcfe.resposta.padrao.RespostaSAT | Below is the the instruction that describes the task:
### Input:
Sobrepõe :meth:`~satcfe.base.FuncoesSAT.consultar_sat`.
:return: Uma resposta SAT padrão.
:rtype: satcfe.resposta.padrao.RespostaSAT
### Response:
def consultar_sat(self):
"""Sobrepõe :meth:`~satcfe.base.FuncoesSAT.consultar_... |
def nodes(self, t=None, data=False):
"""Return a list of the nodes in the graph at a given snapshot.
Parameters
----------
t : snapshot id (default=None)
If None the the method returns all the nodes of the flattened graph.
data : boolean, optional (default=False)
... | Return a list of the nodes in the graph at a given snapshot.
Parameters
----------
t : snapshot id (default=None)
If None the the method returns all the nodes of the flattened graph.
data : boolean, optional (default=False)
If False return a list of nodes. If... | Below is the the instruction that describes the task:
### Input:
Return a list of the nodes in the graph at a given snapshot.
Parameters
----------
t : snapshot id (default=None)
If None the the method returns all the nodes of the flattened graph.
data : boolean, optiona... |
def get_metatab_doc(nb_path):
"""Read a notebook and extract the metatab document. Only returns the first document"""
from metatab.generate import CsvDataRowGenerator
from metatab.rowgenerators import TextRowGenerator
from metatab import MetatabDoc
with open(nb_path) as f:
nb = nbformat.re... | Read a notebook and extract the metatab document. Only returns the first document | Below is the the instruction that describes the task:
### Input:
Read a notebook and extract the metatab document. Only returns the first document
### Response:
def get_metatab_doc(nb_path):
"""Read a notebook and extract the metatab document. Only returns the first document"""
from metatab.generate impor... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.