code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def get_stories(self, userids: Optional[List[int]] = None) -> Iterator[Story]:
"""Get available stories from followees or all stories of users whose ID are given.
Does not mark stories as seen.
To use this, one needs to be logged in
:param userids: List of user IDs to be processed in te... | Get available stories from followees or all stories of users whose ID are given.
Does not mark stories as seen.
To use this, one needs to be logged in
:param userids: List of user IDs to be processed in terms of downloading their stories, or None. | Below is the the instruction that describes the task:
### Input:
Get available stories from followees or all stories of users whose ID are given.
Does not mark stories as seen.
To use this, one needs to be logged in
:param userids: List of user IDs to be processed in terms of downloading th... |
def raise_exception_if_baseline_file_is_unstaged(filename):
"""We want to make sure that if there are changes to the baseline
file, they will be included in the commit. This way, we can keep
our baselines up-to-date.
:raises: ValueError
"""
try:
files_changed_but_not_staged = subprocess... | We want to make sure that if there are changes to the baseline
file, they will be included in the commit. This way, we can keep
our baselines up-to-date.
:raises: ValueError | Below is the the instruction that describes the task:
### Input:
We want to make sure that if there are changes to the baseline
file, they will be included in the commit. This way, we can keep
our baselines up-to-date.
:raises: ValueError
### Response:
def raise_exception_if_baseline_file_is_unstaged(... |
async def display_columns_and_rows(
self,
database,
table,
description,
rows,
link_column=False,
truncate_cells=0,
):
"Returns columns, rows for specified table - including fancy foreign key treatment"
table_metadata = self.ds.table_metadata(da... | Returns columns, rows for specified table - including fancy foreign key treatment | Below is the the instruction that describes the task:
### Input:
Returns columns, rows for specified table - including fancy foreign key treatment
### Response:
async def display_columns_and_rows(
self,
database,
table,
description,
rows,
link_column=False,
t... |
def from_uint8(arr_uint8, shape, min_value=0.0, max_value=1.0):
"""
Create a heatmaps object from an heatmap array containing values ranging from 0 to 255.
Parameters
----------
arr_uint8 : (H,W) ndarray or (H,W,C) ndarray
Heatmap(s) array, where ``H`` is height, ``W... | Create a heatmaps object from an heatmap array containing values ranging from 0 to 255.
Parameters
----------
arr_uint8 : (H,W) ndarray or (H,W,C) ndarray
Heatmap(s) array, where ``H`` is height, ``W`` is width and ``C`` is the number of heatmap channels.
Expected dtype ... | Below is the the instruction that describes the task:
### Input:
Create a heatmaps object from an heatmap array containing values ranging from 0 to 255.
Parameters
----------
arr_uint8 : (H,W) ndarray or (H,W,C) ndarray
Heatmap(s) array, where ``H`` is height, ``W`` is width and... |
def with_mfa(self, mfa_token):
"""Set the MFA token for the next request.
`mfa_token`s are only good for one request. Use this method to chain into
the protected action you want to perform.
Note: Only useful for Application authentication.
Usage:
account.with_mfa(appli... | Set the MFA token for the next request.
`mfa_token`s are only good for one request. Use this method to chain into
the protected action you want to perform.
Note: Only useful for Application authentication.
Usage:
account.with_mfa(application.totp.now()).pay(...)
Args:... | Below is the the instruction that describes the task:
### Input:
Set the MFA token for the next request.
`mfa_token`s are only good for one request. Use this method to chain into
the protected action you want to perform.
Note: Only useful for Application authentication.
Usage:
... |
def get_best_splitting_attr(self):
"""
Returns the name of the attribute with the highest gain.
"""
best = (-1e999999, None)
for attr in self.attributes:
best = max(best, (self.get_gain(attr), attr))
best_gain, best_attr = best
return best_attr | Returns the name of the attribute with the highest gain. | Below is the the instruction that describes the task:
### Input:
Returns the name of the attribute with the highest gain.
### Response:
def get_best_splitting_attr(self):
"""
Returns the name of the attribute with the highest gain.
"""
best = (-1e999999, None)
for attr in se... |
def decrease_writes_in_units(
current_provisioning, units, min_provisioned_writes, log_tag):
""" Decrease the current_provisioning with units units
:type current_provisioning: int
:param current_provisioning: The current provisioning
:type units: int
:param units: How many units should we d... | Decrease the current_provisioning with units units
:type current_provisioning: int
:param current_provisioning: The current provisioning
:type units: int
:param units: How many units should we decrease with
:returns: int -- New provisioning value
:type min_provisioned_writes: int
:param min... | Below is the the instruction that describes the task:
### Input:
Decrease the current_provisioning with units units
:type current_provisioning: int
:param current_provisioning: The current provisioning
:type units: int
:param units: How many units should we decrease with
:returns: int -- New pr... |
def safe_call(cls, method, *args):
""" Call a remote api method but don't raise if an error occurred."""
return cls.call(method, *args, safe=True) | Call a remote api method but don't raise if an error occurred. | Below is the the instruction that describes the task:
### Input:
Call a remote api method but don't raise if an error occurred.
### Response:
def safe_call(cls, method, *args):
""" Call a remote api method but don't raise if an error occurred."""
return cls.call(method, *args, safe=True) |
def ap_state(value, failure_string=None):
"""
Converts a state's name, postal abbreviation or FIPS to A.P. style.
Example usage:
>> ap_state("California")
'Calif.'
"""
try:
return statestyle.get(value).ap
except:
if failure_string:
retur... | Converts a state's name, postal abbreviation or FIPS to A.P. style.
Example usage:
>> ap_state("California")
'Calif.' | Below is the the instruction that describes the task:
### Input:
Converts a state's name, postal abbreviation or FIPS to A.P. style.
Example usage:
>> ap_state("California")
'Calif.'
### Response:
def ap_state(value, failure_string=None):
"""
Converts a state's name, postal ab... |
def _get_path(entity_id):
'''Get the entity_id as a string if it is a Reference.
@param entity_id The ID either a reference or a string of the entity
to get.
@return entity_id as a string
'''
try:
path = entity_id.path()
except AttributeError:
path = entity_id
if p... | Get the entity_id as a string if it is a Reference.
@param entity_id The ID either a reference or a string of the entity
to get.
@return entity_id as a string | Below is the the instruction that describes the task:
### Input:
Get the entity_id as a string if it is a Reference.
@param entity_id The ID either a reference or a string of the entity
to get.
@return entity_id as a string
### Response:
def _get_path(entity_id):
'''Get the entity_id as a st... |
def downgrades(src):
"""Decorator for marking that a method is a downgrade to a version to the
previous version.
Parameters
----------
src : int
The version this downgrades from.
Returns
-------
decorator : callable[(callable) -> callable]
The decorator to apply.
""... | Decorator for marking that a method is a downgrade to a version to the
previous version.
Parameters
----------
src : int
The version this downgrades from.
Returns
-------
decorator : callable[(callable) -> callable]
The decorator to apply. | Below is the the instruction that describes the task:
### Input:
Decorator for marking that a method is a downgrade to a version to the
previous version.
Parameters
----------
src : int
The version this downgrades from.
Returns
-------
decorator : callable[(callable) -> callabl... |
def observe(self, seconds=None):
""" Begins the observer loop (synchronously).
Loops for ``seconds`` or until this region's stopObserver() method is called.
If ``seconds`` is None, the observer loop cycles until stopped. If this
method is called while the observer loop is already runnin... | Begins the observer loop (synchronously).
Loops for ``seconds`` or until this region's stopObserver() method is called.
If ``seconds`` is None, the observer loop cycles until stopped. If this
method is called while the observer loop is already running, it returns False.
Returns True if... | Below is the the instruction that describes the task:
### Input:
Begins the observer loop (synchronously).
Loops for ``seconds`` or until this region's stopObserver() method is called.
If ``seconds`` is None, the observer loop cycles until stopped. If this
method is called while the observe... |
def infer_named_tuple(node, context=None):
"""Specific inference function for namedtuple Call node"""
tuple_base_name = nodes.Name(name="tuple", parent=node.root())
class_node, name, attributes = infer_func_form(
node, tuple_base_name, context=context
)
call_site = arguments.CallSite.from_ca... | Specific inference function for namedtuple Call node | Below is the the instruction that describes the task:
### Input:
Specific inference function for namedtuple Call node
### Response:
def infer_named_tuple(node, context=None):
"""Specific inference function for namedtuple Call node"""
tuple_base_name = nodes.Name(name="tuple", parent=node.root())
class_... |
def all_devices(cl_device_type=None, platform=None):
"""Get multiple device environments, optionally only of the indicated type.
This will only fetch devices that support double point precision.
Args:
cl_device_type (cl.device_type.* or string): The type of the device we want,
... | Get multiple device environments, optionally only of the indicated type.
This will only fetch devices that support double point precision.
Args:
cl_device_type (cl.device_type.* or string): The type of the device we want,
can be a opencl device type or a string matching 'GP... | Below is the the instruction that describes the task:
### Input:
Get multiple device environments, optionally only of the indicated type.
This will only fetch devices that support double point precision.
Args:
cl_device_type (cl.device_type.* or string): The type of the device we want,... |
def resolve_polytomy(
self,
dist=1.0,
support=100,
recursive=True):
"""
Returns a copy of the tree with all polytomies randomly resolved.
Does not transform tree in-place.
"""
nself = self.copy()
nself.treenode.resolve_polytomy(
... | Returns a copy of the tree with all polytomies randomly resolved.
Does not transform tree in-place. | Below is the the instruction that describes the task:
### Input:
Returns a copy of the tree with all polytomies randomly resolved.
Does not transform tree in-place.
### Response:
def resolve_polytomy(
self,
dist=1.0,
support=100,
recursive=True):
"""
Returns ... |
def enr_at_fpr(fg_vals, bg_vals, fpr=0.01):
"""
Computes the enrichment at a specific FPR (default 1%).
Parameters
----------
fg_vals : array_like
The list of values for the positive set.
bg_vals : array_like
The list of values for the negative set.
fpr : float, option... | Computes the enrichment at a specific FPR (default 1%).
Parameters
----------
fg_vals : array_like
The list of values for the positive set.
bg_vals : array_like
The list of values for the negative set.
fpr : float, optional
The FPR (between 0.0 and 1.0).
Retur... | Below is the the instruction that describes the task:
### Input:
Computes the enrichment at a specific FPR (default 1%).
Parameters
----------
fg_vals : array_like
The list of values for the positive set.
bg_vals : array_like
The list of values for the negative set.
fpr : ... |
def main(params=None):
"""
Main function to launch usufy.
The function is created in this way so as to let other applications make
use of the full configuration capabilities of the application. The
parameters received are used as parsed by this modules `getParser()`.
Args:
-----
pa... | Main function to launch usufy.
The function is created in this way so as to let other applications make
use of the full configuration capabilities of the application. The
parameters received are used as parsed by this modules `getParser()`.
Args:
-----
params: A list with the parameters as... | Below is the the instruction that describes the task:
### Input:
Main function to launch usufy.
The function is created in this way so as to let other applications make
use of the full configuration capabilities of the application. The
parameters received are used as parsed by this modules `getParser()... |
def _find_ancestor(self, task_spec):
"""
Returns the ancestor that has the given task spec assigned.
If no such ancestor was found, the root task is returned.
:type task_spec: TaskSpec
:param task_spec: The wanted task spec.
:rtype: Task
:returns: The ancestor.... | Returns the ancestor that has the given task spec assigned.
If no such ancestor was found, the root task is returned.
:type task_spec: TaskSpec
:param task_spec: The wanted task spec.
:rtype: Task
:returns: The ancestor. | Below is the the instruction that describes the task:
### Input:
Returns the ancestor that has the given task spec assigned.
If no such ancestor was found, the root task is returned.
:type task_spec: TaskSpec
:param task_spec: The wanted task spec.
:rtype: Task
:returns: T... |
def det_curve(y_true, scores, distances=False):
"""DET curve
Parameters
----------
y_true : (n_samples, ) array-like
Boolean reference.
scores : (n_samples, ) array-like
Predicted score.
distances : boolean, optional
When True, indicate that `scores` are actually `distan... | DET curve
Parameters
----------
y_true : (n_samples, ) array-like
Boolean reference.
scores : (n_samples, ) array-like
Predicted score.
distances : boolean, optional
When True, indicate that `scores` are actually `distances`
Returns
-------
fpr : numpy array
... | Below is the the instruction that describes the task:
### Input:
DET curve
Parameters
----------
y_true : (n_samples, ) array-like
Boolean reference.
scores : (n_samples, ) array-like
Predicted score.
distances : boolean, optional
When True, indicate that `scores` are ac... |
def slice(self, start, stop=None, axis=0):
"""Restrict histogram to bins whose data values (not bin numbers) along axis are between start and stop
(both inclusive). Returns d dimensional histogram."""
if stop is None:
# Make a 1=bin slice
stop = start
axis = self.... | Restrict histogram to bins whose data values (not bin numbers) along axis are between start and stop
(both inclusive). Returns d dimensional histogram. | Below is the the instruction that describes the task:
### Input:
Restrict histogram to bins whose data values (not bin numbers) along axis are between start and stop
(both inclusive). Returns d dimensional histogram.
### Response:
def slice(self, start, stop=None, axis=0):
"""Restrict histogram to ... |
def get_between_times(self, t1, t2, target=None):
"""
Query for OPUS data between times t1 and t2.
Parameters
----------
t1, t2 : datetime.datetime, strings
Start and end time for the query. If type is datetime, will be
converted to isoformat string. If t... | Query for OPUS data between times t1 and t2.
Parameters
----------
t1, t2 : datetime.datetime, strings
Start and end time for the query. If type is datetime, will be
converted to isoformat string. If type is string already, it needs
to be in an accepted inter... | Below is the the instruction that describes the task:
### Input:
Query for OPUS data between times t1 and t2.
Parameters
----------
t1, t2 : datetime.datetime, strings
Start and end time for the query. If type is datetime, will be
converted to isoformat string. If ty... |
def filter_queryset(self, request, queryset, view):
"""Apply the relevant behaviors to the view queryset."""
start_value = self.get_start(request)
if start_value:
queryset = self.apply_published_filter(queryset, "after", start_value)
end_value = self.get_end(request)
... | Apply the relevant behaviors to the view queryset. | Below is the the instruction that describes the task:
### Input:
Apply the relevant behaviors to the view queryset.
### Response:
def filter_queryset(self, request, queryset, view):
"""Apply the relevant behaviors to the view queryset."""
start_value = self.get_start(request)
if start_value... |
def read(self, nrml_file, validate=False,
simple_fault_spacing=1.0, complex_mesh_spacing=5.0,
mfd_spacing=0.1):
"""
Build the source model from nrml format
"""
self.source_file = nrml_file
if validate:
converter = SourceConverter(1.0, simple_... | Build the source model from nrml format | Below is the the instruction that describes the task:
### Input:
Build the source model from nrml format
### Response:
def read(self, nrml_file, validate=False,
simple_fault_spacing=1.0, complex_mesh_spacing=5.0,
mfd_spacing=0.1):
"""
Build the source model from nrml forma... |
def local_temp_dir():
"""
Creates a local temporary directory. The directory is removed when no longer needed. Failure to do
so will be ignored.
:return: Path to the temporary directory.
:rtype: unicode
"""
path = tempfile.mkdtemp()
yield path
shutil.rmtree(path, ignore_errors=True) | Creates a local temporary directory. The directory is removed when no longer needed. Failure to do
so will be ignored.
:return: Path to the temporary directory.
:rtype: unicode | Below is the the instruction that describes the task:
### Input:
Creates a local temporary directory. The directory is removed when no longer needed. Failure to do
so will be ignored.
:return: Path to the temporary directory.
:rtype: unicode
### Response:
def local_temp_dir():
"""
Creates a lo... |
def _incr_exceptions(self, conn):
"""Increment the number of exceptions for the current connection.
:param psycopg2.extensions.connection conn: the psycopg2 connection
"""
self._pool_manager.get_connection(self.pid, conn).exceptions += 1 | Increment the number of exceptions for the current connection.
:param psycopg2.extensions.connection conn: the psycopg2 connection | Below is the the instruction that describes the task:
### Input:
Increment the number of exceptions for the current connection.
:param psycopg2.extensions.connection conn: the psycopg2 connection
### Response:
def _incr_exceptions(self, conn):
"""Increment the number of exceptions for the current ... |
def QRatio(s1, s2, force_ascii=True, full_process=True):
"""
Quick ratio comparison between two strings.
Runs full_process from utils on both strings
Short circuits if either of the strings is empty after processing.
:param s1:
:param s2:
:param force_ascii: Allow only ASCII characters (De... | Quick ratio comparison between two strings.
Runs full_process from utils on both strings
Short circuits if either of the strings is empty after processing.
:param s1:
:param s2:
:param force_ascii: Allow only ASCII characters (Default: True)
:full_process: Process inputs, used here to avoid do... | Below is the the instruction that describes the task:
### Input:
Quick ratio comparison between two strings.
Runs full_process from utils on both strings
Short circuits if either of the strings is empty after processing.
:param s1:
:param s2:
:param force_ascii: Allow only ASCII characters (De... |
def _parse_handler_result(self, result):
"""Parses the item(s) returned by your handler implementation.
Handlers may return a single item (payload), or a tuple that gets
passed to the Response class __init__ method of your HTTP layer.
_parse_handler_result separates the payload from th... | Parses the item(s) returned by your handler implementation.
Handlers may return a single item (payload), or a tuple that gets
passed to the Response class __init__ method of your HTTP layer.
_parse_handler_result separates the payload from the rest the tuple,
as well as providing the t... | Below is the the instruction that describes the task:
### Input:
Parses the item(s) returned by your handler implementation.
Handlers may return a single item (payload), or a tuple that gets
passed to the Response class __init__ method of your HTTP layer.
_parse_handler_result separates th... |
def merge_keywords(x,y):
"""Given two dicts, merge them into a new dict as a shallow copy."""
z = x.copy()
z.update(y)
return z | Given two dicts, merge them into a new dict as a shallow copy. | Below is the the instruction that describes the task:
### Input:
Given two dicts, merge them into a new dict as a shallow copy.
### Response:
def merge_keywords(x,y):
"""Given two dicts, merge them into a new dict as a shallow copy."""
z = x.copy()
z.update(y)
return z |
def get_function_from_config(item):
"""
Import the function to get profile by handle.
"""
config = get_configuration()
func_path = config.get(item)
module_path, func_name = func_path.rsplit(".", 1)
module = importlib.import_module(module_path)
func = getattr(module, func_name)
return... | Import the function to get profile by handle. | Below is the the instruction that describes the task:
### Input:
Import the function to get profile by handle.
### Response:
def get_function_from_config(item):
"""
Import the function to get profile by handle.
"""
config = get_configuration()
func_path = config.get(item)
module_path, func_... |
def split_bezier(bpoints, t):
"""Uses deCasteljau's recursion to split the Bezier curve at t into two
Bezier curves of the same order."""
def split_bezier_recursion(bpoints_left_, bpoints_right_, bpoints_, t_):
if len(bpoints_) == 1:
bpoints_left_.append(bpoints_[0])
bpoints_... | Uses deCasteljau's recursion to split the Bezier curve at t into two
Bezier curves of the same order. | Below is the the instruction that describes the task:
### Input:
Uses deCasteljau's recursion to split the Bezier curve at t into two
Bezier curves of the same order.
### Response:
def split_bezier(bpoints, t):
"""Uses deCasteljau's recursion to split the Bezier curve at t into two
Bezier curves of the... |
def get_parser(segmenter, **options):
"""Gets a parser.
Args:
segmenter (str): Segmenter to use.
options (:obj:`dict`, optional): Optional settings.
Returns:
Parser (:obj:`budou.parser.Parser`)
Raises:
ValueError: If unsupported segmenter is specified.
"""
if segmenter == 'nlapi':
ret... | Gets a parser.
Args:
segmenter (str): Segmenter to use.
options (:obj:`dict`, optional): Optional settings.
Returns:
Parser (:obj:`budou.parser.Parser`)
Raises:
ValueError: If unsupported segmenter is specified. | Below is the the instruction that describes the task:
### Input:
Gets a parser.
Args:
segmenter (str): Segmenter to use.
options (:obj:`dict`, optional): Optional settings.
Returns:
Parser (:obj:`budou.parser.Parser`)
Raises:
ValueError: If unsupported segmenter is specified.
### Response: ... |
def _read_opt_type(self, kind):
"""Read option type field.
Positional arguments:
* kind -- int, option kind value
Returns:
* dict -- extracted IPv6_Opts option
Structure of option type field [RFC 791]:
Octets Bits Name ... | Read option type field.
Positional arguments:
* kind -- int, option kind value
Returns:
* dict -- extracted IPv6_Opts option
Structure of option type field [RFC 791]:
Octets Bits Name Descriptions
0 ... | Below is the the instruction that describes the task:
### Input:
Read option type field.
Positional arguments:
* kind -- int, option kind value
Returns:
* dict -- extracted IPv6_Opts option
Structure of option type field [RFC 791]:
Octets Bits ... |
def find_types_removed_from_unions(
old_schema: GraphQLSchema, new_schema: GraphQLSchema
) -> List[BreakingChange]:
"""Find types removed from unions.
Given two schemas, returns a list containing descriptions of any breaking changes
in the new_schema related to removing types from a union type.
"""... | Find types removed from unions.
Given two schemas, returns a list containing descriptions of any breaking changes
in the new_schema related to removing types from a union type. | Below is the the instruction that describes the task:
### Input:
Find types removed from unions.
Given two schemas, returns a list containing descriptions of any breaking changes
in the new_schema related to removing types from a union type.
### Response:
def find_types_removed_from_unions(
old_schema... |
def strip_possessives(self, word):
"""
Get rid of apostrophes indicating possession.
"""
if word.endswith("'s'"):
return word[:-3]
elif word.endswith("'s"):
return word[:-2]
elif word.endswith("'"):
return word[:-1]
else:
... | Get rid of apostrophes indicating possession. | Below is the the instruction that describes the task:
### Input:
Get rid of apostrophes indicating possession.
### Response:
def strip_possessives(self, word):
"""
Get rid of apostrophes indicating possession.
"""
if word.endswith("'s'"):
return word[:-3]
elif w... |
def list_snapshots(self):
"""
Returns a list of all snapshots of this volume.
"""
return [snap for snap in self.manager.list_snapshots()
if snap.volume_id == self.id] | Returns a list of all snapshots of this volume. | Below is the the instruction that describes the task:
### Input:
Returns a list of all snapshots of this volume.
### Response:
def list_snapshots(self):
"""
Returns a list of all snapshots of this volume.
"""
return [snap for snap in self.manager.list_snapshots()
if ... |
def matches(self, pattern, flags=0):
"""
Ensures :attr:`subject` matches regular expression *pattern*.
"""
if not re.match(pattern, self._subject, flags):
raise self._error_factory(_format("Expected {} to match {}", self._subject, pattern))
return ChainInspector(self.... | Ensures :attr:`subject` matches regular expression *pattern*. | Below is the the instruction that describes the task:
### Input:
Ensures :attr:`subject` matches regular expression *pattern*.
### Response:
def matches(self, pattern, flags=0):
"""
Ensures :attr:`subject` matches regular expression *pattern*.
"""
if not re.match(pattern, self._subj... |
def describe_config_variable(self, config_id):
"""Describe the config variable by its id."""
config = self._config_variables.get(config_id)
if config is None:
return [Error.INVALID_ARRAY_KEY, 0, 0, 0, 0]
packed_size = config.total_size
packed_size |= int(config.vari... | Describe the config variable by its id. | Below is the the instruction that describes the task:
### Input:
Describe the config variable by its id.
### Response:
def describe_config_variable(self, config_id):
"""Describe the config variable by its id."""
config = self._config_variables.get(config_id)
if config is None:
... |
def loadPng(varNumVol, tplPngSize, strPathPng):
"""Load PNG files.
Parameters
----------
varNumVol : float
Number of volumes, i.e. number of time points in all runs.
tplPngSize : tuple
Shape of the stimulus image (i.e. png).
strPathPng: str
Path to the folder cointaining... | Load PNG files.
Parameters
----------
varNumVol : float
Number of volumes, i.e. number of time points in all runs.
tplPngSize : tuple
Shape of the stimulus image (i.e. png).
strPathPng: str
Path to the folder cointaining the png files.
Returns
-------
aryPngData ... | Below is the the instruction that describes the task:
### Input:
Load PNG files.
Parameters
----------
varNumVol : float
Number of volumes, i.e. number of time points in all runs.
tplPngSize : tuple
Shape of the stimulus image (i.e. png).
strPathPng: str
Path to the fold... |
def print_output(self, per_identity_data: 'RDD') -> None:
"""
Basic helper function to write data to stdout. If window BTS was provided then the window
BTS output is written, otherwise, the streaming BTS output is written to stdout.
WARNING - For large datasets this will be extremely sl... | Basic helper function to write data to stdout. If window BTS was provided then the window
BTS output is written, otherwise, the streaming BTS output is written to stdout.
WARNING - For large datasets this will be extremely slow.
:param per_identity_data: Output of the `execute()` call. | Below is the the instruction that describes the task:
### Input:
Basic helper function to write data to stdout. If window BTS was provided then the window
BTS output is written, otherwise, the streaming BTS output is written to stdout.
WARNING - For large datasets this will be extremely slow.
... |
def _type_string(label, case=None):
"""Shortcut for string like fields"""
return label, abstractSearch.in_string, lambda s: abstractRender.default(s, case=case), "" | Shortcut for string like fields | Below is the the instruction that describes the task:
### Input:
Shortcut for string like fields
### Response:
def _type_string(label, case=None):
"""Shortcut for string like fields"""
return label, abstractSearch.in_string, lambda s: abstractRender.default(s, case=case), "" |
def serialize(self, data=None):
"""
Transforms the object into an acceptable format for transmission.
@throws ValueError
To indicate this serializer does not support the encoding of the
specified object.
"""
if data is not None and self.response is not No... | Transforms the object into an acceptable format for transmission.
@throws ValueError
To indicate this serializer does not support the encoding of the
specified object. | Below is the the instruction that describes the task:
### Input:
Transforms the object into an acceptable format for transmission.
@throws ValueError
To indicate this serializer does not support the encoding of the
specified object.
### Response:
def serialize(self, data=None):
... |
def is_vert_aligned(c):
"""Return true if all the components of c are vertically aligned.
Vertical alignment means that the bounding boxes of each Mention of c
shares a similar x-axis value in the visual rendering of the document.
:param c: The candidate to evaluate
:rtype: boolean
"""
ret... | Return true if all the components of c are vertically aligned.
Vertical alignment means that the bounding boxes of each Mention of c
shares a similar x-axis value in the visual rendering of the document.
:param c: The candidate to evaluate
:rtype: boolean | Below is the the instruction that describes the task:
### Input:
Return true if all the components of c are vertically aligned.
Vertical alignment means that the bounding boxes of each Mention of c
shares a similar x-axis value in the visual rendering of the document.
:param c: The candidate to evalua... |
def from_function(cls, function):
"""Create a FunctionDescriptor from a function instance.
This function is used to create the function descriptor from
a python function. If a function is a class function, it should
not be used by this function.
Args:
cls: Current c... | Create a FunctionDescriptor from a function instance.
This function is used to create the function descriptor from
a python function. If a function is a class function, it should
not be used by this function.
Args:
cls: Current class which is required argument for classmeth... | Below is the the instruction that describes the task:
### Input:
Create a FunctionDescriptor from a function instance.
This function is used to create the function descriptor from
a python function. If a function is a class function, it should
not be used by this function.
Args:
... |
def write_to_file(filename, content):
"""
Writes content to the given file. The file's directory will be created if needed.
:param filename: name of the output file, relative to the "destination folder" provided by the user
:param content: iterable (line-by-line) that should be written to the file. ... | Writes content to the given file. The file's directory will be created if needed.
:param filename: name of the output file, relative to the "destination folder" provided by the user
:param content: iterable (line-by-line) that should be written to the file. Either a list or a generator. Each
... | Below is the the instruction that describes the task:
### Input:
Writes content to the given file. The file's directory will be created if needed.
:param filename: name of the output file, relative to the "destination folder" provided by the user
:param content: iterable (line-by-line) that should be wr... |
def namer(cls, imageUrl, pageUrl):
"""Use strip index number for image name."""
index = int(compile(r'id=(\d+)').search(pageUrl).group(1))
ext = imageUrl.rsplit('.', 1)[1]
return "SnowFlakes-%d.%s" % (index, ext) | Use strip index number for image name. | Below is the the instruction that describes the task:
### Input:
Use strip index number for image name.
### Response:
def namer(cls, imageUrl, pageUrl):
"""Use strip index number for image name."""
index = int(compile(r'id=(\d+)').search(pageUrl).group(1))
ext = imageUrl.rsplit('.', 1)[1]
... |
def visit(self, event):
"""
Visit the stop if it has not been visited already by an event with
earlier arr_time_ut (or with other trip that does not require a transfer)
Parameters
----------
event : Event
an instance of the Event (namedtuple)
Returns... | Visit the stop if it has not been visited already by an event with
earlier arr_time_ut (or with other trip that does not require a transfer)
Parameters
----------
event : Event
an instance of the Event (namedtuple)
Returns
-------
visited : bool
... | Below is the the instruction that describes the task:
### Input:
Visit the stop if it has not been visited already by an event with
earlier arr_time_ut (or with other trip that does not require a transfer)
Parameters
----------
event : Event
an instance of the Event (nam... |
def autocommit(data_access):
"""Make statements autocommit.
:param data_access: a DataAccess instance
"""
if not data_access.autocommit:
data_access.commit()
old_autocommit = data_access.autocommit
data_access.autocommit = True
try:
yield data_access
finally:
data_access.autocommit = old_au... | Make statements autocommit.
:param data_access: a DataAccess instance | Below is the the instruction that describes the task:
### Input:
Make statements autocommit.
:param data_access: a DataAccess instance
### Response:
def autocommit(data_access):
"""Make statements autocommit.
:param data_access: a DataAccess instance
"""
if not data_access.autocommit:
data_access.c... |
def _node_le(self, node_self, node_other):
'''_node_le
Low-level api: Return True if all descendants of one node exist in the
other node. Otherwise False. This is a recursive method.
Parameters
----------
node_self : `Element`
A node to be compared.
... | _node_le
Low-level api: Return True if all descendants of one node exist in the
other node. Otherwise False. This is a recursive method.
Parameters
----------
node_self : `Element`
A node to be compared.
node_other : `Element`
Another node to b... | Below is the the instruction that describes the task:
### Input:
_node_le
Low-level api: Return True if all descendants of one node exist in the
other node. Otherwise False. This is a recursive method.
Parameters
----------
node_self : `Element`
A node to be co... |
def cli(env, identifier, enabled, port, weight, healthcheck_type, ip_address):
"""Adds a new load balancer service."""
mgr = SoftLayer.LoadBalancerManager(env.client)
loadbal_id, group_id = loadbal.parse_id(identifier)
# check if the IP is valid
ip_address_id = None
if ip_address:
ip_... | Adds a new load balancer service. | Below is the the instruction that describes the task:
### Input:
Adds a new load balancer service.
### Response:
def cli(env, identifier, enabled, port, weight, healthcheck_type, ip_address):
"""Adds a new load balancer service."""
mgr = SoftLayer.LoadBalancerManager(env.client)
loadbal_id, group_id ... |
def update_checkplotdict_nbrlcs(
checkplotdict,
timecol, magcol, errcol,
lcformat='hat-sql',
lcformatdir=None,
verbose=True,
):
'''For all neighbors in a checkplotdict, make LCs and phased LCs.
Parameters
----------
checkplotdict : dict
This is the chec... | For all neighbors in a checkplotdict, make LCs and phased LCs.
Parameters
----------
checkplotdict : dict
This is the checkplot to process. The light curves for the neighbors to
the object here will be extracted from the stored file paths, and this
function will make plots of these... | Below is the the instruction that describes the task:
### Input:
For all neighbors in a checkplotdict, make LCs and phased LCs.
Parameters
----------
checkplotdict : dict
This is the checkplot to process. The light curves for the neighbors to
the object here will be extracted from the ... |
def parse_field(fld, selectable, aggregated=True, default_aggregation='sum'):
""" Parse a field object from yaml into a sqlalchemy expression """
# An aggregation is a callable that takes a single field expression
# None will perform no aggregation
aggregation_lookup = {
'sum': func.sum,
... | Parse a field object from yaml into a sqlalchemy expression | Below is the the instruction that describes the task:
### Input:
Parse a field object from yaml into a sqlalchemy expression
### Response:
def parse_field(fld, selectable, aggregated=True, default_aggregation='sum'):
""" Parse a field object from yaml into a sqlalchemy expression """
# An aggregation is a ... |
def stop(opts, bot, event):
"""Usage: stop [--name=<name>] [--notify=<slack_username>]
Stop a timer.
_name_ works the same as for `start`.
If given _slack_username_, reply with an at-mention to the given user.
"""
name = opts['--name']
slack_username = opts['--notify']
now = datetime... | Usage: stop [--name=<name>] [--notify=<slack_username>]
Stop a timer.
_name_ works the same as for `start`.
If given _slack_username_, reply with an at-mention to the given user. | Below is the the instruction that describes the task:
### Input:
Usage: stop [--name=<name>] [--notify=<slack_username>]
Stop a timer.
_name_ works the same as for `start`.
If given _slack_username_, reply with an at-mention to the given user.
### Response:
def stop(opts, bot, event):
"""Usage: s... |
def _gpdfit(x):
"""Estimate the parameters for the Generalized Pareto Distribution (GPD).
Empirical Bayes estimate for the parameters of the generalized Pareto
distribution given the data.
Parameters
----------
x : array
sorted 1D data array
Returns
-------
k : float
... | Estimate the parameters for the Generalized Pareto Distribution (GPD).
Empirical Bayes estimate for the parameters of the generalized Pareto
distribution given the data.
Parameters
----------
x : array
sorted 1D data array
Returns
-------
k : float
estimated shape para... | Below is the the instruction that describes the task:
### Input:
Estimate the parameters for the Generalized Pareto Distribution (GPD).
Empirical Bayes estimate for the parameters of the generalized Pareto
distribution given the data.
Parameters
----------
x : array
sorted 1D data arra... |
def l2traceroute_input_rbridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
l2traceroute = ET.Element("l2traceroute")
config = l2traceroute
input = ET.SubElement(l2traceroute, "input")
rbridge_id = ET.SubElement(input, "rbridge-id")... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def l2traceroute_input_rbridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
l2traceroute = ET.Element("l2traceroute")
config = l2traceroute
... |
def to_grpc_address(target: str) -> str:
"""Converts a standard gRPC target to one that is supported by grpcio
:param target: the server address.
:returns: the converted address.
"""
u = urlparse(target)
if u.scheme == "dns":
raise ValueError("dns:// not supported")
if u.scheme ==... | Converts a standard gRPC target to one that is supported by grpcio
:param target: the server address.
:returns: the converted address. | Below is the the instruction that describes the task:
### Input:
Converts a standard gRPC target to one that is supported by grpcio
:param target: the server address.
:returns: the converted address.
### Response:
def to_grpc_address(target: str) -> str:
"""Converts a standard gRPC target to one that ... |
def download(ctx):
"""Download code of the current project."""
user, project_name = get_project_or_local(ctx.obj.get('project'))
try:
PolyaxonClient().project.download_repo(user, project_name)
except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:
Printer.prin... | Download code of the current project. | Below is the the instruction that describes the task:
### Input:
Download code of the current project.
### Response:
def download(ctx):
"""Download code of the current project."""
user, project_name = get_project_or_local(ctx.obj.get('project'))
try:
PolyaxonClient().project.download_repo(user,... |
def passed(self):
"""
Return all the passing testcases
:return:
"""
return [test for test in self.all() if not test.failed() and not test.skipped()] | Return all the passing testcases
:return: | Below is the the instruction that describes the task:
### Input:
Return all the passing testcases
:return:
### Response:
def passed(self):
"""
Return all the passing testcases
:return:
"""
return [test for test in self.all() if not test.failed() and not test.skipped(... |
def user_identity_show(self, user_id, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/user_identities#show-identity"
api_path = "/api/v2/users/{user_id}/identities/{id}.json"
api_path = api_path.format(user_id=user_id, id=id)
return self.call(api_path, **kwargs) | https://developer.zendesk.com/rest_api/docs/core/user_identities#show-identity | Below is the the instruction that describes the task:
### Input:
https://developer.zendesk.com/rest_api/docs/core/user_identities#show-identity
### Response:
def user_identity_show(self, user_id, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/user_identities#show-identity"
api_pat... |
def bell(self, percent = 0, onerror = None):
"""Ring the bell at the volume percent which is relative the base
volume. See XBell(3X11)."""
request.Bell(display = self.display,
onerror = onerror,
percent = percent) | Ring the bell at the volume percent which is relative the base
volume. See XBell(3X11). | Below is the the instruction that describes the task:
### Input:
Ring the bell at the volume percent which is relative the base
volume. See XBell(3X11).
### Response:
def bell(self, percent = 0, onerror = None):
"""Ring the bell at the volume percent which is relative the base
volume. See X... |
def _validate_and_parse(self, batch_object):
"""
Performs validation on the batch object to make sure it is in the proper format.
Parameters:
* batch_object: The data provided to a POST. The expected format is the following:
{
"username": "username",
... | Performs validation on the batch object to make sure it is in the proper format.
Parameters:
* batch_object: The data provided to a POST. The expected format is the following:
{
"username": "username",
"course_key": "course-key",
"blocks":... | Below is the the instruction that describes the task:
### Input:
Performs validation on the batch object to make sure it is in the proper format.
Parameters:
* batch_object: The data provided to a POST. The expected format is the following:
{
"username": "username",
... |
def rgb_to_websafe(r, g=None, b=None, alt=False):
"""Convert the color from RGB to 'web safe' RGB
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
:alt:
If True, use the alternative color instead of th... | Convert the color from RGB to 'web safe' RGB
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
:alt:
If True, use the alternative color instead of the nearest one.
Can be used for dithering.
Retu... | Below is the the instruction that describes the task:
### Input:
Convert the color from RGB to 'web safe' RGB
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
:alt:
If True, use the alternative color... |
def add_device_callback(self, devices, callback):
"""Register a device callback."""
if not devices:
return False
if not isinstance(devices, (tuple, list)):
devices = [devices]
for device in devices:
# Device may be a device_id
device_id =... | Register a device callback. | Below is the the instruction that describes the task:
### Input:
Register a device callback.
### Response:
def add_device_callback(self, devices, callback):
"""Register a device callback."""
if not devices:
return False
if not isinstance(devices, (tuple, list)):
dev... |
def calf(self, spec):
"""
Typical safe usage is this, which sets everything that could be
problematic up.
Requires the filename which everything will be produced to.
"""
if not isinstance(spec, Spec):
raise TypeError('spec must be of type Spec')
if ... | Typical safe usage is this, which sets everything that could be
problematic up.
Requires the filename which everything will be produced to. | Below is the the instruction that describes the task:
### Input:
Typical safe usage is this, which sets everything that could be
problematic up.
Requires the filename which everything will be produced to.
### Response:
def calf(self, spec):
"""
Typical safe usage is this, which set... |
def hops(node1, node2):
"""returns # of hops it takes to get from node1 to node2, 1 means they're on the same link"""
if node1 == node2:
return 0
elif set(node1.interfaces) & set(node2.interfaces):
# they share a common interface
return 1
else:
# Not implemented yet, grap... | returns # of hops it takes to get from node1 to node2, 1 means they're on the same link | Below is the the instruction that describes the task:
### Input:
returns # of hops it takes to get from node1 to node2, 1 means they're on the same link
### Response:
def hops(node1, node2):
"""returns # of hops it takes to get from node1 to node2, 1 means they're on the same link"""
if node1 == node2:
... |
def qnh_estimate(self):
'''estimate QNH pressure from GPS altitude and scaled pressure'''
alt_gps = self.master.field('GPS_RAW_INT', 'alt', 0) * 0.001
pressure2 = self.master.field('SCALED_PRESSURE', 'press_abs', 0)
ground_temp = self.get_mav_param('GND_TEMP', 21)
temp = ground_t... | estimate QNH pressure from GPS altitude and scaled pressure | Below is the the instruction that describes the task:
### Input:
estimate QNH pressure from GPS altitude and scaled pressure
### Response:
def qnh_estimate(self):
'''estimate QNH pressure from GPS altitude and scaled pressure'''
alt_gps = self.master.field('GPS_RAW_INT', 'alt', 0) * 0.001
p... |
def device_statistics(fritz, args):
"""Command that prints the device statistics."""
stats = fritz.get_device_statistics(args.ain)
print(stats) | Command that prints the device statistics. | Below is the the instruction that describes the task:
### Input:
Command that prints the device statistics.
### Response:
def device_statistics(fritz, args):
"""Command that prints the device statistics."""
stats = fritz.get_device_statistics(args.ain)
print(stats) |
def get_role_by_code(role_code,**kwargs):
"""
Get a role by its code
"""
try:
role = db.DBSession.query(Role).filter(Role.code==role_code).one()
return role
except NoResultFound:
raise ResourceNotFoundError("Role not found (role_code={})".format(role_code)) | Get a role by its code | Below is the the instruction that describes the task:
### Input:
Get a role by its code
### Response:
def get_role_by_code(role_code,**kwargs):
"""
Get a role by its code
"""
try:
role = db.DBSession.query(Role).filter(Role.code==role_code).one()
return role
except NoResultF... |
def is_text_visible(driver, text, selector, by=By.CSS_SELECTOR):
"""
Returns whether the specified text is visible in the specified selector.
@Params
driver - the webdriver object (required)
text - the text string to search for
selector - the locator that is used (required)
by - the method t... | Returns whether the specified text is visible in the specified selector.
@Params
driver - the webdriver object (required)
text - the text string to search for
selector - the locator that is used (required)
by - the method to search for the locator (Default: By.CSS_SELECTOR)
@Returns
Boolean ... | Below is the the instruction that describes the task:
### Input:
Returns whether the specified text is visible in the specified selector.
@Params
driver - the webdriver object (required)
text - the text string to search for
selector - the locator that is used (required)
by - the method to search... |
def get_active_for(self, user, user_agent=_MARK, ip_address=_MARK):
"""Return last known session for given user.
:param user: user session
:type user: `abilian.core.models.subjects.User`
:param user_agent: *exact* user agent string to lookup, or `None` to have
user_agent extrac... | Return last known session for given user.
:param user: user session
:type user: `abilian.core.models.subjects.User`
:param user_agent: *exact* user agent string to lookup, or `None` to have
user_agent extracted from request object. If not provided at all, no
filtering on user_a... | Below is the the instruction that describes the task:
### Input:
Return last known session for given user.
:param user: user session
:type user: `abilian.core.models.subjects.User`
:param user_agent: *exact* user agent string to lookup, or `None` to have
user_agent extracted from r... |
def clean_headers(headers):
"""Forces header keys and values to be strings, i.e not unicode.
The httplib module just concats the header keys and values in a way that
may make the message header a unicode string, which, if it then tries to
contatenate to a binary request body may result in a unicode dec... | Forces header keys and values to be strings, i.e not unicode.
The httplib module just concats the header keys and values in a way that
may make the message header a unicode string, which, if it then tries to
contatenate to a binary request body may result in a unicode decode error.
Args:
heade... | Below is the the instruction that describes the task:
### Input:
Forces header keys and values to be strings, i.e not unicode.
The httplib module just concats the header keys and values in a way that
may make the message header a unicode string, which, if it then tries to
contatenate to a binary reques... |
def get_step(self, grad):
"""Computes the 'step' to take for the next gradient descent update.
Returns the step rather than performing the update so that
parameters can be updated in place rather than overwritten.
Examples
--------
>>> gradient = # ...
>>> optim... | Computes the 'step' to take for the next gradient descent update.
Returns the step rather than performing the update so that
parameters can be updated in place rather than overwritten.
Examples
--------
>>> gradient = # ...
>>> optimizer = AdaGradOptimizer(0.01)
... | Below is the the instruction that describes the task:
### Input:
Computes the 'step' to take for the next gradient descent update.
Returns the step rather than performing the update so that
parameters can be updated in place rather than overwritten.
Examples
--------
>>> gr... |
def parse_args(self, args, scope):
"""Parse arguments to mixin. Add them to scope
as variables. Sets upp special variable @arguments
as well.
args:
args (list): arguments
scope (Scope): current scope
raises:
SyntaxError
"""
argu... | Parse arguments to mixin. Add them to scope
as variables. Sets upp special variable @arguments
as well.
args:
args (list): arguments
scope (Scope): current scope
raises:
SyntaxError | Below is the the instruction that describes the task:
### Input:
Parse arguments to mixin. Add them to scope
as variables. Sets upp special variable @arguments
as well.
args:
args (list): arguments
scope (Scope): current scope
raises:
SyntaxError
#... |
def put_settings(self, body=None, params=None):
"""
Update cluster wide specific settings.
`<http://www.elastic.co/guide/en/elasticsearch/reference/current/cluster-update-settings.html>`_
:arg body: The settings to be updated. Can be either `transient` or
`persistent` (survi... | Update cluster wide specific settings.
`<http://www.elastic.co/guide/en/elasticsearch/reference/current/cluster-update-settings.html>`_
:arg body: The settings to be updated. Can be either `transient` or
`persistent` (survives cluster restart).
:arg flat_settings: Return settings in... | Below is the the instruction that describes the task:
### Input:
Update cluster wide specific settings.
`<http://www.elastic.co/guide/en/elasticsearch/reference/current/cluster-update-settings.html>`_
:arg body: The settings to be updated. Can be either `transient` or
`persistent` (surv... |
def get_distribute_verbatim_metadata(self):
"""Gets the metadata for the distribute verbatim rights flag.
return: (osid.Metadata) - metadata for the distribution rights
fields
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from tem... | Gets the metadata for the distribute verbatim rights flag.
return: (osid.Metadata) - metadata for the distribution rights
fields
*compliance: mandatory -- This method must be implemented.* | Below is the the instruction that describes the task:
### Input:
Gets the metadata for the distribute verbatim rights flag.
return: (osid.Metadata) - metadata for the distribution rights
fields
*compliance: mandatory -- This method must be implemented.*
### Response:
def get_distri... |
def moveoutletstostrm(np, flowdir, streamRaster, outlet, modifiedOutlet,
workingdir=None, mpiexedir=None,
exedir=None, log_file=None, runtime_file=None, hostfile=None):
"""Run move the given outlets to stream"""
fname = TauDEM.func_name('moveoutletstos... | Run move the given outlets to stream | Below is the the instruction that describes the task:
### Input:
Run move the given outlets to stream
### Response:
def moveoutletstostrm(np, flowdir, streamRaster, outlet, modifiedOutlet,
workingdir=None, mpiexedir=None,
exedir=None, log_file=None, runtime_file=... |
def find_primitive(cell, symprec=1e-5):
"""
A primitive cell is searched in the input cell. When a primitive
cell is found, an object of Atoms class of the primitive cell is
returned. When not, None is returned.
"""
lattice, positions, numbers = spg.find_primitive(cell.totuple(), symprec)
if... | A primitive cell is searched in the input cell. When a primitive
cell is found, an object of Atoms class of the primitive cell is
returned. When not, None is returned. | Below is the the instruction that describes the task:
### Input:
A primitive cell is searched in the input cell. When a primitive
cell is found, an object of Atoms class of the primitive cell is
returned. When not, None is returned.
### Response:
def find_primitive(cell, symprec=1e-5):
"""
A primit... |
def output(self, value):
"""SPL output port assignment expression.
Arguments:
value(str): SPL expression used for an output assignment. This can be a string, a constant, or an :py:class:`Expression`.
Returns:
Expression: Output assignment expression that is valid as a t... | SPL output port assignment expression.
Arguments:
value(str): SPL expression used for an output assignment. This can be a string, a constant, or an :py:class:`Expression`.
Returns:
Expression: Output assignment expression that is valid as a the context of this operator. | Below is the the instruction that describes the task:
### Input:
SPL output port assignment expression.
Arguments:
value(str): SPL expression used for an output assignment. This can be a string, a constant, or an :py:class:`Expression`.
Returns:
Expression: Output assignmen... |
def get(self, name, acc=None, default=None):
"""Return the named config for the given account.
If an account is given, first checks the account space for the name.
If no account given, or if the name not found in the account space,
look for the name in the global config space. If still... | Return the named config for the given account.
If an account is given, first checks the account space for the name.
If no account given, or if the name not found in the account space,
look for the name in the global config space. If still not found,
return the default, if given, otherw... | Below is the the instruction that describes the task:
### Input:
Return the named config for the given account.
If an account is given, first checks the account space for the name.
If no account given, or if the name not found in the account space,
look for the name in the global config spa... |
def shell_sqlalchemy(session: SqlalchemySession, backend: ShellBackend):
"""
This command includes SQLAlchemy DB Session
"""
namespace = {
'session': session
}
namespace.update(backend.get_namespace())
embed(user_ns=namespace, header=backend.header) | This command includes SQLAlchemy DB Session | Below is the the instruction that describes the task:
### Input:
This command includes SQLAlchemy DB Session
### Response:
def shell_sqlalchemy(session: SqlalchemySession, backend: ShellBackend):
"""
This command includes SQLAlchemy DB Session
"""
namespace = {
'session': session
}
... |
def count_leases_by_owner(self, leases): # pylint: disable=no-self-use
"""
Returns a dictionary of leases by current owner.
"""
owners = [l.owner for l in leases]
return dict(Counter(owners)) | Returns a dictionary of leases by current owner. | Below is the the instruction that describes the task:
### Input:
Returns a dictionary of leases by current owner.
### Response:
def count_leases_by_owner(self, leases): # pylint: disable=no-self-use
"""
Returns a dictionary of leases by current owner.
"""
owners = [l.owner for l in... |
def _get_network(project_id, network_name, service):
'''
Fetch network selfLink from network name.
'''
return service.networks().get(project=project_id,
network=network_name).execute() | Fetch network selfLink from network name. | Below is the the instruction that describes the task:
### Input:
Fetch network selfLink from network name.
### Response:
def _get_network(project_id, network_name, service):
'''
Fetch network selfLink from network name.
'''
return service.networks().get(project=project_id,
... |
def get_attrs(cls):
"""
Get all class attributes ordered by definition
"""
ignore = dir(type('dummy', (object,), {})) + ['__metaclass__']
attrs = [
item for item in inspect.getmembers(cls) if item[0] not in ignore
and not isinstance(
item[1... | Get all class attributes ordered by definition | Below is the the instruction that describes the task:
### Input:
Get all class attributes ordered by definition
### Response:
def get_attrs(cls):
"""
Get all class attributes ordered by definition
"""
ignore = dir(type('dummy', (object,), {})) + ['__metaclass__']
attrs = [
... |
def update_dataset_marker(self):
"""Update markers which are in the dataset. It always updates the list
of events. Depending on the settings, it might add the markers to
overview and traces.
"""
start_time = self.parent.overview.start_time
markers = []
if self.pa... | Update markers which are in the dataset. It always updates the list
of events. Depending on the settings, it might add the markers to
overview and traces. | Below is the the instruction that describes the task:
### Input:
Update markers which are in the dataset. It always updates the list
of events. Depending on the settings, it might add the markers to
overview and traces.
### Response:
def update_dataset_marker(self):
"""Update markers which ... |
def from_string(contents):
"""
Creates GaussianInput from a string.
Args:
contents: String representing an Gaussian input file.
Returns:
GaussianInput object
"""
lines = [l.strip() for l in contents.split("\n")]
link0_patt = re.compile(r... | Creates GaussianInput from a string.
Args:
contents: String representing an Gaussian input file.
Returns:
GaussianInput object | Below is the the instruction that describes the task:
### Input:
Creates GaussianInput from a string.
Args:
contents: String representing an Gaussian input file.
Returns:
GaussianInput object
### Response:
def from_string(contents):
"""
Creates GaussianInpu... |
def sequence(context, data):
"""Generate a sequence of numbers.
It is the memorious equivalent of the xrange function, accepting the
``start``, ``stop`` and ``step`` parameters.
This can run in two ways:
* As a single function generating all numbers in the given range.
* Recursively, generatin... | Generate a sequence of numbers.
It is the memorious equivalent of the xrange function, accepting the
``start``, ``stop`` and ``step`` parameters.
This can run in two ways:
* As a single function generating all numbers in the given range.
* Recursively, generating numbers one by one with an optiona... | Below is the the instruction that describes the task:
### Input:
Generate a sequence of numbers.
It is the memorious equivalent of the xrange function, accepting the
``start``, ``stop`` and ``step`` parameters.
This can run in two ways:
* As a single function generating all numbers in the given ra... |
def _updateWordSet(self):
"""Make a set of words, which shall be completed, from text
"""
self._wordSet = set(self._keywords) | set(self._customCompletions)
start = time.time()
for line in self._qpart.lines:
for match in _wordRegExp.findall(line):
se... | Make a set of words, which shall be completed, from text | Below is the the instruction that describes the task:
### Input:
Make a set of words, which shall be completed, from text
### Response:
def _updateWordSet(self):
"""Make a set of words, which shall be completed, from text
"""
self._wordSet = set(self._keywords) | set(self._customCompletions... |
def rename_acquisition(self, plate_name, name, new_name):
'''Renames an acquisition.
Parameters
----------
plate_name: str
name of the parent plate
name: str
name of the acquisition that should be renamed
new_name: str
name that should... | Renames an acquisition.
Parameters
----------
plate_name: str
name of the parent plate
name: str
name of the acquisition that should be renamed
new_name: str
name that should be given to the acquisition
See also
--------
... | Below is the the instruction that describes the task:
### Input:
Renames an acquisition.
Parameters
----------
plate_name: str
name of the parent plate
name: str
name of the acquisition that should be renamed
new_name: str
name that should... |
def backlink(node):
"""Given a CFG with outgoing links, create incoming links."""
seen = set()
to_see = [node]
while to_see:
node = to_see.pop()
seen.add(node)
for succ in node.next:
succ.prev.add(node)
if succ not in seen:
to_see.append(succ) | Given a CFG with outgoing links, create incoming links. | Below is the the instruction that describes the task:
### Input:
Given a CFG with outgoing links, create incoming links.
### Response:
def backlink(node):
"""Given a CFG with outgoing links, create incoming links."""
seen = set()
to_see = [node]
while to_see:
node = to_see.pop()
seen.ad... |
def makeOrmValuesSubqueryCondition(ormSession, column, values: List[Union[int, str]]):
""" Make Orm Values Subquery
:param ormSession: The orm session instance
:param column: The column from the Declarative table, eg TableItem.colName
:param values: A list of string or int values
"""
if isPostG... | Make Orm Values Subquery
:param ormSession: The orm session instance
:param column: The column from the Declarative table, eg TableItem.colName
:param values: A list of string or int values | Below is the the instruction that describes the task:
### Input:
Make Orm Values Subquery
:param ormSession: The orm session instance
:param column: The column from the Declarative table, eg TableItem.colName
:param values: A list of string or int values
### Response:
def makeOrmValuesSubqueryConditio... |
def hide(self):
"""Hides all annotation artists associated with the DataCursor. Returns
self to allow "chaining". (e.g. ``datacursor.hide().disable()``)"""
self._hidden = True
for artist in self.annotations.values():
artist.set_visible(False)
for fig in self.figures:
... | Hides all annotation artists associated with the DataCursor. Returns
self to allow "chaining". (e.g. ``datacursor.hide().disable()``) | Below is the the instruction that describes the task:
### Input:
Hides all annotation artists associated with the DataCursor. Returns
self to allow "chaining". (e.g. ``datacursor.hide().disable()``)
### Response:
def hide(self):
"""Hides all annotation artists associated with the DataCursor. Return... |
def _straight_line_vertices(adjacency_mat, node_coords, directed=False):
"""
Generate the vertices for straight lines between nodes.
If it is a directed graph, it also generates the vertices which can be
passed to an :class:`ArrowVisual`.
Parameters
----------
adjacency_mat : array
... | Generate the vertices for straight lines between nodes.
If it is a directed graph, it also generates the vertices which can be
passed to an :class:`ArrowVisual`.
Parameters
----------
adjacency_mat : array
The adjacency matrix of the graph
node_coords : array
The current coordi... | Below is the the instruction that describes the task:
### Input:
Generate the vertices for straight lines between nodes.
If it is a directed graph, it also generates the vertices which can be
passed to an :class:`ArrowVisual`.
Parameters
----------
adjacency_mat : array
The adjacency m... |
def list(self,table, **kparams):
"""
get a collection of records by table name.
returns a dict (the json map) for python 3.4
"""
result = self.table_api_get(table, **kparams)
return self.to_records(result, table) | get a collection of records by table name.
returns a dict (the json map) for python 3.4 | Below is the the instruction that describes the task:
### Input:
get a collection of records by table name.
returns a dict (the json map) for python 3.4
### Response:
def list(self,table, **kparams):
"""
get a collection of records by table name.
returns a dict (the json map) for py... |
def have_thumbnail(self, fitsimage, image):
"""Returns True if we already have a thumbnail version of this image
cached, False otherwise.
"""
chname = self.fv.get_channel_name(fitsimage)
# Look up our version of the thumb
idx = image.get('idx', None)
path = image... | Returns True if we already have a thumbnail version of this image
cached, False otherwise. | Below is the the instruction that describes the task:
### Input:
Returns True if we already have a thumbnail version of this image
cached, False otherwise.
### Response:
def have_thumbnail(self, fitsimage, image):
"""Returns True if we already have a thumbnail version of this image
cached, ... |
def setupNodding(self):
"""
Setup Nodding for GTC
"""
g = get_root(self).globals
if not self.nod():
# re-enable clear mode box if not drift
if not self.isDrift():
self.clear.enable()
# clear existing nod pattern
se... | Setup Nodding for GTC | Below is the the instruction that describes the task:
### Input:
Setup Nodding for GTC
### Response:
def setupNodding(self):
"""
Setup Nodding for GTC
"""
g = get_root(self).globals
if not self.nod():
# re-enable clear mode box if not drift
if not se... |
def copy(self, key):
"""Copy the set to another key and return the new Set.
WARNING: If the key exists, it overwrites it.
"""
copy = Set(key=key, db=self.db)
copy.clear()
copy |= self
return copy | Copy the set to another key and return the new Set.
WARNING: If the key exists, it overwrites it. | Below is the the instruction that describes the task:
### Input:
Copy the set to another key and return the new Set.
WARNING: If the key exists, it overwrites it.
### Response:
def copy(self, key):
"""Copy the set to another key and return the new Set.
WARNING: If the key exists, it overw... |
def parameterize(
self,
country: Optional[str] = "South Sudan",
state: Optional[str] = None,
year: Optional[int] = None,
month: Optional[int] = None,
unit: Optional[str] = None,
fallback_aggaxes: List[str] = ["year", "month"],
aggfunc: Callable = np.mean,
... | Parameterize the analysis graph.
Args:
country
year
month
fallback_aggaxes:
An iterable of strings denoting the axes upon which to perform
fallback aggregation if the desired constraints cannot be met.
aggfunc: The func... | Below is the the instruction that describes the task:
### Input:
Parameterize the analysis graph.
Args:
country
year
month
fallback_aggaxes:
An iterable of strings denoting the axes upon which to perform
fallback aggregation if... |
def kill_process(procname, scriptname):
"""kill WSGI processes that may be running in development"""
# from http://stackoverflow.com/a/2940878
import signal
import subprocess
p = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE)
out, err = p.communicate()
for line in out.decode().sp... | kill WSGI processes that may be running in development | Below is the the instruction that describes the task:
### Input:
kill WSGI processes that may be running in development
### Response:
def kill_process(procname, scriptname):
"""kill WSGI processes that may be running in development"""
# from http://stackoverflow.com/a/2940878
import signal
import ... |
def check_snmp(self):
"""Chek if SNMP is available on the server."""
# Import the SNMP client class
from glances.snmp import GlancesSNMPClient
# Create an instance of the SNMP client
clientsnmp = GlancesSNMPClient(host=self.args.client,
por... | Chek if SNMP is available on the server. | Below is the the instruction that describes the task:
### Input:
Chek if SNMP is available on the server.
### Response:
def check_snmp(self):
"""Chek if SNMP is available on the server."""
# Import the SNMP client class
from glances.snmp import GlancesSNMPClient
# Create an instanc... |
def next_page(self, max_=None):
"""
Return a query set which requests the page after this response.
:param max_: Maximum number of items to return.
:type max_: :class:`int` or :data:`None`
:rtype: :class:`ResultSetMetadata`
:return: A new request set up to request the ne... | Return a query set which requests the page after this response.
:param max_: Maximum number of items to return.
:type max_: :class:`int` or :data:`None`
:rtype: :class:`ResultSetMetadata`
:return: A new request set up to request the next page.
Must be called on a result set whi... | Below is the the instruction that describes the task:
### Input:
Return a query set which requests the page after this response.
:param max_: Maximum number of items to return.
:type max_: :class:`int` or :data:`None`
:rtype: :class:`ResultSetMetadata`
:return: A new request set up ... |
def read(self):
"""Reads the data stored in the files we have been initialized with. It will
ignore files that cannot be read, possibly leaving an empty configuration
:return: Nothing
:raise IOError: if a file cannot be handled"""
if self._is_initialized:
return
... | Reads the data stored in the files we have been initialized with. It will
ignore files that cannot be read, possibly leaving an empty configuration
:return: Nothing
:raise IOError: if a file cannot be handled | Below is the the instruction that describes the task:
### Input:
Reads the data stored in the files we have been initialized with. It will
ignore files that cannot be read, possibly leaving an empty configuration
:return: Nothing
:raise IOError: if a file cannot be handled
### Response:
de... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.