code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def begin_transaction(
self,
database,
options_=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Starts a new transaction.
Example:
>>> from google.cloud im... | Starts a new transaction.
Example:
>>> from google.cloud import firestore_v1beta1
>>>
>>> client = firestore_v1beta1.FirestoreClient()
>>>
>>> database = client.database_root_path('[PROJECT]', '[DATABASE]')
>>>
>>> response = c... | Below is the the instruction that describes the task:
### Input:
Starts a new transaction.
Example:
>>> from google.cloud import firestore_v1beta1
>>>
>>> client = firestore_v1beta1.FirestoreClient()
>>>
>>> database = client.database_root_path('[... |
def cursor(self, pos):
"""Returns a line at the nearest row split between tests.
Re-implemented from :meth:`AbstractDragView<sparkle.gui.abstract_drag_view.AbstractDragView.cursor>`
"""
row = self.indexAt(pos).row()
if row == -1:
row = self.model().rowCount()
... | Returns a line at the nearest row split between tests.
Re-implemented from :meth:`AbstractDragView<sparkle.gui.abstract_drag_view.AbstractDragView.cursor>` | Below is the the instruction that describes the task:
### Input:
Returns a line at the nearest row split between tests.
Re-implemented from :meth:`AbstractDragView<sparkle.gui.abstract_drag_view.AbstractDragView.cursor>`
### Response:
def cursor(self, pos):
"""Returns a line at the nearest row spl... |
def split(table, field, pattern, newfields=None, include_original=False,
maxsplit=0, flags=0):
"""
Add one or more new fields with values generated by splitting an
existing value around occurrences of a regular expression. E.g.::
>>> import petl as etl
>>> table1 = [['id', 'variab... | Add one or more new fields with values generated by splitting an
existing value around occurrences of a regular expression. E.g.::
>>> import petl as etl
>>> table1 = [['id', 'variable', 'value'],
... ['1', 'parad1', '12'],
... ['2', 'parad2', '15'],
... ... | Below is the the instruction that describes the task:
### Input:
Add one or more new fields with values generated by splitting an
existing value around occurrences of a regular expression. E.g.::
>>> import petl as etl
>>> table1 = [['id', 'variable', 'value'],
... ['1', 'para... |
def loadInputs(self, fname):
"""Load previsouly saved input values, and load them to GUI widgets
:param fname: file path where stashed input values are stored
:type fname: str
"""
inputsfname = os.path.join(systools.get_appdir(), fname)
try:
with open(inputsf... | Load previsouly saved input values, and load them to GUI widgets
:param fname: file path where stashed input values are stored
:type fname: str | Below is the the instruction that describes the task:
### Input:
Load previsouly saved input values, and load them to GUI widgets
:param fname: file path where stashed input values are stored
:type fname: str
### Response:
def loadInputs(self, fname):
"""Load previsouly saved input values,... |
def index(self, value):
"""
Return index of *value* in self.
Raises ValueError if *value* is not found.
"""
# pylint: disable=arguments-differ
for idx, val in enumerate(self):
if value == val:
return idx
raise ValueError('{0!r} is not ... | Return index of *value* in self.
Raises ValueError if *value* is not found. | Below is the the instruction that describes the task:
### Input:
Return index of *value* in self.
Raises ValueError if *value* is not found.
### Response:
def index(self, value):
"""
Return index of *value* in self.
Raises ValueError if *value* is not found.
"""
# ... |
def _format_date(self, obj) -> str:
"""
Short date format.
:param obj: date or datetime or None
:return: str
"""
if obj is None:
return ''
if isinstance(obj, datetime):
obj = obj.date()
return date_format(obj, 'SHORT_DATE_FORMAT') | Short date format.
:param obj: date or datetime or None
:return: str | Below is the the instruction that describes the task:
### Input:
Short date format.
:param obj: date or datetime or None
:return: str
### Response:
def _format_date(self, obj) -> str:
"""
Short date format.
:param obj: date or datetime or None
:return: str
""... |
def get_hash(self):
"""Generate and return the dict index hash of the given queue item.
Note:
Cookies should not be included in the hash calculation because
otherwise requests are crawled multiple times with e.g. different
session keys, causing infinite crawling recu... | Generate and return the dict index hash of the given queue item.
Note:
Cookies should not be included in the hash calculation because
otherwise requests are crawled multiple times with e.g. different
session keys, causing infinite crawling recursion.
Note:
... | Below is the the instruction that describes the task:
### Input:
Generate and return the dict index hash of the given queue item.
Note:
Cookies should not be included in the hash calculation because
otherwise requests are crawled multiple times with e.g. different
sessio... |
def worker_unreject(self, chosen_hit, assignment_ids = None):
''' Unreject worker '''
if chosen_hit:
workers = self.amt_services.get_workers("Rejected")
assignment_ids = [worker['assignmentId'] for worker in workers if \
worker['hitId'] == chosen_hit... | Unreject worker | Below is the the instruction that describes the task:
### Input:
Unreject worker
### Response:
def worker_unreject(self, chosen_hit, assignment_ids = None):
''' Unreject worker '''
if chosen_hit:
workers = self.amt_services.get_workers("Rejected")
assignment_ids = [worker['a... |
def map_masked_1d_array_to_2d_array_from_array_1d_shape_and_one_to_two(array_1d, shape, one_to_two):
"""For a 1D array that was computed by mapping unmasked values from a 2D array of shape (rows, columns), map its \
values back to the original 2D array where masked values are set to zero.
This uses a 1D ar... | For a 1D array that was computed by mapping unmasked values from a 2D array of shape (rows, columns), map its \
values back to the original 2D array where masked values are set to zero.
This uses a 1D array 'one_to_two' where each index gives the 2D pixel indexes of the 1D array's unmasked pixels, \
for ex... | Below is the the instruction that describes the task:
### Input:
For a 1D array that was computed by mapping unmasked values from a 2D array of shape (rows, columns), map its \
values back to the original 2D array where masked values are set to zero.
This uses a 1D array 'one_to_two' where each index gives... |
def check_token(token):
''' Verify http header token authentification '''
user = models.User.objects(api_key=token).first()
return user or None | Verify http header token authentification | Below is the the instruction that describes the task:
### Input:
Verify http header token authentification
### Response:
def check_token(token):
''' Verify http header token authentification '''
user = models.User.objects(api_key=token).first()
return user or None |
def groupby(iterable, key=0, filter=None):
"""
wrapper to itertools.groupby that returns a list of each group, rather
than a generator and accepts integers or strings as the key and
automatically converts them to callables with itemgetter(key)
Arguments:
iterable: iterable
key: stri... | wrapper to itertools.groupby that returns a list of each group, rather
than a generator and accepts integers or strings as the key and
automatically converts them to callables with itemgetter(key)
Arguments:
iterable: iterable
key: string, int or callable that tells how to group
Return... | Below is the the instruction that describes the task:
### Input:
wrapper to itertools.groupby that returns a list of each group, rather
than a generator and accepts integers or strings as the key and
automatically converts them to callables with itemgetter(key)
Arguments:
iterable: iterable
... |
def on_disconnect(self=None) -> callable:
"""Use this decorator to automatically register a function for handling disconnections.
This does the same thing as :meth:`add_handler` using the :class:`DisconnectHandler`.
"""
def decorator(func: callable) -> Handler:
handler = pyr... | Use this decorator to automatically register a function for handling disconnections.
This does the same thing as :meth:`add_handler` using the :class:`DisconnectHandler`. | Below is the the instruction that describes the task:
### Input:
Use this decorator to automatically register a function for handling disconnections.
This does the same thing as :meth:`add_handler` using the :class:`DisconnectHandler`.
### Response:
def on_disconnect(self=None) -> callable:
"""Use ... |
def com_google_fonts_check_metadata_valid_copyright(font_metadata):
"""Copyright notices match canonical pattern in METADATA.pb"""
import re
string = font_metadata.copyright
does_match = re.search(r'Copyright [0-9]{4} The .* Project Authors \([^\@]*\)',
string)
if does_match:
yi... | Copyright notices match canonical pattern in METADATA.pb | Below is the the instruction that describes the task:
### Input:
Copyright notices match canonical pattern in METADATA.pb
### Response:
def com_google_fonts_check_metadata_valid_copyright(font_metadata):
"""Copyright notices match canonical pattern in METADATA.pb"""
import re
string = font_metadata.copyright... |
def remote_run(cmd, instance_name, detach=False, retries=1):
"""Run command on GCS instance, optionally detached."""
if detach:
cmd = SCREEN.format(command=cmd)
args = SSH.format(instance_name=instance_name).split()
args.append(cmd)
for i in range(retries + 1):
try:
if i > 0:
tf.logging.... | Run command on GCS instance, optionally detached. | Below is the the instruction that describes the task:
### Input:
Run command on GCS instance, optionally detached.
### Response:
def remote_run(cmd, instance_name, detach=False, retries=1):
"""Run command on GCS instance, optionally detached."""
if detach:
cmd = SCREEN.format(command=cmd)
args = SSH.form... |
def popitem(self):
"""Remove and return the `(key, value)` pair least recently used that
has not already expired.
"""
with self.__timer as time:
self.expire(time)
try:
key = next(iter(self.__links))
except StopIteration:
... | Remove and return the `(key, value)` pair least recently used that
has not already expired. | Below is the the instruction that describes the task:
### Input:
Remove and return the `(key, value)` pair least recently used that
has not already expired.
### Response:
def popitem(self):
"""Remove and return the `(key, value)` pair least recently used that
has not already expired.
... |
def check_resume(args: argparse.Namespace, output_folder: str) -> bool:
"""
Check if we should resume a broken training run.
:param args: Arguments as returned by argparse.
:param output_folder: Main output folder for the model.
:return: Flag signaling if we are resuming training and the directory ... | Check if we should resume a broken training run.
:param args: Arguments as returned by argparse.
:param output_folder: Main output folder for the model.
:return: Flag signaling if we are resuming training and the directory with
the training status. | Below is the the instruction that describes the task:
### Input:
Check if we should resume a broken training run.
:param args: Arguments as returned by argparse.
:param output_folder: Main output folder for the model.
:return: Flag signaling if we are resuming training and the directory with
th... |
def format_map(self, format_string, mapping):
"""format a string by a map
Args:
format_string(str): A format string
mapping(dict): A map to format the string
Returns:
A formatted string.
Raises:
KeyError: if key is not provided by the gi... | format a string by a map
Args:
format_string(str): A format string
mapping(dict): A map to format the string
Returns:
A formatted string.
Raises:
KeyError: if key is not provided by the given map. | Below is the the instruction that describes the task:
### Input:
format a string by a map
Args:
format_string(str): A format string
mapping(dict): A map to format the string
Returns:
A formatted string.
Raises:
KeyError: if key is not provid... |
def slices(self):
"""Returns a generator yielding tuple of slice objects.
Order is not guaranteed.
"""
if self.chunks is None:
yield tuple(slice(None, s) for s in self.shape)
else:
ceilings = tuple(-(-s // c) for s, c in zip(self.shape, self.chunks))
... | Returns a generator yielding tuple of slice objects.
Order is not guaranteed. | Below is the the instruction that describes the task:
### Input:
Returns a generator yielding tuple of slice objects.
Order is not guaranteed.
### Response:
def slices(self):
"""Returns a generator yielding tuple of slice objects.
Order is not guaranteed.
"""
if self.chunk... |
def _radial_profile(autocorr, r_max, nbins=100):
r"""
Helper functions to calculate the radial profile of the autocorrelation
Masks the image in radial segments from the center and averages the values
The distance values are normalized and 100 bins are used as default.
Parameters
----------
... | r"""
Helper functions to calculate the radial profile of the autocorrelation
Masks the image in radial segments from the center and averages the values
The distance values are normalized and 100 bins are used as default.
Parameters
----------
autocorr : ND-array
The image of autocorrela... | Below is the the instruction that describes the task:
### Input:
r"""
Helper functions to calculate the radial profile of the autocorrelation
Masks the image in radial segments from the center and averages the values
The distance values are normalized and 100 bins are used as default.
Parameters
... |
def _sumDiceRolls(self, rollList):
"""convert from dice roll structure to a single integer result"""
if isinstance(rollList, RollList):
self.rolls.append(rollList)
return rollList.sum()
else:
return rollList | convert from dice roll structure to a single integer result | Below is the the instruction that describes the task:
### Input:
convert from dice roll structure to a single integer result
### Response:
def _sumDiceRolls(self, rollList):
"""convert from dice roll structure to a single integer result"""
if isinstance(rollList, RollList):
self.rolls.a... |
def setType(self, polygonID, polygonType):
"""setType(string, string) -> None
Sets the (abstract) type of the polygon.
"""
self._connection._beginMessage(
tc.CMD_SET_POLYGON_VARIABLE, tc.VAR_TYPE, polygonID, 1 + 4 + len(polygonType))
self._connection._packString(poly... | setType(string, string) -> None
Sets the (abstract) type of the polygon. | Below is the the instruction that describes the task:
### Input:
setType(string, string) -> None
Sets the (abstract) type of the polygon.
### Response:
def setType(self, polygonID, polygonType):
"""setType(string, string) -> None
Sets the (abstract) type of the polygon.
"""
... |
def pixel_to_utm(row, column, transform):
""" Convert pixel coordinate to UTM coordinate given a transform
:param row: row pixel coordinate
:type row: int or float
:param column: column pixel coordinate
:type column: int or float
:param transform: georeferencing transform of the image, e.g. `(x... | Convert pixel coordinate to UTM coordinate given a transform
:param row: row pixel coordinate
:type row: int or float
:param column: column pixel coordinate
:type column: int or float
:param transform: georeferencing transform of the image, e.g. `(x_upper_left, res_x, 0, y_upper_left, 0, -res_y)`
... | Below is the the instruction that describes the task:
### Input:
Convert pixel coordinate to UTM coordinate given a transform
:param row: row pixel coordinate
:type row: int or float
:param column: column pixel coordinate
:type column: int or float
:param transform: georeferencing transform of ... |
def get_mipmap_pixel(
self, left: float, top: float, right: float, bottom: float
) -> Tuple[int, int, int]:
"""Get the average color of a rectangle in this Image.
Parameters should stay within the following limits:
* 0 <= left < right < Image.width
* 0 <= top < bottom < Imag... | Get the average color of a rectangle in this Image.
Parameters should stay within the following limits:
* 0 <= left < right < Image.width
* 0 <= top < bottom < Image.height
Args:
left (float): Left corner of the region.
top (float): Top corner of the region.
... | Below is the the instruction that describes the task:
### Input:
Get the average color of a rectangle in this Image.
Parameters should stay within the following limits:
* 0 <= left < right < Image.width
* 0 <= top < bottom < Image.height
Args:
left (float): Left corner ... |
def get_query_results(self, query_execution_id):
"""
Fetch submitted athena query results. returns none if query is in intermediate state or
failed/cancelled state else dict of query output
:param query_execution_id: Id of submitted athena query
:type query_execution_id: str
... | Fetch submitted athena query results. returns none if query is in intermediate state or
failed/cancelled state else dict of query output
:param query_execution_id: Id of submitted athena query
:type query_execution_id: str
:return: dict | Below is the the instruction that describes the task:
### Input:
Fetch submitted athena query results. returns none if query is in intermediate state or
failed/cancelled state else dict of query output
:param query_execution_id: Id of submitted athena query
:type query_execution_id: str
... |
def get_debug_info():
"""Return a list of lines with backend info.
"""
from . import __version__
from .parser import SPEC_VERSION
d = OrderedDict()
d['Version'] = '%s' % __version__
d['Spec version'] = SPEC_VERSION
return d | Return a list of lines with backend info. | Below is the the instruction that describes the task:
### Input:
Return a list of lines with backend info.
### Response:
def get_debug_info():
"""Return a list of lines with backend info.
"""
from . import __version__
from .parser import SPEC_VERSION
d = OrderedDict()
... |
def update_list_positions_obj(client, positions_obj_id, revision, values):
'''
Updates the ordering of lists to have the given value. The given ID and revision should match the singleton object defining how lists are laid out.
See https://developer.wunderlist.com/documentation/endpoints/positions for more ... | Updates the ordering of lists to have the given value. The given ID and revision should match the singleton object defining how lists are laid out.
See https://developer.wunderlist.com/documentation/endpoints/positions for more info
Return:
The updated ListPositionsObj-mapped object defining the order of ... | Below is the the instruction that describes the task:
### Input:
Updates the ordering of lists to have the given value. The given ID and revision should match the singleton object defining how lists are laid out.
See https://developer.wunderlist.com/documentation/endpoints/positions for more info
Return:
... |
def get_cpuid_leaf_by_ordinal(self, ordinal):
"""Used to enumerate CPUID information override values.
in ordinal of type int
The ordinal number of the leaf to get.
out idx of type int
CPUID leaf index.
out idx_sub of type int
CPUID leaf sub-index.
... | Used to enumerate CPUID information override values.
in ordinal of type int
The ordinal number of the leaf to get.
out idx of type int
CPUID leaf index.
out idx_sub of type int
CPUID leaf sub-index.
out val_eax of type int
CPUID leaf va... | Below is the the instruction that describes the task:
### Input:
Used to enumerate CPUID information override values.
in ordinal of type int
The ordinal number of the leaf to get.
out idx of type int
CPUID leaf index.
out idx_sub of type int
CPUID leaf ... |
def combine_slices(self, slices, tensor_shape, device=None):
"""Turns a set of slices into a single tensor.
Args:
slices: list of tf.Tensor with length self.size.
tensor_shape: Shape.
device: optional str. If absent, we use the devices of the slices.
Returns:
tf.Tensor.
"""
... | Turns a set of slices into a single tensor.
Args:
slices: list of tf.Tensor with length self.size.
tensor_shape: Shape.
device: optional str. If absent, we use the devices of the slices.
Returns:
tf.Tensor. | Below is the the instruction that describes the task:
### Input:
Turns a set of slices into a single tensor.
Args:
slices: list of tf.Tensor with length self.size.
tensor_shape: Shape.
device: optional str. If absent, we use the devices of the slices.
Returns:
tf.Tensor.
### Respon... |
def create(cls, schema, name):
"""
Create an object based on the root tag name.
@param schema: A schema object.
@type schema: L{schema.Schema}
@param name: The name.
@type name: str
@return: The created object.
@rtype: L{XBuiltin}
"""
fn ... | Create an object based on the root tag name.
@param schema: A schema object.
@type schema: L{schema.Schema}
@param name: The name.
@type name: str
@return: The created object.
@rtype: L{XBuiltin} | Below is the the instruction that describes the task:
### Input:
Create an object based on the root tag name.
@param schema: A schema object.
@type schema: L{schema.Schema}
@param name: The name.
@type name: str
@return: The created object.
@rtype: L{XBuiltin}
### Re... |
def to_shapely_polygon(self):
"""
Convert this polygon to a Shapely polygon.
Returns
-------
shapely.geometry.Polygon
The Shapely polygon matching this polygon's exterior.
"""
# load shapely lazily, which makes the dependency more optional
im... | Convert this polygon to a Shapely polygon.
Returns
-------
shapely.geometry.Polygon
The Shapely polygon matching this polygon's exterior. | Below is the the instruction that describes the task:
### Input:
Convert this polygon to a Shapely polygon.
Returns
-------
shapely.geometry.Polygon
The Shapely polygon matching this polygon's exterior.
### Response:
def to_shapely_polygon(self):
"""
Convert thi... |
def readU8(self, register):
"""Read an unsigned byte from the specified register."""
result = self._bus.read_byte_data(self._address, register) & 0xFF
self._logger.debug("Read 0x%02X from register 0x%02X",
result, register)
return result | Read an unsigned byte from the specified register. | Below is the the instruction that describes the task:
### Input:
Read an unsigned byte from the specified register.
### Response:
def readU8(self, register):
"""Read an unsigned byte from the specified register."""
result = self._bus.read_byte_data(self._address, register) & 0xFF
self._logg... |
def data_indicators(self, indicators, entity_count):
"""Process Indicator data."""
data = []
# process indicator objects
for xid, indicator_data in indicators.items():
entity_count += 1
if isinstance(indicator_data, dict):
data.append(indicator_dat... | Process Indicator data. | Below is the the instruction that describes the task:
### Input:
Process Indicator data.
### Response:
def data_indicators(self, indicators, entity_count):
"""Process Indicator data."""
data = []
# process indicator objects
for xid, indicator_data in indicators.items():
... |
def run_followers(self, prompt):
"""
First caller adds a prompt to queue and
runs followers until there are no more
pending prompts.
Subsequent callers just add a prompt
to the queue, avoiding recursion.
"""
assert isinstance(prompt, Prompt)
# Put... | First caller adds a prompt to queue and
runs followers until there are no more
pending prompts.
Subsequent callers just add a prompt
to the queue, avoiding recursion. | Below is the the instruction that describes the task:
### Input:
First caller adds a prompt to queue and
runs followers until there are no more
pending prompts.
Subsequent callers just add a prompt
to the queue, avoiding recursion.
### Response:
def run_followers(self, prompt):
... |
def revoke(self, role):
"""Remove a role from the entity.
:type role: str
:param role: The role to remove from the entity.
"""
if role in self.roles:
self.roles.remove(role) | Remove a role from the entity.
:type role: str
:param role: The role to remove from the entity. | Below is the the instruction that describes the task:
### Input:
Remove a role from the entity.
:type role: str
:param role: The role to remove from the entity.
### Response:
def revoke(self, role):
"""Remove a role from the entity.
:type role: str
:param role: The role to... |
def toggle_comments(self):
"""
Toggles comments on the document selected lines.
:return: Method success.
:rtype: bool
"""
if not self.__comment_marker:
return True
cursor = self.textCursor()
if not cursor.hasSelection():
cursor.m... | Toggles comments on the document selected lines.
:return: Method success.
:rtype: bool | Below is the the instruction that describes the task:
### Input:
Toggles comments on the document selected lines.
:return: Method success.
:rtype: bool
### Response:
def toggle_comments(self):
"""
Toggles comments on the document selected lines.
:return: Method success.
... |
def plot_gallery(saveplot=False):
'''Make plot of colormaps and labels, like in the matplotlib
gallery.
:param saveplot=False: Whether to save the plot or not.
'''
from colorspacious import cspace_converter
gradient = np.linspace(0, 1, 256)
gradient = np.vstack((gradient, gradient))
... | Make plot of colormaps and labels, like in the matplotlib
gallery.
:param saveplot=False: Whether to save the plot or not. | Below is the the instruction that describes the task:
### Input:
Make plot of colormaps and labels, like in the matplotlib
gallery.
:param saveplot=False: Whether to save the plot or not.
### Response:
def plot_gallery(saveplot=False):
'''Make plot of colormaps and labels, like in the matplotlib
g... |
def snapshot(self, at):
""" Return a new Table which is a snapshot of this table at the specified time.
Args:
at: the time of the snapshot. This can be a Python datetime (absolute) or timedelta
(relative to current time). The result must be after the table was created and no more
than... | Return a new Table which is a snapshot of this table at the specified time.
Args:
at: the time of the snapshot. This can be a Python datetime (absolute) or timedelta
(relative to current time). The result must be after the table was created and no more
than seven days in the past. Passing... | Below is the the instruction that describes the task:
### Input:
Return a new Table which is a snapshot of this table at the specified time.
Args:
at: the time of the snapshot. This can be a Python datetime (absolute) or timedelta
(relative to current time). The result must be after the table w... |
def remove_node_attributes(G: nx.DiGraph, attributes: Union[str, Iterable[str]]):
"""
Return a copy of the graph with the given attributes
deleted from all nodes.
"""
G = G.copy()
for _, data in G.nodes(data=True):
for attribute in setwrap(attributes):
if attribute in data:
... | Return a copy of the graph with the given attributes
deleted from all nodes. | Below is the the instruction that describes the task:
### Input:
Return a copy of the graph with the given attributes
deleted from all nodes.
### Response:
def remove_node_attributes(G: nx.DiGraph, attributes: Union[str, Iterable[str]]):
"""
Return a copy of the graph with the given attributes
dele... |
def split(str, pattern, limit=-1):
"""
Splits str around matches of the given pattern.
:param str: a string expression to split
:param pattern: a string representing a regular expression. The regex string should be
a Java regular expression.
:param limit: an integer which controls the numbe... | Splits str around matches of the given pattern.
:param str: a string expression to split
:param pattern: a string representing a regular expression. The regex string should be
a Java regular expression.
:param limit: an integer which controls the number of times `pattern` is applied.
* ``l... | Below is the the instruction that describes the task:
### Input:
Splits str around matches of the given pattern.
:param str: a string expression to split
:param pattern: a string representing a regular expression. The regex string should be
a Java regular expression.
:param limit: an integer wh... |
def _exclude_by_filter(self, frame, filename):
'''
:param str filename:
The filename to filter.
:return: True if it should be excluded, False if it should be included and None
if no rule matched the given file.
'''
try:
return self._exclude_by... | :param str filename:
The filename to filter.
:return: True if it should be excluded, False if it should be included and None
if no rule matched the given file. | Below is the the instruction that describes the task:
### Input:
:param str filename:
The filename to filter.
:return: True if it should be excluded, False if it should be included and None
if no rule matched the given file.
### Response:
def _exclude_by_filter(self, frame, filenam... |
def read_headers(rfile, hdict=None):
"""Read headers from the given stream into the given header dict.
If hdict is None, a new header dict is created. Returns the populated
header dict.
Headers which are repeated are folded together using a comma if their
specification so dictates.
... | Read headers from the given stream into the given header dict.
If hdict is None, a new header dict is created. Returns the populated
header dict.
Headers which are repeated are folded together using a comma if their
specification so dictates.
This function raises ValueError when the r... | Below is the the instruction that describes the task:
### Input:
Read headers from the given stream into the given header dict.
If hdict is None, a new header dict is created. Returns the populated
header dict.
Headers which are repeated are folded together using a comma if their
specifica... |
def remove_device(self, device: Union[DeviceType, str]) -> None:
"""Remove the given |Node| or |Element| object from the actual
|Nodes| or |Elements| object.
You can pass either a string or a device:
>>> from hydpy import Node, Nodes
>>> nodes = Nodes('node_x', 'node_y')
... | Remove the given |Node| or |Element| object from the actual
|Nodes| or |Elements| object.
You can pass either a string or a device:
>>> from hydpy import Node, Nodes
>>> nodes = Nodes('node_x', 'node_y')
>>> node_x, node_y = nodes
>>> nodes.remove_device(Node('node_y'))... | Below is the the instruction that describes the task:
### Input:
Remove the given |Node| or |Element| object from the actual
|Nodes| or |Elements| object.
You can pass either a string or a device:
>>> from hydpy import Node, Nodes
>>> nodes = Nodes('node_x', 'node_y')
>>> n... |
def _aggregate(self, source, aggregators, data, result):
"""Performs aggregation at a specific node in the data/aggregator tree."""
if data is None:
return
if hasattr(aggregators, 'items'):
# Keep walking the tree.
for key, value in six.iteritems(aggregators):
if isinstance(key, t... | Performs aggregation at a specific node in the data/aggregator tree. | Below is the the instruction that describes the task:
### Input:
Performs aggregation at a specific node in the data/aggregator tree.
### Response:
def _aggregate(self, source, aggregators, data, result):
"""Performs aggregation at a specific node in the data/aggregator tree."""
if data is None:
retu... |
def main():
'''Main routine.'''
# validate command line arguments
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument('--vmssname', '-n', required=True, action='store',
help='Scale set name')
arg_parser.add_argument('--rgname', '-g', required=True, action='sto... | Main routine. | Below is the the instruction that describes the task:
### Input:
Main routine.
### Response:
def main():
'''Main routine.'''
# validate command line arguments
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument('--vmssname', '-n', required=True, action='store',
... |
def zero_pad(m, n=1):
"""Pad a matrix with zeros, on all sides."""
return np.pad(m, (n, n), mode='constant', constant_values=[0]) | Pad a matrix with zeros, on all sides. | Below is the the instruction that describes the task:
### Input:
Pad a matrix with zeros, on all sides.
### Response:
def zero_pad(m, n=1):
"""Pad a matrix with zeros, on all sides."""
return np.pad(m, (n, n), mode='constant', constant_values=[0]) |
def _validate_annotation(self, annotation):
'''Ensures that the annotation has the right fields.'''
required_keys = set(self._required_keys)
keys = set(key for key, val in annotation.items() if val)
missing_keys = required_keys.difference(keys)
if missing_keys:
error ... | Ensures that the annotation has the right fields. | Below is the the instruction that describes the task:
### Input:
Ensures that the annotation has the right fields.
### Response:
def _validate_annotation(self, annotation):
'''Ensures that the annotation has the right fields.'''
required_keys = set(self._required_keys)
keys = set(key for ke... |
def assert_has_calls(self, calls, any_order=False):
"""assert the mock has been called with the specified calls.
The `mock_calls` list is checked for the calls.
If `any_order` is False (the default) then the calls must be
sequential. There can be extra calls before or after the
... | assert the mock has been called with the specified calls.
The `mock_calls` list is checked for the calls.
If `any_order` is False (the default) then the calls must be
sequential. There can be extra calls before or after the
specified calls.
If `any_order` is True then the calls... | Below is the the instruction that describes the task:
### Input:
assert the mock has been called with the specified calls.
The `mock_calls` list is checked for the calls.
If `any_order` is False (the default) then the calls must be
sequential. There can be extra calls before or after the
... |
def check_permissions(self, request):
""" Retrieves the controlled object and perform the permissions check. """
obj = (
hasattr(self, 'get_controlled_object') and self.get_controlled_object() or
hasattr(self, 'get_object') and self.get_object() or getattr(self, 'object', None)
... | Retrieves the controlled object and perform the permissions check. | Below is the the instruction that describes the task:
### Input:
Retrieves the controlled object and perform the permissions check.
### Response:
def check_permissions(self, request):
""" Retrieves the controlled object and perform the permissions check. """
obj = (
hasattr(self, 'get_c... |
def plot_learning_curve(clf, X, y, title='Learning Curve', cv=None,
shuffle=False, random_state=None,
train_sizes=None, n_jobs=1, scoring=None,
ax=None, figsize=None, title_fontsize="large",
text_fontsize="medium"):
"""G... | Generates a plot of the train and test learning curves for a classifier.
Args:
clf: Classifier instance that implements ``fit`` and ``predict``
methods.
X (array-like, shape (n_samples, n_features)):
Training vector, where n_samples is the number of samples and
... | Below is the the instruction that describes the task:
### Input:
Generates a plot of the train and test learning curves for a classifier.
Args:
clf: Classifier instance that implements ``fit`` and ``predict``
methods.
X (array-like, shape (n_samples, n_features)):
Train... |
def pi_revision():
"""Detect the revision number of a Raspberry Pi, useful for changing
functionality like default I2C bus based on revision."""
# Revision list available at: http://elinux.org/RPi_HardwareHistory#Board_Revision_History
with open('/proc/cpuinfo', 'r') as infile:
for line in infil... | Detect the revision number of a Raspberry Pi, useful for changing
functionality like default I2C bus based on revision. | Below is the the instruction that describes the task:
### Input:
Detect the revision number of a Raspberry Pi, useful for changing
functionality like default I2C bus based on revision.
### Response:
def pi_revision():
"""Detect the revision number of a Raspberry Pi, useful for changing
functionality li... |
def stop(self):
"""Stop serving. Always call this to clean up after yourself."""
self._stopped = True
threads = [self._accept_thread]
threads.extend(self._server_threads)
self._listening_sock.close()
for sock in list(self._server_socks):
try:
s... | Stop serving. Always call this to clean up after yourself. | Below is the the instruction that describes the task:
### Input:
Stop serving. Always call this to clean up after yourself.
### Response:
def stop(self):
"""Stop serving. Always call this to clean up after yourself."""
self._stopped = True
threads = [self._accept_thread]
threads.ext... |
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
"""
# extract dictionaries of coefficients specific to required
# ... | See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values. | Below is the the instruction that describes the task:
### Input:
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
### Response:
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
See :m... |
def fill_binop(left, right, fill_value):
"""
If a non-None fill_value is given, replace null entries in left and right
with this value, but only in positions where _one_ of left/right is null,
not both.
Parameters
----------
left : array-like
right : array-like
fill_value : object
... | If a non-None fill_value is given, replace null entries in left and right
with this value, but only in positions where _one_ of left/right is null,
not both.
Parameters
----------
left : array-like
right : array-like
fill_value : object
Returns
-------
left : array-like
rig... | Below is the the instruction that describes the task:
### Input:
If a non-None fill_value is given, replace null entries in left and right
with this value, but only in positions where _one_ of left/right is null,
not both.
Parameters
----------
left : array-like
right : array-like
fill_... |
def get_graph_data(self, graph, benchmark):
"""
Iterator over graph data sets
Yields
------
param_idx
Flat index to parameter permutations for parameterized benchmarks.
None if benchmark is not parameterized.
entry_name
Name for the da... | Iterator over graph data sets
Yields
------
param_idx
Flat index to parameter permutations for parameterized benchmarks.
None if benchmark is not parameterized.
entry_name
Name for the data set. If benchmark is non-parameterized, this is the
... | Below is the the instruction that describes the task:
### Input:
Iterator over graph data sets
Yields
------
param_idx
Flat index to parameter permutations for parameterized benchmarks.
None if benchmark is not parameterized.
entry_name
Name for t... |
def count(self):
"""
Return a new DStream in which each RDD has a single element
generated by counting each RDD of this DStream.
"""
return self.mapPartitions(lambda i: [sum(1 for _ in i)]).reduce(operator.add) | Return a new DStream in which each RDD has a single element
generated by counting each RDD of this DStream. | Below is the the instruction that describes the task:
### Input:
Return a new DStream in which each RDD has a single element
generated by counting each RDD of this DStream.
### Response:
def count(self):
"""
Return a new DStream in which each RDD has a single element
generated by co... |
def simple_predictive_probability_multistate(
self, M_c, X_L_list, X_D_list, Y, Q):
"""Calculate probability of a cell taking a value given a latent state.
:param Y: A list of constraints to apply when querying. Each constraint
is a triplet of (r,d,v): r is the row index, d is ... | Calculate probability of a cell taking a value given a latent state.
:param Y: A list of constraints to apply when querying. Each constraint
is a triplet of (r,d,v): r is the row index, d is the column
index and v is the value of the constraint
:type Y: list of lists
:... | Below is the the instruction that describes the task:
### Input:
Calculate probability of a cell taking a value given a latent state.
:param Y: A list of constraints to apply when querying. Each constraint
is a triplet of (r,d,v): r is the row index, d is the column
index and v is ... |
def pdf(cls, mass, log_mode=True):
""" PDF for the Kroupa IMF.
Normalization is set over the mass range from 0.1 Msun to 100 Msun
"""
log_mass = np.log10(mass)
# From Eq 2
mb = mbreak = [0.08, 0.5] # Msun
a = alpha = [0.3, 1.3, 2.3] # alpha
# Normalizat... | PDF for the Kroupa IMF.
Normalization is set over the mass range from 0.1 Msun to 100 Msun | Below is the the instruction that describes the task:
### Input:
PDF for the Kroupa IMF.
Normalization is set over the mass range from 0.1 Msun to 100 Msun
### Response:
def pdf(cls, mass, log_mode=True):
""" PDF for the Kroupa IMF.
Normalization is set over the mass range from 0.1 Msun t... |
def submit_cookbook(self, cookbook, params={}, _extra_params={}):
"""
Submit a cookbook.
"""
self._check_user_parameters(params)
files = {'cookbook': cookbook}
return self._submit(params, files, _extra_params=_extra_params) | Submit a cookbook. | Below is the the instruction that describes the task:
### Input:
Submit a cookbook.
### Response:
def submit_cookbook(self, cookbook, params={}, _extra_params={}):
"""
Submit a cookbook.
"""
self._check_user_parameters(params)
files = {'cookbook': cookbook}
return se... |
def _merge_ex_dicts(sexdict, oexdict):
"""Merge callable look-up tables from two objects."""
# pylint: disable=R0101
for okey, ovalue in oexdict.items():
# Keys in other dictionary are callable paths or
# callables ids depending on the full_cname argument
# of the handler
if ... | Merge callable look-up tables from two objects. | Below is the the instruction that describes the task:
### Input:
Merge callable look-up tables from two objects.
### Response:
def _merge_ex_dicts(sexdict, oexdict):
"""Merge callable look-up tables from two objects."""
# pylint: disable=R0101
for okey, ovalue in oexdict.items():
# Keys in othe... |
def load(target:str, namespace:str=None, default=nodefault, executable:bool=False, separators:Sequence[str]=('.', ':'),
protect:bool=True):
"""This helper function loads an object identified by a dotted-notation string.
For example::
# Load class Foo from example.objects
load('example.objects:Foo')
# L... | This helper function loads an object identified by a dotted-notation string.
For example::
# Load class Foo from example.objects
load('example.objects:Foo')
# Load the result of the class method ``new`` of the Foo object
load('example.objects:Foo.new', executable=True)
If a plugin namespace is provid... | Below is the the instruction that describes the task:
### Input:
This helper function loads an object identified by a dotted-notation string.
For example::
# Load class Foo from example.objects
load('example.objects:Foo')
# Load the result of the class method ``new`` of the Foo object
load('example.... |
def assemble(
cls,
args,
input_tube,
output_tubes,
size,
disable_result,
do_stop_task,
):
"""Create, assemble and start workers.
Workers are created of class *cls*, initialized with *args*, and given
task/result communication c... | Create, assemble and start workers.
Workers are created of class *cls*, initialized with *args*, and given
task/result communication channels *input_tube* and *output_tubes*.
The number of workers created is according to *size* parameter.
*do_stop_task* indicates whether doTask() will be... | Below is the the instruction that describes the task:
### Input:
Create, assemble and start workers.
Workers are created of class *cls*, initialized with *args*, and given
task/result communication channels *input_tube* and *output_tubes*.
The number of workers created is according to *size*... |
def _extract_links_from_lecture_assets(self, asset_ids):
"""
Extract links to files of the asset ids.
@param asset_ids: List of asset ids.
@type asset_ids: [str]
@return: @see CourseraOnDemand._extract_links_from_text
"""
links = {}
def _add_asset(name,... | Extract links to files of the asset ids.
@param asset_ids: List of asset ids.
@type asset_ids: [str]
@return: @see CourseraOnDemand._extract_links_from_text | Below is the the instruction that describes the task:
### Input:
Extract links to files of the asset ids.
@param asset_ids: List of asset ids.
@type asset_ids: [str]
@return: @see CourseraOnDemand._extract_links_from_text
### Response:
def _extract_links_from_lecture_assets(self, asset_id... |
def iter_breadth_first(self, root=None):
""" Traverses the belief state's structure breadth-first """
if root == None:
root = self
yield root
last = root
for node in self.iter_breadth_first(root):
if isinstance(node, DictCell):
# recurse
... | Traverses the belief state's structure breadth-first | Below is the the instruction that describes the task:
### Input:
Traverses the belief state's structure breadth-first
### Response:
def iter_breadth_first(self, root=None):
""" Traverses the belief state's structure breadth-first """
if root == None:
root = self
yield root
... |
def get_form_kwargs(self):
"""
Build the keyword arguments required to instantiate the form.
"""
kwargs = {}
for key in six.iterkeys(self.form_classes):
if self.request.method in ('POST', 'PUT'):
kwargs[key] = {
'data': self.reques... | Build the keyword arguments required to instantiate the form. | Below is the the instruction that describes the task:
### Input:
Build the keyword arguments required to instantiate the form.
### Response:
def get_form_kwargs(self):
"""
Build the keyword arguments required to instantiate the form.
"""
kwargs = {}
for key in six.iterkeys(... |
def get_port_profile_for_intf_output_interface_interface_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_port_profile_for_intf = ET.Element("get_port_profile_for_intf")
config = get_port_profile_for_intf
output = ET.SubElement(get_port_p... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def get_port_profile_for_intf_output_interface_interface_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_port_profile_for_intf = ET.Element("get_port... |
def DateField(formatter=types.DEFAULT_DATE_FORMAT, default=NOTHING,
required=True, repr=True, cmp=True, key=None):
"""
Create new date field on a model.
:param formatter: date formatter string (default: "%Y-%m-%d")
:param default: any date or string that can be converted to a date value
... | Create new date field on a model.
:param formatter: date formatter string (default: "%Y-%m-%d")
:param default: any date or string that can be converted to a date value
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in obje... | Below is the the instruction that describes the task:
### Input:
Create new date field on a model.
:param formatter: date formatter string (default: "%Y-%m-%d")
:param default: any date or string that can be converted to a date value
:param bool required: whether or not the object is invalid if not pro... |
def generate(self, save=True):
"""
Generates photo file in current format.
If ``save`` is ``True``, file is saved too.
"""
stretched_photo, crop_box = self._generate_img()
# set crop_box to (0,0,0,0) if photo not cropped
if not crop_box:
crop_box = 0... | Generates photo file in current format.
If ``save`` is ``True``, file is saved too. | Below is the the instruction that describes the task:
### Input:
Generates photo file in current format.
If ``save`` is ``True``, file is saved too.
### Response:
def generate(self, save=True):
"""
Generates photo file in current format.
If ``save`` is ``True``, file is saved too.... |
def open_dataset(self, recent=None, debug_filename=None, bids=False):
"""Open a new dataset.
Parameters
----------
recent : path to file
one of the recent datasets to read
"""
if recent:
filename = recent
elif debug_filename is not None:
... | Open a new dataset.
Parameters
----------
recent : path to file
one of the recent datasets to read | Below is the the instruction that describes the task:
### Input:
Open a new dataset.
Parameters
----------
recent : path to file
one of the recent datasets to read
### Response:
def open_dataset(self, recent=None, debug_filename=None, bids=False):
"""Open a new dataset.... |
def datasets_delete(self, dataset_name, delete_contents):
"""Issues a request to delete a dataset.
Args:
dataset_name: the name of the dataset to delete.
delete_contents: if True, any tables in the dataset will be deleted. If False and the
dataset is non-empty an exception will be raised.... | Issues a request to delete a dataset.
Args:
dataset_name: the name of the dataset to delete.
delete_contents: if True, any tables in the dataset will be deleted. If False and the
dataset is non-empty an exception will be raised.
Returns:
A parsed result object.
Raises:
Exc... | Below is the the instruction that describes the task:
### Input:
Issues a request to delete a dataset.
Args:
dataset_name: the name of the dataset to delete.
delete_contents: if True, any tables in the dataset will be deleted. If False and the
dataset is non-empty an exception will be rai... |
def to_location(location):
"""Serializes location to string
:param location: object to serialize
:return: string
"""
if not location:
raise SbgError('Location is required!')
if isinstance(location, six.string_types):
return location
else:
... | Serializes location to string
:param location: object to serialize
:return: string | Below is the the instruction that describes the task:
### Input:
Serializes location to string
:param location: object to serialize
:return: string
### Response:
def to_location(location):
"""Serializes location to string
:param location: object to serialize
:return: string
... |
def all(self, data={}, **kwargs):
""""
Fetch all Invoice entities
Returns:
Dictionary of Invoice data
"""
return super(Invoice, self).all(data, **kwargs) | Fetch all Invoice entities
Returns:
Dictionary of Invoice data | Below is the the instruction that describes the task:
### Input:
Fetch all Invoice entities
Returns:
Dictionary of Invoice data
### Response:
def all(self, data={}, **kwargs):
""""
Fetch all Invoice entities
Returns:
Dictionary of Invoice data
"""
... |
def login(self, username, password, mode="demo"):
"""login function"""
url = "https://trading212.com/it/login"
try:
logger.debug(f"visiting %s" % url)
self.browser.visit(url)
logger.debug(f"connected to %s" % url)
except selenium.common.exceptions.WebD... | login function | Below is the the instruction that describes the task:
### Input:
login function
### Response:
def login(self, username, password, mode="demo"):
"""login function"""
url = "https://trading212.com/it/login"
try:
logger.debug(f"visiting %s" % url)
self.browser.visit(url... |
def get_preference_type(self, type, user_id, address, notification):
"""
Get a preference.
Fetch the preference for the given notification for the given communicaiton channel
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - user_id
... | Get a preference.
Fetch the preference for the given notification for the given communicaiton channel | Below is the the instruction that describes the task:
### Input:
Get a preference.
Fetch the preference for the given notification for the given communicaiton channel
### Response:
def get_preference_type(self, type, user_id, address, notification):
"""
Get a preference.
Fet... |
def do_rmpostfix(self, arg):
"""Removes a postfix function from a variable. See 'postfix'."""
altered = False
if arg in self.curargs["functions"]:
del self.curargs["functions"][arg]
altered = True
elif arg == "*":
for varname in list(self.curargs["func... | Removes a postfix function from a variable. See 'postfix'. | Below is the the instruction that describes the task:
### Input:
Removes a postfix function from a variable. See 'postfix'.
### Response:
def do_rmpostfix(self, arg):
"""Removes a postfix function from a variable. See 'postfix'."""
altered = False
if arg in self.curargs["functions"]:
... |
def setExtraSelections(self, selections):
"""Set list of extra selections.
Selections are list of tuples ``(startAbsolutePosition, length)``.
Extra selections are reset on any text modification.
This is reimplemented method of QPlainTextEdit, it has different signature. Do not use QPlai... | Set list of extra selections.
Selections are list of tuples ``(startAbsolutePosition, length)``.
Extra selections are reset on any text modification.
This is reimplemented method of QPlainTextEdit, it has different signature. Do not use QPlainTextEdit method | Below is the the instruction that describes the task:
### Input:
Set list of extra selections.
Selections are list of tuples ``(startAbsolutePosition, length)``.
Extra selections are reset on any text modification.
This is reimplemented method of QPlainTextEdit, it has different signature. ... |
def setFilenames( self, filenames ):
"""
Sets the list of filenames that will be used for this menu to the \
inputed list.
:param filenames | [<str>, ..]
"""
mapped = []
for filename in filenames:
filename = nativestring(filename)
... | Sets the list of filenames that will be used for this menu to the \
inputed list.
:param filenames | [<str>, ..] | Below is the the instruction that describes the task:
### Input:
Sets the list of filenames that will be used for this menu to the \
inputed list.
:param filenames | [<str>, ..]
### Response:
def setFilenames( self, filenames ):
"""
Sets the list of filenames that will... |
def _assign_database_backend(self, db):
"""Assign Trace instance to stochastics and deterministics and Database instance
to self.
:Parameters:
- `db` : string, Database instance
The name of the database module (see below), or a Database instance.
Available databas... | Assign Trace instance to stochastics and deterministics and Database instance
to self.
:Parameters:
- `db` : string, Database instance
The name of the database module (see below), or a Database instance.
Available databases:
- `no_trace` : Traces are not stored ... | Below is the the instruction that describes the task:
### Input:
Assign Trace instance to stochastics and deterministics and Database instance
to self.
:Parameters:
- `db` : string, Database instance
The name of the database module (see below), or a Database instance.
... |
def set_rotation_rate(self, val):
"""value ca be between 0x00 and 0xFF:
value is a multiplied with 0.784 degrees/s except for:
0 --> 1 degrees/s
255 --> jumps to 400 degrees/s
"""
return self.write(request.SetRotationRate(self.seq, val)) | value ca be between 0x00 and 0xFF:
value is a multiplied with 0.784 degrees/s except for:
0 --> 1 degrees/s
255 --> jumps to 400 degrees/s | Below is the the instruction that describes the task:
### Input:
value ca be between 0x00 and 0xFF:
value is a multiplied with 0.784 degrees/s except for:
0 --> 1 degrees/s
255 --> jumps to 400 degrees/s
### Response:
def set_rotation_rate(self, val):
"""value ca be be... |
def graph_nodes_sorted(self):
""" Returns an (ascending) sorted list of graph's nodes (name is used as key).
Returns
-------
:any:`list`
Description #TODO check
"""
return sorted(self._graph.nodes(), key=lambda _: repr(_)) | Returns an (ascending) sorted list of graph's nodes (name is used as key).
Returns
-------
:any:`list`
Description #TODO check | Below is the the instruction that describes the task:
### Input:
Returns an (ascending) sorted list of graph's nodes (name is used as key).
Returns
-------
:any:`list`
Description #TODO check
### Response:
def graph_nodes_sorted(self):
""" Returns an (ascending)... |
def course_is_open_to_user(self, course, username=None, lti=None):
"""
Checks if a user is can access a course
:param course: a Course object
:param username: The username of the user that we want to check. If None, uses self.session_username()
:param lti: indicates if the user i... | Checks if a user is can access a course
:param course: a Course object
:param username: The username of the user that we want to check. If None, uses self.session_username()
:param lti: indicates if the user is currently in a LTI session or not.
- None to ignore the check
... | Below is the the instruction that describes the task:
### Input:
Checks if a user is can access a course
:param course: a Course object
:param username: The username of the user that we want to check. If None, uses self.session_username()
:param lti: indicates if the user is currently in a L... |
def editex(src, tar, cost=(0, 1, 2), local=False):
"""Return the Editex distance between two strings.
This is a wrapper for :py:meth:`Editex.dist_abs`.
Parameters
----------
src : str
Source string for comparison
tar : str
Target string for comparison
cost : tuple
A... | Return the Editex distance between two strings.
This is a wrapper for :py:meth:`Editex.dist_abs`.
Parameters
----------
src : str
Source string for comparison
tar : str
Target string for comparison
cost : tuple
A 3-tuple representing the cost of the four possible edits:... | Below is the the instruction that describes the task:
### Input:
Return the Editex distance between two strings.
This is a wrapper for :py:meth:`Editex.dist_abs`.
Parameters
----------
src : str
Source string for comparison
tar : str
Target string for comparison
cost : tupl... |
def point_seg_sep(ar, br1, br2):
"""Return the minimum separation vector between a point and a line segment,
in 3 dimensions.
Parameters
----------
ar: array-like, shape (3,)
Coordinates of a point.
br1, br2: array-like, shape (3,)
Coordinates for the points of a line segment
... | Return the minimum separation vector between a point and a line segment,
in 3 dimensions.
Parameters
----------
ar: array-like, shape (3,)
Coordinates of a point.
br1, br2: array-like, shape (3,)
Coordinates for the points of a line segment
Returns
-------
sep: float ar... | Below is the the instruction that describes the task:
### Input:
Return the minimum separation vector between a point and a line segment,
in 3 dimensions.
Parameters
----------
ar: array-like, shape (3,)
Coordinates of a point.
br1, br2: array-like, shape (3,)
Coordinates for th... |
async def main():
"""The main part of the example script."""
async with aiohttp.ClientSession() as session:
data = Glances(loop, session, version=VERSION)
# Get the metrics for the memory
await data.get_metrics('mem')
# Print the values
print("Memory values:", data.valu... | The main part of the example script. | Below is the the instruction that describes the task:
### Input:
The main part of the example script.
### Response:
async def main():
"""The main part of the example script."""
async with aiohttp.ClientSession() as session:
data = Glances(loop, session, version=VERSION)
# Get the metrics f... |
def data(self, index, role=Qt.DisplayRole):
"""Cell content"""
if not index.isValid():
return to_qvariant()
value = self.get_value(index)
if index.column() == 3 and self.remote:
value = value['view']
if index.column() == 3:
display = va... | Cell content | Below is the the instruction that describes the task:
### Input:
Cell content
### Response:
def data(self, index, role=Qt.DisplayRole):
"""Cell content"""
if not index.isValid():
return to_qvariant()
value = self.get_value(index)
if index.column() == 3 and self.remo... |
def get_state_paths(cls, impl, working_dir):
"""
Get the set of state paths that point to the current chain and state info.
Returns a list of paths.
"""
return [config.get_db_filename(impl, working_dir), config.get_snapshots_filename(impl, working_dir)] | Get the set of state paths that point to the current chain and state info.
Returns a list of paths. | Below is the the instruction that describes the task:
### Input:
Get the set of state paths that point to the current chain and state info.
Returns a list of paths.
### Response:
def get_state_paths(cls, impl, working_dir):
"""
Get the set of state paths that point to the current chain and ... |
def redirect_std():
"""
Connect stdin/stdout to controlling terminal even if the scripts input and output
were redirected. This is useful in utilities based on termenu.
"""
stdin = sys.stdin
stdout = sys.stdout
if not sys.stdin.isatty():
sys.stdin = open_raw("/dev/tty", "r", 0)
i... | Connect stdin/stdout to controlling terminal even if the scripts input and output
were redirected. This is useful in utilities based on termenu. | Below is the the instruction that describes the task:
### Input:
Connect stdin/stdout to controlling terminal even if the scripts input and output
were redirected. This is useful in utilities based on termenu.
### Response:
def redirect_std():
"""
Connect stdin/stdout to controlling terminal even if th... |
def update_user_type(self):
"""Return either 'tutor' or 'student' based on which radio
button is selected.
"""
if self.rb_tutor.isChecked():
self.user_type = 'tutor'
elif self.rb_student.isChecked():
self.user_type = 'student'
self.accept() | Return either 'tutor' or 'student' based on which radio
button is selected. | Below is the the instruction that describes the task:
### Input:
Return either 'tutor' or 'student' based on which radio
button is selected.
### Response:
def update_user_type(self):
"""Return either 'tutor' or 'student' based on which radio
button is selected.
"""
if self.r... |
def disconnect():
""" disconnect signals """
post_save.disconnect(node_created_handler, sender=Node)
node_status_changed.disconnect(node_status_changed_handler)
pre_delete.disconnect(node_deleted_handler, sender=Node) | disconnect signals | Below is the the instruction that describes the task:
### Input:
disconnect signals
### Response:
def disconnect():
""" disconnect signals """
post_save.disconnect(node_created_handler, sender=Node)
node_status_changed.disconnect(node_status_changed_handler)
pre_delete.disconnect(node_deleted_handl... |
async def send_animation(self,
animation: typing.Union[base.InputFile, base.String],
duration: typing.Union[base.Integer, None] = None,
width: typing.Union[base.Integer, None] = None,
height: typing.Union... | Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound).
On success, the sent Message is returned.
Bots can currently send animation files of up to 50 MB in size, this limit may be changed in the future.
Source https://core.telegram.org/bots/api#sendanimation
... | Below is the the instruction that describes the task:
### Input:
Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound).
On success, the sent Message is returned.
Bots can currently send animation files of up to 50 MB in size, this limit may be changed in the future.
... |
def reset_stats_history(self):
"""Reset the stats history (dict of GlancesAttribute)."""
if self.history_enable():
reset_list = [a['name'] for a in self.get_items_history_list()]
logger.debug("Reset history for plugin {} (items: {})".format(self.plugin_name, reset_list))
... | Reset the stats history (dict of GlancesAttribute). | Below is the the instruction that describes the task:
### Input:
Reset the stats history (dict of GlancesAttribute).
### Response:
def reset_stats_history(self):
"""Reset the stats history (dict of GlancesAttribute)."""
if self.history_enable():
reset_list = [a['name'] for a in self.get... |
def sg_lookup(tensor, opt):
r"""Looks up the `tensor`, which is the embedding matrix.
Args:
tensor: A tensor ( automatically given by chain )
opt:
emb: A 2-D `Tensor`. An embedding matrix.
name: If provided, replace current tensor's name.
Returns:
A `Tensor`.
... | r"""Looks up the `tensor`, which is the embedding matrix.
Args:
tensor: A tensor ( automatically given by chain )
opt:
emb: A 2-D `Tensor`. An embedding matrix.
name: If provided, replace current tensor's name.
Returns:
A `Tensor`. | Below is the the instruction that describes the task:
### Input:
r"""Looks up the `tensor`, which is the embedding matrix.
Args:
tensor: A tensor ( automatically given by chain )
opt:
emb: A 2-D `Tensor`. An embedding matrix.
name: If provided, replace current tensor's name.... |
def vinet_k_num(v, v0, k0, k0p, precision=1.e-5):
"""
calculate bulk modulus numerically from volume, not pressure
according to test this differs from analytical result by 1.e-5
:param v: unit-cell volume in A^3
:param v0: unit-cell volume in A^3 at 1 bar
:param k0: bulk modulus at reference co... | calculate bulk modulus numerically from volume, not pressure
according to test this differs from analytical result by 1.e-5
:param v: unit-cell volume in A^3
:param v0: unit-cell volume in A^3 at 1 bar
:param k0: bulk modulus at reference conditions
:param k0p: pressure derivative of bulk modulus a... | Below is the the instruction that describes the task:
### Input:
calculate bulk modulus numerically from volume, not pressure
according to test this differs from analytical result by 1.e-5
:param v: unit-cell volume in A^3
:param v0: unit-cell volume in A^3 at 1 bar
:param k0: bulk modulus at refer... |
def get_child_ids(self, parent_alias):
"""Returns child IDs of the given parent category
:param str parent_alias: Parent category alias
:rtype: list
:return: a list of child IDs
"""
self._cache_init()
return self._cache_get_entry(self.CACHE_NAME_PARENTS, parent_a... | Returns child IDs of the given parent category
:param str parent_alias: Parent category alias
:rtype: list
:return: a list of child IDs | Below is the the instruction that describes the task:
### Input:
Returns child IDs of the given parent category
:param str parent_alias: Parent category alias
:rtype: list
:return: a list of child IDs
### Response:
def get_child_ids(self, parent_alias):
"""Returns child IDs of the ... |
def _variable(lexer):
"""Return a variable expression."""
names = _names(lexer)
tok = next(lexer)
# NAMES '[' ... ']'
if isinstance(tok, LBRACK):
indices = _indices(lexer)
_expect_token(lexer, {RBRACK})
# NAMES
else:
lexer.unpop_token(tok)
indices = tuple()
... | Return a variable expression. | Below is the the instruction that describes the task:
### Input:
Return a variable expression.
### Response:
def _variable(lexer):
"""Return a variable expression."""
names = _names(lexer)
tok = next(lexer)
# NAMES '[' ... ']'
if isinstance(tok, LBRACK):
indices = _indices(lexer)
... |
def _process_container_metric(self, type, metric_name, metric, scraper_config):
"""
Takes a simple metric about a container, reports it as a rate or gauge.
If several series are found for a given container, values are summed before submission.
"""
if metric.type not in METRIC_TYP... | Takes a simple metric about a container, reports it as a rate or gauge.
If several series are found for a given container, values are summed before submission. | Below is the the instruction that describes the task:
### Input:
Takes a simple metric about a container, reports it as a rate or gauge.
If several series are found for a given container, values are summed before submission.
### Response:
def _process_container_metric(self, type, metric_name, metric, scrap... |
def open_in_composer(self):
"""Open in layout designer a given MapReport instance.
.. versionadded: 4.3.0
"""
impact_layer = self.impact_function.analysis_impacted
report_path = dirname(impact_layer.source())
impact_report = self.impact_function.impact_report
cu... | Open in layout designer a given MapReport instance.
.. versionadded: 4.3.0 | Below is the the instruction that describes the task:
### Input:
Open in layout designer a given MapReport instance.
.. versionadded: 4.3.0
### Response:
def open_in_composer(self):
"""Open in layout designer a given MapReport instance.
.. versionadded: 4.3.0
"""
impact_la... |
def replicated_dataset(dataset, weights, n=None):
"Copy dataset, replicating each example in proportion to its weight."
n = n or len(dataset.examples)
result = copy.copy(dataset)
result.examples = weighted_replicate(dataset.examples, weights, n)
return result | Copy dataset, replicating each example in proportion to its weight. | Below is the the instruction that describes the task:
### Input:
Copy dataset, replicating each example in proportion to its weight.
### Response:
def replicated_dataset(dataset, weights, n=None):
"Copy dataset, replicating each example in proportion to its weight."
n = n or len(dataset.examples)
resul... |
def collect(self):
"""Collect statistics from /proc/self/mountstats.
Currently, we do fairly naive parsing and do not actually check
the statvers value returned by mountstats.
"""
if str_to_bool(self.config['use_sudo']):
if not os.access(self.config['sudo_cmd'], os.... | Collect statistics from /proc/self/mountstats.
Currently, we do fairly naive parsing and do not actually check
the statvers value returned by mountstats. | Below is the the instruction that describes the task:
### Input:
Collect statistics from /proc/self/mountstats.
Currently, we do fairly naive parsing and do not actually check
the statvers value returned by mountstats.
### Response:
def collect(self):
"""Collect statistics from /proc/self/... |
def MFI(frame, n=14, high_col='high', low_col='low', close_col='close', vol_col='Volume'):
"""money flow inedx"""
return _frame_to_series(frame, [high_col, low_col, close_col, vol_col], talib.MFI, n) | money flow inedx | Below is the the instruction that describes the task:
### Input:
money flow inedx
### Response:
def MFI(frame, n=14, high_col='high', low_col='low', close_col='close', vol_col='Volume'):
"""money flow inedx"""
return _frame_to_series(frame, [high_col, low_col, close_col, vol_col], talib.MFI, n) |
def participate(self):
"""Finish reading and send text"""
try:
logger.info("Entering participate method")
ready = WebDriverWait(self.driver, 10).until(
EC.element_to_be_clickable((By.ID, "finish-reading"))
)
stimulus = self.driver.find_elem... | Finish reading and send text | Below is the the instruction that describes the task:
### Input:
Finish reading and send text
### Response:
def participate(self):
"""Finish reading and send text"""
try:
logger.info("Entering participate method")
ready = WebDriverWait(self.driver, 10).until(
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.