code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def randkey(bits, keyspace=string.ascii_letters + string.digits + '#/.',
rng=None):
""" Returns a cryptographically secure random key of desired @bits of
entropy within @keyspace using :class:random.SystemRandom
@bits: (#int) minimum bits of entropy
@keyspace: (#str) or iterable... | Returns a cryptographically secure random key of desired @bits of
entropy within @keyspace using :class:random.SystemRandom
@bits: (#int) minimum bits of entropy
@keyspace: (#str) or iterable allowed output chars
@rng: the random number generator to use. Defaults to
:class:r... | Below is the the instruction that describes the task:
### Input:
Returns a cryptographically secure random key of desired @bits of
entropy within @keyspace using :class:random.SystemRandom
@bits: (#int) minimum bits of entropy
@keyspace: (#str) or iterable allowed output chars
@rng:... |
def idx_infeasible(self, solution_genotype):
"""return indices of "infeasible" variables, that is,
variables that do not directly map into the feasible domain such that
``tf.inverse(tf(x)) == x``.
"""
res = [i for i, x in enumerate(solution_genotype)
... | return indices of "infeasible" variables, that is,
variables that do not directly map into the feasible domain such that
``tf.inverse(tf(x)) == x``. | Below is the the instruction that describes the task:
### Input:
return indices of "infeasible" variables, that is,
variables that do not directly map into the feasible domain such that
``tf.inverse(tf(x)) == x``.
### Response:
def idx_infeasible(self, solution_genotype):
"""return indices ... |
def smooth_ot_semi_dual(a, b, M, reg, reg_type='l2', method="L-BFGS-B", stopThr=1e-9,
numItermax=500, verbose=False, log=False):
r"""
Solve the regularized OT problem in the semi-dual and return the OT matrix
The function solves the smooth relaxed dual formulation (10) in [17]_ :
... | r"""
Solve the regularized OT problem in the semi-dual and return the OT matrix
The function solves the smooth relaxed dual formulation (10) in [17]_ :
.. math::
\max_{\alpha}\quad a^T\alpha-OT_\Omega^*(\alpha,b)
where :
.. math::
OT_\Omega^*(\alpha,b)=\sum_j b_j
- :math:`\m... | Below is the the instruction that describes the task:
### Input:
r"""
Solve the regularized OT problem in the semi-dual and return the OT matrix
The function solves the smooth relaxed dual formulation (10) in [17]_ :
.. math::
\max_{\alpha}\quad a^T\alpha-OT_\Omega^*(\alpha,b)
where :
... |
def post(self, url, body=None):
""" Executes an HTTP POST request for the given URL. """
response = self.http.post(url,
headers=self.headers,
data=body,
**self.requests_params)
return self.proc... | Executes an HTTP POST request for the given URL. | Below is the the instruction that describes the task:
### Input:
Executes an HTTP POST request for the given URL.
### Response:
def post(self, url, body=None):
""" Executes an HTTP POST request for the given URL. """
response = self.http.post(url,
headers=self.head... |
def schema_digest(self) -> str:
"""Generate schema digest (to be used primarily by clients).
Returns:
Condensed information about the schema in JSON format.
"""
res = self.schema._node_digest()
res["config"] = True
return json.dumps(res) | Generate schema digest (to be used primarily by clients).
Returns:
Condensed information about the schema in JSON format. | Below is the the instruction that describes the task:
### Input:
Generate schema digest (to be used primarily by clients).
Returns:
Condensed information about the schema in JSON format.
### Response:
def schema_digest(self) -> str:
"""Generate schema digest (to be used primarily by cl... |
def export_serving(model_path):
"""Export trained model to use it in TensorFlow Serving or cloudML. """
pred_config = PredictConfig(
session_init=get_model_loader(model_path),
model=InferenceOnlyModel(),
input_names=['input_img_bytes'],
output_names=['prediction_img_bytes'])
... | Export trained model to use it in TensorFlow Serving or cloudML. | Below is the the instruction that describes the task:
### Input:
Export trained model to use it in TensorFlow Serving or cloudML.
### Response:
def export_serving(model_path):
"""Export trained model to use it in TensorFlow Serving or cloudML. """
pred_config = PredictConfig(
session_init=get_model... |
def push(self, path, name, tag=None):
'''push an image to Google Cloud Storage, meaning uploading it
path: should correspond to an absolte image path (or derive it)
name: should be the complete uri that the user has requested to push.
tag: should correspond with an image tag. This is provided to mi... | push an image to Google Cloud Storage, meaning uploading it
path: should correspond to an absolte image path (or derive it)
name: should be the complete uri that the user has requested to push.
tag: should correspond with an image tag. This is provided to mirror Docker | Below is the the instruction that describes the task:
### Input:
push an image to Google Cloud Storage, meaning uploading it
path: should correspond to an absolte image path (or derive it)
name: should be the complete uri that the user has requested to push.
tag: should correspond with an image tag... |
def import_name(name, default_ns=None):
"""Import an object based on the dotted string.
>>> import_name('textwrap') # doctest: +ELLIPSIS
<module 'textwrap' from '...'>
>>> import_name('birding.config') # doctest: +ELLIPSIS
<module 'birding.config' from '...'>
>>> import_name('birding.config.get... | Import an object based on the dotted string.
>>> import_name('textwrap') # doctest: +ELLIPSIS
<module 'textwrap' from '...'>
>>> import_name('birding.config') # doctest: +ELLIPSIS
<module 'birding.config' from '...'>
>>> import_name('birding.config.get_config') # doctest: +ELLIPSIS
<function ge... | Below is the the instruction that describes the task:
### Input:
Import an object based on the dotted string.
>>> import_name('textwrap') # doctest: +ELLIPSIS
<module 'textwrap' from '...'>
>>> import_name('birding.config') # doctest: +ELLIPSIS
<module 'birding.config' from '...'>
>>> import_na... |
def list_groups(self, **kwargs):
"""List all groups in organisation.
:param int limit: The number of groups to retrieve
:param str order: The ordering direction, ascending (asc) or descending (desc)
:param str after: Get groups after/starting at given group ID
:returns: a list o... | List all groups in organisation.
:param int limit: The number of groups to retrieve
:param str order: The ordering direction, ascending (asc) or descending (desc)
:param str after: Get groups after/starting at given group ID
:returns: a list of :py:class:`Group` objects.
:rtype:... | Below is the the instruction that describes the task:
### Input:
List all groups in organisation.
:param int limit: The number of groups to retrieve
:param str order: The ordering direction, ascending (asc) or descending (desc)
:param str after: Get groups after/starting at given group ID
... |
def header(self, item0, *items):
"""print string item0 to the current position and next strings to defined positions
example: .header("Name", 75, "Quantity", 100, "Unit")
"""
self.txt(item0)
at_x = None
for item in items:
if at_x is None:
at_x ... | print string item0 to the current position and next strings to defined positions
example: .header("Name", 75, "Quantity", 100, "Unit") | Below is the the instruction that describes the task:
### Input:
print string item0 to the current position and next strings to defined positions
example: .header("Name", 75, "Quantity", 100, "Unit")
### Response:
def header(self, item0, *items):
"""print string item0 to the current position and ne... |
def user(self, email):
"""Fetch a user from the database.
Args:
email(str)
Returns:
user_obj(dict)
"""
LOG.info("Fetching user %s", email)
user_obj = self.user_collection.find_one({'_id': email})
return us... | Fetch a user from the database.
Args:
email(str)
Returns:
user_obj(dict) | Below is the the instruction that describes the task:
### Input:
Fetch a user from the database.
Args:
email(str)
Returns:
user_obj(dict)
### Response:
def user(self, email):
"""Fetch a user from the database.
Ar... |
def run_edisgo_twice(run_args):
"""
Run grid analysis twice on same grid: once w/ and once w/o new generators
First run without connection of new generators approves sufficient grid
hosting capacity. Otherwise, grid is reinforced.
Second run assessment grid extension needs in terms of RES integrati... | Run grid analysis twice on same grid: once w/ and once w/o new generators
First run without connection of new generators approves sufficient grid
hosting capacity. Otherwise, grid is reinforced.
Second run assessment grid extension needs in terms of RES integration
Parameters
----------
run_ar... | Below is the the instruction that describes the task:
### Input:
Run grid analysis twice on same grid: once w/ and once w/o new generators
First run without connection of new generators approves sufficient grid
hosting capacity. Otherwise, grid is reinforced.
Second run assessment grid extension needs ... |
def format_value(value):
"""This function should return unicode representation of the value
"""
value_id = id(value)
if value_id in recursion_breaker.processed:
return u'<recursion>'
recursion_breaker.processed.add(value_id)
try:
if isinstance(value, six.binary_type):
... | This function should return unicode representation of the value | Below is the the instruction that describes the task:
### Input:
This function should return unicode representation of the value
### Response:
def format_value(value):
"""This function should return unicode representation of the value
"""
value_id = id(value)
if value_id in recursion_breaker.proce... |
def files_type(fs0, fs1, files):
"""Inspects the file type of the given files."""
for file_meta in files['deleted_files']:
file_meta['type'] = fs0.file(file_meta['path'])
for file_meta in files['created_files'] + files['modified_files']:
file_meta['type'] = fs1.file(file_meta['path'])
r... | Inspects the file type of the given files. | Below is the the instruction that describes the task:
### Input:
Inspects the file type of the given files.
### Response:
def files_type(fs0, fs1, files):
"""Inspects the file type of the given files."""
for file_meta in files['deleted_files']:
file_meta['type'] = fs0.file(file_meta['path'])
fo... |
def is_float(tg_type, inc_array=False):
"""Tells if the given tango type is float
:param tg_type: tango type
:type tg_type: :class:`tango.CmdArgType`
:param inc_array: (optional, default is False) determines if include array
in the list of checked types
:type inc_array: :py:ob... | Tells if the given tango type is float
:param tg_type: tango type
:type tg_type: :class:`tango.CmdArgType`
:param inc_array: (optional, default is False) determines if include array
in the list of checked types
:type inc_array: :py:obj:`bool`
:return: True if the given tango ... | Below is the the instruction that describes the task:
### Input:
Tells if the given tango type is float
:param tg_type: tango type
:type tg_type: :class:`tango.CmdArgType`
:param inc_array: (optional, default is False) determines if include array
in the list of checked types
:... |
def get_charge_calibration(calibation_file, max_tdc):
''' Open the hit or calibration file and return the calibration per pixel'''
with tb.open_file(calibation_file, mode="r") as in_file_calibration_h5:
tdc_calibration = in_file_calibration_h5.root.HitOrCalibration[:, :, :, 1]
tdc_calibration_va... | Open the hit or calibration file and return the calibration per pixel | Below is the the instruction that describes the task:
### Input:
Open the hit or calibration file and return the calibration per pixel
### Response:
def get_charge_calibration(calibation_file, max_tdc):
''' Open the hit or calibration file and return the calibration per pixel'''
with tb.open_file(calibatio... |
def toConsole(self, level, fmt_spec, printChildren=True):
'''
Debugging tool for printing hierarchies / ownership to the console. Recursively
calls children ``toConsole`` if this node is not a directory or a file, and
``printChildren == True``.
.. todo:: fmt_spec docs needed. k... | Debugging tool for printing hierarchies / ownership to the console. Recursively
calls children ``toConsole`` if this node is not a directory or a file, and
``printChildren == True``.
.. todo:: fmt_spec docs needed. keys are ``kind`` and values are color spec
:Parameters:
`... | Below is the the instruction that describes the task:
### Input:
Debugging tool for printing hierarchies / ownership to the console. Recursively
calls children ``toConsole`` if this node is not a directory or a file, and
``printChildren == True``.
.. todo:: fmt_spec docs needed. keys are `... |
def _search(self):
""" Search - search URLs and text.
"""
text = "Search: {}".format(self.search_string)
footerwid = urwid.AttrMap(urwid.Text(text), 'footer')
self.top.footer = footerwid
search_items = []
for grp in self.items_org:
done = False
... | Search - search URLs and text. | Below is the the instruction that describes the task:
### Input:
Search - search URLs and text.
### Response:
def _search(self):
""" Search - search URLs and text.
"""
text = "Search: {}".format(self.search_string)
footerwid = urwid.AttrMap(urwid.Text(text), 'footer')
self.... |
def _quote(data):
"""Prepare a string for quoting for DIGEST-MD5 challenge or response.
Don't add the quotes, only escape '"' and "\\" with backslashes.
:Parameters:
- `data`: a raw string.
:Types:
- `data`: `bytes`
:return: `data` with '"' and "\\" escaped using "\\".
:return... | Prepare a string for quoting for DIGEST-MD5 challenge or response.
Don't add the quotes, only escape '"' and "\\" with backslashes.
:Parameters:
- `data`: a raw string.
:Types:
- `data`: `bytes`
:return: `data` with '"' and "\\" escaped using "\\".
:returntype: `bytes` | Below is the the instruction that describes the task:
### Input:
Prepare a string for quoting for DIGEST-MD5 challenge or response.
Don't add the quotes, only escape '"' and "\\" with backslashes.
:Parameters:
- `data`: a raw string.
:Types:
- `data`: `bytes`
:return: `data` with ... |
def make_serviceitem_servicedllmd5sum(servicedll_md5, condition='is', negate=False):
"""
Create a node for ServiceItem/serviceDLLmd5sum
:return: A IndicatorItem represented as an Element node
"""
document = 'ServiceItem'
search = 'ServiceItem/serviceDLLmd5sum'
content_type = 'md5'
c... | Create a node for ServiceItem/serviceDLLmd5sum
:return: A IndicatorItem represented as an Element node | Below is the the instruction that describes the task:
### Input:
Create a node for ServiceItem/serviceDLLmd5sum
:return: A IndicatorItem represented as an Element node
### Response:
def make_serviceitem_servicedllmd5sum(servicedll_md5, condition='is', negate=False):
"""
Create a node for ServiceIt... |
def send_email_sns(sender, subject, message, topic_ARN, image_png):
"""
Sends notification through AWS SNS. Takes Topic ARN from recipients.
Does not handle access keys. Use either
1/ configuration file
2/ EC2 instance profile
See also https://boto3.readthedocs.io/en/latest/guide/configur... | Sends notification through AWS SNS. Takes Topic ARN from recipients.
Does not handle access keys. Use either
1/ configuration file
2/ EC2 instance profile
See also https://boto3.readthedocs.io/en/latest/guide/configuration.html. | Below is the the instruction that describes the task:
### Input:
Sends notification through AWS SNS. Takes Topic ARN from recipients.
Does not handle access keys. Use either
1/ configuration file
2/ EC2 instance profile
See also https://boto3.readthedocs.io/en/latest/guide/configuration.html.... |
def reeval(self, X, fit, func, ask, args=()):
"""store two fitness lists, `fit` and ``fitre`` reevaluating some
solutions in `X`.
``self.evaluations`` evaluations are done for each reevaluated
fitness value.
See `__call__()`, where `reeval()` is called.
"""
self.... | store two fitness lists, `fit` and ``fitre`` reevaluating some
solutions in `X`.
``self.evaluations`` evaluations are done for each reevaluated
fitness value.
See `__call__()`, where `reeval()` is called. | Below is the the instruction that describes the task:
### Input:
store two fitness lists, `fit` and ``fitre`` reevaluating some
solutions in `X`.
``self.evaluations`` evaluations are done for each reevaluated
fitness value.
See `__call__()`, where `reeval()` is called.
### Response: ... |
def fill(self, byte):
"""
fill: byte -> None
Adds the given raw byte to this APIFrame. If this APIFrame is marked
as escaped and this byte is an escape byte, the next byte in a call
to fill() will be unescaped.
"""
if self._unescape_next_byte:
byte =... | fill: byte -> None
Adds the given raw byte to this APIFrame. If this APIFrame is marked
as escaped and this byte is an escape byte, the next byte in a call
to fill() will be unescaped. | Below is the the instruction that describes the task:
### Input:
fill: byte -> None
Adds the given raw byte to this APIFrame. If this APIFrame is marked
as escaped and this byte is an escape byte, the next byte in a call
to fill() will be unescaped.
### Response:
def fill(self, byte):
... |
def calls(ctx, obj, limit):
""" List call/short positions of an account or an asset
"""
if obj.upper() == obj:
# Asset
from bitshares.asset import Asset
asset = Asset(obj, full=True)
calls = asset.get_call_orders(limit)
t = [["acount", "debt", "collateral", "call pri... | List call/short positions of an account or an asset | Below is the the instruction that describes the task:
### Input:
List call/short positions of an account or an asset
### Response:
def calls(ctx, obj, limit):
""" List call/short positions of an account or an asset
"""
if obj.upper() == obj:
# Asset
from bitshares.asset import Asset
... |
def make_export(self, exports):
"""Populate library exported function data."""
sql = 'drop table if exists export'
logging.debug(sql)
self.cursor.execute(sql)
sql = 'create table if not exists export ' \
'(func text unique, module text)'
logging.debug(sql)
... | Populate library exported function data. | Below is the the instruction that describes the task:
### Input:
Populate library exported function data.
### Response:
def make_export(self, exports):
"""Populate library exported function data."""
sql = 'drop table if exists export'
logging.debug(sql)
self.cursor.execute(sql)
... |
def sig_encode(r, s):
"""Serialize ECDSA signature data into GPG S-expression."""
r = util.assuan_serialize(util.num2bytes(r, 32))
s = util.assuan_serialize(util.num2bytes(s, 32))
return b'(7:sig-val(5:ecdsa(1:r32:' + r + b')(1:s32:' + s + b')))' | Serialize ECDSA signature data into GPG S-expression. | Below is the the instruction that describes the task:
### Input:
Serialize ECDSA signature data into GPG S-expression.
### Response:
def sig_encode(r, s):
"""Serialize ECDSA signature data into GPG S-expression."""
r = util.assuan_serialize(util.num2bytes(r, 32))
s = util.assuan_serialize(util.num2byte... |
def preprocess(input_file,
output_file,
defines=None,
options=None,
content_types_db=None,
_preprocessed_files=None,
_depth=0):
"""
Preprocesses the specified file.
:param input_filename:
The input path.
:... | Preprocesses the specified file.
:param input_filename:
The input path.
:param output_filename:
The output file (NOT path).
:param defines:
a dictionary of defined variables that will be
understood in preprocessor statements. Keys must be strings and,
currently, only... | Below is the the instruction that describes the task:
### Input:
Preprocesses the specified file.
:param input_filename:
The input path.
:param output_filename:
The output file (NOT path).
:param defines:
a dictionary of defined variables that will be
understood in prepr... |
def load_creditscoring1(cost_mat_parameters=None):
"""Load and return the credit scoring Kaggle Credit competition dataset (classification).
The credit scoring is a easily transformable example-dependent cost-sensitive classification dataset.
Parameters
----------
cost_mat_parameters : Dictionary-... | Load and return the credit scoring Kaggle Credit competition dataset (classification).
The credit scoring is a easily transformable example-dependent cost-sensitive classification dataset.
Parameters
----------
cost_mat_parameters : Dictionary-like object, optional (default=None)
If not None, ... | Below is the the instruction that describes the task:
### Input:
Load and return the credit scoring Kaggle Credit competition dataset (classification).
The credit scoring is a easily transformable example-dependent cost-sensitive classification dataset.
Parameters
----------
cost_mat_parameters : ... |
def members(self, as_set=False):
"""Return the set members tuple/frozenset."""
if as_set:
return frozenset(map(self._members.__getitem__, self._indexes()))
return tuple(map(self._members.__getitem__, self._indexes())) | Return the set members tuple/frozenset. | Below is the the instruction that describes the task:
### Input:
Return the set members tuple/frozenset.
### Response:
def members(self, as_set=False):
"""Return the set members tuple/frozenset."""
if as_set:
return frozenset(map(self._members.__getitem__, self._indexes()))
retu... |
def formatBodyNode(root,path):
'''Format the root node for use as the body node.'''
body = root
body.name = "body"
body.weight = calcFnWeight(body)
body.path = path
body.pclass = None
return body | Format the root node for use as the body node. | Below is the the instruction that describes the task:
### Input:
Format the root node for use as the body node.
### Response:
def formatBodyNode(root,path):
'''Format the root node for use as the body node.'''
body = root
body.name = "body"
body.weight = calcFnWeight(body)
body.path ... |
def get_sub_area(area, xslice, yslice):
"""Apply slices to the area_extent and size of the area."""
new_area_extent = ((area.pixel_upper_left[0] +
(xslice.start - 0.5) * area.pixel_size_x),
(area.pixel_upper_left[1] -
(yslice.stop - 0.5) * a... | Apply slices to the area_extent and size of the area. | Below is the the instruction that describes the task:
### Input:
Apply slices to the area_extent and size of the area.
### Response:
def get_sub_area(area, xslice, yslice):
"""Apply slices to the area_extent and size of the area."""
new_area_extent = ((area.pixel_upper_left[0] +
(xs... |
def skip(stackframe=1):
"""
Must be called from within `__enter__()`. Performs some magic to have a
#ContextSkipped exception be raised the moment the with context is entered.
The #ContextSkipped must then be handled in `__exit__()` to suppress the
propagation of the exception.
> Important: This function d... | Must be called from within `__enter__()`. Performs some magic to have a
#ContextSkipped exception be raised the moment the with context is entered.
The #ContextSkipped must then be handled in `__exit__()` to suppress the
propagation of the exception.
> Important: This function does not raise an exception by it... | Below is the the instruction that describes the task:
### Input:
Must be called from within `__enter__()`. Performs some magic to have a
#ContextSkipped exception be raised the moment the with context is entered.
The #ContextSkipped must then be handled in `__exit__()` to suppress the
propagation of the excep... |
def read_message(self):
"""
Return the next text or binary message from the socket.
This is an internal method as calling this will not cleanup correctly
if an exception is called. Use `receive` instead.
"""
opcode = None
message = None
while True:
... | Return the next text or binary message from the socket.
This is an internal method as calling this will not cleanup correctly
if an exception is called. Use `receive` instead. | Below is the the instruction that describes the task:
### Input:
Return the next text or binary message from the socket.
This is an internal method as calling this will not cleanup correctly
if an exception is called. Use `receive` instead.
### Response:
def read_message(self):
"""
... |
def reload(self, client=None):
"""Update this notification from the server configuration.
See:
https://cloud.google.com/storage/docs/json_api/v1/notifications/get
If :attr:`user_project` is set on the bucket, bills the API request
to that project.
:type client: :class:... | Update this notification from the server configuration.
See:
https://cloud.google.com/storage/docs/json_api/v1/notifications/get
If :attr:`user_project` is set on the bucket, bills the API request
to that project.
:type client: :class:`~google.cloud.storage.client.Client` or
... | Below is the the instruction that describes the task:
### Input:
Update this notification from the server configuration.
See:
https://cloud.google.com/storage/docs/json_api/v1/notifications/get
If :attr:`user_project` is set on the bucket, bills the API request
to that project.
... |
def _gen_project_trend_graph(project, start, end, force_overwrite=False):
"""Generates a bar graph for a project
Keyword arguments:
project -- Project
start -- start date
end -- end date
"""
filename = graphs.get_project_trend_graph_filename(project, start, end)
csv_filename = os.path.... | Generates a bar graph for a project
Keyword arguments:
project -- Project
start -- start date
end -- end date | Below is the the instruction that describes the task:
### Input:
Generates a bar graph for a project
Keyword arguments:
project -- Project
start -- start date
end -- end date
### Response:
def _gen_project_trend_graph(project, start, end, force_overwrite=False):
"""Generates a bar graph for a ... |
def write_spmatrix_to_sparse_tensor(file, array, labels=None):
"""Writes a scipy sparse matrix to a sparse tensor"""
if not issparse(array):
raise TypeError("Array must be sparse")
# Validate shape of array and labels, resolve array and label types
if not len(array.shape) == 2:
raise V... | Writes a scipy sparse matrix to a sparse tensor | Below is the the instruction that describes the task:
### Input:
Writes a scipy sparse matrix to a sparse tensor
### Response:
def write_spmatrix_to_sparse_tensor(file, array, labels=None):
"""Writes a scipy sparse matrix to a sparse tensor"""
if not issparse(array):
raise TypeError("Array must be... |
def on_palette_name_changed(self, combo):
"""Changes the value of palette in dconf
"""
palette_name = combo.get_active_text()
if palette_name not in PALETTES:
return
self.settings.styleFont.set_string('palette', PALETTES[palette_name])
self.settings.styleFont.... | Changes the value of palette in dconf | Below is the the instruction that describes the task:
### Input:
Changes the value of palette in dconf
### Response:
def on_palette_name_changed(self, combo):
"""Changes the value of palette in dconf
"""
palette_name = combo.get_active_text()
if palette_name not in PALETTES:
... |
def get_root(self):
""":returns: the root node for the current node object."""
return get_result_class(self.__class__).objects.get(
path=self.path[0:self.steplen]) | :returns: the root node for the current node object. | Below is the the instruction that describes the task:
### Input:
:returns: the root node for the current node object.
### Response:
def get_root(self):
""":returns: the root node for the current node object."""
return get_result_class(self.__class__).objects.get(
path=self.path[0:self.s... |
def format_time(time):
""" Formats the given time into HH:MM:SS """
h, r = divmod(time / 1000, 3600)
m, s = divmod(r, 60)
return "%02d:%02d:%02d" % (h, m, s) | Formats the given time into HH:MM:SS | Below is the the instruction that describes the task:
### Input:
Formats the given time into HH:MM:SS
### Response:
def format_time(time):
""" Formats the given time into HH:MM:SS """
h, r = divmod(time / 1000, 3600)
m, s = divmod(r, 60)
return "%02d:%02d:%02d" % (h, m, s) |
def resize(self, size, interp='nearest'):
"""Resize the image.
Parameters
----------
size : int, float, or tuple
* int - Percentage of current size.
* float - Fraction of current size.
* tuple - Size of the output image.
interp : :obj:`str`... | Resize the image.
Parameters
----------
size : int, float, or tuple
* int - Percentage of current size.
* float - Fraction of current size.
* tuple - Size of the output image.
interp : :obj:`str`, optional
Interpolation to use for re-si... | Below is the the instruction that describes the task:
### Input:
Resize the image.
Parameters
----------
size : int, float, or tuple
* int - Percentage of current size.
* float - Fraction of current size.
* tuple - Size of the output image.
int... |
def trigger(self, source):
"""
Triggers all actions meant to trigger on the board state from `source`.
"""
actions = self.evaluate(source)
if actions:
if not hasattr(actions, "__iter__"):
actions = (actions, )
source.game.trigger_actions(source, actions) | Triggers all actions meant to trigger on the board state from `source`. | Below is the the instruction that describes the task:
### Input:
Triggers all actions meant to trigger on the board state from `source`.
### Response:
def trigger(self, source):
"""
Triggers all actions meant to trigger on the board state from `source`.
"""
actions = self.evaluate(source)
if actions:
... |
def _execute_batch(self, actions):
"""
Execute a single batch of Actions.
For each action that has a problem, we annotate the action with the
error information for that action, and we return the number of
successful actions in the batch.
:param actions: the list of Action... | Execute a single batch of Actions.
For each action that has a problem, we annotate the action with the
error information for that action, and we return the number of
successful actions in the batch.
:param actions: the list of Action objects to be executed
:return: count of succe... | Below is the the instruction that describes the task:
### Input:
Execute a single batch of Actions.
For each action that has a problem, we annotate the action with the
error information for that action, and we return the number of
successful actions in the batch.
:param actions: the ... |
def role_exists(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if an IAM role exists.
CLI Example:
.. code-block:: bash
salt myminion boto_iam.role_exists myirole
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
conn... | Check to see if an IAM role exists.
CLI Example:
.. code-block:: bash
salt myminion boto_iam.role_exists myirole | Below is the the instruction that describes the task:
### Input:
Check to see if an IAM role exists.
CLI Example:
.. code-block:: bash
salt myminion boto_iam.role_exists myirole
### Response:
def role_exists(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if an I... |
def add_notification(self, notification):
"""Add a notification into actions list
:param notification: notification to add
:type notification: alignak.notification.Notification
:return: None
"""
if notification.uuid in self.actions:
logger.warning("Already ex... | Add a notification into actions list
:param notification: notification to add
:type notification: alignak.notification.Notification
:return: None | Below is the the instruction that describes the task:
### Input:
Add a notification into actions list
:param notification: notification to add
:type notification: alignak.notification.Notification
:return: None
### Response:
def add_notification(self, notification):
"""Add a notifi... |
def geo_perimeter(arg, use_spheroid=None):
"""
Compute perimeter of a geo spatial data
Parameters
----------
arg : geometry or geography
use_spheroid : default None
Returns
-------
perimeter : double scalar
"""
op = ops.GeoPerimeter(arg, use_spheroid)
return op.to_expr(... | Compute perimeter of a geo spatial data
Parameters
----------
arg : geometry or geography
use_spheroid : default None
Returns
-------
perimeter : double scalar | Below is the the instruction that describes the task:
### Input:
Compute perimeter of a geo spatial data
Parameters
----------
arg : geometry or geography
use_spheroid : default None
Returns
-------
perimeter : double scalar
### Response:
def geo_perimeter(arg, use_spheroid=None):
... |
def is_template(self, filename):
"""Check if a file is a template.
A file is a considered a template if it is neither a partial nor
ignored.
:param filename: the name of the file to check
"""
if self.is_partial(filename):
return False
if self.is_ign... | Check if a file is a template.
A file is a considered a template if it is neither a partial nor
ignored.
:param filename: the name of the file to check | Below is the the instruction that describes the task:
### Input:
Check if a file is a template.
A file is a considered a template if it is neither a partial nor
ignored.
:param filename: the name of the file to check
### Response:
def is_template(self, filename):
"""Check if a fil... |
def delete_(*keyname):
'''
Delete metadata
prop : string
name of property
CLI Example:
.. code-block:: bash
salt '*' mdata.get salt:role
salt '*' mdata.get user-script salt:role
'''
mdata = _check_mdata_delete()
valid_keynames = list_()
ret = {}
for k... | Delete metadata
prop : string
name of property
CLI Example:
.. code-block:: bash
salt '*' mdata.get salt:role
salt '*' mdata.get user-script salt:role | Below is the the instruction that describes the task:
### Input:
Delete metadata
prop : string
name of property
CLI Example:
.. code-block:: bash
salt '*' mdata.get salt:role
salt '*' mdata.get user-script salt:role
### Response:
def delete_(*keyname):
'''
Delete met... |
def _buffer(editor, variables, force=False):
"""
Go to one of the open buffers.
"""
eb = editor.window_arrangement.active_editor_buffer
force = bool(variables['force'])
buffer_name = variables.get('buffer_name')
if buffer_name:
if not force and eb.has_unsaved_changes:
ed... | Go to one of the open buffers. | Below is the the instruction that describes the task:
### Input:
Go to one of the open buffers.
### Response:
def _buffer(editor, variables, force=False):
"""
Go to one of the open buffers.
"""
eb = editor.window_arrangement.active_editor_buffer
force = bool(variables['force'])
buffer_name... |
def jhk_to_sdssg(jmag,hmag,kmag):
'''Converts given J, H, Ks mags to an SDSS g magnitude value.
Parameters
----------
jmag,hmag,kmag : float
2MASS J, H, Ks mags of the object.
Returns
-------
float
The converted SDSS g band magnitude.
'''
return convert_constant... | Converts given J, H, Ks mags to an SDSS g magnitude value.
Parameters
----------
jmag,hmag,kmag : float
2MASS J, H, Ks mags of the object.
Returns
-------
float
The converted SDSS g band magnitude. | Below is the the instruction that describes the task:
### Input:
Converts given J, H, Ks mags to an SDSS g magnitude value.
Parameters
----------
jmag,hmag,kmag : float
2MASS J, H, Ks mags of the object.
Returns
-------
float
The converted SDSS g band magnitude.
### Respo... |
def to_native_types(self, slicer=None, na_rep='', float_format=None,
decimal='.', quoting=None, **kwargs):
""" convert to our native types format, slicing if desired """
values = self.values
if slicer is not None:
values = values[:, slicer]
# see gh-... | convert to our native types format, slicing if desired | Below is the the instruction that describes the task:
### Input:
convert to our native types format, slicing if desired
### Response:
def to_native_types(self, slicer=None, na_rep='', float_format=None,
decimal='.', quoting=None, **kwargs):
""" convert to our native types format, sl... |
def handle_build_cache(
conf: Config, name: str, tag: str, icb: ImageCachingBehavior):
"""Handle Docker image build cache.
Return image ID if image is cached, and there's no need to redo the build.
Return None if need to build the image (whether cached locally or not).
Raise RuntimeError if not... | Handle Docker image build cache.
Return image ID if image is cached, and there's no need to redo the build.
Return None if need to build the image (whether cached locally or not).
Raise RuntimeError if not allowed to build the image because of state of
local cache.
TODO(itamar): figure out a bette... | Below is the the instruction that describes the task:
### Input:
Handle Docker image build cache.
Return image ID if image is cached, and there's no need to redo the build.
Return None if need to build the image (whether cached locally or not).
Raise RuntimeError if not allowed to build the image becau... |
def cov_dvrpmllbb_to_vxyz_single(d,e_d,e_vr,pmll,pmbb,cov_pmllbb,l,b):
"""
NAME:
cov_dvrpmllbb_to_vxyz
PURPOSE:
propagate distance, radial velocity, and proper motion uncertainties to
Galactic coordinates for scalar inputs
INPUT:
d - distance [kpc, as/mas for plx]
e_d ... | NAME:
cov_dvrpmllbb_to_vxyz
PURPOSE:
propagate distance, radial velocity, and proper motion uncertainties to
Galactic coordinates for scalar inputs
INPUT:
d - distance [kpc, as/mas for plx]
e_d - distance uncertainty [kpc, [as/mas] for plx]
e_vr - low velocity uncertai... | Below is the the instruction that describes the task:
### Input:
NAME:
cov_dvrpmllbb_to_vxyz
PURPOSE:
propagate distance, radial velocity, and proper motion uncertainties to
Galactic coordinates for scalar inputs
INPUT:
d - distance [kpc, as/mas for plx]
e_d - distance unc... |
def parse_ensembl_exon_request(result):
"""Parse a dataframe with ensembl exon information
Args:
res(pandas.DataFrame)
Yields:
gene_info(dict)
"""
keys = [
'chrom',
'gene',
'transcript',
'exon_id',
'exon_chrom_start',
'exon_chrom_end'... | Parse a dataframe with ensembl exon information
Args:
res(pandas.DataFrame)
Yields:
gene_info(dict) | Below is the the instruction that describes the task:
### Input:
Parse a dataframe with ensembl exon information
Args:
res(pandas.DataFrame)
Yields:
gene_info(dict)
### Response:
def parse_ensembl_exon_request(result):
"""Parse a dataframe with ensembl exon information
Args:
... |
def _log_prefix(self, prefix, request):
"""
Returns a formatted prefix for logging for the given request.
"""
# After a celery task runs, the request cache is cleared. So if celery
# tasks are running synchronously (CELERY_ALWAYS _EAGER), "guid_key"
# will no longer be in... | Returns a formatted prefix for logging for the given request. | Below is the the instruction that describes the task:
### Input:
Returns a formatted prefix for logging for the given request.
### Response:
def _log_prefix(self, prefix, request):
"""
Returns a formatted prefix for logging for the given request.
"""
# After a celery task runs, the ... |
def updateSession(self, request):
"""
Update the cookie after session object was modified
@param request: the request object which should get a new cookie
"""
# we actually need to copy some hardcoded constants from twisted :-(
# Make sure we aren't creating a secure ses... | Update the cookie after session object was modified
@param request: the request object which should get a new cookie | Below is the the instruction that describes the task:
### Input:
Update the cookie after session object was modified
@param request: the request object which should get a new cookie
### Response:
def updateSession(self, request):
"""
Update the cookie after session object was modified
... |
def max(self, axis=None, dtype=None, out=None, keepdims=False):
"""Return the maximum of ``self``.
See Also
--------
numpy.amax
min
"""
return self.elem.__array_ufunc__(
np.maximum, 'reduce', self.elem,
axis=axis, dtype=dtype, out=(out,), ... | Return the maximum of ``self``.
See Also
--------
numpy.amax
min | Below is the the instruction that describes the task:
### Input:
Return the maximum of ``self``.
See Also
--------
numpy.amax
min
### Response:
def max(self, axis=None, dtype=None, out=None, keepdims=False):
"""Return the maximum of ``self``.
See Also
-----... |
def any(self, predicate):
"""
Returns true if any elements that satisfy predicate are found
:param predicate: condition to satisfy as lambda expression
:return: boolean True or False
"""
if predicate is None:
raise NullArgumentError(
u"predicat... | Returns true if any elements that satisfy predicate are found
:param predicate: condition to satisfy as lambda expression
:return: boolean True or False | Below is the the instruction that describes the task:
### Input:
Returns true if any elements that satisfy predicate are found
:param predicate: condition to satisfy as lambda expression
:return: boolean True or False
### Response:
def any(self, predicate):
"""
Returns true if any e... |
def txt_line_iterator(txt_path):
"""Iterate through lines of file."""
with tf.gfile.Open(txt_path) as f:
for line in f:
yield line.strip() | Iterate through lines of file. | Below is the the instruction that describes the task:
### Input:
Iterate through lines of file.
### Response:
def txt_line_iterator(txt_path):
"""Iterate through lines of file."""
with tf.gfile.Open(txt_path) as f:
for line in f:
yield line.strip() |
def encloses(self,
location: FileLocation
) -> Optional[FunctionDesc]:
"""
Returns the function, if any, that encloses a given location.
"""
for func in self.in_file(location.filename):
if location in func.location:
return fun... | Returns the function, if any, that encloses a given location. | Below is the the instruction that describes the task:
### Input:
Returns the function, if any, that encloses a given location.
### Response:
def encloses(self,
location: FileLocation
) -> Optional[FunctionDesc]:
"""
Returns the function, if any, that encloses a giv... |
def find_datastore_by_name(self, si, path, name):
"""
Finds datastore in the vCenter or returns "None"
:param si: pyvmomi 'ServiceInstance'
:param path: the path to find the object ('dc' or 'dc/folder' or 'dc/folder/folder/etc...')
:param name: the datastore ... | Finds datastore in the vCenter or returns "None"
:param si: pyvmomi 'ServiceInstance'
:param path: the path to find the object ('dc' or 'dc/folder' or 'dc/folder/folder/etc...')
:param name: the datastore name to return | Below is the the instruction that describes the task:
### Input:
Finds datastore in the vCenter or returns "None"
:param si: pyvmomi 'ServiceInstance'
:param path: the path to find the object ('dc' or 'dc/folder' or 'dc/folder/folder/etc...')
:param name: the datastore n... |
def convert_frames_to_video(tar_file_path, output_path="output.mp4", framerate=60, overwrite=False):
"""
Try to convert a tar file containing a sequence of frames saved by the
meshcat viewer into a single video file.
This relies on having `ffmpeg` installed on your system.
"""
output_path = os.... | Try to convert a tar file containing a sequence of frames saved by the
meshcat viewer into a single video file.
This relies on having `ffmpeg` installed on your system. | Below is the the instruction that describes the task:
### Input:
Try to convert a tar file containing a sequence of frames saved by the
meshcat viewer into a single video file.
This relies on having `ffmpeg` installed on your system.
### Response:
def convert_frames_to_video(tar_file_path, output_path="ou... |
def dead_code_elimination(node):
"""Perform a simple form of dead code elimination on a Python AST.
This method performs reaching definitions analysis on all function
definitions. It then looks for the definition of variables that are not used
elsewhere and removes those definitions.
This function takes int... | Perform a simple form of dead code elimination on a Python AST.
This method performs reaching definitions analysis on all function
definitions. It then looks for the definition of variables that are not used
elsewhere and removes those definitions.
This function takes into consideration push and pop statement... | Below is the the instruction that describes the task:
### Input:
Perform a simple form of dead code elimination on a Python AST.
This method performs reaching definitions analysis on all function
definitions. It then looks for the definition of variables that are not used
elsewhere and removes those definiti... |
async def start(self, remoteParameters):
"""
Start DTLS transport negotiation with the parameters of the remote
DTLS transport.
:param: remoteParameters: An :class:`RTCDtlsParameters`.
"""
assert self._state == State.NEW
assert len(remoteParameters.fingerprints)
... | Start DTLS transport negotiation with the parameters of the remote
DTLS transport.
:param: remoteParameters: An :class:`RTCDtlsParameters`. | Below is the the instruction that describes the task:
### Input:
Start DTLS transport negotiation with the parameters of the remote
DTLS transport.
:param: remoteParameters: An :class:`RTCDtlsParameters`.
### Response:
async def start(self, remoteParameters):
"""
Start DTLS transpo... |
def is_managed():
"""
Check if a Django project is being managed with ``manage.py`` or
``django-admin`` scripts
:return: Check result
:rtype: bool
"""
for item in sys.argv:
if re.search(r'manage.py|django-admin|django', item) is not None:
return True
return False | Check if a Django project is being managed with ``manage.py`` or
``django-admin`` scripts
:return: Check result
:rtype: bool | Below is the the instruction that describes the task:
### Input:
Check if a Django project is being managed with ``manage.py`` or
``django-admin`` scripts
:return: Check result
:rtype: bool
### Response:
def is_managed():
"""
Check if a Django project is being managed with ``manage.py`` or
... |
def memoized(maxsize=1024):
"""
Momoization decorator for immutable classes and pure functions.
"""
cache = SimpleCache(maxsize=maxsize)
def decorator(obj):
@wraps(obj)
def new_callable(*a, **kw):
def create_new():
return obj(*a, **kw)
key = ... | Momoization decorator for immutable classes and pure functions. | Below is the the instruction that describes the task:
### Input:
Momoization decorator for immutable classes and pure functions.
### Response:
def memoized(maxsize=1024):
"""
Momoization decorator for immutable classes and pure functions.
"""
cache = SimpleCache(maxsize=maxsize)
def decorator(... |
def results(self):
"""
Returns a list of tuple, ordered by similarity.
"""
d = dict()
words = [word.strip() for word in self.haystack]
if not words:
raise NoResultException('No similar word found.')
for w in words:
d[w] = Levenshtein.rati... | Returns a list of tuple, ordered by similarity. | Below is the the instruction that describes the task:
### Input:
Returns a list of tuple, ordered by similarity.
### Response:
def results(self):
"""
Returns a list of tuple, ordered by similarity.
"""
d = dict()
words = [word.strip() for word in self.haystack]
if n... |
def voxel_loop(self):
'''iterator that loops through each voxel and yields the coords and time series as a tuple'''
# Prob not the most efficient, but the best I can do for now:
for x in xrange(len(self.data)):
for y in xrange(len(self.data[x])):
for z in xrange(len(s... | iterator that loops through each voxel and yields the coords and time series as a tuple | Below is the the instruction that describes the task:
### Input:
iterator that loops through each voxel and yields the coords and time series as a tuple
### Response:
def voxel_loop(self):
'''iterator that loops through each voxel and yields the coords and time series as a tuple'''
# Prob not the m... |
def get_font_options(self):
"""Retrieves font rendering options set via :meth:`set_font_options`.
Note that the returned options do not include any options
derived from the underlying surface;
they are literally the options passed to :meth:`set_font_options`.
:return: A new :cla... | Retrieves font rendering options set via :meth:`set_font_options`.
Note that the returned options do not include any options
derived from the underlying surface;
they are literally the options passed to :meth:`set_font_options`.
:return: A new :class:`FontOptions` object. | Below is the the instruction that describes the task:
### Input:
Retrieves font rendering options set via :meth:`set_font_options`.
Note that the returned options do not include any options
derived from the underlying surface;
they are literally the options passed to :meth:`set_font_options`... |
def is_child_of_objective_bank(self, id_, objective_bank_id):
"""Tests if an objective bank is a direct child of another.
arg: id (osid.id.Id): an ``Id``
arg: objective_bank_id (osid.id.Id): the ``Id`` of an
objective bank
return: (boolean) - ``true`` if the ``id``... | Tests if an objective bank is a direct child of another.
arg: id (osid.id.Id): an ``Id``
arg: objective_bank_id (osid.id.Id): the ``Id`` of an
objective bank
return: (boolean) - ``true`` if the ``id`` is a child of
``objective_bank_id,`` ``false`` otherwis... | Below is the the instruction that describes the task:
### Input:
Tests if an objective bank is a direct child of another.
arg: id (osid.id.Id): an ``Id``
arg: objective_bank_id (osid.id.Id): the ``Id`` of an
objective bank
return: (boolean) - ``true`` if the ``id`` is ... |
def __install_perforce(self, config):
""" install perforce binary """
if not system.is_64_bit():
self.logger.warn("Perforce formula is only designed for 64 bit systems! Not install executables...")
return False
version = config.get('version', 'r13.2')
key = 'osx' ... | install perforce binary | Below is the the instruction that describes the task:
### Input:
install perforce binary
### Response:
def __install_perforce(self, config):
""" install perforce binary """
if not system.is_64_bit():
self.logger.warn("Perforce formula is only designed for 64 bit systems! Not install exe... |
def new_filename(original_filename, new_locale):
"""Returns a filename derived from original_filename, using new_locale as the locale"""
orig_file = Path(original_filename)
new_file = orig_file.parent.parent.parent / new_locale / orig_file.parent.name / orig_file.name
return new_file.abspath() | Returns a filename derived from original_filename, using new_locale as the locale | Below is the the instruction that describes the task:
### Input:
Returns a filename derived from original_filename, using new_locale as the locale
### Response:
def new_filename(original_filename, new_locale):
"""Returns a filename derived from original_filename, using new_locale as the locale"""
orig_file... |
def bip32_deserialize(data):
"""
Derived from code from pybitcointools (https://github.com/vbuterin/pybitcointools)
by Vitalik Buterin
"""
dbin = changebase(data, 58, 256)
if bin_dbl_sha256(dbin[:-4])[:4] != dbin[-4:]:
raise Exception("Invalid checksum")
vbytes = dbin[0:4]
depth ... | Derived from code from pybitcointools (https://github.com/vbuterin/pybitcointools)
by Vitalik Buterin | Below is the the instruction that describes the task:
### Input:
Derived from code from pybitcointools (https://github.com/vbuterin/pybitcointools)
by Vitalik Buterin
### Response:
def bip32_deserialize(data):
"""
Derived from code from pybitcointools (https://github.com/vbuterin/pybitcointools)
by... |
def list_metrics(self, project, page_size=None, page_token=None):
"""List metrics for the project associated with this client.
See
https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.metrics/list
:type project: str
:param project: ID of the project whose metrics... | List metrics for the project associated with this client.
See
https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.metrics/list
:type project: str
:param project: ID of the project whose metrics are to be listed.
:type page_size: int
:param page_size: ma... | Below is the the instruction that describes the task:
### Input:
List metrics for the project associated with this client.
See
https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.metrics/list
:type project: str
:param project: ID of the project whose metrics are to ... |
def _clean_text(self, text):
"""Clean the text of extraneous punction.
By default, ':', ';', and '.' are defined as stops.
:param text: raw text
:return: clean text
:rtype : string
"""
clean = []
for char in text:
if char in self.punc_stops:
... | Clean the text of extraneous punction.
By default, ':', ';', and '.' are defined as stops.
:param text: raw text
:return: clean text
:rtype : string | Below is the the instruction that describes the task:
### Input:
Clean the text of extraneous punction.
By default, ':', ';', and '.' are defined as stops.
:param text: raw text
:return: clean text
:rtype : string
### Response:
def _clean_text(self, text):
"""Clean the text... |
def _add_punctuation_spacing(self, input):
'''
Adds additional spacing to punctuation characters. For example,
this puts an extra space after a fullwidth full stop.
'''
for replacement in punct_spacing:
input = re.sub(replacement[0], replacement[1], input)
re... | Adds additional spacing to punctuation characters. For example,
this puts an extra space after a fullwidth full stop. | Below is the the instruction that describes the task:
### Input:
Adds additional spacing to punctuation characters. For example,
this puts an extra space after a fullwidth full stop.
### Response:
def _add_punctuation_spacing(self, input):
'''
Adds additional spacing to punctuation characte... |
def decrypt(self, data):
'''
verify HMAC-SHA256 signature and decrypt data with AES-CBC
'''
aes_key, hmac_key = self.keys
sig = data[-self.SIG_SIZE:]
data = data[:-self.SIG_SIZE]
if six.PY3 and not isinstance(data, bytes):
data = salt.utils.stringutils... | verify HMAC-SHA256 signature and decrypt data with AES-CBC | Below is the the instruction that describes the task:
### Input:
verify HMAC-SHA256 signature and decrypt data with AES-CBC
### Response:
def decrypt(self, data):
'''
verify HMAC-SHA256 signature and decrypt data with AES-CBC
'''
aes_key, hmac_key = self.keys
sig = data[-sel... |
def ComponentsToPath(components):
"""Converts a list of path components to a canonical path representation.
Args:
components: A sequence of path components.
Returns:
A canonical MySQL path representation.
"""
precondition.AssertIterableType(components, Text)
for component in components:
if not... | Converts a list of path components to a canonical path representation.
Args:
components: A sequence of path components.
Returns:
A canonical MySQL path representation. | Below is the the instruction that describes the task:
### Input:
Converts a list of path components to a canonical path representation.
Args:
components: A sequence of path components.
Returns:
A canonical MySQL path representation.
### Response:
def ComponentsToPath(components):
"""Converts a list... |
def softmax_categorical_cross_entropy_cost( outputs, targets, derivative=False, epsilon=1e-11 ):
"""
The output signals should be in the range [0, 1]
"""
outputs = np.clip(outputs, epsilon, 1 - epsilon)
if derivative:
return outputs - targets
else:
return np.mean(-np.sum(tar... | The output signals should be in the range [0, 1] | Below is the the instruction that describes the task:
### Input:
The output signals should be in the range [0, 1]
### Response:
def softmax_categorical_cross_entropy_cost( outputs, targets, derivative=False, epsilon=1e-11 ):
"""
The output signals should be in the range [0, 1]
"""
outputs = np.clip... |
def append_translated(model, fields):
"If translated field is encountered, add also all its translation fields."
fields = set(fields)
from modeltranslation.translator import translator
opts = translator.get_options_for_model(model)
for key, translated in opts.fields.items():
if key in fields... | If translated field is encountered, add also all its translation fields. | Below is the the instruction that describes the task:
### Input:
If translated field is encountered, add also all its translation fields.
### Response:
def append_translated(model, fields):
"If translated field is encountered, add also all its translation fields."
fields = set(fields)
from modeltransla... |
def after_import(self, dataset, result, using_transactions, dry_run, **kwargs):
"""
Reset the SQL sequences after new objects are imported
"""
# Adapted from django's loaddata
if not dry_run and any(r.import_type == RowResult.IMPORT_TYPE_NEW for r in result.rows):
con... | Reset the SQL sequences after new objects are imported | Below is the the instruction that describes the task:
### Input:
Reset the SQL sequences after new objects are imported
### Response:
def after_import(self, dataset, result, using_transactions, dry_run, **kwargs):
"""
Reset the SQL sequences after new objects are imported
"""
# Adap... |
def get_card(self, index=-1, cache=True, remove=True):
"""
Retrieve a card any number of cards from the top. Returns a
``Card`` object loaded from a library if one is specified otherwise
just it will simply return its code.
If `index` is not set then the top card will be retrie... | Retrieve a card any number of cards from the top. Returns a
``Card`` object loaded from a library if one is specified otherwise
just it will simply return its code.
If `index` is not set then the top card will be retrieved.
If cache is set to True (the default) it will tell the librar... | Below is the the instruction that describes the task:
### Input:
Retrieve a card any number of cards from the top. Returns a
``Card`` object loaded from a library if one is specified otherwise
just it will simply return its code.
If `index` is not set then the top card will be retrieved.
... |
def guess_matches(video, guess, partial=False):
"""Get matches between a `video` and a `guess`.
If a guess is `partial`, the absence information won't be counted as a match.
:param video: the video.
:type video: :class:`~subliminal.video.Video`
:param guess: the guess.
:type guess: dict
:p... | Get matches between a `video` and a `guess`.
If a guess is `partial`, the absence information won't be counted as a match.
:param video: the video.
:type video: :class:`~subliminal.video.Video`
:param guess: the guess.
:type guess: dict
:param bool partial: whether or not the guess is partial.... | Below is the the instruction that describes the task:
### Input:
Get matches between a `video` and a `guess`.
If a guess is `partial`, the absence information won't be counted as a match.
:param video: the video.
:type video: :class:`~subliminal.video.Video`
:param guess: the guess.
:type gues... |
def _get_persistent_mpe_dir(self):
""" get persistent storage for mpe """
mpe_address = self.get_mpe_address().lower()
registry_address = self.get_registry_address().lower()
return Path.home().joinpath(".snet", "mpe_client", "%s_%s"%(mpe_address, registry_address)) | get persistent storage for mpe | Below is the the instruction that describes the task:
### Input:
get persistent storage for mpe
### Response:
def _get_persistent_mpe_dir(self):
""" get persistent storage for mpe """
mpe_address = self.get_mpe_address().lower()
registry_address = self.get_registry_address().lower()
... |
def classifyplot_from_plotfiles(plot_files, out_csv, outtype="png", title=None, size=None):
"""Create a plot from individual summary csv files with classification metrics.
"""
dfs = [pd.read_csv(x) for x in plot_files]
samples = []
for df in dfs:
for sample in df["sample"].unique():
... | Create a plot from individual summary csv files with classification metrics. | Below is the the instruction that describes the task:
### Input:
Create a plot from individual summary csv files with classification metrics.
### Response:
def classifyplot_from_plotfiles(plot_files, out_csv, outtype="png", title=None, size=None):
"""Create a plot from individual summary csv files with classif... |
def _get_jvm_opts(data, out_file):
"""Retrieve JVM options when running the Java version of VarDict.
"""
if get_vardict_command(data) == "vardict-java":
resources = config_utils.get_resources("vardict", data["config"])
jvm_opts = resources.get("jvm_opts", ["-Xms750m", "-Xmx4g"])
jvm_... | Retrieve JVM options when running the Java version of VarDict. | Below is the the instruction that describes the task:
### Input:
Retrieve JVM options when running the Java version of VarDict.
### Response:
def _get_jvm_opts(data, out_file):
"""Retrieve JVM options when running the Java version of VarDict.
"""
if get_vardict_command(data) == "vardict-java":
... |
def header_match(cls, header):
'''
Parse the 4-line (320-byte) library member header.
'''
mo = cls.header_re.match(header)
if mo is None:
msg = f'Expected {cls.header_re.pattern!r}, got {header!r}'
raise ValueError(msg)
return {
'name':... | Parse the 4-line (320-byte) library member header. | Below is the the instruction that describes the task:
### Input:
Parse the 4-line (320-byte) library member header.
### Response:
def header_match(cls, header):
'''
Parse the 4-line (320-byte) library member header.
'''
mo = cls.header_re.match(header)
if mo is None:
... |
def one_step(self, current_state, previous_kernel_results):
"""Runs one iteration of NeuTra.
Args:
current_state: `Tensor` or Python `list` of `Tensor`s representing the
current state(s) of the Markov chain(s). The first `r` dimensions index
independent chains, `r = tf.rank(target_log_pro... | Runs one iteration of NeuTra.
Args:
current_state: `Tensor` or Python `list` of `Tensor`s representing the
current state(s) of the Markov chain(s). The first `r` dimensions index
independent chains, `r = tf.rank(target_log_prob_fn(*current_state))`.
previous_kernel_results: `collections... | Below is the the instruction that describes the task:
### Input:
Runs one iteration of NeuTra.
Args:
current_state: `Tensor` or Python `list` of `Tensor`s representing the
current state(s) of the Markov chain(s). The first `r` dimensions index
independent chains, `r = tf.rank(target_log_p... |
async def connect(self):
"""Establish a connection to the chat server.
Returns when an error has occurred, or :func:`disconnect` has been
called.
"""
proxy = os.environ.get('HTTP_PROXY')
self._session = http_utils.Session(self._cookies, proxy=proxy)
try:
... | Establish a connection to the chat server.
Returns when an error has occurred, or :func:`disconnect` has been
called. | Below is the the instruction that describes the task:
### Input:
Establish a connection to the chat server.
Returns when an error has occurred, or :func:`disconnect` has been
called.
### Response:
async def connect(self):
"""Establish a connection to the chat server.
Returns when ... |
def _cleanup(self):
""" Cleanup open channels and handlers """
for channel in self._open_channels:
try:
self.disconnect_channel(channel)
except Exception: # pylint: disable=broad-except
pass
for handler in self._handlers.values():
... | Cleanup open channels and handlers | Below is the the instruction that describes the task:
### Input:
Cleanup open channels and handlers
### Response:
def _cleanup(self):
""" Cleanup open channels and handlers """
for channel in self._open_channels:
try:
self.disconnect_channel(channel)
except E... |
def conflicting_deps(tree):
"""Returns dependencies which are not present or conflict with the
requirements of other packages.
e.g. will warn if pkg1 requires pkg2==2.0 and pkg2==1.0 is installed
:param tree: the requirements tree (dict)
:returns: dict of DistPackage -> list of unsatisfied/unknown... | Returns dependencies which are not present or conflict with the
requirements of other packages.
e.g. will warn if pkg1 requires pkg2==2.0 and pkg2==1.0 is installed
:param tree: the requirements tree (dict)
:returns: dict of DistPackage -> list of unsatisfied/unknown ReqPackage
:rtype: dict | Below is the the instruction that describes the task:
### Input:
Returns dependencies which are not present or conflict with the
requirements of other packages.
e.g. will warn if pkg1 requires pkg2==2.0 and pkg2==1.0 is installed
:param tree: the requirements tree (dict)
:returns: dict of DistPack... |
def config_changed(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Will prompt if the configuration has been changed.
:return: A tuple with a boolean that specifies if the config was changed on the device.\
And a string that provides more details of the reason why the con... | Will prompt if the configuration has been changed.
:return: A tuple with a boolean that specifies if the config was changed on the device.\
And a string that provides more details of the reason why the configuration was not changed.
CLI Example:
.. code-block:: bash
salt '*' net.config_chang... | Below is the the instruction that describes the task:
### Input:
Will prompt if the configuration has been changed.
:return: A tuple with a boolean that specifies if the config was changed on the device.\
And a string that provides more details of the reason why the configuration was not changed.
CLI ... |
def hosts_in_group(self, groupname):
"""
Return a list of hostnames that are in a group.
"""
result = []
for hostname, hostinfo in self.hosts.items():
if groupname == 'all':
result.append(hostname)
elif 'groups' in hostinfo:
... | Return a list of hostnames that are in a group. | Below is the the instruction that describes the task:
### Input:
Return a list of hostnames that are in a group.
### Response:
def hosts_in_group(self, groupname):
"""
Return a list of hostnames that are in a group.
"""
result = []
for hostname, hostinfo in self.hosts.items(... |
def setXlimits(self, lims):
"""Sets the X axis limits of the signal plots
:param lims: (min, max) of x axis, in same units as data
:type lims: (float, float)
"""
self.responseSignalPlot.setXlim(lims)
self.stimSignalPlot.setXlim(lims) | Sets the X axis limits of the signal plots
:param lims: (min, max) of x axis, in same units as data
:type lims: (float, float) | Below is the the instruction that describes the task:
### Input:
Sets the X axis limits of the signal plots
:param lims: (min, max) of x axis, in same units as data
:type lims: (float, float)
### Response:
def setXlimits(self, lims):
"""Sets the X axis limits of the signal plots
:... |
def clear_provider_links(self):
"""Removes the provider chain.
raise: NoAccess - ``Metadata.isRequired()`` is ``true`` or
``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for osid.... | Removes the provider chain.
raise: NoAccess - ``Metadata.isRequired()`` is ``true`` or
``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.* | Below is the the instruction that describes the task:
### Input:
Removes the provider chain.
raise: NoAccess - ``Metadata.isRequired()`` is ``true`` or
``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.*
### Response:
def clear_provide... |
def bvlci_contents(self, use_dict=None, as_class=dict):
"""Return the contents of an object as a dict."""
if _debug: BVLCI._debug("bvlci_contents use_dict=%r as_class=%r", use_dict, as_class)
# make/extend the dictionary of content
if use_dict is None:
use_dict = as_class()
... | Return the contents of an object as a dict. | Below is the the instruction that describes the task:
### Input:
Return the contents of an object as a dict.
### Response:
def bvlci_contents(self, use_dict=None, as_class=dict):
"""Return the contents of an object as a dict."""
if _debug: BVLCI._debug("bvlci_contents use_dict=%r as_class=%r", use_... |
def nullable(self, ctype: ContentType) -> bool:
"""Override the superclass method."""
return (not self.check_when() or self.pattern.nullable(ctype)) | Override the superclass method. | Below is the the instruction that describes the task:
### Input:
Override the superclass method.
### Response:
def nullable(self, ctype: ContentType) -> bool:
"""Override the superclass method."""
return (not self.check_when() or self.pattern.nullable(ctype)) |
def _fingerprint(jvm_options, classpath, java_version):
"""Compute a fingerprint for this invocation of a Java task.
:param list jvm_options: JVM options passed to the java invocation
:param list classpath: The -cp arguments passed to the java invocation
:param Revision java_version: return va... | Compute a fingerprint for this invocation of a Java task.
:param list jvm_options: JVM options passed to the java invocation
:param list classpath: The -cp arguments passed to the java invocation
:param Revision java_version: return value from Distribution.version()
:return: a hexstring rep... | Below is the the instruction that describes the task:
### Input:
Compute a fingerprint for this invocation of a Java task.
:param list jvm_options: JVM options passed to the java invocation
:param list classpath: The -cp arguments passed to the java invocation
:param Revision java_version: ret... |
def _initial_guess(self, countsmat):
"""Generate an initial guess for \theta.
"""
if self.theta_ is not None:
return self.theta_
if self.guess == 'log':
transmat, pi = _transmat_mle_prinz(countsmat)
K = np.real(scipy.linalg.logm(transmat)) / self.lag... | Generate an initial guess for \theta. | Below is the the instruction that describes the task:
### Input:
Generate an initial guess for \theta.
### Response:
def _initial_guess(self, countsmat):
"""Generate an initial guess for \theta.
"""
if self.theta_ is not None:
return self.theta_
if self.guess == 'log':... |
def pretty_xml(data):
"""Return a pretty formated xml
"""
parsed_string = minidom.parseString(data.decode('utf-8'))
return parsed_string.toprettyxml(indent='\t', encoding='utf-8') | Return a pretty formated xml | Below is the the instruction that describes the task:
### Input:
Return a pretty formated xml
### Response:
def pretty_xml(data):
"""Return a pretty formated xml
"""
parsed_string = minidom.parseString(data.decode('utf-8'))
return parsed_string.toprettyxml(indent='\t', encoding='utf-8') |
def getPharLapVersion():
"""Returns the version of the installed ETS Tool Suite as a
decimal number. This version comes from the ETS_VER #define in
the embkern.h header. For example, '#define ETS_VER 1010' (which
is what Phar Lap 10.1 defines) would cause this method to return
1010. Phar Lap 9.1 d... | Returns the version of the installed ETS Tool Suite as a
decimal number. This version comes from the ETS_VER #define in
the embkern.h header. For example, '#define ETS_VER 1010' (which
is what Phar Lap 10.1 defines) would cause this method to return
1010. Phar Lap 9.1 does not have such a #define, but... | Below is the the instruction that describes the task:
### Input:
Returns the version of the installed ETS Tool Suite as a
decimal number. This version comes from the ETS_VER #define in
the embkern.h header. For example, '#define ETS_VER 1010' (which
is what Phar Lap 10.1 defines) would cause this meth... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.