code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def group_pop(name, app, **kwargs):
"""
Remove application from the specified routing group.
"""
ctx = Context(**kwargs)
ctx.execute_action('group:app:remove', **{
'storage': ctx.repo.create_secure_service('storage'),
'name': name,
'app': app,
}) | Remove application from the specified routing group. | Below is the the instruction that describes the task:
### Input:
Remove application from the specified routing group.
### Response:
def group_pop(name, app, **kwargs):
"""
Remove application from the specified routing group.
"""
ctx = Context(**kwargs)
ctx.execute_action('group:app:remove', **{... |
def incr(l, cap): # to increment a list up to a max-list of 'cap'
"""
Simulate a counting system from an n-dimensional list.
Usage: lincr(l,cap) l=list to increment, cap=max values for each list pos'n
Returns: next set of values for list l, OR -1 (if overflow)
"""
l[0] = l[0] + 1 # e.g., [0,0,0]... | Simulate a counting system from an n-dimensional list.
Usage: lincr(l,cap) l=list to increment, cap=max values for each list pos'n
Returns: next set of values for list l, OR -1 (if overflow) | Below is the the instruction that describes the task:
### Input:
Simulate a counting system from an n-dimensional list.
Usage: lincr(l,cap) l=list to increment, cap=max values for each list pos'n
Returns: next set of values for list l, OR -1 (if overflow)
### Response:
def incr(l, cap): # to increment ... |
def log_proto(self, message, client=None, **kw):
"""API call: log a protobuf message via a POST request
See
https://cloud.google.com/logging/docs/reference/v2/rest/v2/entries/list
:type message: :class:`~google.protobuf.message.Message`
:param message: The protobuf message to ... | API call: log a protobuf message via a POST request
See
https://cloud.google.com/logging/docs/reference/v2/rest/v2/entries/list
:type message: :class:`~google.protobuf.message.Message`
:param message: The protobuf message to be logged.
:type client: :class:`~google.cloud.logg... | Below is the the instruction that describes the task:
### Input:
API call: log a protobuf message via a POST request
See
https://cloud.google.com/logging/docs/reference/v2/rest/v2/entries/list
:type message: :class:`~google.protobuf.message.Message`
:param message: The protobuf me... |
def _new_open_bin(self, remaining_rect):
"""
Extract the next bin where at least one of the rectangles in
rem
Arguments:
remaining_rect (dict): rectangles not placed yet
Returns:
PackingAlgorithm: Initialized empty packing bin.
None: No bin b... | Extract the next bin where at least one of the rectangles in
rem
Arguments:
remaining_rect (dict): rectangles not placed yet
Returns:
PackingAlgorithm: Initialized empty packing bin.
None: No bin big enough for the rectangle was found | Below is the the instruction that describes the task:
### Input:
Extract the next bin where at least one of the rectangles in
rem
Arguments:
remaining_rect (dict): rectangles not placed yet
Returns:
PackingAlgorithm: Initialized empty packing bin.
None: ... |
def set_initial_values(self):
"""Set initial values form existing self.data value
:return: None
"""
self.normals = self.data['normals']
self.vectors = numpy.ones((
self.data['vectors'].shape[0],
self.data['vectors'].shape[1],
self.data['vectors... | Set initial values form existing self.data value
:return: None | Below is the the instruction that describes the task:
### Input:
Set initial values form existing self.data value
:return: None
### Response:
def set_initial_values(self):
"""Set initial values form existing self.data value
:return: None
"""
self.normals = self.data['normals... |
def get_id_token_hint(self, request_args=None, **kwargs):
"""
Add id_token_hint to request
:param request_args:
:param kwargs:
:return:
"""
request_args = self.multiple_extend_request_args(
request_args, kwargs['state'], ['id_token'],
['au... | Add id_token_hint to request
:param request_args:
:param kwargs:
:return: | Below is the the instruction that describes the task:
### Input:
Add id_token_hint to request
:param request_args:
:param kwargs:
:return:
### Response:
def get_id_token_hint(self, request_args=None, **kwargs):
"""
Add id_token_hint to request
:param request_args:
... |
def shift(
self,
periods: int = 1,
fill_value: object = None,
) -> ABCExtensionArray:
"""
Shift values by desired number.
Newly introduced missing values are filled with
``self.dtype.na_value``.
.. versionadded:: 0.24.0
Parameter... | Shift values by desired number.
Newly introduced missing values are filled with
``self.dtype.na_value``.
.. versionadded:: 0.24.0
Parameters
----------
periods : int, default 1
The number of periods to shift. Negative values are allowed
for shif... | Below is the the instruction that describes the task:
### Input:
Shift values by desired number.
Newly introduced missing values are filled with
``self.dtype.na_value``.
.. versionadded:: 0.24.0
Parameters
----------
periods : int, default 1
The number ... |
def _convert_key(self, key, is_setter=False):
""" require integer args (and convert to label arguments) """
for a, i in zip(self.obj.axes, key):
if not is_integer(i):
raise ValueError("iAt based indexing can only have integer "
"indexers")
... | require integer args (and convert to label arguments) | Below is the the instruction that describes the task:
### Input:
require integer args (and convert to label arguments)
### Response:
def _convert_key(self, key, is_setter=False):
""" require integer args (and convert to label arguments) """
for a, i in zip(self.obj.axes, key):
if not is... |
def _parse_codeargs(argstr):
'''
Parse and clean up argument to user code; separate *args from
**kwargs.
'''
args = []
kwargs = {}
if isinstance(argstr, str):
for a in argstr.split():
if '=' in a:
k,attr = a.split('=')
kwargs[k] = attr
... | Parse and clean up argument to user code; separate *args from
**kwargs. | Below is the the instruction that describes the task:
### Input:
Parse and clean up argument to user code; separate *args from
**kwargs.
### Response:
def _parse_codeargs(argstr):
'''
Parse and clean up argument to user code; separate *args from
**kwargs.
'''
args = []
kwargs = {}
i... |
def status_count(self, project):
'''
return a dict
'''
pipe = self.redis.pipeline(transaction=False)
for status in range(1, 5):
pipe.scard(self._gen_status_key(project, status))
ret = pipe.execute()
result = {}
for status, count in enumerate(r... | return a dict | Below is the the instruction that describes the task:
### Input:
return a dict
### Response:
def status_count(self, project):
'''
return a dict
'''
pipe = self.redis.pipeline(transaction=False)
for status in range(1, 5):
pipe.scard(self._gen_status_key(project, s... |
def intersect(self, other_seg, tol=1e-12):
"""Finds the intersections of two segments.
returns a list of tuples (t1, t2) such that
self.point(t1) == other_seg.point(t2).
Note: This will fail if the two segments coincide for more than a
finite collection of points."""
if i... | Finds the intersections of two segments.
returns a list of tuples (t1, t2) such that
self.point(t1) == other_seg.point(t2).
Note: This will fail if the two segments coincide for more than a
finite collection of points. | Below is the the instruction that describes the task:
### Input:
Finds the intersections of two segments.
returns a list of tuples (t1, t2) such that
self.point(t1) == other_seg.point(t2).
Note: This will fail if the two segments coincide for more than a
finite collection of points.
... |
def buy(self, account_id, **params):
"""https://developers.coinbase.com/api/v2#buy-bitcoin"""
if 'amount' not in params and 'total' not in params:
raise ValueError("Missing required parameter: 'amount' or 'total'")
for required in ['currency', 'payment_method']:
if requir... | https://developers.coinbase.com/api/v2#buy-bitcoin | Below is the the instruction that describes the task:
### Input:
https://developers.coinbase.com/api/v2#buy-bitcoin
### Response:
def buy(self, account_id, **params):
"""https://developers.coinbase.com/api/v2#buy-bitcoin"""
if 'amount' not in params and 'total' not in params:
raise Valu... |
def env_maker(environment_id):
""" Create a relatively raw atari environment """
env = gym.make(environment_id)
assert 'NoFrameskip' in env.spec.id
# Wait for between 1 and 30 rounds doing nothing on start
env = NoopResetEnv(env, noop_max=30)
# Do the same action for k steps. Return max of las... | Create a relatively raw atari environment | Below is the the instruction that describes the task:
### Input:
Create a relatively raw atari environment
### Response:
def env_maker(environment_id):
""" Create a relatively raw atari environment """
env = gym.make(environment_id)
assert 'NoFrameskip' in env.spec.id
# Wait for between 1 and 30 r... |
def ensure_file(path):
""" Checks if file exists, if fails, tries to create file """
try:
exists = isfile(path)
if not exists:
with open(path, 'w+') as fname:
fname.write('initialized')
return (True, path)
return (Tr... | Checks if file exists, if fails, tries to create file | Below is the the instruction that describes the task:
### Input:
Checks if file exists, if fails, tries to create file
### Response:
def ensure_file(path):
""" Checks if file exists, if fails, tries to create file """
try:
exists = isfile(path)
if not exists:
... |
def make_figure_hmaps(extractors, what):
"""
$ oq plot 'hmaps?kind=mean&imt=PGA'
"""
import matplotlib.pyplot as plt
fig = plt.figure()
ncalcs = len(extractors)
for i, ex in enumerate(extractors):
oq = ex.oqparam
n_poes = len(oq.poes)
sitecol = ex.get('sitecol')
... | $ oq plot 'hmaps?kind=mean&imt=PGA' | Below is the the instruction that describes the task:
### Input:
$ oq plot 'hmaps?kind=mean&imt=PGA'
### Response:
def make_figure_hmaps(extractors, what):
"""
$ oq plot 'hmaps?kind=mean&imt=PGA'
"""
import matplotlib.pyplot as plt
fig = plt.figure()
ncalcs = len(extractors)
for i, ex i... |
def delete(cls, id, api_key=None, **kwargs):
"""Delete an entity from the server by ID."""
inst = cls(api_key=api_key)
endpoint = '/'.join((cls.get_endpoint(), id))
inst.request('DELETE', endpoint=endpoint, query_params=kwargs)
inst._is_deleted = True
return True | Delete an entity from the server by ID. | Below is the the instruction that describes the task:
### Input:
Delete an entity from the server by ID.
### Response:
def delete(cls, id, api_key=None, **kwargs):
"""Delete an entity from the server by ID."""
inst = cls(api_key=api_key)
endpoint = '/'.join((cls.get_endpoint(), id))
... |
def loop(self):
"""Main loop daemon."""
while True:
sleep(1)
new_file_list = self.walk(self.file_path, {})
if new_file_list != self.file_list:
if self.debug:
self.diff_list(new_file_list, self.file_list)
self.run_tes... | Main loop daemon. | Below is the the instruction that describes the task:
### Input:
Main loop daemon.
### Response:
def loop(self):
"""Main loop daemon."""
while True:
sleep(1)
new_file_list = self.walk(self.file_path, {})
if new_file_list != self.file_list:
if self... |
def drop_indexes(self):
"""Drops all indexes on this collection.
Can be used on non-existant collections or collections with no indexes.
Raises OperationFailure on an error.
.. note:: The :attr:`~pymongo.collection.Collection.write_concern` of
this collection is automaticall... | Drops all indexes on this collection.
Can be used on non-existant collections or collections with no indexes.
Raises OperationFailure on an error.
.. note:: The :attr:`~pymongo.collection.Collection.write_concern` of
this collection is automatically applied to this operation when us... | Below is the the instruction that describes the task:
### Input:
Drops all indexes on this collection.
Can be used on non-existant collections or collections with no indexes.
Raises OperationFailure on an error.
.. note:: The :attr:`~pymongo.collection.Collection.write_concern` of
... |
def _blocks_to_samples(sig_data, n_samp, fmt):
"""
Convert uint8 blocks into signal samples for unaligned dat formats.
Parameters
----------
sig_data : numpy array
The uint8 data blocks.
n_samp : int
The number of samples contained in the bytes
Returns
-------
signa... | Convert uint8 blocks into signal samples for unaligned dat formats.
Parameters
----------
sig_data : numpy array
The uint8 data blocks.
n_samp : int
The number of samples contained in the bytes
Returns
-------
signal : numpy array
The numpy array of digital samples | Below is the the instruction that describes the task:
### Input:
Convert uint8 blocks into signal samples for unaligned dat formats.
Parameters
----------
sig_data : numpy array
The uint8 data blocks.
n_samp : int
The number of samples contained in the bytes
Returns
-------... |
def get_submission_filenames(self, tournament=None, round_num=None):
"""Get filenames of the submission of the user.
Args:
tournament (int): optionally filter by ID of the tournament
round_num (int): optionally filter round number
Returns:
list: list of user... | Get filenames of the submission of the user.
Args:
tournament (int): optionally filter by ID of the tournament
round_num (int): optionally filter round number
Returns:
list: list of user filenames (`dict`)
Each filenames in the list as the following str... | Below is the the instruction that describes the task:
### Input:
Get filenames of the submission of the user.
Args:
tournament (int): optionally filter by ID of the tournament
round_num (int): optionally filter round number
Returns:
list: list of user filenames ... |
def byteswap(self, fmt=None, start=None, end=None, repeat=True):
"""Change the endianness in-place. Return number of repeats of fmt done.
fmt -- A compact structure string, an integer number of bytes or
an iterable of integers. Defaults to 0, which byte reverses the
whole ... | Change the endianness in-place. Return number of repeats of fmt done.
fmt -- A compact structure string, an integer number of bytes or
an iterable of integers. Defaults to 0, which byte reverses the
whole bitstring.
start -- Start bit position, defaults to 0.
end -... | Below is the the instruction that describes the task:
### Input:
Change the endianness in-place. Return number of repeats of fmt done.
fmt -- A compact structure string, an integer number of bytes or
an iterable of integers. Defaults to 0, which byte reverses the
whole bitstri... |
def is_valid(self, tol: float = DISTANCE_TOLERANCE) -> bool:
"""
True if SiteCollection does not contain atoms that are too close
together. Note that the distance definition is based on type of
SiteCollection. Cartesian distances are used for non-periodic
Molecules, while PBC is ... | True if SiteCollection does not contain atoms that are too close
together. Note that the distance definition is based on type of
SiteCollection. Cartesian distances are used for non-periodic
Molecules, while PBC is taken into account for periodic structures.
Args:
tol (float... | Below is the the instruction that describes the task:
### Input:
True if SiteCollection does not contain atoms that are too close
together. Note that the distance definition is based on type of
SiteCollection. Cartesian distances are used for non-periodic
Molecules, while PBC is taken into a... |
def post_json(session, url, json):
"""
Post JSON to the Forest endpoint.
"""
res = session.post(url, json=json)
if res.status_code >= 400:
raise parse_error(res)
return res | Post JSON to the Forest endpoint. | Below is the the instruction that describes the task:
### Input:
Post JSON to the Forest endpoint.
### Response:
def post_json(session, url, json):
"""
Post JSON to the Forest endpoint.
"""
res = session.post(url, json=json)
if res.status_code >= 400:
raise parse_error(res)
return r... |
def app_context_processor(self, f):
"""Like :meth:`Flask.context_processor` but for a blueprint. Such a
function is executed each request, even if outside of the blueprint.
"""
self.record_once(lambda s: s.app.template_context_processors
.setdefault(None, []).append(f))
... | Like :meth:`Flask.context_processor` but for a blueprint. Such a
function is executed each request, even if outside of the blueprint. | Below is the the instruction that describes the task:
### Input:
Like :meth:`Flask.context_processor` but for a blueprint. Such a
function is executed each request, even if outside of the blueprint.
### Response:
def app_context_processor(self, f):
"""Like :meth:`Flask.context_processor` but for a... |
def fft(wave, npoints=None, indep_min=None, indep_max=None):
r"""
Return the Fast Fourier Transform of a waveform.
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:param npoints: Number of points to use in the transform. If **npoints**
is less than the size of ... | r"""
Return the Fast Fourier Transform of a waveform.
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:param npoints: Number of points to use in the transform. If **npoints**
is less than the size of the independent variable vector
the waveform ... | Below is the the instruction that describes the task:
### Input:
r"""
Return the Fast Fourier Transform of a waveform.
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:param npoints: Number of points to use in the transform. If **npoints**
is less than the size... |
def remove_missing(self, data, return_bool="any"):
""" ???
Parameters
----------
data : pd.DataFrame()
Input dataframe.
return_bool : bool
???
Returns
-------
pd.DataFrame()
???
"""
... | ???
Parameters
----------
data : pd.DataFrame()
Input dataframe.
return_bool : bool
???
Returns
-------
pd.DataFrame()
??? | Below is the the instruction that describes the task:
### Input:
???
Parameters
----------
data : pd.DataFrame()
Input dataframe.
return_bool : bool
???
Returns
-------
pd.DataFrame()
???
### Respon... |
def _read_http_headers(self, size, kind, flag):
"""Read HTTP/2 HEADERS frames.
Structure of HTTP/2 HEADERS frame [RFC 7540]:
+-----------------------------------------------+
| Length (24) |
+---------------+---------------+---------... | Read HTTP/2 HEADERS frames.
Structure of HTTP/2 HEADERS frame [RFC 7540]:
+-----------------------------------------------+
| Length (24) |
+---------------+---------------+---------------+
| Type (8) | Flags (8) |
... | Below is the the instruction that describes the task:
### Input:
Read HTTP/2 HEADERS frames.
Structure of HTTP/2 HEADERS frame [RFC 7540]:
+-----------------------------------------------+
| Length (24) |
+---------------+---------------... |
def update(self, tickDict):
''' consume ticks '''
if not self.__trakers:
self.__setUpTrakers()
for security, tick in tickDict.items():
if security in self.__trakers:
self.__trakers[security].tickUpdate(tick) | consume ticks | Below is the the instruction that describes the task:
### Input:
consume ticks
### Response:
def update(self, tickDict):
''' consume ticks '''
if not self.__trakers:
self.__setUpTrakers()
for security, tick in tickDict.items():
if security in self.__trakers:
... |
def keystone_configure_api_version(self, sentry_relation_pairs, deployment,
api_version):
"""Configure preferred-api-version of keystone in deployment and
monitor provided list of relation objects for propagation
before returning to caller.
:... | Configure preferred-api-version of keystone in deployment and
monitor provided list of relation objects for propagation
before returning to caller.
:param sentry_relation_pairs: list of sentry, relation tuples used for
monitoring propagation of relati... | Below is the the instruction that describes the task:
### Input:
Configure preferred-api-version of keystone in deployment and
monitor provided list of relation objects for propagation
before returning to caller.
:param sentry_relation_pairs: list of sentry, relation tuples used for
... |
def centerLatLon(self):
"""
Get the center lat/lon of model
"""
# GET CENTROID FROM GSSHA GRID
gssha_grid = self.getGrid()
min_x, max_x, min_y, max_y = gssha_grid.bounds()
x_ext, y_ext = transform(gssha_grid.proj,
Proj(init='epsg:... | Get the center lat/lon of model | Below is the the instruction that describes the task:
### Input:
Get the center lat/lon of model
### Response:
def centerLatLon(self):
"""
Get the center lat/lon of model
"""
# GET CENTROID FROM GSSHA GRID
gssha_grid = self.getGrid()
min_x, max_x, min_y, max_y = gss... |
def read_embedded(self, data, parent_var_type):
"""Read method for "mixed" variable type.
.. Note:: The ``read()`` method will automatically determine if the input is a variable or
needs to be searched for embedded variables. There usually is no reason to call
this m... | Read method for "mixed" variable type.
.. Note:: The ``read()`` method will automatically determine if the input is a variable or
needs to be searched for embedded variables. There usually is no reason to call
this method directly.
This method will automatically cov... | Below is the the instruction that describes the task:
### Input:
Read method for "mixed" variable type.
.. Note:: The ``read()`` method will automatically determine if the input is a variable or
needs to be searched for embedded variables. There usually is no reason to call
... |
def construct_makeblastdb_cmd(
filename, outdir, blastdb_exe=pyani_config.MAKEBLASTDB_DEFAULT
):
"""Returns a single makeblastdb command.
- filename - input filename
- blastdb_exe - path to the makeblastdb executable
"""
title = os.path.splitext(os.path.split(filename)[-1])[0]
outfilename =... | Returns a single makeblastdb command.
- filename - input filename
- blastdb_exe - path to the makeblastdb executable | Below is the the instruction that describes the task:
### Input:
Returns a single makeblastdb command.
- filename - input filename
- blastdb_exe - path to the makeblastdb executable
### Response:
def construct_makeblastdb_cmd(
filename, outdir, blastdb_exe=pyani_config.MAKEBLASTDB_DEFAULT
):
"""Re... |
def _remove_duplicates(objects):
"""Removes duplicate objects.
http://www.peterbe.com/plog/uniqifiers-benchmark.
"""
seen, uniq = set(), []
for obj in objects:
obj_id = id(obj)
if obj_id in seen:
continue
seen.add(obj_id)
uniq.append(obj)
return uniq | Removes duplicate objects.
http://www.peterbe.com/plog/uniqifiers-benchmark. | Below is the the instruction that describes the task:
### Input:
Removes duplicate objects.
http://www.peterbe.com/plog/uniqifiers-benchmark.
### Response:
def _remove_duplicates(objects):
"""Removes duplicate objects.
http://www.peterbe.com/plog/uniqifiers-benchmark.
"""
seen, uniq = set(), ... |
def shape_based_slice_interpolation(img, dim, nslices):
"""
Adds `nslices` slices between all slices of the binary image `img` along dimension
`dim` respecting the original slice values to be situated in the middle of each
slice. Extrapolation situations are handled by simple repeating.
Interpo... | Adds `nslices` slices between all slices of the binary image `img` along dimension
`dim` respecting the original slice values to be situated in the middle of each
slice. Extrapolation situations are handled by simple repeating.
Interpolation of new slices is performed using shape based interpolation.
... | Below is the the instruction that describes the task:
### Input:
Adds `nslices` slices between all slices of the binary image `img` along dimension
`dim` respecting the original slice values to be situated in the middle of each
slice. Extrapolation situations are handled by simple repeating.
Interp... |
def _R2deriv(self,R,z,phi=0.,t=0.):
"""
NAME:
_R2deriv
PURPOSE:
evaluate the second radial derivative for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPU... | NAME:
_R2deriv
PURPOSE:
evaluate the second radial derivative for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
the second radial derivative | Below is the the instruction that describes the task:
### Input:
NAME:
_R2deriv
PURPOSE:
evaluate the second radial derivative for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
... |
def create_client(self,only_db=False):
"""返回连接的客户端
"""
#database = parse_uri(self.uri).get("database")
if self.ioloop:
if only_db == False:
client = AsyncIOMotorClient("/".join(self.uri.split("/")[:-1]), io_loop=self.ioloop)
else:
... | 返回连接的客户端 | Below is the the instruction that describes the task:
### Input:
返回连接的客户端
### Response:
def create_client(self,only_db=False):
"""返回连接的客户端
"""
#database = parse_uri(self.uri).get("database")
if self.ioloop:
if only_db == False:
client = AsyncIOMotorClien... |
def _process_failures(self, key):
'''
Handles the retrying of the failed key
'''
if self.settings['RETRY_FAILURES']:
self.logger.debug("going to retry failure")
# get the current failure count
failkey = self._get_fail_key(key)
current = sel... | Handles the retrying of the failed key | Below is the the instruction that describes the task:
### Input:
Handles the retrying of the failed key
### Response:
def _process_failures(self, key):
'''
Handles the retrying of the failed key
'''
if self.settings['RETRY_FAILURES']:
self.logger.debug("going to retry fa... |
def get_units_per_page(self, per_page=1000, page=1, params=None):
"""
Get units per page
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:param params: Search parameters. Default: {}
:return: list
"""
return s... | Get units per page
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:param params: Search parameters. Default: {}
:return: list | Below is the the instruction that describes the task:
### Input:
Get units per page
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:param params: Search parameters. Default: {}
:return: list
### Response:
def get_units_per_page(self, p... |
def cli_put_account(context):
"""
Performs a PUT on the account.
See :py:mod:`swiftly.cli.put` for context usage information.
See :py:class:`CLIPut` for more information.
"""
body = None
if context.input_:
if context.input_ == '-':
body = context.io_manager.get_stdin()
... | Performs a PUT on the account.
See :py:mod:`swiftly.cli.put` for context usage information.
See :py:class:`CLIPut` for more information. | Below is the the instruction that describes the task:
### Input:
Performs a PUT on the account.
See :py:mod:`swiftly.cli.put` for context usage information.
See :py:class:`CLIPut` for more information.
### Response:
def cli_put_account(context):
"""
Performs a PUT on the account.
See :py:mod... |
def get(self, *, asset_id, operation=None, headers=None):
"""Given an asset id, get its list of transactions (and
optionally filter for only ``'CREATE'`` or ``'TRANSFER'``
transactions).
Args:
asset_id (str): Id of the asset.
operation (str): The type of operatio... | Given an asset id, get its list of transactions (and
optionally filter for only ``'CREATE'`` or ``'TRANSFER'``
transactions).
Args:
asset_id (str): Id of the asset.
operation (str): The type of operation the transaction
should be. Either ``'CREATE'`` or `... | Below is the the instruction that describes the task:
### Input:
Given an asset id, get its list of transactions (and
optionally filter for only ``'CREATE'`` or ``'TRANSFER'``
transactions).
Args:
asset_id (str): Id of the asset.
operation (str): The type of operatio... |
def clean_structure(self, out_suffix='_clean', outdir=None, force_rerun=False,
remove_atom_alt=True, keep_atom_alt_id='A',remove_atom_hydrogen=True, add_atom_occ=True,
remove_res_hetero=True, keep_chemicals=None, keep_res_only=None,
add_chain_id_i... | Clean the structure file associated with this structure, and save it as a new file. Returns the file path.
Args:
out_suffix (str): Suffix to append to original filename
outdir (str): Path to output directory
force_rerun (bool): If structure should be re-cleaned if a clean fi... | Below is the the instruction that describes the task:
### Input:
Clean the structure file associated with this structure, and save it as a new file. Returns the file path.
Args:
out_suffix (str): Suffix to append to original filename
outdir (str): Path to output directory
... |
def _interpret_angle(name, angle_object, angle_float, unit='degrees'):
"""Return an angle in radians from one of two arguments.
It is common for Skyfield routines to accept both an argument like
`alt` that takes an Angle object as well as an `alt_degrees` that
can be given a bare float or a sexagesimal... | Return an angle in radians from one of two arguments.
It is common for Skyfield routines to accept both an argument like
`alt` that takes an Angle object as well as an `alt_degrees` that
can be given a bare float or a sexagesimal tuple. A pair of such
arguments can be passed to this routine for interp... | Below is the the instruction that describes the task:
### Input:
Return an angle in radians from one of two arguments.
It is common for Skyfield routines to accept both an argument like
`alt` that takes an Angle object as well as an `alt_degrees` that
can be given a bare float or a sexagesimal tuple. ... |
def create(self, **kwargs):
"""Create a metric."""
url_str = self.base_url
if 'tenant_id' in kwargs:
url_str = url_str + '?tenant_id=%s' % kwargs['tenant_id']
del kwargs['tenant_id']
data = kwargs['jsonbody'] if 'jsonbody' in kwargs else kwargs
body = sel... | Create a metric. | Below is the the instruction that describes the task:
### Input:
Create a metric.
### Response:
def create(self, **kwargs):
"""Create a metric."""
url_str = self.base_url
if 'tenant_id' in kwargs:
url_str = url_str + '?tenant_id=%s' % kwargs['tenant_id']
del kwargs['... |
def generate_random_sframe(num_rows, column_codes, random_seed = 0):
"""
Creates a random SFrame with `num_rows` rows and randomly
generated column types determined by `column_codes`. The output
SFrame is deterministic based on `random_seed`.
`column_types` is a string with each character denoti... | Creates a random SFrame with `num_rows` rows and randomly
generated column types determined by `column_codes`. The output
SFrame is deterministic based on `random_seed`.
`column_types` is a string with each character denoting one type
of column, with the output SFrame having one column for each
... | Below is the the instruction that describes the task:
### Input:
Creates a random SFrame with `num_rows` rows and randomly
generated column types determined by `column_codes`. The output
SFrame is deterministic based on `random_seed`.
`column_types` is a string with each character denoting one type
... |
def card_auth(self, auth_mode, block_address, key, uid):
"""
Authenticates to use specified block address. Tag must be selected using select_tag(uid) before auth.
auth_mode -- RFID.auth_a or RFID.auth_b
key -- list or tuple with six bytes key
uid -- list or tuple with four bytes ... | Authenticates to use specified block address. Tag must be selected using select_tag(uid) before auth.
auth_mode -- RFID.auth_a or RFID.auth_b
key -- list or tuple with six bytes key
uid -- list or tuple with four bytes tag ID
Returns error state. | Below is the the instruction that describes the task:
### Input:
Authenticates to use specified block address. Tag must be selected using select_tag(uid) before auth.
auth_mode -- RFID.auth_a or RFID.auth_b
key -- list or tuple with six bytes key
uid -- list or tuple with four bytes tag ID
... |
def get_aligned_adjacent_coords(x, y):
'''
returns the nine clockwise adjacent coordinates on a keypad, where each row is vertically aligned.
'''
return [(x-1, y), (x-1, y-1), (x, y-1), (x+1, y-1), (x+1, y), (x+1, y+1), (x, y+1), (x-1, y+1)] | returns the nine clockwise adjacent coordinates on a keypad, where each row is vertically aligned. | Below is the the instruction that describes the task:
### Input:
returns the nine clockwise adjacent coordinates on a keypad, where each row is vertically aligned.
### Response:
def get_aligned_adjacent_coords(x, y):
'''
returns the nine clockwise adjacent coordinates on a keypad, where each row is vertica... |
def _string_to_int(self, string):
"""
Convert a string to a number, using the given alphabet..
"""
number = 0
for char in string[::-1]:
number = number * self._alpha_len + self._alphabet.index(char)
return number | Convert a string to a number, using the given alphabet.. | Below is the the instruction that describes the task:
### Input:
Convert a string to a number, using the given alphabet..
### Response:
def _string_to_int(self, string):
"""
Convert a string to a number, using the given alphabet..
"""
number = 0
for char in string[::-1]:
... |
def stream_user(self, listener, run_async=False, timeout=__DEFAULT_STREAM_TIMEOUT, reconnect_async=False, reconnect_async_wait_sec=__DEFAULT_STREAM_RECONNECT_WAIT_SEC):
"""
Streams events that are relevant to the authorized user, i.e. home
timeline and notifications.
"""
return s... | Streams events that are relevant to the authorized user, i.e. home
timeline and notifications. | Below is the the instruction that describes the task:
### Input:
Streams events that are relevant to the authorized user, i.e. home
timeline and notifications.
### Response:
def stream_user(self, listener, run_async=False, timeout=__DEFAULT_STREAM_TIMEOUT, reconnect_async=False, reconnect_async_wait_sec=__... |
def do_usufy(self, query, **kwargs):
"""
Verifying a usufy query in this platform.
This might be redefined in any class inheriting from Platform.
Args:
-----
query: The element to be searched.
Return:
-------
A list of elements to be app... | Verifying a usufy query in this platform.
This might be redefined in any class inheriting from Platform.
Args:
-----
query: The element to be searched.
Return:
-------
A list of elements to be appended. | Below is the the instruction that describes the task:
### Input:
Verifying a usufy query in this platform.
This might be redefined in any class inheriting from Platform.
Args:
-----
query: The element to be searched.
Return:
-------
A list of elemen... |
def tradeBreaksSSE(symbols=None, on_data=None, token='', version=''):
'''Trade report messages are sent when an order on the IEX Order Book is executed in whole or in part. DEEP sends a Trade report message for every individual fill.
https://iexcloud.io/docs/api/#deep-trades
Args:
symbols (string)... | Trade report messages are sent when an order on the IEX Order Book is executed in whole or in part. DEEP sends a Trade report message for every individual fill.
https://iexcloud.io/docs/api/#deep-trades
Args:
symbols (string); Tickers to request
on_data (function): Callback on data
tok... | Below is the the instruction that describes the task:
### Input:
Trade report messages are sent when an order on the IEX Order Book is executed in whole or in part. DEEP sends a Trade report message for every individual fill.
https://iexcloud.io/docs/api/#deep-trades
Args:
symbols (string); Ticker... |
def do_file_update_metadata(client, args):
"""Update file metadata"""
client.update_file_metadata(args.uri, filename=args.filename,
description=args.description, mtime=args.mtime,
privacy=args.privacy)
return True | Update file metadata | Below is the the instruction that describes the task:
### Input:
Update file metadata
### Response:
def do_file_update_metadata(client, args):
"""Update file metadata"""
client.update_file_metadata(args.uri, filename=args.filename,
description=args.description, mtime=args.mt... |
def srfcss(code, bodstr, srflen=_default_len_out):
"""
Translate a surface ID code, together with a body string, to the
corresponding surface name. If no such surface name exists,
return a string representation of the surface ID code.
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/... | Translate a surface ID code, together with a body string, to the
corresponding surface name. If no such surface name exists,
return a string representation of the surface ID code.
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/srfcss_c.html
:param code: Integer surface ID code to ... | Below is the the instruction that describes the task:
### Input:
Translate a surface ID code, together with a body string, to the
corresponding surface name. If no such surface name exists,
return a string representation of the surface ID code.
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/c... |
def grade(adjective, suffix=COMPARATIVE):
""" Returns the comparative or superlative form of the given (inflected) adjective.
"""
b = predicative(adjective)
# groß => großt, schön => schönst
if suffix == SUPERLATIVE and b.endswith(("s", u"ß")):
suffix = suffix[1:]
# große => großere, sch... | Returns the comparative or superlative form of the given (inflected) adjective. | Below is the the instruction that describes the task:
### Input:
Returns the comparative or superlative form of the given (inflected) adjective.
### Response:
def grade(adjective, suffix=COMPARATIVE):
""" Returns the comparative or superlative form of the given (inflected) adjective.
"""
b = predicativ... |
def use_token(self, token=None):
"""
Function to use static AUTH_TOKEN as auth for the constructor instead of full login process.
**Parameters:**:
- **token**: Static AUTH_TOKEN
**Returns:** Bool on success or failure. In addition the function will mutate the `cloudgenix.API... | Function to use static AUTH_TOKEN as auth for the constructor instead of full login process.
**Parameters:**:
- **token**: Static AUTH_TOKEN
**Returns:** Bool on success or failure. In addition the function will mutate the `cloudgenix.API`
constructor items as needed. | Below is the the instruction that describes the task:
### Input:
Function to use static AUTH_TOKEN as auth for the constructor instead of full login process.
**Parameters:**:
- **token**: Static AUTH_TOKEN
**Returns:** Bool on success or failure. In addition the function will mutate the... |
def system_content(self):
r"""A property that returns the content that is rendered
regardless of the :attr:`Message.type`.
In the case of :attr:`MessageType.default`\, this just returns the
regular :attr:`Message.content`. Otherwise this returns an English
message denoting the c... | r"""A property that returns the content that is rendered
regardless of the :attr:`Message.type`.
In the case of :attr:`MessageType.default`\, this just returns the
regular :attr:`Message.content`. Otherwise this returns an English
message denoting the contents of the system message. | Below is the the instruction that describes the task:
### Input:
r"""A property that returns the content that is rendered
regardless of the :attr:`Message.type`.
In the case of :attr:`MessageType.default`\, this just returns the
regular :attr:`Message.content`. Otherwise this returns an Eng... |
def build(self, plot):
"""
Build the guides
Parameters
----------
plot : ggplot
ggplot object being drawn
Returns
-------
box : matplotlib.offsetbox.Offsetbox | None
A box that contains all the guides for the plot.
If ... | Build the guides
Parameters
----------
plot : ggplot
ggplot object being drawn
Returns
-------
box : matplotlib.offsetbox.Offsetbox | None
A box that contains all the guides for the plot.
If there are no guides, **None** is returned. | Below is the the instruction that describes the task:
### Input:
Build the guides
Parameters
----------
plot : ggplot
ggplot object being drawn
Returns
-------
box : matplotlib.offsetbox.Offsetbox | None
A box that contains all the guides for... |
def attach_video(self, video: typing.Union[InputMediaVideo, base.InputFile],
thumb: typing.Union[base.InputFile, base.String] = None,
caption: base.String = None,
width: base.Integer = None, height: base.Integer = None, duration: base.Integer = None):
... | Attach video
:param video:
:param caption:
:param width:
:param height:
:param duration: | Below is the the instruction that describes the task:
### Input:
Attach video
:param video:
:param caption:
:param width:
:param height:
:param duration:
### Response:
def attach_video(self, video: typing.Union[InputMediaVideo, base.InputFile],
thumb: t... |
def _ref_bus_angle_constraint(self, buses, Va, xmin, xmax):
""" Adds a constraint on the reference bus angles.
"""
refs = [bus._i for bus in buses if bus.type == REFERENCE]
Varefs = array([b.v_angle for b in buses if b.type == REFERENCE])
xmin[Va.i1 - 1 + refs] = Varefs
... | Adds a constraint on the reference bus angles. | Below is the the instruction that describes the task:
### Input:
Adds a constraint on the reference bus angles.
### Response:
def _ref_bus_angle_constraint(self, buses, Va, xmin, xmax):
""" Adds a constraint on the reference bus angles.
"""
refs = [bus._i for bus in buses if bus.type == REF... |
def poke(url, accesskey=None, secretkey=None, __method__='GET', **req_args):
"""
Poke the Rancher API. Returns a Rod object instance. Central starting
point for the cattleprod package.
:param url: The full Rancher URL to the API endpoint.
:param accesskey: The rancher access key, optional.
:para... | Poke the Rancher API. Returns a Rod object instance. Central starting
point for the cattleprod package.
:param url: The full Rancher URL to the API endpoint.
:param accesskey: The rancher access key, optional.
:param secretkey: The rancher secret key, optional.
:param __method__: Internal method, do... | Below is the the instruction that describes the task:
### Input:
Poke the Rancher API. Returns a Rod object instance. Central starting
point for the cattleprod package.
:param url: The full Rancher URL to the API endpoint.
:param accesskey: The rancher access key, optional.
:param secretkey: The ran... |
def _agent_import_failed(trace):
"""Returns dummy agent class for if PyTorch etc. is not installed."""
class _AgentImportFailed(Trainer):
_name = "AgentImportFailed"
_default_config = with_common_config({})
def _setup(self, config):
raise ImportError(trace)
return _Age... | Returns dummy agent class for if PyTorch etc. is not installed. | Below is the the instruction that describes the task:
### Input:
Returns dummy agent class for if PyTorch etc. is not installed.
### Response:
def _agent_import_failed(trace):
"""Returns dummy agent class for if PyTorch etc. is not installed."""
class _AgentImportFailed(Trainer):
_name = "AgentImp... |
def norm(self, valu):
'''
Normalize the value for a given type.
Args:
valu (obj): The value to normalize.
Returns:
((obj,dict)): The normalized valu, info tuple.
Notes:
The info dictionary uses the following key conventions:
... | Normalize the value for a given type.
Args:
valu (obj): The value to normalize.
Returns:
((obj,dict)): The normalized valu, info tuple.
Notes:
The info dictionary uses the following key conventions:
subs (dict): The normalized sub-fields as ... | Below is the the instruction that describes the task:
### Input:
Normalize the value for a given type.
Args:
valu (obj): The value to normalize.
Returns:
((obj,dict)): The normalized valu, info tuple.
Notes:
The info dictionary uses the following key co... |
def get_objective_query_session(self, proxy):
"""Gets the ``OsidSession`` associated with the objective query service.
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: an ``ObjectiveQuerySession``
:rtype: ``osid.learning.ObjectiveQuerySession``
:raise: ``... | Gets the ``OsidSession`` associated with the objective query service.
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: an ``ObjectiveQuerySession``
:rtype: ``osid.learning.ObjectiveQuerySession``
:raise: ``NullArgument`` -- ``proxy`` is ``null``
:raise: `... | Below is the the instruction that describes the task:
### Input:
Gets the ``OsidSession`` associated with the objective query service.
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: an ``ObjectiveQuerySession``
:rtype: ``osid.learning.ObjectiveQuerySession``
... |
def pop(self, symbol):
"""
Delete current metadata of `symbol`
Parameters
----------
symbol : `str`
symbol name to delete
Returns
-------
Deleted metadata
"""
last_metadata = self.find_one({'symbol': symbol}, sort=[('start_tim... | Delete current metadata of `symbol`
Parameters
----------
symbol : `str`
symbol name to delete
Returns
-------
Deleted metadata | Below is the the instruction that describes the task:
### Input:
Delete current metadata of `symbol`
Parameters
----------
symbol : `str`
symbol name to delete
Returns
-------
Deleted metadata
### Response:
def pop(self, symbol):
"""
Del... |
def create(self, term, options):
"""Create a monitor using passed configuration."""
if not self._state:
raise InvalidState("State was not properly obtained from the app")
options['action'] = 'CREATE'
payload = self._build_payload(term, options)
url = self.ALERTS_CREAT... | Create a monitor using passed configuration. | Below is the the instruction that describes the task:
### Input:
Create a monitor using passed configuration.
### Response:
def create(self, term, options):
"""Create a monitor using passed configuration."""
if not self._state:
raise InvalidState("State was not properly obtained from th... |
def parse(data):
"""
Parse the given ChangeLog data into a list of Hashes.
@param [String] data File data from the ChangeLog.md
@return [Array<Hash>] Parsed data, e.g. [{ 'version' => ..., 'url' => ..., 'date' => ..., 'content' => ...}, ...]
"""
sections = re.compile("^## .+$", re.MULTILINE).s... | Parse the given ChangeLog data into a list of Hashes.
@param [String] data File data from the ChangeLog.md
@return [Array<Hash>] Parsed data, e.g. [{ 'version' => ..., 'url' => ..., 'date' => ..., 'content' => ...}, ...] | Below is the the instruction that describes the task:
### Input:
Parse the given ChangeLog data into a list of Hashes.
@param [String] data File data from the ChangeLog.md
@return [Array<Hash>] Parsed data, e.g. [{ 'version' => ..., 'url' => ..., 'date' => ..., 'content' => ...}, ...]
### Response:
def pa... |
def update_pos(pos_dict, start_key, nbr=2):
"Update the `pos_dict` by moving all positions after `start_key` by `nbr`."
for key,idx in pos_dict.items():
if str.lower(key) >= str.lower(start_key): pos_dict[key] += nbr
return pos_dict | Update the `pos_dict` by moving all positions after `start_key` by `nbr`. | Below is the the instruction that describes the task:
### Input:
Update the `pos_dict` by moving all positions after `start_key` by `nbr`.
### Response:
def update_pos(pos_dict, start_key, nbr=2):
"Update the `pos_dict` by moving all positions after `start_key` by `nbr`."
for key,idx in pos_dict.items():
... |
def _threshold_nans(data, tolerate_nans):
"""Thresholds data based on proportion of subjects with NaNs
Takes in data and a threshold value (float between 0.0 and 1.0) determining
the permissible proportion of subjects with non-NaN values. For example, if
threshold=.8, any voxel where >= 80% of subject... | Thresholds data based on proportion of subjects with NaNs
Takes in data and a threshold value (float between 0.0 and 1.0) determining
the permissible proportion of subjects with non-NaN values. For example, if
threshold=.8, any voxel where >= 80% of subjects have non-NaN values will
be left unchanged, ... | Below is the the instruction that describes the task:
### Input:
Thresholds data based on proportion of subjects with NaNs
Takes in data and a threshold value (float between 0.0 and 1.0) determining
the permissible proportion of subjects with non-NaN values. For example, if
threshold=.8, any voxel wher... |
def scrape(language, method, word, *args, **kwargs):
''' Uses custom scrapers and calls provided method. '''
scraper = Scrape(language, word)
if hasattr(scraper, method):
function = getattr(scraper, method)
if callable(function):
return function(*args, **kwargs)
else:
raise NotImplementedError('The method... | Uses custom scrapers and calls provided method. | Below is the the instruction that describes the task:
### Input:
Uses custom scrapers and calls provided method.
### Response:
def scrape(language, method, word, *args, **kwargs):
''' Uses custom scrapers and calls provided method. '''
scraper = Scrape(language, word)
if hasattr(scraper, method):
function = ... |
def readFile(cls, filepath):
"""Try different encoding to open a file in readonly mode"""
for mode in ("utf-8", 'gbk', 'cp1252', 'windows-1252', 'latin-1'):
try:
with open(filepath, mode='r', encoding=mode) as f:
content = f.read()
cit.... | Try different encoding to open a file in readonly mode | Below is the the instruction that describes the task:
### Input:
Try different encoding to open a file in readonly mode
### Response:
def readFile(cls, filepath):
"""Try different encoding to open a file in readonly mode"""
for mode in ("utf-8", 'gbk', 'cp1252', 'windows-1252', 'latin-1'):
... |
def _identify_os(self, msg):
'''
Using the prefix of the syslog message,
we are able to identify the operating system and then continue parsing.
'''
ret = []
for dev_os, data in self.compiled_prefixes.items():
# TODO Should we prevent attepmting to determine t... | Using the prefix of the syslog message,
we are able to identify the operating system and then continue parsing. | Below is the the instruction that describes the task:
### Input:
Using the prefix of the syslog message,
we are able to identify the operating system and then continue parsing.
### Response:
def _identify_os(self, msg):
'''
Using the prefix of the syslog message,
we are able to iden... |
def _render_profile(path, caller, runner):
'''
Render profile as Jinja2.
:param path:
:return:
'''
env = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(path)), trim_blocks=False)
return env.get_template(os.path.basename(path)).render(salt=caller, runners=runner).strip() | Render profile as Jinja2.
:param path:
:return: | Below is the the instruction that describes the task:
### Input:
Render profile as Jinja2.
:param path:
:return:
### Response:
def _render_profile(path, caller, runner):
'''
Render profile as Jinja2.
:param path:
:return:
'''
env = jinja2.Environment(loader=jinja2.FileSystemLoader(o... |
def _log_joint(current_target_log_prob, current_momentum):
"""Log-joint probability given a state's log-probability and momentum."""
momentum_log_prob = -sum(
[tf.reduce_sum(input_tensor=0.5 * (m**2.)) for m in current_momentum])
return current_target_log_prob + momentum_log_prob | Log-joint probability given a state's log-probability and momentum. | Below is the the instruction that describes the task:
### Input:
Log-joint probability given a state's log-probability and momentum.
### Response:
def _log_joint(current_target_log_prob, current_momentum):
"""Log-joint probability given a state's log-probability and momentum."""
momentum_log_prob = -sum(
... |
def get_tree(self, *page_numbers):
"""
Return lxml.etree.ElementTree for entire document, or page numbers
given if any.
"""
cache_key = "_".join(map(str, _flatten(page_numbers)))
tree = self._parse_tree_cacher.get(cache_key)
if tree is None:
... | Return lxml.etree.ElementTree for entire document, or page numbers
given if any. | Below is the the instruction that describes the task:
### Input:
Return lxml.etree.ElementTree for entire document, or page numbers
given if any.
### Response:
def get_tree(self, *page_numbers):
"""
Return lxml.etree.ElementTree for entire document, or page numbers
g... |
def neverCalledWithMatch(cls, spy, *args, **kwargs): #pylint: disable=invalid-name
"""
Checking the inspector is never called with partial SinonMatcher(args/kwargs)
Args: SinonSpy, args/kwargs
"""
cls.__is_spy(spy)
if not (spy.neverCalledWithMatch(*args, **kwargs)):
... | Checking the inspector is never called with partial SinonMatcher(args/kwargs)
Args: SinonSpy, args/kwargs | Below is the the instruction that describes the task:
### Input:
Checking the inspector is never called with partial SinonMatcher(args/kwargs)
Args: SinonSpy, args/kwargs
### Response:
def neverCalledWithMatch(cls, spy, *args, **kwargs): #pylint: disable=invalid-name
"""
Checking the inspec... |
def prsint(string):
"""
Parse a string as an integer, encapsulating error handling.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/prsint_c.html
:param string: String representing an integer.
:type string: str
:return: Integer value obtained by parsing string.
:rtype: int
"""
... | Parse a string as an integer, encapsulating error handling.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/prsint_c.html
:param string: String representing an integer.
:type string: str
:return: Integer value obtained by parsing string.
:rtype: int | Below is the the instruction that describes the task:
### Input:
Parse a string as an integer, encapsulating error handling.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/prsint_c.html
:param string: String representing an integer.
:type string: str
:return: Integer value obtained by par... |
def are_metadata_file_based(layer):
"""Check if metadata should be read/written to file or our metadata db.
Determine which metadata lookup system to use (file base or cache db)
based on the layer's provider type. True indicates we should use the
datasource as a file and look for a meta... | Check if metadata should be read/written to file or our metadata db.
Determine which metadata lookup system to use (file base or cache db)
based on the layer's provider type. True indicates we should use the
datasource as a file and look for a metadata file, False and we look
in the met... | Below is the the instruction that describes the task:
### Input:
Check if metadata should be read/written to file or our metadata db.
Determine which metadata lookup system to use (file base or cache db)
based on the layer's provider type. True indicates we should use the
datasource as a fi... |
def Parse(self, value):
"""Parse a 'Value' declaration.
Args:
value: String line from a template file, must begin with 'Value '.
Raises:
TextFSMTemplateError: Value declaration contains an error.
"""
value_line = value.split(' ')
if len(value_line) < 3:
raise TextFSMTemplat... | Parse a 'Value' declaration.
Args:
value: String line from a template file, must begin with 'Value '.
Raises:
TextFSMTemplateError: Value declaration contains an error. | Below is the the instruction that describes the task:
### Input:
Parse a 'Value' declaration.
Args:
value: String line from a template file, must begin with 'Value '.
Raises:
TextFSMTemplateError: Value declaration contains an error.
### Response:
def Parse(self, value):
"""Parse a 'Value... |
def get_object(self, view_name, view_args, view_kwargs):
"""
Return the object corresponding to a matched URL.
Takes the matched URL conf arguments, and should return an
object instance, or raise an `ObjectDoesNotExist` exception.
"""
lookup_value = view_kwargs.get(self.... | Return the object corresponding to a matched URL.
Takes the matched URL conf arguments, and should return an
object instance, or raise an `ObjectDoesNotExist` exception. | Below is the the instruction that describes the task:
### Input:
Return the object corresponding to a matched URL.
Takes the matched URL conf arguments, and should return an
object instance, or raise an `ObjectDoesNotExist` exception.
### Response:
def get_object(self, view_name, view_args, view_k... |
def register_logger(self, logger):
"""
Register a new logger.
"""
handler = CommandHandler(self)
handler.setFormatter(CommandFormatter())
logger.handlers = [handler]
logger.propagate = False
output = self.output
level = logging.WARNING
if ... | Register a new logger. | Below is the the instruction that describes the task:
### Input:
Register a new logger.
### Response:
def register_logger(self, logger):
"""
Register a new logger.
"""
handler = CommandHandler(self)
handler.setFormatter(CommandFormatter())
logger.handlers = [handler]... |
def mnist_tutorial(train_start=0, train_end=60000, test_start=0,
test_end=10000, nb_epochs=NB_EPOCHS, batch_size=BATCH_SIZE,
learning_rate=LEARNING_RATE, testing=False,
label_smoothing=0.1):
"""
MNIST CleverHans tutorial
:param train_start: index of first t... | MNIST CleverHans tutorial
:param train_start: index of first training set example
:param train_end: index of last training set example
:param test_start: index of first test set example
:param test_end: index of last test set example
:param nb_epochs: number of epochs to train model
:param batch_size: size ... | Below is the the instruction that describes the task:
### Input:
MNIST CleverHans tutorial
:param train_start: index of first training set example
:param train_end: index of last training set example
:param test_start: index of first test set example
:param test_end: index of last test set example
:param ... |
def p_valueInitializer(p):
"""valueInitializer : identifier defaultValue ';'
| qualifierList identifier defaultValue ';'
"""
if len(p) == 4:
id_ = p[1]
val = p[2]
quals = []
else:
quals = p[1]
id_ = p[2]
val = p[... | valueInitializer : identifier defaultValue ';'
| qualifierList identifier defaultValue ';' | Below is the the instruction that describes the task:
### Input:
valueInitializer : identifier defaultValue ';'
| qualifierList identifier defaultValue ';'
### Response:
def p_valueInitializer(p):
"""valueInitializer : identifier defaultValue ';'
| qualifierList ... |
def _parse_group(self, group_name, group):
"""
Parse a group definition from a dynamic inventory. These are top-level
elements which are not '_meta(data)'.
"""
if type(group) == dict:
# Example:
# {
# "mgmt": {
# "... | Parse a group definition from a dynamic inventory. These are top-level
elements which are not '_meta(data)'. | Below is the the instruction that describes the task:
### Input:
Parse a group definition from a dynamic inventory. These are top-level
elements which are not '_meta(data)'.
### Response:
def _parse_group(self, group_name, group):
"""
Parse a group definition from a dynamic inventory. These... |
def create_namespaced_job(self, namespace, body, **kwargs):
"""
create a Job
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_namespaced_job(namespace, body, async_req=True)
>... | create a Job
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_namespaced_job(namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str names... | Below is the the instruction that describes the task:
### Input:
create a Job
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_namespaced_job(namespace, body, async_req=True)
>>> result =... |
def _init_glyph(self, plot, mapping, properties):
"""
Returns a Bokeh glyph object.
"""
properties = mpl_to_bokeh(properties)
properties = dict(properties, **mapping)
if 'xs' in mapping:
renderer = plot.patches(**properties)
else:
renderer ... | Returns a Bokeh glyph object. | Below is the the instruction that describes the task:
### Input:
Returns a Bokeh glyph object.
### Response:
def _init_glyph(self, plot, mapping, properties):
"""
Returns a Bokeh glyph object.
"""
properties = mpl_to_bokeh(properties)
properties = dict(properties, **mapping)... |
def unfold(self, mode):
"""
Unfolds a dense tensor in mode n.
Parameters
----------
mode : int
Mode in which tensor is unfolded
Returns
-------
unfolded_dtensor : unfolded_dtensor object
Tensor unfolded along mode
Example... | Unfolds a dense tensor in mode n.
Parameters
----------
mode : int
Mode in which tensor is unfolded
Returns
-------
unfolded_dtensor : unfolded_dtensor object
Tensor unfolded along mode
Examples
--------
Create dense tens... | Below is the the instruction that describes the task:
### Input:
Unfolds a dense tensor in mode n.
Parameters
----------
mode : int
Mode in which tensor is unfolded
Returns
-------
unfolded_dtensor : unfolded_dtensor object
Tensor unfolded al... |
def wait_for(self, pattern, timeout=None):
"""
Block until a pattern have been found in stdout and stderr
Args:
pattern(:class:`~re.Pattern`): The pattern to search
timeout(int): Maximum number of second to wait. If None, wait infinitely
Raises:
Tim... | Block until a pattern have been found in stdout and stderr
Args:
pattern(:class:`~re.Pattern`): The pattern to search
timeout(int): Maximum number of second to wait. If None, wait infinitely
Raises:
TimeoutError: When timeout is reach | Below is the the instruction that describes the task:
### Input:
Block until a pattern have been found in stdout and stderr
Args:
pattern(:class:`~re.Pattern`): The pattern to search
timeout(int): Maximum number of second to wait. If None, wait infinitely
Raises:
... |
def cdf(self, y, f):
r"""
Cumulative density function of the likelihood.
Parameters
----------
y: ndarray
query quantiles, i.e.\ :math:`P(Y \leq y)`.
f: ndarray
latent function from the GLM prior (:math:`\mathbf{f} =
\boldsymbol\Phi \... | r"""
Cumulative density function of the likelihood.
Parameters
----------
y: ndarray
query quantiles, i.e.\ :math:`P(Y \leq y)`.
f: ndarray
latent function from the GLM prior (:math:`\mathbf{f} =
\boldsymbol\Phi \mathbf{w}`)
Returns
... | Below is the the instruction that describes the task:
### Input:
r"""
Cumulative density function of the likelihood.
Parameters
----------
y: ndarray
query quantiles, i.e.\ :math:`P(Y \leq y)`.
f: ndarray
latent function from the GLM prior (:math:`\m... |
def get_mtype_and_number_from_code(si, sensor_code):
"""
Given a sensor sensor_code, get motion type and sensor number
:param si: dict, sensor index json dictionary
:param sensor_code: str, a sensor code (e.g. ACCX-UB1-L2C-M)
:return:
"""
mtype_and_ory, x, y, z = sensor_code.split("-")
... | Given a sensor sensor_code, get motion type and sensor number
:param si: dict, sensor index json dictionary
:param sensor_code: str, a sensor code (e.g. ACCX-UB1-L2C-M)
:return: | Below is the the instruction that describes the task:
### Input:
Given a sensor sensor_code, get motion type and sensor number
:param si: dict, sensor index json dictionary
:param sensor_code: str, a sensor code (e.g. ACCX-UB1-L2C-M)
:return:
### Response:
def get_mtype_and_number_from_code(si, sensor... |
def _prefix_from_opts(opts):
""" Return a prefix based on options passed from command line
Used by add_prefix() and add_prefix_from_pool() to avoid duplicate
parsing
"""
p = Prefix()
p.prefix = opts.get('prefix')
p.type = opts.get('type')
p.description = opts.get('description')
... | Return a prefix based on options passed from command line
Used by add_prefix() and add_prefix_from_pool() to avoid duplicate
parsing | Below is the the instruction that describes the task:
### Input:
Return a prefix based on options passed from command line
Used by add_prefix() and add_prefix_from_pool() to avoid duplicate
parsing
### Response:
def _prefix_from_opts(opts):
""" Return a prefix based on options passed from comm... |
def _read_select_kqueue(k_queue):
"""
Read PIPES using BSD Kqueue
"""
npipes = len(NonBlockingStreamReader._streams)
# Create list of kevent objects
# pylint: disable=no-member
kevents = [select.kevent(s.stream.fileno(),
filter=sel... | Read PIPES using BSD Kqueue | Below is the the instruction that describes the task:
### Input:
Read PIPES using BSD Kqueue
### Response:
def _read_select_kqueue(k_queue):
"""
Read PIPES using BSD Kqueue
"""
npipes = len(NonBlockingStreamReader._streams)
# Create list of kevent objects
# pylint: d... |
def _load(content_or_fp):
"""YAML Parse a file or str and check version.
"""
try:
data = yaml.load(content_or_fp, Loader=yaml.loader.BaseLoader)
except Exception as e:
raise type(e)('Malformed yaml file:\n%r' % format_exc())
try:
ver = data['spec']
except:
raise ... | YAML Parse a file or str and check version. | Below is the the instruction that describes the task:
### Input:
YAML Parse a file or str and check version.
### Response:
def _load(content_or_fp):
"""YAML Parse a file or str and check version.
"""
try:
data = yaml.load(content_or_fp, Loader=yaml.loader.BaseLoader)
except Exception as e:
... |
def count_single_dots(self):
"""Count all strokes of this recording that have only a single dot.
"""
pointlist = self.get_pointlist()
single_dots = 0
for stroke in pointlist:
if len(stroke) == 1:
single_dots += 1
return single_dots | Count all strokes of this recording that have only a single dot. | Below is the the instruction that describes the task:
### Input:
Count all strokes of this recording that have only a single dot.
### Response:
def count_single_dots(self):
"""Count all strokes of this recording that have only a single dot.
"""
pointlist = self.get_pointlist()
singl... |
async def make_conditional(
self,
request_range: Range,
max_partial_size: Optional[int]=None,
) -> None:
"""Make the response conditional to the
Arguments:
request_range: The range as requested by the request.
max_partial_size: The maximum... | Make the response conditional to the
Arguments:
request_range: The range as requested by the request.
max_partial_size: The maximum length the server is willing
to serve in a single response. Defaults to unlimited. | Below is the the instruction that describes the task:
### Input:
Make the response conditional to the
Arguments:
request_range: The range as requested by the request.
max_partial_size: The maximum length the server is willing
to serve in a single response. Defaults t... |
def backbone(self):
"""Returns a new `Polymer` containing only the backbone atoms.
Notes
-----
Metadata is not currently preserved from the parent object.
Sequence data is retained, but only the main chain atoms are retained.
Returns
-------
bb_poly : Po... | Returns a new `Polymer` containing only the backbone atoms.
Notes
-----
Metadata is not currently preserved from the parent object.
Sequence data is retained, but only the main chain atoms are retained.
Returns
-------
bb_poly : Polypeptide
Polymer c... | Below is the the instruction that describes the task:
### Input:
Returns a new `Polymer` containing only the backbone atoms.
Notes
-----
Metadata is not currently preserved from the parent object.
Sequence data is retained, but only the main chain atoms are retained.
Return... |
def _orderedCleanDict(attrsObj):
"""
-> dict with false-values removed
Also evaluates attr-instances for false-ness by looking at the values of their properties
"""
def _filt(k, v):
if attr.has(v):
return not not any(attr.astuple(v))
return not not v
return attr.asd... | -> dict with false-values removed
Also evaluates attr-instances for false-ness by looking at the values of their properties | Below is the the instruction that describes the task:
### Input:
-> dict with false-values removed
Also evaluates attr-instances for false-ness by looking at the values of their properties
### Response:
def _orderedCleanDict(attrsObj):
"""
-> dict with false-values removed
Also evaluates attr-ins... |
def make_anchor_id(self):
"""Return string to use as URL anchor for this comment.
"""
result = re.sub(
'[^a-zA-Z0-9_]', '_', self.user + '_' + self.timestamp)
return result | Return string to use as URL anchor for this comment. | Below is the the instruction that describes the task:
### Input:
Return string to use as URL anchor for this comment.
### Response:
def make_anchor_id(self):
"""Return string to use as URL anchor for this comment.
"""
result = re.sub(
'[^a-zA-Z0-9_]', '_', self.user + '_' + self... |
def unescape_html(text):
"""
Removes HTML or XML character references and entities from a text string.
@param text The HTML (or XML) source text.
@return The plain text, as a Unicode string, if necessary.
Source: http://effbot.org/zone/re-sub.htm#unescape-html
"""
def fixup(m):
tex... | Removes HTML or XML character references and entities from a text string.
@param text The HTML (or XML) source text.
@return The plain text, as a Unicode string, if necessary.
Source: http://effbot.org/zone/re-sub.htm#unescape-html | Below is the the instruction that describes the task:
### Input:
Removes HTML or XML character references and entities from a text string.
@param text The HTML (or XML) source text.
@return The plain text, as a Unicode string, if necessary.
Source: http://effbot.org/zone/re-sub.htm#unescape-html
### R... |
def _GetLink(self):
"""Retrieves the link.
Returns:
str: link.
"""
if self._link is None:
if self._tar_info:
self._link = self._tar_info.linkname
return self._link | Retrieves the link.
Returns:
str: link. | Below is the the instruction that describes the task:
### Input:
Retrieves the link.
Returns:
str: link.
### Response:
def _GetLink(self):
"""Retrieves the link.
Returns:
str: link.
"""
if self._link is None:
if self._tar_info:
self._link = self._tar_info.linkname
... |
def sub_dfs_by_num(df, num):
"""Get a generator yielding num consecutive sub-dataframes of the given df.
Arguments
---------
df : pandas.DataFrame
The dataframe for which to get sub-dataframes.
num : int
The number of sub-dataframe to divide the given dataframe into.
Returns
... | Get a generator yielding num consecutive sub-dataframes of the given df.
Arguments
---------
df : pandas.DataFrame
The dataframe for which to get sub-dataframes.
num : int
The number of sub-dataframe to divide the given dataframe into.
Returns
-------
generator
A ge... | Below is the the instruction that describes the task:
### Input:
Get a generator yielding num consecutive sub-dataframes of the given df.
Arguments
---------
df : pandas.DataFrame
The dataframe for which to get sub-dataframes.
num : int
The number of sub-dataframe to divide the give... |
def email_domain_free(value):
"""
Confirms that the email address is not using a free service.
@param {str} value
@returns {None}
@raises AssertionError
"""
domain = helpers.get_domain_from_email_address(value)
if domain.lower() in free_domains:
raise ValidationError(MESSAGE_US... | Confirms that the email address is not using a free service.
@param {str} value
@returns {None}
@raises AssertionError | Below is the the instruction that describes the task:
### Input:
Confirms that the email address is not using a free service.
@param {str} value
@returns {None}
@raises AssertionError
### Response:
def email_domain_free(value):
"""
Confirms that the email address is not using a free service.
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.