code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def sg_summary_image(tensor, prefix=None, name=None):
r"""Register `tensor` to summary report as `image`
Args:
tensor: A tensor to log as image
prefix: A `string`. A prefix to display in the tensor board web UI.
name: A `string`. A name to display in the tensor board web UI.
Returns:
... | r"""Register `tensor` to summary report as `image`
Args:
tensor: A tensor to log as image
prefix: A `string`. A prefix to display in the tensor board web UI.
name: A `string`. A name to display in the tensor board web UI.
Returns:
None | Below is the the instruction that describes the task:
### Input:
r"""Register `tensor` to summary report as `image`
Args:
tensor: A tensor to log as image
prefix: A `string`. A prefix to display in the tensor board web UI.
name: A `string`. A name to display in the tensor board web UI.
R... |
def send_message(self, destination_id, namespace, data,
inc_session_id=False, callback_function=False,
no_add_request_id=False, force=False):
""" Send a message to the Chromecast. """
# namespace is a string containing namespace
# data is a dict that wi... | Send a message to the Chromecast. | Below is the the instruction that describes the task:
### Input:
Send a message to the Chromecast.
### Response:
def send_message(self, destination_id, namespace, data,
inc_session_id=False, callback_function=False,
no_add_request_id=False, force=False):
""" Send a... |
def _check_existence_by_collection(self, container, item_name):
'''Check existnce of item based on get collection call.
:param collection: container object -- capable of get_collection()
:param item_name: str -- name of item to search for in collection
'''
coll = container.get_... | Check existnce of item based on get collection call.
:param collection: container object -- capable of get_collection()
:param item_name: str -- name of item to search for in collection | Below is the the instruction that describes the task:
### Input:
Check existnce of item based on get collection call.
:param collection: container object -- capable of get_collection()
:param item_name: str -- name of item to search for in collection
### Response:
def _check_existence_by_collectio... |
def TBH(cpu, dest):
"""
Table Branch Halfword causes a PC-relative forward branch using a table of single halfword offsets. A base
register provides a pointer to the table, and a second register supplies an index into the table. The branch
length is twice the value of the halfword return... | Table Branch Halfword causes a PC-relative forward branch using a table of single halfword offsets. A base
register provides a pointer to the table, and a second register supplies an index into the table. The branch
length is twice the value of the halfword returned from the table.
:param ARMv7... | Below is the the instruction that describes the task:
### Input:
Table Branch Halfword causes a PC-relative forward branch using a table of single halfword offsets. A base
register provides a pointer to the table, and a second register supplies an index into the table. The branch
length is twice the... |
def routes(name, **kwargs):
'''
Manage network interface static routes.
name
Interface name to apply the route to.
kwargs
Named routes
'''
ret = {
'name': name,
'changes': {},
'result': True,
'comment': 'Interface {0} routes are up to date.'.form... | Manage network interface static routes.
name
Interface name to apply the route to.
kwargs
Named routes | Below is the the instruction that describes the task:
### Input:
Manage network interface static routes.
name
Interface name to apply the route to.
kwargs
Named routes
### Response:
def routes(name, **kwargs):
'''
Manage network interface static routes.
name
Interface... |
def remove_tag(tag_name, string):
"""
Remove open and close tags - the tags themselves only - using
a non-greedy angle bracket pattern match
"""
if not string:
return string
pattern = re.compile('</?' + tag_name + '.*?>')
string = pattern.sub('', string)
return string | Remove open and close tags - the tags themselves only - using
a non-greedy angle bracket pattern match | Below is the the instruction that describes the task:
### Input:
Remove open and close tags - the tags themselves only - using
a non-greedy angle bracket pattern match
### Response:
def remove_tag(tag_name, string):
"""
Remove open and close tags - the tags themselves only - using
a non-greedy angl... |
def whowas(self, nick, max="", server=""):
"""Send a WHOWAS command."""
self.send_items('WHOWAS', nick, max, server) | Send a WHOWAS command. | Below is the the instruction that describes the task:
### Input:
Send a WHOWAS command.
### Response:
def whowas(self, nick, max="", server=""):
"""Send a WHOWAS command."""
self.send_items('WHOWAS', nick, max, server) |
def _guess_normalized(self):
"""Returns true if the collated counts in `self._results` appear to be normalized.
Notes
-----
It's possible that the _results df has already been normalized, which can cause some
methods to fail. This method lets us guess whether that's true and act... | Returns true if the collated counts in `self._results` appear to be normalized.
Notes
-----
It's possible that the _results df has already been normalized, which can cause some
methods to fail. This method lets us guess whether that's true and act accordingly. | Below is the the instruction that describes the task:
### Input:
Returns true if the collated counts in `self._results` appear to be normalized.
Notes
-----
It's possible that the _results df has already been normalized, which can cause some
methods to fail. This method lets us gues... |
def add(self, instance, modified=True, **params):
'''Add an ``instance`` to the session.
If the session is not in a
:ref:`transactional state <transactional-state>`, this operation
commits changes to the back-end server immediately.
:parameter instance: a :class:`Model` ... | Add an ``instance`` to the session.
If the session is not in a
:ref:`transactional state <transactional-state>`, this operation
commits changes to the back-end server immediately.
:parameter instance: a :class:`Model` instance. It must be registered
with the :attr:`r... | Below is the the instruction that describes the task:
### Input:
Add an ``instance`` to the session.
If the session is not in a
:ref:`transactional state <transactional-state>`, this operation
commits changes to the back-end server immediately.
:parameter instance: a :class:`... |
def export(self, swf, frame, **export_opts):
""" Exports a frame of the specified SWF to SVG.
@param swf The SWF.
@param frame Which frame to export, by 0-based index (int)
"""
self.wanted_frame = frame
return super(FrameSVGExporterMixin, self).export(swf, *export_opts... | Exports a frame of the specified SWF to SVG.
@param swf The SWF.
@param frame Which frame to export, by 0-based index (int) | Below is the the instruction that describes the task:
### Input:
Exports a frame of the specified SWF to SVG.
@param swf The SWF.
@param frame Which frame to export, by 0-based index (int)
### Response:
def export(self, swf, frame, **export_opts):
""" Exports a frame of the specified SWF... |
def fcat(*fs):
"""Concatenate a sequence of farrays.
The variadic *fs* input is a homogeneous sequence of functions or arrays.
"""
items = list()
for f in fs:
if isinstance(f, boolfunc.Function):
items.append(f)
elif isinstance(f, farray):
items.extend(f.flat... | Concatenate a sequence of farrays.
The variadic *fs* input is a homogeneous sequence of functions or arrays. | Below is the the instruction that describes the task:
### Input:
Concatenate a sequence of farrays.
The variadic *fs* input is a homogeneous sequence of functions or arrays.
### Response:
def fcat(*fs):
"""Concatenate a sequence of farrays.
The variadic *fs* input is a homogeneous sequence of functio... |
def solvedbd_sm(ah, d, b, c=None, axis=4):
r"""
Solve a diagonal block linear system with a diagonal term
using the Sherman-Morrison equation.
The solution is obtained by independently solving a set of linear
systems of the form (see :cite:`wohlberg-2016-efficient`)
.. math::
(\mathbf{d}... | r"""
Solve a diagonal block linear system with a diagonal term
using the Sherman-Morrison equation.
The solution is obtained by independently solving a set of linear
systems of the form (see :cite:`wohlberg-2016-efficient`)
.. math::
(\mathbf{d} + \mathbf{a} \mathbf{a}^H ) \; \mathbf{x} = \... | Below is the the instruction that describes the task:
### Input:
r"""
Solve a diagonal block linear system with a diagonal term
using the Sherman-Morrison equation.
The solution is obtained by independently solving a set of linear
systems of the form (see :cite:`wohlberg-2016-efficient`)
.. ma... |
def authorize(self):
"""Authenticates the superuser account via the web login."""
response = self.client.login(username=self.USERNAME,
password=self.PASSWORD)
self.assertTrue(response)
self.authed = True | Authenticates the superuser account via the web login. | Below is the the instruction that describes the task:
### Input:
Authenticates the superuser account via the web login.
### Response:
def authorize(self):
"""Authenticates the superuser account via the web login."""
response = self.client.login(username=self.USERNAME,
password=self.PAS... |
def ip_between(ip, start, finish):
"""Checks to see if IP is between start and finish"""
if is_IPv4Address(ip) and is_IPv4Address(start) and is_IPv4Address(finish):
return IPAddress(ip) in IPRange(start, finish)
else:
return False | Checks to see if IP is between start and finish | Below is the the instruction that describes the task:
### Input:
Checks to see if IP is between start and finish
### Response:
def ip_between(ip, start, finish):
"""Checks to see if IP is between start and finish"""
if is_IPv4Address(ip) and is_IPv4Address(start) and is_IPv4Address(finish):
return... |
def readfrom(fpath, aslines=False, errors='replace', verbose=None):
"""
Reads (utf8) text from a file.
Args:
fpath (PathLike): file path
aslines (bool): if True returns list of lines
verbose (bool): verbosity flag
Returns:
str: text from fpath (this is unicode)
"""
... | Reads (utf8) text from a file.
Args:
fpath (PathLike): file path
aslines (bool): if True returns list of lines
verbose (bool): verbosity flag
Returns:
str: text from fpath (this is unicode) | Below is the the instruction that describes the task:
### Input:
Reads (utf8) text from a file.
Args:
fpath (PathLike): file path
aslines (bool): if True returns list of lines
verbose (bool): verbosity flag
Returns:
str: text from fpath (this is unicode)
### Response:
def ... |
def get_values(self):
"""
Applies parsing functions to each input as specified in init before returning a tuple with first entry being a boolean which specifies if the user entered all values and a second entry which is a dictionary of input names to parsed values.
"""
return_dict = {}
... | Applies parsing functions to each input as specified in init before returning a tuple with first entry being a boolean which specifies if the user entered all values and a second entry which is a dictionary of input names to parsed values. | Below is the the instruction that describes the task:
### Input:
Applies parsing functions to each input as specified in init before returning a tuple with first entry being a boolean which specifies if the user entered all values and a second entry which is a dictionary of input names to parsed values.
### Respons... |
def _getChar(self, char_spec):
"""
Returns character from given code point or character.
"""
if len(char_spec) >= 4 and all(c in string.hexdigits for c in char_spec):
char_number = int(char_spec, 16)
if char_number not in range(0x110000):
raise Val... | Returns character from given code point or character. | Below is the the instruction that describes the task:
### Input:
Returns character from given code point or character.
### Response:
def _getChar(self, char_spec):
"""
Returns character from given code point or character.
"""
if len(char_spec) >= 4 and all(c in string.hexdigits for ... |
def register_dataframe_method(method):
"""Register a function as a method attached to the Pandas DataFrame.
Example
-------
.. code-block:: python
@register_dataframe_method
def print_column(df, col):
'''Print the dataframe column given'''
print(df[col])
""... | Register a function as a method attached to the Pandas DataFrame.
Example
-------
.. code-block:: python
@register_dataframe_method
def print_column(df, col):
'''Print the dataframe column given'''
print(df[col]) | Below is the the instruction that describes the task:
### Input:
Register a function as a method attached to the Pandas DataFrame.
Example
-------
.. code-block:: python
@register_dataframe_method
def print_column(df, col):
'''Print the dataframe column given'''
... |
def encode_params(params, **kwargs):
"""Clean and JSON-encode a dict of parameters."""
cleaned = clean_params(params, **kwargs)
return json.dumps(cleaned) | Clean and JSON-encode a dict of parameters. | Below is the the instruction that describes the task:
### Input:
Clean and JSON-encode a dict of parameters.
### Response:
def encode_params(params, **kwargs):
"""Clean and JSON-encode a dict of parameters."""
cleaned = clean_params(params, **kwargs)
return json.dumps(cleaned) |
def score(self, testing_features, testing_labels):
"""estimates accuracy on testing set"""
# print("test features shape:",testing_features.shape)
# print("testing labels shape:",testing_labels.shape)
yhat = self.predict(testing_features)
return self.scoring_function(testing_label... | estimates accuracy on testing set | Below is the the instruction that describes the task:
### Input:
estimates accuracy on testing set
### Response:
def score(self, testing_features, testing_labels):
"""estimates accuracy on testing set"""
# print("test features shape:",testing_features.shape)
# print("testing labels shape:",... |
def filtered(self, indices):
"""
:param indices:
a subset of indices in the range [0 .. tot_sites - 1]
:returns:
a filtered SiteCollection instance if `indices` is a proper subset
of the available indices, otherwise returns the full SiteCollection
"""
... | :param indices:
a subset of indices in the range [0 .. tot_sites - 1]
:returns:
a filtered SiteCollection instance if `indices` is a proper subset
of the available indices, otherwise returns the full SiteCollection | Below is the the instruction that describes the task:
### Input:
:param indices:
a subset of indices in the range [0 .. tot_sites - 1]
:returns:
a filtered SiteCollection instance if `indices` is a proper subset
of the available indices, otherwise returns the full SiteCollec... |
def call_actions(self, event, *args, **kwargs):
"""Call each function in self._actions after setting self._event."""
self._event = event
for func in self._actions:
func(event, *args, **kwargs) | Call each function in self._actions after setting self._event. | Below is the the instruction that describes the task:
### Input:
Call each function in self._actions after setting self._event.
### Response:
def call_actions(self, event, *args, **kwargs):
"""Call each function in self._actions after setting self._event."""
self._event = event
for func in... |
def get_result(self, indices_or_msg_ids=None, block=None):
"""Retrieve a result by msg_id or history index, wrapped in an AsyncResult object.
If the client already has the results, no request to the Hub will be made.
This is a convenient way to construct AsyncResult objects, which are wrappers... | Retrieve a result by msg_id or history index, wrapped in an AsyncResult object.
If the client already has the results, no request to the Hub will be made.
This is a convenient way to construct AsyncResult objects, which are wrappers
that include metadata about execution, and allow for awaiting... | Below is the the instruction that describes the task:
### Input:
Retrieve a result by msg_id or history index, wrapped in an AsyncResult object.
If the client already has the results, no request to the Hub will be made.
This is a convenient way to construct AsyncResult objects, which are wrappers
... |
def forward(self, # pylint: disable=arguments-differ
inputs: torch.Tensor,
mask: torch.LongTensor) -> torch.Tensor:
"""
Parameters
----------
inputs : ``torch.Tensor``, required.
A Tensor of shape ``(batch_size, sequence_length, hidden_size)``... | Parameters
----------
inputs : ``torch.Tensor``, required.
A Tensor of shape ``(batch_size, sequence_length, hidden_size)``.
mask : ``torch.LongTensor``, required.
A binary mask of shape ``(batch_size, sequence_length)`` representing the
non-padded elements in... | Below is the the instruction that describes the task:
### Input:
Parameters
----------
inputs : ``torch.Tensor``, required.
A Tensor of shape ``(batch_size, sequence_length, hidden_size)``.
mask : ``torch.LongTensor``, required.
A binary mask of shape ``(batch_size, s... |
def human_time(seconds):
''' DocTests:
>>> human_time(0) == ''
True
>>> human_time(122.1) == '2m2s'
True
>>> human_time(133) == '2m13s'
True
>>> human_time(12345678) == '20W2D21h21m18s'
True
'''
isec = int(seconds)
s = isec % 60
m = isec // 60 % 60
h = isec // 60 // 60 % 24
d = isec // 60 // 60 // 24 % 7... | DocTests:
>>> human_time(0) == ''
True
>>> human_time(122.1) == '2m2s'
True
>>> human_time(133) == '2m13s'
True
>>> human_time(12345678) == '20W2D21h21m18s'
True | Below is the the instruction that describes the task:
### Input:
DocTests:
>>> human_time(0) == ''
True
>>> human_time(122.1) == '2m2s'
True
>>> human_time(133) == '2m13s'
True
>>> human_time(12345678) == '20W2D21h21m18s'
True
### Response:
def human_time(seconds):
''' DocTests:
>>> human_time(0) == ''
... |
def calc_weight_of_multiple_paths(path_scores, impact_div=12):
"""Caluculate the weight of multipe paths."""
number_of_paths = len(path_scores)
if number_of_paths > 1:
score_total = 0.0
highest_score = 0.0
for score in path_scores.Scores:
score_total += score
... | Caluculate the weight of multipe paths. | Below is the the instruction that describes the task:
### Input:
Caluculate the weight of multipe paths.
### Response:
def calc_weight_of_multiple_paths(path_scores, impact_div=12):
"""Caluculate the weight of multipe paths."""
number_of_paths = len(path_scores)
if number_of_paths > 1:
score_to... |
def stop(self):
"""Stop stream."""
if self.stream and self.stream.session.state != STATE_STOPPED:
self.stream.stop() | Stop stream. | Below is the the instruction that describes the task:
### Input:
Stop stream.
### Response:
def stop(self):
"""Stop stream."""
if self.stream and self.stream.session.state != STATE_STOPPED:
self.stream.stop() |
def ApplyEdit(self, row, col, grid):
"""
This function should save the value of the control into the
grid or grid table. It is called only after EndEdit() returns
a non-None value.
*Must Override*
"""
val = self._tc.GetValue()
grid.GetTable().SetValue(row... | This function should save the value of the control into the
grid or grid table. It is called only after EndEdit() returns
a non-None value.
*Must Override* | Below is the the instruction that describes the task:
### Input:
This function should save the value of the control into the
grid or grid table. It is called only after EndEdit() returns
a non-None value.
*Must Override*
### Response:
def ApplyEdit(self, row, col, grid):
"""
... |
async def _cache_and_maybe_retract_mount(self, mount: top_types.Mount):
""" Retract the 'other' mount if necessary
If `mount` does not match the value in :py:attr:`_last_moved_mount`
(and :py:attr:`_last_moved_mount` exists) then retract the mount
in :py:attr:`_last_moved_mount`. Also u... | Retract the 'other' mount if necessary
If `mount` does not match the value in :py:attr:`_last_moved_mount`
(and :py:attr:`_last_moved_mount` exists) then retract the mount
in :py:attr:`_last_moved_mount`. Also unconditionally update
:py:attr:`_last_moved_mount` to contain `mount`. | Below is the the instruction that describes the task:
### Input:
Retract the 'other' mount if necessary
If `mount` does not match the value in :py:attr:`_last_moved_mount`
(and :py:attr:`_last_moved_mount` exists) then retract the mount
in :py:attr:`_last_moved_mount`. Also unconditionally ... |
def safe_to_file(folder, results):
"""
Receives a list of results (type :class:`Clazz` or :class:`Function`), and put them into the right files in :var:`folder`
:param folder: Where the files should be in.
:type folder: str
:param results: A list of :class:`Clazz` or :class:`Function` objects, wh... | Receives a list of results (type :class:`Clazz` or :class:`Function`), and put them into the right files in :var:`folder`
:param folder: Where the files should be in.
:type folder: str
:param results: A list of :class:`Clazz` or :class:`Function` objects, which will be used to calculate the source code.
... | Below is the the instruction that describes the task:
### Input:
Receives a list of results (type :class:`Clazz` or :class:`Function`), and put them into the right files in :var:`folder`
:param folder: Where the files should be in.
:type folder: str
:param results: A list of :class:`Clazz` or :class:... |
def _init_rate_limit(self):
"""Initialize rate limit information"""
url = urijoin(self.base_url, 'projects', self.owner + '%2F' + self.repository)
try:
response = super().fetch(url)
self.update_rate_limit(response)
except requests.exceptions.HTTPError as error:
... | Initialize rate limit information | Below is the the instruction that describes the task:
### Input:
Initialize rate limit information
### Response:
def _init_rate_limit(self):
"""Initialize rate limit information"""
url = urijoin(self.base_url, 'projects', self.owner + '%2F' + self.repository)
try:
response = su... |
def check_perms(parser, token):
"""
Returns a list of permissions (as ``codename`` strings) for a given
``user``/``group`` and ``obj`` (Model instance).
Parses ``check_perms`` tag which should be in format::
{% check_perms "perm1[, perm2, ...]" for user in slug as "context_var" %}
or
... | Returns a list of permissions (as ``codename`` strings) for a given
``user``/``group`` and ``obj`` (Model instance).
Parses ``check_perms`` tag which should be in format::
{% check_perms "perm1[, perm2, ...]" for user in slug as "context_var" %}
or
{% check_perms "perm1[, perm2, ...]" fo... | Below is the the instruction that describes the task:
### Input:
Returns a list of permissions (as ``codename`` strings) for a given
``user``/``group`` and ``obj`` (Model instance).
Parses ``check_perms`` tag which should be in format::
{% check_perms "perm1[, perm2, ...]" for user in slug as "con... |
def normalize_missing(xs):
"""Normalize missing values to avoid string 'None' inputs.
"""
if isinstance(xs, dict):
for k, v in xs.items():
xs[k] = normalize_missing(v)
elif isinstance(xs, (list, tuple)):
xs = [normalize_missing(x) for x in xs]
elif isinstance(xs, six.stri... | Normalize missing values to avoid string 'None' inputs. | Below is the the instruction that describes the task:
### Input:
Normalize missing values to avoid string 'None' inputs.
### Response:
def normalize_missing(xs):
"""Normalize missing values to avoid string 'None' inputs.
"""
if isinstance(xs, dict):
for k, v in xs.items():
xs[k] = n... |
def update_attribute(self, attr, value):
"""Set the value of a workspace attribute."""
update = [fapi._attr_up(attr, value)]
r = fapi.update_workspace_attributes(self.namespace, self.name,
update, self.api_url)
fapi._check_response_code(r, 200... | Set the value of a workspace attribute. | Below is the the instruction that describes the task:
### Input:
Set the value of a workspace attribute.
### Response:
def update_attribute(self, attr, value):
"""Set the value of a workspace attribute."""
update = [fapi._attr_up(attr, value)]
r = fapi.update_workspace_attributes(self.names... |
def report_alerts(alerts, output_format='table'):
"""
Print our alerts in the given format.
"""
num_alerts = len(alerts)
if output_format == 'json':
click.echo(json.dumps(alerts, indent=4))
else:
console.info('Issues found: {0}'.format(num_alerts))
if num_alerts > 0:
... | Print our alerts in the given format. | Below is the the instruction that describes the task:
### Input:
Print our alerts in the given format.
### Response:
def report_alerts(alerts, output_format='table'):
"""
Print our alerts in the given format.
"""
num_alerts = len(alerts)
if output_format == 'json':
click.echo(json.dump... |
def export_svg(self):
""" Exports the path as SVG.
Uses the filename given when creating this object.
The file is automatically updated to reflect
changes to the path.
"""
d = ""
if len(self._points) > 0:
d += "M "+s... | Exports the path as SVG.
Uses the filename given when creating this object.
The file is automatically updated to reflect
changes to the path. | Below is the the instruction that describes the task:
### Input:
Exports the path as SVG.
Uses the filename given when creating this object.
The file is automatically updated to reflect
changes to the path.
### Response:
def export_svg(self):
""" Exports the path a... |
def get_main_doc(self):
"""Returns PyQuery object for the main season URL.
:returns: PyQuery object.
"""
url = (sportsref.nba.BASE_URL +
'/leagues/NBA_{}.html'.format(self.yr))
return pq(sportsref.utils.get_html(url)) | Returns PyQuery object for the main season URL.
:returns: PyQuery object. | Below is the the instruction that describes the task:
### Input:
Returns PyQuery object for the main season URL.
:returns: PyQuery object.
### Response:
def get_main_doc(self):
"""Returns PyQuery object for the main season URL.
:returns: PyQuery object.
"""
url = (sportsref.... |
def update(self, enabled=None, cnames=None, comment=None):
"""
Update the configuration of the StreamingDistribution. The only values
of the StreamingDistributionConfig that can be directly updated are:
* CNAMES
* Comment
* Whether the Distribution is enabled or not
... | Update the configuration of the StreamingDistribution. The only values
of the StreamingDistributionConfig that can be directly updated are:
* CNAMES
* Comment
* Whether the Distribution is enabled or not
Any changes to the ``trusted_signers`` or ``origin`` properties of
... | Below is the the instruction that describes the task:
### Input:
Update the configuration of the StreamingDistribution. The only values
of the StreamingDistributionConfig that can be directly updated are:
* CNAMES
* Comment
* Whether the Distribution is enabled or not
A... |
def application_simple_state(context, application):
""" Render current state of application, verbose. """
state_machine = get_state_machine(application)
state = state_machine.get_state(application)
return state.name | Render current state of application, verbose. | Below is the the instruction that describes the task:
### Input:
Render current state of application, verbose.
### Response:
def application_simple_state(context, application):
""" Render current state of application, verbose. """
state_machine = get_state_machine(application)
state = state_machine.get... |
def chunks(self, shape=256, pad=False):
"""This method returns GeoRaster chunks out of the original raster.
The chunck is evaluated only when fetched from the iterator.
Useful when you want to iterate over a big rasters.
Parameters
----------
shape : int or tuple, optio... | This method returns GeoRaster chunks out of the original raster.
The chunck is evaluated only when fetched from the iterator.
Useful when you want to iterate over a big rasters.
Parameters
----------
shape : int or tuple, optional
The shape of the chunk. Default: 25... | Below is the the instruction that describes the task:
### Input:
This method returns GeoRaster chunks out of the original raster.
The chunck is evaluated only when fetched from the iterator.
Useful when you want to iterate over a big rasters.
Parameters
----------
shape : i... |
def UNas(self, to='name_short'):
"""
Return UN member states in the specified classification
Parameters
----------
to : str, optional
Output classification (valid str for an index of
country_data file), default: name_short
Returns
-------... | Return UN member states in the specified classification
Parameters
----------
to : str, optional
Output classification (valid str for an index of
country_data file), default: name_short
Returns
-------
Pandas DataFrame | Below is the the instruction that describes the task:
### Input:
Return UN member states in the specified classification
Parameters
----------
to : str, optional
Output classification (valid str for an index of
country_data file), default: name_short
Returns... |
def configure_security_group_ingress(self, security_group_id, port, desired_cidr_blocks):
"""Configures the security group ID allowing access
only to the specified CIDR blocks, for the specified
port number.
:param security_group_id: (str) Security Group ID
:param port: (str) TC... | Configures the security group ID allowing access
only to the specified CIDR blocks, for the specified
port number.
:param security_group_id: (str) Security Group ID
:param port: (str) TCP Port number
:param desired_cidr_blocks: (list) List of desired CIDR
blocks, ... | Below is the the instruction that describes the task:
### Input:
Configures the security group ID allowing access
only to the specified CIDR blocks, for the specified
port number.
:param security_group_id: (str) Security Group ID
:param port: (str) TCP Port number
:param des... |
def applymap(self, func):
"""
Apply a function to a Dataframe elementwise.
This method applies a function that accepts and returns a scalar
to every element of a DataFrame.
Parameters
----------
func : callable
Python function, returns a single value... | Apply a function to a Dataframe elementwise.
This method applies a function that accepts and returns a scalar
to every element of a DataFrame.
Parameters
----------
func : callable
Python function, returns a single value from a single value.
Returns
... | Below is the the instruction that describes the task:
### Input:
Apply a function to a Dataframe elementwise.
This method applies a function that accepts and returns a scalar
to every element of a DataFrame.
Parameters
----------
func : callable
Python function,... |
def plan(self):
"""Create website CFN module and run stacker diff."""
if self.options.get('environments', {}).get(self.context.env_name):
self.setup_website_module(command='plan')
else:
LOGGER.info("Skipping staticsite plan of %s; no environment "
... | Create website CFN module and run stacker diff. | Below is the the instruction that describes the task:
### Input:
Create website CFN module and run stacker diff.
### Response:
def plan(self):
"""Create website CFN module and run stacker diff."""
if self.options.get('environments', {}).get(self.context.env_name):
self.setup_website_mod... |
def find_by(cls, parent=None, **attributes):
"""
Gets the first resource of the given type and parent (if provided) with matching attributes.
This will trigger an api GET request.
:param parent ResourceBase: the parent of the resource - used for nesting the request url, optional
... | Gets the first resource of the given type and parent (if provided) with matching attributes.
This will trigger an api GET request.
:param parent ResourceBase: the parent of the resource - used for nesting the request url, optional
:param **attributes: any number of keyword arguments as attribute... | Below is the the instruction that describes the task:
### Input:
Gets the first resource of the given type and parent (if provided) with matching attributes.
This will trigger an api GET request.
:param parent ResourceBase: the parent of the resource - used for nesting the request url, optional
... |
def update_lbaas_member(self, lbaas_member, lbaas_pool, body=None):
"""Updates a lbaas_member."""
return self.put(self.lbaas_member_path % (lbaas_pool, lbaas_member),
body=body) | Updates a lbaas_member. | Below is the the instruction that describes the task:
### Input:
Updates a lbaas_member.
### Response:
def update_lbaas_member(self, lbaas_member, lbaas_pool, body=None):
"""Updates a lbaas_member."""
return self.put(self.lbaas_member_path % (lbaas_pool, lbaas_member),
body=... |
def compile(pattern, flags, code, groups=0, groupindex={}, indexgroup=[None]):
"""Compiles (or rather just converts) a pattern descriptor to a SRE_Pattern
object. Actual compilation to opcodes happens in sre_compile."""
return SRE_Pattern(pattern, flags, code, groups, groupindex, indexgroup) | Compiles (or rather just converts) a pattern descriptor to a SRE_Pattern
object. Actual compilation to opcodes happens in sre_compile. | Below is the the instruction that describes the task:
### Input:
Compiles (or rather just converts) a pattern descriptor to a SRE_Pattern
object. Actual compilation to opcodes happens in sre_compile.
### Response:
def compile(pattern, flags, code, groups=0, groupindex={}, indexgroup=[None]):
"""Compiles (o... |
def save(self, force_insert=False, force_update=False, *args, **kwargs):
"""
Makes sure we are in sync with the User field
"""
self.first_name = self.user.first_name
self.last_name = self.user.last_name
self.email = self.user.email
full_name = '%s %s' % (self.firs... | Makes sure we are in sync with the User field | Below is the the instruction that describes the task:
### Input:
Makes sure we are in sync with the User field
### Response:
def save(self, force_insert=False, force_update=False, *args, **kwargs):
"""
Makes sure we are in sync with the User field
"""
self.first_name = self.user.fir... |
def validate_settings(settings):
"""
Raise an error in prod if we see any insecure settings.
This used to warn during development but that was changed in
71718bec324c2561da6cc3990c927ee87362f0f7
"""
from django.core.exceptions import ImproperlyConfigured
if settings.SECRET_KEY == '':
... | Raise an error in prod if we see any insecure settings.
This used to warn during development but that was changed in
71718bec324c2561da6cc3990c927ee87362f0f7 | Below is the the instruction that describes the task:
### Input:
Raise an error in prod if we see any insecure settings.
This used to warn during development but that was changed in
71718bec324c2561da6cc3990c927ee87362f0f7
### Response:
def validate_settings(settings):
"""
Raise an error in prod i... |
def tickets_create_many(self, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/tickets#create-many-tickets"
api_path = "/api/v2/tickets/create_many.json"
return self.call(api_path, method="POST", data=data, **kwargs) | https://developer.zendesk.com/rest_api/docs/core/tickets#create-many-tickets | Below is the the instruction that describes the task:
### Input:
https://developer.zendesk.com/rest_api/docs/core/tickets#create-many-tickets
### Response:
def tickets_create_many(self, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/tickets#create-many-tickets"
api_path = "/api/... |
def estimate_hr(self,R,z=0.,dR=10.**-8.,**kwargs):
"""
NAME:
estimate_hr
PURPOSE:
estimate the exponential scale length at R
INPUT:
R - Galactocentric radius (can be Quantity)
z= height (default: 0 pc) (can be Quantity)
dR- ra... | NAME:
estimate_hr
PURPOSE:
estimate the exponential scale length at R
INPUT:
R - Galactocentric radius (can be Quantity)
z= height (default: 0 pc) (can be Quantity)
dR- range in R to use (can be Quantity)
density kwargs
O... | Below is the the instruction that describes the task:
### Input:
NAME:
estimate_hr
PURPOSE:
estimate the exponential scale length at R
INPUT:
R - Galactocentric radius (can be Quantity)
z= height (default: 0 pc) (can be Quantity)
dR- rang... |
def recursive_chmod(path, mode=0755):
"""
Recursively change ``mode`` for given ``path``. Same as ``chmod -R mode``.
Args:
path (str): Path of the directory/file.
mode (octal int, default 0755): New mode of the file.
Warning:
Don't forget to add ``0`` at the beginning of the nu... | Recursively change ``mode`` for given ``path``. Same as ``chmod -R mode``.
Args:
path (str): Path of the directory/file.
mode (octal int, default 0755): New mode of the file.
Warning:
Don't forget to add ``0`` at the beginning of the numbers of `mode`, or
`Unspeakable hOrRoRs` ... | Below is the the instruction that describes the task:
### Input:
Recursively change ``mode`` for given ``path``. Same as ``chmod -R mode``.
Args:
path (str): Path of the directory/file.
mode (octal int, default 0755): New mode of the file.
Warning:
Don't forget to add ``0`` at the ... |
def load_from_name(module_name):
"""
从python module文件中获取配置
:param module_name:
:return:
"""
global _CONFIG_CACHE
if module_name not in _CONFIG_CACHE:
settings = OrderedDict()
if isinstance(module_name, six.string_types):
settings = _load_from_module(_import_module... | 从python module文件中获取配置
:param module_name:
:return: | Below is the the instruction that describes the task:
### Input:
从python module文件中获取配置
:param module_name:
:return:
### Response:
def load_from_name(module_name):
"""
从python module文件中获取配置
:param module_name:
:return:
"""
global _CONFIG_CACHE
if module_name not in _CONFIG_CACHE:... |
def gce_list(service=None, **kwargs):
"""General list function for the GCE service."""
resp_list = []
req = service.list(**kwargs)
while req is not None:
resp = req.execute()
for item in resp.get('items', []):
resp_list.append(item)
req = service.list_next(previous_r... | General list function for the GCE service. | Below is the the instruction that describes the task:
### Input:
General list function for the GCE service.
### Response:
def gce_list(service=None, **kwargs):
"""General list function for the GCE service."""
resp_list = []
req = service.list(**kwargs)
while req is not None:
resp = req.exe... |
def sendInstanceChange(self, view_no: int,
suspicion=Suspicions.PRIMARY_DEGRADED):
"""
Broadcast an instance change request to all the remaining nodes
:param view_no: the view number when the instance change is requested
"""
# If not found any sent in... | Broadcast an instance change request to all the remaining nodes
:param view_no: the view number when the instance change is requested | Below is the the instruction that describes the task:
### Input:
Broadcast an instance change request to all the remaining nodes
:param view_no: the view number when the instance change is requested
### Response:
def sendInstanceChange(self, view_no: int,
suspicion=Suspicions.PR... |
def create_pool(hostname, username, password, name, members=None,
allow_nat=None,
allow_snat=None,
description=None,
gateway_failsafe_device=None,
ignore_persisted_weight=None,
ip_tos_to_client=None,
ip_tos_t... | A function to connect to a bigip device and create a pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to create.
members
List of comma delimited pool members ... | Below is the the instruction that describes the task:
### Input:
A function to connect to a bigip device and create a pool.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool... |
def create(cls, data, id_=None, **kwargs):
r"""Create a new record instance and store it in the database.
#. Send a signal :data:`invenio_records.signals.before_record_insert`
with the new record as parameter.
#. Validate the new record data.
#. Add the new record in the da... | r"""Create a new record instance and store it in the database.
#. Send a signal :data:`invenio_records.signals.before_record_insert`
with the new record as parameter.
#. Validate the new record data.
#. Add the new record in the database.
#. Send a signal :data:`invenio_re... | Below is the the instruction that describes the task:
### Input:
r"""Create a new record instance and store it in the database.
#. Send a signal :data:`invenio_records.signals.before_record_insert`
with the new record as parameter.
#. Validate the new record data.
#. Add the ne... |
def _get_name(self, name):
"""
Find a team's name and abbreviation.
Given the team's HTML name tag, determine their name, and abbreviation.
Parameters
----------
name : PyQuery object
A PyQuery object of a team's HTML name tag in the boxscore.
Retur... | Find a team's name and abbreviation.
Given the team's HTML name tag, determine their name, and abbreviation.
Parameters
----------
name : PyQuery object
A PyQuery object of a team's HTML name tag in the boxscore.
Returns
-------
tuple
Re... | Below is the the instruction that describes the task:
### Input:
Find a team's name and abbreviation.
Given the team's HTML name tag, determine their name, and abbreviation.
Parameters
----------
name : PyQuery object
A PyQuery object of a team's HTML name tag in the bo... |
def get_target_bucket(buckets: List[Tuple[int, int]],
length_target: int) -> Optional[Tuple[int, Tuple[int, int]]]:
"""
Returns bucket index and bucket from a list of buckets, given source and target length.
Returns (None, None) if no bucket fits.
:param buckets: List of buckets.
... | Returns bucket index and bucket from a list of buckets, given source and target length.
Returns (None, None) if no bucket fits.
:param buckets: List of buckets.
:param length_target: Length of target sequence.
:return: Tuple of (bucket index, bucket), or (None, None) if not fitting. | Below is the the instruction that describes the task:
### Input:
Returns bucket index and bucket from a list of buckets, given source and target length.
Returns (None, None) if no bucket fits.
:param buckets: List of buckets.
:param length_target: Length of target sequence.
:return: Tuple of (bucke... |
def encode_csv(data_dict, column_names):
"""Builds a csv string.
Args:
data_dict: dict of {column_name: 1 value}
column_names: list of column names
Returns:
A csv string version of data_dict
"""
import csv
import six
values = [str(data_dict[x]) for x in column_names]
str_buff = six.StringI... | Builds a csv string.
Args:
data_dict: dict of {column_name: 1 value}
column_names: list of column names
Returns:
A csv string version of data_dict | Below is the the instruction that describes the task:
### Input:
Builds a csv string.
Args:
data_dict: dict of {column_name: 1 value}
column_names: list of column names
Returns:
A csv string version of data_dict
### Response:
def encode_csv(data_dict, column_names):
"""Builds a csv string.
A... |
def healthy(self):
""" Return task health. If None - task is healthy, otherwise - maximum severity of sensors
:return: None or WTaskHealthSensor.WTaskSensorSeverity
"""
state = None
for sensor in self._sensors.values():
if sensor.healthy() is False:
if state is None or sensor.severity().value > state.... | Return task health. If None - task is healthy, otherwise - maximum severity of sensors
:return: None or WTaskHealthSensor.WTaskSensorSeverity | Below is the the instruction that describes the task:
### Input:
Return task health. If None - task is healthy, otherwise - maximum severity of sensors
:return: None or WTaskHealthSensor.WTaskSensorSeverity
### Response:
def healthy(self):
""" Return task health. If None - task is healthy, otherwise - maximum... |
def get_string(self, key, default=UndefinedKey):
"""Return string representation of value found at key
:param key: key to use (dot separated). E.g., a.b.c
:type key: basestring
:param default: default value if key not found
:type default: basestring
:return: string value... | Return string representation of value found at key
:param key: key to use (dot separated). E.g., a.b.c
:type key: basestring
:param default: default value if key not found
:type default: basestring
:return: string value
:type return: basestring | Below is the the instruction that describes the task:
### Input:
Return string representation of value found at key
:param key: key to use (dot separated). E.g., a.b.c
:type key: basestring
:param default: default value if key not found
:type default: basestring
:return: str... |
def load_data(self, filename, *args, **kwargs):
"""
Load text data from different sheets.
"""
# load text data
data = super(MixedTextXLS, self).load_data(filename)
# iterate through sheets in parameters
for sheet_params in self.parameters.itervalues():
... | Load text data from different sheets. | Below is the the instruction that describes the task:
### Input:
Load text data from different sheets.
### Response:
def load_data(self, filename, *args, **kwargs):
"""
Load text data from different sheets.
"""
# load text data
data = super(MixedTextXLS, self).load_data(file... |
def parse_export_request(request_str):
"""Parse a CIM-XML export request message, and return
a tuple(msgid, methodname, params).
"""
# Parse the XML into a tuple tree (may raise CIMXMLParseError or
# XMLParseError):
tt_ = xml_to_tupletree_sax(request_str, "CIM-XML expor... | Parse a CIM-XML export request message, and return
a tuple(msgid, methodname, params). | Below is the the instruction that describes the task:
### Input:
Parse a CIM-XML export request message, and return
a tuple(msgid, methodname, params).
### Response:
def parse_export_request(request_str):
"""Parse a CIM-XML export request message, and return
a tuple(msgid, methodname, param... |
def _preserve_settings(method: T.Callable) -> T.Callable:
"""Decorator that ensures ObservableProperty-specific attributes
are kept when using methods to change deleter, getter or setter."""
@functools.wraps(method)
def _wrapper(
old: "ObservableProperty", handler: T.Callable
) -> "Obse... | Decorator that ensures ObservableProperty-specific attributes
are kept when using methods to change deleter, getter or setter. | Below is the the instruction that describes the task:
### Input:
Decorator that ensures ObservableProperty-specific attributes
are kept when using methods to change deleter, getter or setter.
### Response:
def _preserve_settings(method: T.Callable) -> T.Callable:
"""Decorator that ensures ObservablePropert... |
def set_uint_info(self, field, data):
"""Set uint type property into the DMatrix.
Parameters
----------
field: str
The field name of the information
data: numpy array
The array of data to be set
"""
if getattr(data, 'base', None) is not N... | Set uint type property into the DMatrix.
Parameters
----------
field: str
The field name of the information
data: numpy array
The array of data to be set | Below is the the instruction that describes the task:
### Input:
Set uint type property into the DMatrix.
Parameters
----------
field: str
The field name of the information
data: numpy array
The array of data to be set
### Response:
def set_uint_info(self, ... |
def filter_genes_dispersion(data,
flavor='seurat',
min_disp=None, max_disp=None,
min_mean=None, max_mean=None,
n_bins=20,
n_top_genes=None,
log=True,
... | Extract highly variable genes [Satija15]_ [Zheng17]_.
.. warning::
.. deprecated:: 1.3.6
Use :func:`~scanpy.api.pp.highly_variable_genes`
instead. The new function is equivalent to the present
function, except that
* the new function always expects logarithm... | Below is the the instruction that describes the task:
### Input:
Extract highly variable genes [Satija15]_ [Zheng17]_.
.. warning::
.. deprecated:: 1.3.6
Use :func:`~scanpy.api.pp.highly_variable_genes`
instead. The new function is equivalent to the present
function,... |
def _maybe_start_instance(instance):
"""Starts instance if it's stopped, no-op otherwise."""
if not instance:
return
if instance.state['Name'] == 'stopped':
instance.start()
while True:
print(f"Waiting for {instance} to start.")
instance.reload()
if instance.state['Name'] == 'runn... | Starts instance if it's stopped, no-op otherwise. | Below is the the instruction that describes the task:
### Input:
Starts instance if it's stopped, no-op otherwise.
### Response:
def _maybe_start_instance(instance):
"""Starts instance if it's stopped, no-op otherwise."""
if not instance:
return
if instance.state['Name'] == 'stopped':
instance.star... |
def recv_until(self, s, max_size=None, timeout='default'):
"""
Recieve data from the socket until the given substring is observed.
Data in the same datagram as the substring, following the substring,
will not be returned and will be cached for future receives.
Aliases: read_unti... | Recieve data from the socket until the given substring is observed.
Data in the same datagram as the substring, following the substring,
will not be returned and will be cached for future receives.
Aliases: read_until, readuntil, recvuntil | Below is the the instruction that describes the task:
### Input:
Recieve data from the socket until the given substring is observed.
Data in the same datagram as the substring, following the substring,
will not be returned and will be cached for future receives.
Aliases: read_until, readunt... |
def close_other_windows(self):
"""
Closes all not current windows. Useful for tests - after each test you
can automatically close all windows.
"""
main_window_handle = self.current_window_handle
for window_handle in self.window_handles:
if window_handle == mai... | Closes all not current windows. Useful for tests - after each test you
can automatically close all windows. | Below is the the instruction that describes the task:
### Input:
Closes all not current windows. Useful for tests - after each test you
can automatically close all windows.
### Response:
def close_other_windows(self):
"""
Closes all not current windows. Useful for tests - after each test yo... |
def connect(url=None, schema=None, sql_path=None, multiprocessing=False):
"""Open a new connection to postgres via psycopg2/sqlalchemy
"""
if url is None:
url = os.environ.get("DATABASE_URL")
return Database(url, schema, sql_path=sql_path, multiprocessing=multiprocessing) | Open a new connection to postgres via psycopg2/sqlalchemy | Below is the the instruction that describes the task:
### Input:
Open a new connection to postgres via psycopg2/sqlalchemy
### Response:
def connect(url=None, schema=None, sql_path=None, multiprocessing=False):
"""Open a new connection to postgres via psycopg2/sqlalchemy
"""
if url is None:
url... |
def validate_version(self, service_id, version_number):
"""Validate the version for a particular service and version."""
content = self._fetch("/service/%s/version/%d/validate" % (service_id, version_number))
return self._status(content) | Validate the version for a particular service and version. | Below is the the instruction that describes the task:
### Input:
Validate the version for a particular service and version.
### Response:
def validate_version(self, service_id, version_number):
"""Validate the version for a particular service and version."""
content = self._fetch("/service/%s/version/%d/valida... |
def select_leaves(self, name):
"""Returns all leaves under all nodes matching name
"""
if self.is_leaf:
return [self] if re.search(name, self.label) else []
else:
leaves = []
if re.search(name, self.label):
for c in self.children:
... | Returns all leaves under all nodes matching name | Below is the the instruction that describes the task:
### Input:
Returns all leaves under all nodes matching name
### Response:
def select_leaves(self, name):
"""Returns all leaves under all nodes matching name
"""
if self.is_leaf:
return [self] if re.search(name, self.label) ... |
def get_parser():
"""Return the parser object for this script."""
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
parser = ArgumentParser(description=__doc__,
formatter_class=ArgumentDefaultsHelpFormatter)
parser.add_argument("-n",
d... | Return the parser object for this script. | Below is the the instruction that describes the task:
### Input:
Return the parser object for this script.
### Response:
def get_parser():
"""Return the parser object for this script."""
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
parser = ArgumentParser(description=__doc__,
... |
def get(self, sid):
"""
Constructs a ParticipantContext
:param sid: The sid
:returns: twilio.rest.video.v1.room.room_participant.ParticipantContext
:rtype: twilio.rest.video.v1.room.room_participant.ParticipantContext
"""
return ParticipantContext(self._version,... | Constructs a ParticipantContext
:param sid: The sid
:returns: twilio.rest.video.v1.room.room_participant.ParticipantContext
:rtype: twilio.rest.video.v1.room.room_participant.ParticipantContext | Below is the the instruction that describes the task:
### Input:
Constructs a ParticipantContext
:param sid: The sid
:returns: twilio.rest.video.v1.room.room_participant.ParticipantContext
:rtype: twilio.rest.video.v1.room.room_participant.ParticipantContext
### Response:
def get(self, si... |
def _surf_smooth_single(image,outfile,dilation,smooth,threshold,inflation,alpha,
cut_idx,cut_side,overlay,overlay_mask,overlay_cmap,overlay_scale,
overlay_alpha,rotation,grayscale,bg_grayscale,verbose):
"""
Generate a surface of the smooth white matter of a brain image.
This is great for displayi... | Generate a surface of the smooth white matter of a brain image.
This is great for displaying functional activations as are typically seen
in the neuroimaging literature.
Arguments
---------
image : ANTsImage
A binary segmentation of the white matter surface.
If you don't have a wh... | Below is the the instruction that describes the task:
### Input:
Generate a surface of the smooth white matter of a brain image.
This is great for displaying functional activations as are typically seen
in the neuroimaging literature.
Arguments
---------
image : ANTsImage
A binary seg... |
def next_generation(self, mut_rate=0, max_mut_amt=0, log_base=10):
'''Generates the next population from a previously evaluated generation
Args:
mut_rate (float): mutation rate for new members (0.0 - 1.0)
max_mut_amt (float): how much the member is allowed to mutate
... | Generates the next population from a previously evaluated generation
Args:
mut_rate (float): mutation rate for new members (0.0 - 1.0)
max_mut_amt (float): how much the member is allowed to mutate
(0.0 - 1.0, proportion change of mutated parameter)
log_base (... | Below is the the instruction that describes the task:
### Input:
Generates the next population from a previously evaluated generation
Args:
mut_rate (float): mutation rate for new members (0.0 - 1.0)
max_mut_amt (float): how much the member is allowed to mutate
(0.0 ... |
def get_injectable(name):
"""
Get an injectable by name. *Does not* evaluate wrapped functions.
Parameters
----------
name : str
Returns
-------
injectable
Original value or evaluated value of an _InjectableFuncWrapper.
"""
i = get_raw_injectable(name)
return i() i... | Get an injectable by name. *Does not* evaluate wrapped functions.
Parameters
----------
name : str
Returns
-------
injectable
Original value or evaluated value of an _InjectableFuncWrapper. | Below is the the instruction that describes the task:
### Input:
Get an injectable by name. *Does not* evaluate wrapped functions.
Parameters
----------
name : str
Returns
-------
injectable
Original value or evaluated value of an _InjectableFuncWrapper.
### Response:
def get_inje... |
def delete_event(self, client, check):
"""
Resolves an event for a given check on a given client. (delayed action)
"""
self._request('DELETE', '/events/{}/{}'.format(client, check))
return True | Resolves an event for a given check on a given client. (delayed action) | Below is the the instruction that describes the task:
### Input:
Resolves an event for a given check on a given client. (delayed action)
### Response:
def delete_event(self, client, check):
"""
Resolves an event for a given check on a given client. (delayed action)
"""
self._request... |
def country(random=random, *args, **kwargs):
"""
Produce a country name
>>> mock_random.seed(0)
>>> country(random=mock_random)
'testasia'
>>> country(random=mock_random, capitalize=True)
'West Xanth'
>>> country(random=mock_random, slugify=True)
'westeros'
"""
return rando... | Produce a country name
>>> mock_random.seed(0)
>>> country(random=mock_random)
'testasia'
>>> country(random=mock_random, capitalize=True)
'West Xanth'
>>> country(random=mock_random, slugify=True)
'westeros' | Below is the the instruction that describes the task:
### Input:
Produce a country name
>>> mock_random.seed(0)
>>> country(random=mock_random)
'testasia'
>>> country(random=mock_random, capitalize=True)
'West Xanth'
>>> country(random=mock_random, slugify=True)
'westeros'
### Response:... |
def grouped_count_sizes(fileslist, fgrouped): # pragma: no cover
'''Compute the total size per group and total number of files. Useful to check that everything is OK.'''
fsizes = {}
total_files = 0
allitems = None
if isinstance(fgrouped, dict):
allitems = fgrouped.iteritems()
elif isins... | Compute the total size per group and total number of files. Useful to check that everything is OK. | Below is the the instruction that describes the task:
### Input:
Compute the total size per group and total number of files. Useful to check that everything is OK.
### Response:
def grouped_count_sizes(fileslist, fgrouped): # pragma: no cover
'''Compute the total size per group and total number of files. Usef... |
def attachment_form(context, obj):
"""
Renders a "upload attachment" form.
The user must own ``attachments.add_attachment permission`` to add
attachments.
"""
if context['user'].has_perm('attachments.add_attachment'):
return {
'form': AttachmentForm(),
'form_url'... | Renders a "upload attachment" form.
The user must own ``attachments.add_attachment permission`` to add
attachments. | Below is the the instruction that describes the task:
### Input:
Renders a "upload attachment" form.
The user must own ``attachments.add_attachment permission`` to add
attachments.
### Response:
def attachment_form(context, obj):
"""
Renders a "upload attachment" form.
The user must own ``att... |
def response(self, parameters):
r"""Complex response of the Cole-Cole model::
:math:`\hat{\rho} = \rho_0 \left(1 - \sum_i m_i (1 - \frac{1}{1 + (j
\omega \tau_i)^c_i})\right)`
Parameters
----------
parameters: list or tuple or numpy.ndarray
Cole-Cole model pa... | r"""Complex response of the Cole-Cole model::
:math:`\hat{\rho} = \rho_0 \left(1 - \sum_i m_i (1 - \frac{1}{1 + (j
\omega \tau_i)^c_i})\right)`
Parameters
----------
parameters: list or tuple or numpy.ndarray
Cole-Cole model parameters: rho0, m, tau, c (all linear)
... | Below is the the instruction that describes the task:
### Input:
r"""Complex response of the Cole-Cole model::
:math:`\hat{\rho} = \rho_0 \left(1 - \sum_i m_i (1 - \frac{1}{1 + (j
\omega \tau_i)^c_i})\right)`
Parameters
----------
parameters: list or tuple or numpy.ndarray
... |
def double_lorgauss(x,p):
"""Evaluates a normalized distribution that is a mixture of a double-sided Gaussian and Double-sided Lorentzian.
Parameters
----------
x : float or array-like
Value(s) at which to evaluate distribution
p : array-like
Input parameters: mu (mode of distribut... | Evaluates a normalized distribution that is a mixture of a double-sided Gaussian and Double-sided Lorentzian.
Parameters
----------
x : float or array-like
Value(s) at which to evaluate distribution
p : array-like
Input parameters: mu (mode of distribution),
s... | Below is the the instruction that describes the task:
### Input:
Evaluates a normalized distribution that is a mixture of a double-sided Gaussian and Double-sided Lorentzian.
Parameters
----------
x : float or array-like
Value(s) at which to evaluate distribution
p : array-like
Inp... |
def post_processor_population_fatality_function(
classification=None, hazard_class=None, population=None):
"""Private function used in the fatality postprocessor.
:param classification: The hazard classification to use.
:type classification: str
:param hazard_class: The hazard class of the fea... | Private function used in the fatality postprocessor.
:param classification: The hazard classification to use.
:type classification: str
:param hazard_class: The hazard class of the feature.
:type hazard_class: str
:param population: We don't use this value here. It's only used for
conditi... | Below is the the instruction that describes the task:
### Input:
Private function used in the fatality postprocessor.
:param classification: The hazard classification to use.
:type classification: str
:param hazard_class: The hazard class of the feature.
:type hazard_class: str
:param populat... |
def get_row_by_task_id(self, task_id):
'''返回这个任务的TreeModelRow, 如果不存在, 就返回None.'''
for row in self.liststore:
if row and row[TASKID_COL] == task_id:
return row
return None | 返回这个任务的TreeModelRow, 如果不存在, 就返回None. | Below is the the instruction that describes the task:
### Input:
返回这个任务的TreeModelRow, 如果不存在, 就返回None.
### Response:
def get_row_by_task_id(self, task_id):
'''返回这个任务的TreeModelRow, 如果不存在, 就返回None.'''
for row in self.liststore:
if row and row[TASKID_COL] == task_id:
return ... |
def clear(self):
"""
Clears out the widgets from this stack.
"""
for i in range(self.count() - 1, -1, -1):
w = self.widget(i)
if w:
self.removeWidget(w)
w.close()
w.deleteLater() | Clears out the widgets from this stack. | Below is the the instruction that describes the task:
### Input:
Clears out the widgets from this stack.
### Response:
def clear(self):
"""
Clears out the widgets from this stack.
"""
for i in range(self.count() - 1, -1, -1):
w = self.widget(i)
if w:
... |
def np2str(value):
"""Convert an `numpy.string_` to str.
Args:
value (ndarray): scalar or 1-element numpy array to convert
Raises:
ValueError: if value is array larger than 1-element or it is not of
type `numpy.string_` or it is not a numpy array
"""
if hasattr... | Convert an `numpy.string_` to str.
Args:
value (ndarray): scalar or 1-element numpy array to convert
Raises:
ValueError: if value is array larger than 1-element or it is not of
type `numpy.string_` or it is not a numpy array | Below is the the instruction that describes the task:
### Input:
Convert an `numpy.string_` to str.
Args:
value (ndarray): scalar or 1-element numpy array to convert
Raises:
ValueError: if value is array larger than 1-element or it is not of
type `numpy.string_` or it i... |
def create_server(
max_workers: int,
options: Optional[List[Tuple[str, Any]]] = None,
interceptors: Optional[List[grpc.ServerInterceptor]] = None,
) -> grpc.Server:
"""Creates a gRPC server
The gRPC server is created with the provided options and intercepts each
incoming RPCs via th... | Creates a gRPC server
The gRPC server is created with the provided options and intercepts each
incoming RPCs via the provided interceptors.
The created server is configured with the following default options:
- "grpc.max_send_message_length": 100MB,
- "grpc.max_receive_message_length": 100... | Below is the the instruction that describes the task:
### Input:
Creates a gRPC server
The gRPC server is created with the provided options and intercepts each
incoming RPCs via the provided interceptors.
The created server is configured with the following default options:
- "grpc.max_send_mes... |
def list_to_str(lst):
"""
Turn a list into a comma- and/or and-separated string.
Parameters
----------
lst : :obj:`list`
A list of strings to join into a single string.
Returns
-------
str_ : :obj:`str`
A string with commas and/or ands separating th elements from ``lst`... | Turn a list into a comma- and/or and-separated string.
Parameters
----------
lst : :obj:`list`
A list of strings to join into a single string.
Returns
-------
str_ : :obj:`str`
A string with commas and/or ands separating th elements from ``lst``. | Below is the the instruction that describes the task:
### Input:
Turn a list into a comma- and/or and-separated string.
Parameters
----------
lst : :obj:`list`
A list of strings to join into a single string.
Returns
-------
str_ : :obj:`str`
A string with commas and/or ands... |
def get_export_table(self):
"""Get the export table."""
symbols = self.binary.DIRECTORY_ENTRY_EXPORT.symbols
names = AttrsGetter(symbols, join=False).name
return names | Get the export table. | Below is the the instruction that describes the task:
### Input:
Get the export table.
### Response:
def get_export_table(self):
"""Get the export table."""
symbols = self.binary.DIRECTORY_ENTRY_EXPORT.symbols
names = AttrsGetter(symbols, join=False).name
return names |
def _run(command, quiet=False, timeout=None):
"""Run a command, returns command output."""
try:
with _spawn(command, quiet, timeout) as child:
command_output = child.read().strip().replace("\r\n", "\n")
except pexpect.TIMEOUT:
logger.info(f"command {command} timed out")
r... | Run a command, returns command output. | Below is the the instruction that describes the task:
### Input:
Run a command, returns command output.
### Response:
def _run(command, quiet=False, timeout=None):
"""Run a command, returns command output."""
try:
with _spawn(command, quiet, timeout) as child:
command_output = child.rea... |
def retrieve_config_file(self):
"""
Retrieve config file
"""
try:
if self.args["configfile"]:
return self.args["configfile"]
except KeyError:
pass
return os.path.expanduser('~/.config/greg/greg.conf') | Retrieve config file | Below is the the instruction that describes the task:
### Input:
Retrieve config file
### Response:
def retrieve_config_file(self):
"""
Retrieve config file
"""
try:
if self.args["configfile"]:
return self.args["configfile"]
except KeyError:
... |
def _get_attr_value(instance, attr, default=None):
"""
Simple helper to get the value of an instance's attribute if it exists.
If the instance attribute is callable it will be called and the result will
be returned.
Optionally accepts a default value to return if the attribute is missing.
Defa... | Simple helper to get the value of an instance's attribute if it exists.
If the instance attribute is callable it will be called and the result will
be returned.
Optionally accepts a default value to return if the attribute is missing.
Defaults to `None`
>>> class Foo(object):
... bar = 'b... | Below is the the instruction that describes the task:
### Input:
Simple helper to get the value of an instance's attribute if it exists.
If the instance attribute is callable it will be called and the result will
be returned.
Optionally accepts a default value to return if the attribute is missing.
... |
def check_log_stream_exists(awsclient, log_group_name, log_stream_name):
"""Check
:param log_group_name: log group name
:param log_stream_name: log stream name
:return: True / False
"""
lg = describe_log_group(awsclient, log_group_name)
if lg and lg['logGroupName'] == log_group_name:
... | Check
:param log_group_name: log group name
:param log_stream_name: log stream name
:return: True / False | Below is the the instruction that describes the task:
### Input:
Check
:param log_group_name: log group name
:param log_stream_name: log stream name
:return: True / False
### Response:
def check_log_stream_exists(awsclient, log_group_name, log_stream_name):
"""Check
:param log_group_name: log... |
def update(self, resource, id_, updates):
"""Update document in index."""
args = self._es_args(resource, refresh=True)
if self._get_retry_on_conflict():
args['retry_on_conflict'] = self._get_retry_on_conflict()
updates.pop('_id', None)
updates.pop('_type', None)
... | Update document in index. | Below is the the instruction that describes the task:
### Input:
Update document in index.
### Response:
def update(self, resource, id_, updates):
"""Update document in index."""
args = self._es_args(resource, refresh=True)
if self._get_retry_on_conflict():
args['retry_on_confli... |
def assert_not_present(self, selector, testid=None, **kwargs):
"""Assert that the element is not present in the dom
Args:
selector (str): the selector used to find the element
test_id (str): the test_id or a str
Kwargs:
wait_until_not_present (bool)
... | Assert that the element is not present in the dom
Args:
selector (str): the selector used to find the element
test_id (str): the test_id or a str
Kwargs:
wait_until_not_present (bool)
Returns:
bool: True is the assertion succeed; False otherwise... | Below is the the instruction that describes the task:
### Input:
Assert that the element is not present in the dom
Args:
selector (str): the selector used to find the element
test_id (str): the test_id or a str
Kwargs:
wait_until_not_present (bool)
Retu... |
def _get_op_name(op, special):
"""
Find the name to attach to this method according to conventions
for special and non-special methods.
Parameters
----------
op : binary operator
special : bool
Returns
-------
op_name : str
"""
opname = op.__name__.strip('_')
if spe... | Find the name to attach to this method according to conventions
for special and non-special methods.
Parameters
----------
op : binary operator
special : bool
Returns
-------
op_name : str | Below is the the instruction that describes the task:
### Input:
Find the name to attach to this method according to conventions
for special and non-special methods.
Parameters
----------
op : binary operator
special : bool
Returns
-------
op_name : str
### Response:
def _get_op_n... |
def _mark_grid_bounds(self, plane, region_bbox):
"""
Assume all lines define a complete grid over the region_bbox.
Detect which lines are missing so that we can recover merged
cells.
"""
# Grid boundaries
vbars = np.zeros([self.num_rows, self.num_cols + 1], dtype=... | Assume all lines define a complete grid over the region_bbox.
Detect which lines are missing so that we can recover merged
cells. | Below is the the instruction that describes the task:
### Input:
Assume all lines define a complete grid over the region_bbox.
Detect which lines are missing so that we can recover merged
cells.
### Response:
def _mark_grid_bounds(self, plane, region_bbox):
"""
Assume all lines defi... |
def setCentre(self, *args, **kwargs):
"""Adds the centre for this loan to a 'assignedCentre' field.
Also adds an 'assignedCentreName' field with the name of the centre.
Centre is a MambuCentre object.
Returns the number of requests done to Mambu.
"""
try:
... | Adds the centre for this loan to a 'assignedCentre' field.
Also adds an 'assignedCentreName' field with the name of the centre.
Centre is a MambuCentre object.
Returns the number of requests done to Mambu. | Below is the the instruction that describes the task:
### Input:
Adds the centre for this loan to a 'assignedCentre' field.
Also adds an 'assignedCentreName' field with the name of the centre.
Centre is a MambuCentre object.
Returns the number of requests done to Mambu.
### Response:
def... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.