code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def zoom(self, factor):
"""
Zoom the camera view by a factor.
"""
camera = self.ren.GetActiveCamera()
camera.Zoom(factor)
self.ren_win.Render() | Zoom the camera view by a factor. | Below is the the instruction that describes the task:
### Input:
Zoom the camera view by a factor.
### Response:
def zoom(self, factor):
"""
Zoom the camera view by a factor.
"""
camera = self.ren.GetActiveCamera()
camera.Zoom(factor)
self.ren_win.Render() |
def parse_rna(rna, s2bins, min_rna):
"""
parse [16,23]SfromHMM.py output
- rna_cov[scaffold] = [0, 0, []] # [bases, length, ranges]
"""
rna_cov = {}
for seq in parse_fasta(rna):
# check that length passes threshold
length = len(seq[1])
if length < min_rna:
con... | parse [16,23]SfromHMM.py output
- rna_cov[scaffold] = [0, 0, []] # [bases, length, ranges] | Below is the the instruction that describes the task:
### Input:
parse [16,23]SfromHMM.py output
- rna_cov[scaffold] = [0, 0, []] # [bases, length, ranges]
### Response:
def parse_rna(rna, s2bins, min_rna):
"""
parse [16,23]SfromHMM.py output
- rna_cov[scaffold] = [0, 0, []] # [bases, length, range... |
def _get_callable_full_name(self, fob, fin, uobj):
"""Get full path [module, class (if applicable), function name] of callable."""
# Check if object is a class property
name = self._property_search(fob)
if name:
del fob, fin, uobj
return name
if os.path.is... | Get full path [module, class (if applicable), function name] of callable. | Below is the the instruction that describes the task:
### Input:
Get full path [module, class (if applicable), function name] of callable.
### Response:
def _get_callable_full_name(self, fob, fin, uobj):
"""Get full path [module, class (if applicable), function name] of callable."""
# Check if obje... |
def run_timeit(self, stmt, setup):
""" Create the function call statement as a string used for timeit. """
_timer = timeit.Timer(stmt=stmt, setup=setup)
trials = _timer.repeat(self.timeit_repeat, self.timeit_number)
self.time_average_seconds = sum(trials) / len(trials) / self.timeit_numb... | Create the function call statement as a string used for timeit. | Below is the the instruction that describes the task:
### Input:
Create the function call statement as a string used for timeit.
### Response:
def run_timeit(self, stmt, setup):
""" Create the function call statement as a string used for timeit. """
_timer = timeit.Timer(stmt=stmt, setup=setup)
... |
def weekday(year_or_num, month=None, day=None, full=False):
"""Simple tag - returns the weekday of the given (year, month, day) or of given (weekday_number).
Usage (in template):
{% weekday 2014 3 3 %}
Result: Mon
Return abbreviation by default. To return full name: pass full=True
{% weekda... | Simple tag - returns the weekday of the given (year, month, day) or of given (weekday_number).
Usage (in template):
{% weekday 2014 3 3 %}
Result: Mon
Return abbreviation by default. To return full name: pass full=True
{% weekday 2014 3 3 full=True %}
Result: Monday
When only number ... | Below is the the instruction that describes the task:
### Input:
Simple tag - returns the weekday of the given (year, month, day) or of given (weekday_number).
Usage (in template):
{% weekday 2014 3 3 %}
Result: Mon
Return abbreviation by default. To return full name: pass full=True
{% week... |
def thaw_decrypt(vault_client, src_file, tmp_dir, opt):
"""Decrypts the encrypted ice file"""
if not os.path.isdir(opt.secrets):
LOG.info("Creating secret directory %s", opt.secrets)
os.mkdir(opt.secrets)
zip_file = "%s/aomi.zip" % tmp_dir
if opt.gpg_pass_path:
gpg_path_bits =... | Decrypts the encrypted ice file | Below is the the instruction that describes the task:
### Input:
Decrypts the encrypted ice file
### Response:
def thaw_decrypt(vault_client, src_file, tmp_dir, opt):
"""Decrypts the encrypted ice file"""
if not os.path.isdir(opt.secrets):
LOG.info("Creating secret directory %s", opt.secrets)
... |
def scantree(path: str) -> Generator:
"""Recursively yield DirEntry objects for given directory."""
for entry in os.scandir(path):
if entry.is_dir(follow_symlinks=False):
yield from scantree(entry.path)
else:
if entry.name.endswith('.py'):
yield entry | Recursively yield DirEntry objects for given directory. | Below is the the instruction that describes the task:
### Input:
Recursively yield DirEntry objects for given directory.
### Response:
def scantree(path: str) -> Generator:
"""Recursively yield DirEntry objects for given directory."""
for entry in os.scandir(path):
if entry.is_dir(follow_symlinks=F... |
def traverse(self, predicate=lambda i, d: True,
prune=lambda i, d: False, depth=-1, branch_first=True,
visit_once=True, ignore_self=1, as_edge=False):
""":return: iterator yielding of items found when traversing self
:param predicate: f(i,d) returns False if item i at ... | :return: iterator yielding of items found when traversing self
:param predicate: f(i,d) returns False if item i at depth d should not be included in the result
:param prune:
f(i,d) return True if the search should stop at item i at depth d.
Item i will not be returned.
... | Below is the the instruction that describes the task:
### Input:
:return: iterator yielding of items found when traversing self
:param predicate: f(i,d) returns False if item i at depth d should not be included in the result
:param prune:
f(i,d) return True if the search should stop at... |
def data_collate(batch:ItemsList)->Tensor:
"Convert `batch` items to tensor data."
return torch.utils.data.dataloader.default_collate(to_data(batch)) | Convert `batch` items to tensor data. | Below is the the instruction that describes the task:
### Input:
Convert `batch` items to tensor data.
### Response:
def data_collate(batch:ItemsList)->Tensor:
"Convert `batch` items to tensor data."
return torch.utils.data.dataloader.default_collate(to_data(batch)) |
def _get_coarse_dataset(self, key, info):
"""Get the coarse dataset refered to by `key` from the XML data."""
angles = self.root.find('.//Tile_Angles')
if key in ['solar_zenith_angle', 'solar_azimuth_angle']:
elts = angles.findall(info['xml_tag'] + '/Values_List/VALUES')
... | Get the coarse dataset refered to by `key` from the XML data. | Below is the the instruction that describes the task:
### Input:
Get the coarse dataset refered to by `key` from the XML data.
### Response:
def _get_coarse_dataset(self, key, info):
"""Get the coarse dataset refered to by `key` from the XML data."""
angles = self.root.find('.//Tile_Angles')
... |
def invalid_ipa_characters(unicode_string, indices=False):
"""
Return the list of Unicode characters
in the given Unicode string
that are not IPA valid.
Return ``None`` if ``unicode_string`` is ``None``.
:param str unicode_string: the Unicode string to be parsed
:param bool indices: if ``T... | Return the list of Unicode characters
in the given Unicode string
that are not IPA valid.
Return ``None`` if ``unicode_string`` is ``None``.
:param str unicode_string: the Unicode string to be parsed
:param bool indices: if ``True``, return a list of pairs (index, invalid character),
... | Below is the the instruction that describes the task:
### Input:
Return the list of Unicode characters
in the given Unicode string
that are not IPA valid.
Return ``None`` if ``unicode_string`` is ``None``.
:param str unicode_string: the Unicode string to be parsed
:param bool indices: if ``Tru... |
def fit(self, X, y, X_val=None, y_val=None):
"""Train a network with the quasi-Newton method.
Args:
X (np.array of float): feature matrix for training
y (np.array of float): target values for training
X_val (np.array of float): feature matrix for validation
... | Train a network with the quasi-Newton method.
Args:
X (np.array of float): feature matrix for training
y (np.array of float): target values for training
X_val (np.array of float): feature matrix for validation
y_val (np.array of float): target values for ... | Below is the the instruction that describes the task:
### Input:
Train a network with the quasi-Newton method.
Args:
X (np.array of float): feature matrix for training
y (np.array of float): target values for training
X_val (np.array of float): feature matrix for... |
def callable_name(callable_obj):
"""
Attempt to return a meaningful name identifying a callable or generator
"""
try:
if (isinstance(callable_obj, type)
and issubclass(callable_obj, param.ParameterizedFunction)):
return callable_obj.__name__
elif (isinstance(calla... | Attempt to return a meaningful name identifying a callable or generator | Below is the the instruction that describes the task:
### Input:
Attempt to return a meaningful name identifying a callable or generator
### Response:
def callable_name(callable_obj):
"""
Attempt to return a meaningful name identifying a callable or generator
"""
try:
if (isinstance(callabl... |
def get_booster_stats(ctx, currency):
"""Prints out price stats for booster packs available in Steam user inventory."""
username = ctx.obj['username']
inventory = User(username)._get_inventory_raw()
boosters = {}
for item in inventory['rgDescriptions'].values():
is_booster = False
... | Prints out price stats for booster packs available in Steam user inventory. | Below is the the instruction that describes the task:
### Input:
Prints out price stats for booster packs available in Steam user inventory.
### Response:
def get_booster_stats(ctx, currency):
"""Prints out price stats for booster packs available in Steam user inventory."""
username = ctx.obj['username']
... |
def get_supported_connections(self):
"""Returns the number of supported simultaneous BLE connections.
The BLED112 is capable of supporting up to 8 simultaneous BLE connections.
However, the default firmware image has a limit of just 3 devices, which
is a lot easier to run up against. T... | Returns the number of supported simultaneous BLE connections.
The BLED112 is capable of supporting up to 8 simultaneous BLE connections.
However, the default firmware image has a limit of just 3 devices, which
is a lot easier to run up against. This method retrieves the current value
o... | Below is the the instruction that describes the task:
### Input:
Returns the number of supported simultaneous BLE connections.
The BLED112 is capable of supporting up to 8 simultaneous BLE connections.
However, the default firmware image has a limit of just 3 devices, which
is a lot easier... |
def accounts(self):
"""
A list of structures describing apps and pages owned by this user.
"""
response = self.graph.get('%s/accounts' % self.id)
accounts = []
for item in response['data']:
account = Structure(
page = Page(
... | A list of structures describing apps and pages owned by this user. | Below is the the instruction that describes the task:
### Input:
A list of structures describing apps and pages owned by this user.
### Response:
def accounts(self):
"""
A list of structures describing apps and pages owned by this user.
"""
response = self.graph.get('%s/accounts' % ... |
def _load_point(big_endian, type_bytes, data_bytes):
"""
Convert byte data for a Point to a GeoJSON `dict`.
:param bool big_endian:
If `True`, interpret the ``data_bytes`` in big endian order, else
little endian.
:param str type_bytes:
4-byte integer (as a binary string) indicat... | Convert byte data for a Point to a GeoJSON `dict`.
:param bool big_endian:
If `True`, interpret the ``data_bytes`` in big endian order, else
little endian.
:param str type_bytes:
4-byte integer (as a binary string) indicating the geometry type
(Point) and the dimensions (2D, Z, ... | Below is the the instruction that describes the task:
### Input:
Convert byte data for a Point to a GeoJSON `dict`.
:param bool big_endian:
If `True`, interpret the ``data_bytes`` in big endian order, else
little endian.
:param str type_bytes:
4-byte integer (as a binary string) ind... |
def _assign_to_null(obj, path, value, force=True):
"""
value IS ASSIGNED TO obj[self.path][key]
path IS AN ARRAY OF PROPERTY NAMES
force=False IF YOU PREFER TO use setDefault()
"""
try:
if obj is Null:
return
if _get(obj, CLASS) is NullType:
d = _get(obj, ... | value IS ASSIGNED TO obj[self.path][key]
path IS AN ARRAY OF PROPERTY NAMES
force=False IF YOU PREFER TO use setDefault() | Below is the the instruction that describes the task:
### Input:
value IS ASSIGNED TO obj[self.path][key]
path IS AN ARRAY OF PROPERTY NAMES
force=False IF YOU PREFER TO use setDefault()
### Response:
def _assign_to_null(obj, path, value, force=True):
"""
value IS ASSIGNED TO obj[self.path][key]
... |
def auto_detect(self, args):
"""Check for already Slackware binary packages exist
"""
suffixes = [
".tgz",
".txz",
".tbz",
".tlz"
]
if (not args[0].startswith("-") and args[0] not in self.commands and
args[0].endswit... | Check for already Slackware binary packages exist | Below is the the instruction that describes the task:
### Input:
Check for already Slackware binary packages exist
### Response:
def auto_detect(self, args):
"""Check for already Slackware binary packages exist
"""
suffixes = [
".tgz",
".txz",
".tbz",
... |
def LMA(XY,ParIni):
"""
input: list of x and y values [[x_1, y_1], [x_2, y_2], ....], and a tuple containing an initial guess (a, b, r)
which is acquired by using an algebraic circle fit (TaubinSVD)
output: a, b, r. a and b are the center of the fitting circle, and r is the radius
% Geom... | input: list of x and y values [[x_1, y_1], [x_2, y_2], ....], and a tuple containing an initial guess (a, b, r)
which is acquired by using an algebraic circle fit (TaubinSVD)
output: a, b, r. a and b are the center of the fitting circle, and r is the radius
% Geometric circle fit (minimizing ort... | Below is the the instruction that describes the task:
### Input:
input: list of x and y values [[x_1, y_1], [x_2, y_2], ....], and a tuple containing an initial guess (a, b, r)
which is acquired by using an algebraic circle fit (TaubinSVD)
output: a, b, r. a and b are the center of the fitting circl... |
def process_cbn_jgif_file(file_name):
"""Return a PybelProcessor by processing a CBN JGIF JSON file.
Parameters
----------
file_name : str
The path to a CBN JGIF JSON file.
Returns
-------
bp : PybelProcessor
A PybelProcessor object which contains INDRA Statements in
... | Return a PybelProcessor by processing a CBN JGIF JSON file.
Parameters
----------
file_name : str
The path to a CBN JGIF JSON file.
Returns
-------
bp : PybelProcessor
A PybelProcessor object which contains INDRA Statements in
bp.statements. | Below is the the instruction that describes the task:
### Input:
Return a PybelProcessor by processing a CBN JGIF JSON file.
Parameters
----------
file_name : str
The path to a CBN JGIF JSON file.
Returns
-------
bp : PybelProcessor
A PybelProcessor object which contains IN... |
def dict_match(d, key, default=None):
"""Like __getitem__ but works as if the keys() are all filename patterns.
Returns the value of any dict key that matches the passed key.
Args:
d (dict): A dict with filename patterns as keys
key (str): A key potentially matching any of the keys
... | Like __getitem__ but works as if the keys() are all filename patterns.
Returns the value of any dict key that matches the passed key.
Args:
d (dict): A dict with filename patterns as keys
key (str): A key potentially matching any of the keys
default (object): The object to return if no ... | Below is the the instruction that describes the task:
### Input:
Like __getitem__ but works as if the keys() are all filename patterns.
Returns the value of any dict key that matches the passed key.
Args:
d (dict): A dict with filename patterns as keys
key (str): A key potentially matching ... |
def set(self, value: dict):
"""
Set the state, completely over-writing the previous value.
.. caution::
This kind of operation usually leads to a data race.
Please take good care while using this.
Use the :py:func:`atomic` deocrator if you're feeling anxio... | Set the state, completely over-writing the previous value.
.. caution::
This kind of operation usually leads to a data race.
Please take good care while using this.
Use the :py:func:`atomic` deocrator if you're feeling anxious. | Below is the the instruction that describes the task:
### Input:
Set the state, completely over-writing the previous value.
.. caution::
This kind of operation usually leads to a data race.
Please take good care while using this.
Use the :py:func:`atomic` deocrator if... |
def generate_schema_mapping(resolver, schema_uri, depth=1):
""" Try and recursively iterate a JSON schema and to generate an ES mapping
that encasulates it. """
visitor = SchemaVisitor({'$ref': schema_uri}, resolver)
return _generate_schema_mapping(visitor, set(), depth) | Try and recursively iterate a JSON schema and to generate an ES mapping
that encasulates it. | Below is the the instruction that describes the task:
### Input:
Try and recursively iterate a JSON schema and to generate an ES mapping
that encasulates it.
### Response:
def generate_schema_mapping(resolver, schema_uri, depth=1):
""" Try and recursively iterate a JSON schema and to generate an ES mapping... |
def manage_service_check_result_brok(self, b): # pylint: disable=too-many-branches
"""A service check result brok has just arrived ..."""
host_name = b.data.get('host_name', None)
service_description = b.data.get('service_description', None)
if not host_name or not service_description:
... | A service check result brok has just arrived ... | Below is the the instruction that describes the task:
### Input:
A service check result brok has just arrived ...
### Response:
def manage_service_check_result_brok(self, b): # pylint: disable=too-many-branches
"""A service check result brok has just arrived ..."""
host_name = b.data.get('host_nam... |
def get_passenger_cpu_usage(self, dict_stats):
"""
Execute % top; and return STDOUT.
"""
try:
proc1 = subprocess.Popen(
["top", "-b", "-n", "2"],
stdout=subprocess.PIPE)
(std_out, std_err) = proc1.communicate()
except OSErro... | Execute % top; and return STDOUT. | Below is the the instruction that describes the task:
### Input:
Execute % top; and return STDOUT.
### Response:
def get_passenger_cpu_usage(self, dict_stats):
"""
Execute % top; and return STDOUT.
"""
try:
proc1 = subprocess.Popen(
["top", "-b", "-n", "2... |
def _protocolObjectGenerator(self, request, numObjects, getByIndexMethod):
"""
Returns a generator over the results for the specified request, from
a set of protocol objects of the specified size. The objects are
returned by call to the specified method, which must take a single
... | Returns a generator over the results for the specified request, from
a set of protocol objects of the specified size. The objects are
returned by call to the specified method, which must take a single
integer as an argument. The returned generator yields a sequence of
(object, nextPageTo... | Below is the the instruction that describes the task:
### Input:
Returns a generator over the results for the specified request, from
a set of protocol objects of the specified size. The objects are
returned by call to the specified method, which must take a single
integer as an argument. Th... |
def get_import_prefixes_from_env(env):
"""
Obtain current Python import prefixes (for `import_by_name`)
from ``document.env``
"""
prefixes = [None]
currmodule = env.temp_data.get('py:module')
if currmodule:
prefixes.insert(0, currmodule)
currclass = env.temp_data.get('py:class'... | Obtain current Python import prefixes (for `import_by_name`)
from ``document.env`` | Below is the the instruction that describes the task:
### Input:
Obtain current Python import prefixes (for `import_by_name`)
from ``document.env``
### Response:
def get_import_prefixes_from_env(env):
"""
Obtain current Python import prefixes (for `import_by_name`)
from ``document.env``
"""
... |
def _getSyntaxByLanguageName(self, syntaxName):
"""Get syntax by its name. Name is defined in the xml file
"""
xmlFileName = self._syntaxNameToXmlFileName[syntaxName]
return self._getSyntaxByXmlFileName(xmlFileName) | Get syntax by its name. Name is defined in the xml file | Below is the the instruction that describes the task:
### Input:
Get syntax by its name. Name is defined in the xml file
### Response:
def _getSyntaxByLanguageName(self, syntaxName):
"""Get syntax by its name. Name is defined in the xml file
"""
xmlFileName = self._syntaxNameToXmlFileName[s... |
def shell(self):
"""
Opens a Django focussed Python shell.
Essentially the equivalent of running `manage.py shell`.
"""
r = self.local_renderer
if '@' in self.genv.host_string:
r.env.shell_host_string = self.genv.host_string
else:
r.env.she... | Opens a Django focussed Python shell.
Essentially the equivalent of running `manage.py shell`. | Below is the the instruction that describes the task:
### Input:
Opens a Django focussed Python shell.
Essentially the equivalent of running `manage.py shell`.
### Response:
def shell(self):
"""
Opens a Django focussed Python shell.
Essentially the equivalent of running `manage.py s... |
def do_request(self, method, url, data=None, headers=None, params=None):
"""
Handle API requests / responses transport
:param method: HTTP method to use as string
:param data: Any data as PyDict (will be converted to XML string)
:param headers: Any data as PyDict
:return... | Handle API requests / responses transport
:param method: HTTP method to use as string
:param data: Any data as PyDict (will be converted to XML string)
:param headers: Any data as PyDict
:return: If response is XML then an xml.etree.ElementTree else the raw content
:raise: Any u... | Below is the the instruction that describes the task:
### Input:
Handle API requests / responses transport
:param method: HTTP method to use as string
:param data: Any data as PyDict (will be converted to XML string)
:param headers: Any data as PyDict
:return: If response is XML the... |
def can_manage(user, semester=None, pool=None, any_pool=False):
"""
Whether a user is allowed to manage a workshift semester. This includes the
current workshift managers, that semester's workshift managers, and site
superusers.
"""
if semester and user in semester.workshift_managers.all():
... | Whether a user is allowed to manage a workshift semester. This includes the
current workshift managers, that semester's workshift managers, and site
superusers. | Below is the the instruction that describes the task:
### Input:
Whether a user is allowed to manage a workshift semester. This includes the
current workshift managers, that semester's workshift managers, and site
superusers.
### Response:
def can_manage(user, semester=None, pool=None, any_pool=False):
... |
def _set_upload_status(self, file_data_object, upload_status):
""" Set file_data_object.file_resource.upload_status
"""
uuid = file_data_object['uuid']
return self.connection.update_data_object(
uuid,
{'uuid': uuid, 'value': { 'upload_status': upload_status}}
... | Set file_data_object.file_resource.upload_status | Below is the the instruction that describes the task:
### Input:
Set file_data_object.file_resource.upload_status
### Response:
def _set_upload_status(self, file_data_object, upload_status):
""" Set file_data_object.file_resource.upload_status
"""
uuid = file_data_object['uuid']
ret... |
def need_completion_refresh(queries):
"""Determines if the completion needs a refresh by checking if the sql
statement is an alter, create, drop or change db."""
tokens = {
'use', '\\u',
'create',
'drop'
}
for query in sqlparse.split(queries):
try:
first_... | Determines if the completion needs a refresh by checking if the sql
statement is an alter, create, drop or change db. | Below is the the instruction that describes the task:
### Input:
Determines if the completion needs a refresh by checking if the sql
statement is an alter, create, drop or change db.
### Response:
def need_completion_refresh(queries):
"""Determines if the completion needs a refresh by checking if the sql
... |
def _set_mixed_moments_to_zero(self, closed_central_moments, n_counter):
r"""
In univariate case, set the cross-terms to 0.
:param closed_central_moments: matrix of closed central moment
:param n_counter: a list of :class:`~means.core.descriptors.Moment`\s representing central moments
... | r"""
In univariate case, set the cross-terms to 0.
:param closed_central_moments: matrix of closed central moment
:param n_counter: a list of :class:`~means.core.descriptors.Moment`\s representing central moments
:type n_counter: list[:class:`~means.core.descriptors.Moment`]
:re... | Below is the the instruction that describes the task:
### Input:
r"""
In univariate case, set the cross-terms to 0.
:param closed_central_moments: matrix of closed central moment
:param n_counter: a list of :class:`~means.core.descriptors.Moment`\s representing central moments
:type... |
def update(self):
"""Update the status of the range setting."""
self._controller.update(self._id, wake_if_asleep=False)
data = self._controller.get_charging_params(self._id)
if data and (time.time() - self.__manual_update_time > 60):
self.__maxrange_state = data['charge_to_ma... | Update the status of the range setting. | Below is the the instruction that describes the task:
### Input:
Update the status of the range setting.
### Response:
def update(self):
"""Update the status of the range setting."""
self._controller.update(self._id, wake_if_asleep=False)
data = self._controller.get_charging_params(self._id... |
def _all_resources(self):
"""Return the complete collection of resources as a list of
dictionaries.
:rtype: :class:`sandman2.model.Model`
"""
queryset = self.__model__.query
args = {k: v for (k, v) in request.args.items() if k not in ('page', 'export')}
limit = N... | Return the complete collection of resources as a list of
dictionaries.
:rtype: :class:`sandman2.model.Model` | Below is the the instruction that describes the task:
### Input:
Return the complete collection of resources as a list of
dictionaries.
:rtype: :class:`sandman2.model.Model`
### Response:
def _all_resources(self):
"""Return the complete collection of resources as a list of
dictiona... |
def qualifier_encoded(self):
"""Union[str, bytes]: The qualifier encoded in binary.
The type is ``str`` (Python 2.x) or ``bytes`` (Python 3.x). The module
will handle base64 encoding for you.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.query.... | Union[str, bytes]: The qualifier encoded in binary.
The type is ``str`` (Python 2.x) or ``bytes`` (Python 3.x). The module
will handle base64 encoding for you.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.query.tableDefinitions.%28key%29.bigtableOptio... | Below is the the instruction that describes the task:
### Input:
Union[str, bytes]: The qualifier encoded in binary.
The type is ``str`` (Python 2.x) or ``bytes`` (Python 3.x). The module
will handle base64 encoding for you.
See
https://cloud.google.com/bigquery/docs/reference/rest... |
def list(self, path=None, with_metadata=False, include_partitions=False):
'''get a list of all of the files in the repository'''
return self.upstream.list(
path,
with_metadata=with_metadata,
include_partitions=include_partitions) | get a list of all of the files in the repository | Below is the the instruction that describes the task:
### Input:
get a list of all of the files in the repository
### Response:
def list(self, path=None, with_metadata=False, include_partitions=False):
'''get a list of all of the files in the repository'''
return self.upstream.list(
pat... |
def showEvent(self, event):
""" Overrides showEvent to update the viewport margins """
super(CodeEdit, self).showEvent(event)
self.panels.refresh() | Overrides showEvent to update the viewport margins | Below is the the instruction that describes the task:
### Input:
Overrides showEvent to update the viewport margins
### Response:
def showEvent(self, event):
""" Overrides showEvent to update the viewport margins """
super(CodeEdit, self).showEvent(event)
self.panels.refresh() |
def _GetISO8601String(self, structure):
"""Normalize date time parsed format to an ISO 8601 date time string.
The date and time values in Apache access log files are formatted as:
"[18/Sep/2011:19:18:28 -0400]".
Args:
structure (pyparsing.ParseResults): structure of tokens derived from a
... | Normalize date time parsed format to an ISO 8601 date time string.
The date and time values in Apache access log files are formatted as:
"[18/Sep/2011:19:18:28 -0400]".
Args:
structure (pyparsing.ParseResults): structure of tokens derived from a
line of a text file.
Returns:
str:... | Below is the the instruction that describes the task:
### Input:
Normalize date time parsed format to an ISO 8601 date time string.
The date and time values in Apache access log files are formatted as:
"[18/Sep/2011:19:18:28 -0400]".
Args:
structure (pyparsing.ParseResults): structure of tokens d... |
def snake_case(a_string):
"""Returns a snake cased version of a string.
:param a_string: any :class:`str` object.
Usage:
>>> snake_case('FooBar')
"foo_bar"
"""
partial = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', a_string)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', partial).lower(... | Returns a snake cased version of a string.
:param a_string: any :class:`str` object.
Usage:
>>> snake_case('FooBar')
"foo_bar" | Below is the the instruction that describes the task:
### Input:
Returns a snake cased version of a string.
:param a_string: any :class:`str` object.
Usage:
>>> snake_case('FooBar')
"foo_bar"
### Response:
def snake_case(a_string):
"""Returns a snake cased version of a string.
:p... |
def desaturate(self):
"""Desaturates the layer, making it grayscale.
Instantly removes all color information from the layer,
while maintaing its alpha channel.
"""
alpha = self.img.split()[3]
self.img = self.img.convert("L")
self.img = self.img... | Desaturates the layer, making it grayscale.
Instantly removes all color information from the layer,
while maintaing its alpha channel. | Below is the the instruction that describes the task:
### Input:
Desaturates the layer, making it grayscale.
Instantly removes all color information from the layer,
while maintaing its alpha channel.
### Response:
def desaturate(self):
"""Desaturates the layer, making it grayscale... |
def step1ab(self):
"""step1ab() gets rid of plurals and -ed or -ing. e.g.
caresses -> caress
ponies -> poni
ties -> ti
caress -> caress
cats -> cat
feed -> feed
agreed -> agree
disabled -> ... | step1ab() gets rid of plurals and -ed or -ing. e.g.
caresses -> caress
ponies -> poni
ties -> ti
caress -> caress
cats -> cat
feed -> feed
agreed -> agree
disabled -> disable
matting ... | Below is the the instruction that describes the task:
### Input:
step1ab() gets rid of plurals and -ed or -ing. e.g.
caresses -> caress
ponies -> poni
ties -> ti
caress -> caress
cats -> cat
feed -> feed
agree... |
def _MakeCacheInvariant(self, urn, age):
"""Returns an invariant key for an AFF4 object.
The object will be cached based on this key. This function is specifically
extracted to ensure that we encapsulate all security critical aspects of the
AFF4 object so that objects do not leak across security bounda... | Returns an invariant key for an AFF4 object.
The object will be cached based on this key. This function is specifically
extracted to ensure that we encapsulate all security critical aspects of the
AFF4 object so that objects do not leak across security boundaries.
Args:
urn: The urn of the obje... | Below is the the instruction that describes the task:
### Input:
Returns an invariant key for an AFF4 object.
The object will be cached based on this key. This function is specifically
extracted to ensure that we encapsulate all security critical aspects of the
AFF4 object so that objects do not leak a... |
def execute(self, input_data):
''' Execute method '''
my_ssdeep = input_data['meta_deep']['ssdeep']
my_md5 = input_data['meta_deep']['md5']
# For every PE sample in the database compute my ssdeep fuzzy match
sample_set = self.workbench.generate_sample_set('exe')
results ... | Execute method | Below is the the instruction that describes the task:
### Input:
Execute method
### Response:
def execute(self, input_data):
''' Execute method '''
my_ssdeep = input_data['meta_deep']['ssdeep']
my_md5 = input_data['meta_deep']['md5']
# For every PE sample in the database compute my... |
def parse_xml_node(self, node):
'''Parse an xml.dom Node object representing a wait_time condition into
this object.
'''
super(WaitTime, self).parse_xml_node(node)
wait_time_nodes = node.getElementsByTagNameNS(RTS_NS, 'WaitTime')
if wait_time_nodes.length != 1:
... | Parse an xml.dom Node object representing a wait_time condition into
this object. | Below is the the instruction that describes the task:
### Input:
Parse an xml.dom Node object representing a wait_time condition into
this object.
### Response:
def parse_xml_node(self, node):
'''Parse an xml.dom Node object representing a wait_time condition into
this object.
'''
... |
def toggle_value(request, name):
"""
For manual shortcut links to perform toggle actions
"""
obj = service.system.namespace.get(name, None)
if not obj or service.read_only:
raise Http404
new_status = obj.status = not obj.status
if service.redirect_from_setters:
return HttpRes... | For manual shortcut links to perform toggle actions | Below is the the instruction that describes the task:
### Input:
For manual shortcut links to perform toggle actions
### Response:
def toggle_value(request, name):
"""
For manual shortcut links to perform toggle actions
"""
obj = service.system.namespace.get(name, None)
if not obj or service.re... |
def lowdata_fmt():
'''
Validate and format lowdata from incoming unserialized request data
This tool requires that the hypermedia_in tool has already been run.
'''
if cherrypy.request.method.upper() != 'POST':
return
data = cherrypy.request.unserialized_data
# if the data was sen... | Validate and format lowdata from incoming unserialized request data
This tool requires that the hypermedia_in tool has already been run. | Below is the the instruction that describes the task:
### Input:
Validate and format lowdata from incoming unserialized request data
This tool requires that the hypermedia_in tool has already been run.
### Response:
def lowdata_fmt():
'''
Validate and format lowdata from incoming unserialized request ... |
def generate_request_header(self, response, host, is_preemptive=False):
"""
Generates the GSSAPI authentication token with kerberos.
If any GSSAPI step fails, raise KerberosExchangeError
with failure detail.
"""
# Flags used by kerberos module.
gssflags = kerbe... | Generates the GSSAPI authentication token with kerberos.
If any GSSAPI step fails, raise KerberosExchangeError
with failure detail. | Below is the the instruction that describes the task:
### Input:
Generates the GSSAPI authentication token with kerberos.
If any GSSAPI step fails, raise KerberosExchangeError
with failure detail.
### Response:
def generate_request_header(self, response, host, is_preemptive=False):
"""
... |
def bbox(self):
"""
The bounding box ``(ymin, xmin, ymax, xmax)`` of the minimal
rectangular region containing the source segment.
"""
# (stop - 1) to return the max pixel location, not the slice index
return (self._slice[0].start, self._slice[1].start,
s... | The bounding box ``(ymin, xmin, ymax, xmax)`` of the minimal
rectangular region containing the source segment. | Below is the the instruction that describes the task:
### Input:
The bounding box ``(ymin, xmin, ymax, xmax)`` of the minimal
rectangular region containing the source segment.
### Response:
def bbox(self):
"""
The bounding box ``(ymin, xmin, ymax, xmax)`` of the minimal
rectangular ... |
def context_list2dict(context_list: typing.Sequence[typing.Any]) -> Context:
"""Converts a list of objects (functions, classes, or modules) to a
dictionary mapping the object names to the objects.
"""
return {obj.__name__.split(".")[-1]: obj for obj in context_list} | Converts a list of objects (functions, classes, or modules) to a
dictionary mapping the object names to the objects. | Below is the the instruction that describes the task:
### Input:
Converts a list of objects (functions, classes, or modules) to a
dictionary mapping the object names to the objects.
### Response:
def context_list2dict(context_list: typing.Sequence[typing.Any]) -> Context:
"""Converts a list of objects (fun... |
def tabLayout(self):
''' For all tabs, specify the number of buttons in a row '''
self.childWindow.column += 1
if self.childWindow.column > Layout.BUTTONS_NUMBER:
self.childWindow.column = 0
self.childWindow.row += 1 | For all tabs, specify the number of buttons in a row | Below is the the instruction that describes the task:
### Input:
For all tabs, specify the number of buttons in a row
### Response:
def tabLayout(self):
''' For all tabs, specify the number of buttons in a row '''
self.childWindow.column += 1
if self.childWindow.column > Layout.BUTTONS_NUMB... |
def save(glob_str, base_path=None, policy="live"):
""" Ensure all files matching *glob_str* are synced to wandb with the policy specified.
base_path: the base path to run the glob relative to
policy:
live: upload the file as it changes, overwriting the previous version
end: only upload file... | Ensure all files matching *glob_str* are synced to wandb with the policy specified.
base_path: the base path to run the glob relative to
policy:
live: upload the file as it changes, overwriting the previous version
end: only upload file when the run ends | Below is the the instruction that describes the task:
### Input:
Ensure all files matching *glob_str* are synced to wandb with the policy specified.
base_path: the base path to run the glob relative to
policy:
live: upload the file as it changes, overwriting the previous version
end: only u... |
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
spaces = ' ' * indent
return spaces + ', '.join(v.pretty_str() for v in self.variables) | Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation. | Below is the the instruction that describes the task:
### Input:
Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
### Response:
def pretty_str(self, indent=0):
"""Return a human-readable string representatio... |
def time_since(self, mtype):
'''return the time since the last message of type mtype was received'''
if not mtype in self.messages:
return time.time() - self.start_time
return time.time() - self.messages[mtype]._timestamp | return the time since the last message of type mtype was received | Below is the the instruction that describes the task:
### Input:
return the time since the last message of type mtype was received
### Response:
def time_since(self, mtype):
'''return the time since the last message of type mtype was received'''
if not mtype in self.messages:
return tim... |
def compute_total(self, precision=None):
'''
Gets the total of the invoice with a defined decimal precision
@param precision: int Number of decimal places
@return: Decimal
'''
return quantize(sum([group.compute_total(precision) for group
in se... | Gets the total of the invoice with a defined decimal precision
@param precision: int Number of decimal places
@return: Decimal | Below is the the instruction that describes the task:
### Input:
Gets the total of the invoice with a defined decimal precision
@param precision: int Number of decimal places
@return: Decimal
### Response:
def compute_total(self, precision=None):
'''
Gets the total of the invoice wi... |
def update_status(self, helper, status):
""" update the helper """
if status:
self.status(status[0])
# if the status is ok, add it to the long output
if status[0] == 0:
self.add_long_output(status[1])
# if the status is not ok, add it to t... | update the helper | Below is the the instruction that describes the task:
### Input:
update the helper
### Response:
def update_status(self, helper, status):
""" update the helper """
if status:
self.status(status[0])
# if the status is ok, add it to the long output
if status[0] ==... |
def get_classification_node(self, project, structure_group, path=None, depth=None):
"""GetClassificationNode.
Gets the classification node for a given node path.
:param str project: Project ID or project name
:param TreeStructureGroup structure_group: Structure group of the classificatio... | GetClassificationNode.
Gets the classification node for a given node path.
:param str project: Project ID or project name
:param TreeStructureGroup structure_group: Structure group of the classification node, area or iteration.
:param str path: Path of the classification node.
:p... | Below is the the instruction that describes the task:
### Input:
GetClassificationNode.
Gets the classification node for a given node path.
:param str project: Project ID or project name
:param TreeStructureGroup structure_group: Structure group of the classification node, area or iteration.... |
def angle2d(self):
"""determine the angle of this point on a circle, measured in radians (presume values represent a Vector)"""
if self.x==0:
if self.y<0: return math.pi/2.0*3
elif self.y>0: return math.pi/2.0
else: return 0
elif self... | determine the angle of this point on a circle, measured in radians (presume values represent a Vector) | Below is the the instruction that describes the task:
### Input:
determine the angle of this point on a circle, measured in radians (presume values represent a Vector)
### Response:
def angle2d(self):
"""determine the angle of this point on a circle, measured in radians (presume values represent a Vector)"... |
def d2BinaryRochedx2(r, D, q, F):
"""
Computes second derivative of the potential with respect to x.
@param r: relative radius vector (3 components)
@param D: instantaneous separation
@param q: mass ratio
@param F: synchronicity parameter
"""
return (2*r[0]*r[0]-r[1]... | Computes second derivative of the potential with respect to x.
@param r: relative radius vector (3 components)
@param D: instantaneous separation
@param q: mass ratio
@param F: synchronicity parameter | Below is the the instruction that describes the task:
### Input:
Computes second derivative of the potential with respect to x.
@param r: relative radius vector (3 components)
@param D: instantaneous separation
@param q: mass ratio
@param F: synchronicity parameter
### Response:... |
def createCertRequest(pkey, digest="sha256"):
"""
Create a certificate request.
Arguments: pkey - The key to associate with the request
digest - Digestion method to use for signing, default is sha256
**name - The name of the subject of the request, possible
... | Create a certificate request.
Arguments: pkey - The key to associate with the request
digest - Digestion method to use for signing, default is sha256
**name - The name of the subject of the request, possible
arguments are:
C - Cou... | Below is the the instruction that describes the task:
### Input:
Create a certificate request.
Arguments: pkey - The key to associate with the request
digest - Digestion method to use for signing, default is sha256
**name - The name of the subject of the request, possible
... |
def get_int(byte_array, signed=True):
"""
Gets the specified integer from its byte array.
This should be used by this module alone, as it works with big endian.
:param byte_array: the byte array representing th integer.
:param signed: whether the number is signed or not.
:return: the integer re... | Gets the specified integer from its byte array.
This should be used by this module alone, as it works with big endian.
:param byte_array: the byte array representing th integer.
:param signed: whether the number is signed or not.
:return: the integer representing the given byte array. | Below is the the instruction that describes the task:
### Input:
Gets the specified integer from its byte array.
This should be used by this module alone, as it works with big endian.
:param byte_array: the byte array representing th integer.
:param signed: whether the number is signed or not.
:ret... |
def make_elb_json(self):
"""Render the JSON template with arguments.
Returns:
str: Rendered ELB template.
"""
env = self.env
region = self.region
elb_settings = self.properties['elb']
LOG.debug('Block ELB Settings:\n%s', pformat(elb_settings))
... | Render the JSON template with arguments.
Returns:
str: Rendered ELB template. | Below is the the instruction that describes the task:
### Input:
Render the JSON template with arguments.
Returns:
str: Rendered ELB template.
### Response:
def make_elb_json(self):
"""Render the JSON template with arguments.
Returns:
str: Rendered ELB template.
... |
def serve(project, port, no_watch):
""" Serve application in development mode """
header("Serving application in development mode ... ")
print("- Project: %s " % project)
print("")
print("- Port: %s" % port)
print("")
module = import_module(project, True)
extra_files = []
if not n... | Serve application in development mode | Below is the the instruction that describes the task:
### Input:
Serve application in development mode
### Response:
def serve(project, port, no_watch):
""" Serve application in development mode """
header("Serving application in development mode ... ")
print("- Project: %s " % project)
print("")
... |
def init(options):
""" Initialize some defaults """
# Set matlplotlib's backend so LIVVkit can plot to files.
import matplotlib
matplotlib.use('agg')
livvkit.output_dir = os.path.abspath(options.out_dir)
livvkit.index_dir = livvkit.output_dir
livvkit.verify = True if options.verify is not ... | Initialize some defaults | Below is the the instruction that describes the task:
### Input:
Initialize some defaults
### Response:
def init(options):
""" Initialize some defaults """
# Set matlplotlib's backend so LIVVkit can plot to files.
import matplotlib
matplotlib.use('agg')
livvkit.output_dir = os.path.abspath(op... |
def update_shortlink(self, shortlink_id, callback_uri=None,
description=None):
"""Update existing shortlink registration
Arguments:
shortlink_id:
Shortlink id assigned by mCASH
"""
arguments = {'callback_uri': callback_uri,
... | Update existing shortlink registration
Arguments:
shortlink_id:
Shortlink id assigned by mCASH | Below is the the instruction that describes the task:
### Input:
Update existing shortlink registration
Arguments:
shortlink_id:
Shortlink id assigned by mCASH
### Response:
def update_shortlink(self, shortlink_id, callback_uri=None,
description=None):
... |
def create_participant(worker_id, hit_id, assignment_id, mode):
"""Create a participant.
This route will be hit very early on as any nodes the participant creates
will be defined in reference to the participant object.
You must specify the worker_id, hit_id, assignment_id and mode in the url.
"""
... | Create a participant.
This route will be hit very early on as any nodes the participant creates
will be defined in reference to the participant object.
You must specify the worker_id, hit_id, assignment_id and mode in the url. | Below is the the instruction that describes the task:
### Input:
Create a participant.
This route will be hit very early on as any nodes the participant creates
will be defined in reference to the participant object.
You must specify the worker_id, hit_id, assignment_id and mode in the url.
### Respons... |
def _init_items(self):
"""
.---------------.
| Ctrl | Screen |
|------| |
| Code | |
| | |
"""
root = self._root
root.resizable(0, 0)
frm_control = tk.Frame(root, bg='#bbb')
frm_control.grid(column=0, row=... | .---------------.
| Ctrl | Screen |
|------| |
| Code | |
| | | | Below is the the instruction that describes the task:
### Input:
.---------------.
| Ctrl | Screen |
|------| |
| Code | |
| | |
### Response:
def _init_items(self):
"""
.---------------.
| Ctrl | Screen |
|------| |
... |
def cumulative_blame(self, branch='master', limit=None, skip=None, num_datapoints=None, committer=True,
ignore_globs=None, include_globs=None):
"""
Returns the blame at every revision of interest. Index is a datetime, column per committer, with number of lines
blamed to ... | Returns the blame at every revision of interest. Index is a datetime, column per committer, with number of lines
blamed to each committer at each timestamp as data.
:param branch: (optional, default 'master') the branch to work in
:param limit: (optional, default None), the maximum number of re... | Below is the the instruction that describes the task:
### Input:
Returns the blame at every revision of interest. Index is a datetime, column per committer, with number of lines
blamed to each committer at each timestamp as data.
:param branch: (optional, default 'master') the branch to work in
... |
def targets_for_class(self, target, classname):
"""Search which targets from `target`'s transitive dependencies contain `classname`."""
targets_with_class = set()
for target in target.closure():
for one_class in self._target_classes(target):
if classname in one_class:
targets_with_cl... | Search which targets from `target`'s transitive dependencies contain `classname`. | Below is the the instruction that describes the task:
### Input:
Search which targets from `target`'s transitive dependencies contain `classname`.
### Response:
def targets_for_class(self, target, classname):
"""Search which targets from `target`'s transitive dependencies contain `classname`."""
targets_wi... |
def _read(self, directory, filename, session, path, name, extension, spatial, spatialReferenceID, maskMap):
"""
WMS Dataset File Read from File Method
"""
# Assign file extension attribute to file object
self.fileExtension = extension
if isinstance(maskMap, RasterMapFile... | WMS Dataset File Read from File Method | Below is the the instruction that describes the task:
### Input:
WMS Dataset File Read from File Method
### Response:
def _read(self, directory, filename, session, path, name, extension, spatial, spatialReferenceID, maskMap):
"""
WMS Dataset File Read from File Method
"""
# Assign f... |
def get_valid_har(har_data):
""" Return list of valid HAR entries.
:rtype: list
"""
new_entries = []
entries = har_data.get('log', {}).get('entries', [])
logger.debug('[+] Detected %(n)d entries in HAR', {'n': len(entries)})
for entry in entries:
url = entry['request']['url']
... | Return list of valid HAR entries.
:rtype: list | Below is the the instruction that describes the task:
### Input:
Return list of valid HAR entries.
:rtype: list
### Response:
def get_valid_har(har_data):
""" Return list of valid HAR entries.
:rtype: list
"""
new_entries = []
entries = har_data.get('log', {}).get('entries', [])
logg... |
def warm(self):
"""
Returns a 2-tuple:
[0]: Number of images successfully pre-warmed
[1]: A list of paths on the storage class associated with the
VersatileImageField field being processed by `self` of
files that could not be successfully seeded.
"""
... | Returns a 2-tuple:
[0]: Number of images successfully pre-warmed
[1]: A list of paths on the storage class associated with the
VersatileImageField field being processed by `self` of
files that could not be successfully seeded. | Below is the the instruction that describes the task:
### Input:
Returns a 2-tuple:
[0]: Number of images successfully pre-warmed
[1]: A list of paths on the storage class associated with the
VersatileImageField field being processed by `self` of
files that could not be suc... |
def not_all(*validation_func, # type: ValidationFuncs
**kwargs
):
# type: (...) -> Callable
"""
An alias for not_(and_(validators)).
:param validation_func: the base validation function or list of base validation functions to use. A callable, a
tuple(callable, help_msg_... | An alias for not_(and_(validators)).
:param validation_func: the base validation function or list of base validation functions to use. A callable, a
tuple(callable, help_msg_str), a tuple(callable, failure_type), or a list of several such elements. Nested lists
are supported and indicate an implici... | Below is the the instruction that describes the task:
### Input:
An alias for not_(and_(validators)).
:param validation_func: the base validation function or list of base validation functions to use. A callable, a
tuple(callable, help_msg_str), a tuple(callable, failure_type), or a list of several such... |
def escape_keywords(arr):
"""append _ to all python keywords"""
for i in arr:
i = i if i not in kwlist else i + '_'
i = i if '-' not in i else i.replace('-', '_')
yield i | append _ to all python keywords | Below is the the instruction that describes the task:
### Input:
append _ to all python keywords
### Response:
def escape_keywords(arr):
"""append _ to all python keywords"""
for i in arr:
i = i if i not in kwlist else i + '_'
i = i if '-' not in i else i.replace('-', '_')
yield i |
def print_flush(*args, **kwargs):
""" Like `print()`, except the file is `.flush()`ed afterwards. """
kwargs.setdefault('file', sys.stdout)
print(*args, **kwargs)
kwargs['file'].flush() | Like `print()`, except the file is `.flush()`ed afterwards. | Below is the the instruction that describes the task:
### Input:
Like `print()`, except the file is `.flush()`ed afterwards.
### Response:
def print_flush(*args, **kwargs):
""" Like `print()`, except the file is `.flush()`ed afterwards. """
kwargs.setdefault('file', sys.stdout)
print(*args, **kwargs)
... |
def format_output(data, fmt='table'): # pylint: disable=R0911,R0912
"""Given some data, will format it for console output.
:param data: One of: String, Table, FormattedItem, List, Tuple,
SequentialOutput
:param string fmt (optional): One of: table, raw, json, python
"""
if isinsta... | Given some data, will format it for console output.
:param data: One of: String, Table, FormattedItem, List, Tuple,
SequentialOutput
:param string fmt (optional): One of: table, raw, json, python | Below is the the instruction that describes the task:
### Input:
Given some data, will format it for console output.
:param data: One of: String, Table, FormattedItem, List, Tuple,
SequentialOutput
:param string fmt (optional): One of: table, raw, json, python
### Response:
def format_out... |
def headers_to_use(self):
'''
Defines features of columns to be used in multiqc table
'''
headers = OrderedDict()
headers['total.reads'] = {
'title': 'Total reads',
'description': 'Total number of reads',
'format': '{:,.0f}',
'scal... | Defines features of columns to be used in multiqc table | Below is the the instruction that describes the task:
### Input:
Defines features of columns to be used in multiqc table
### Response:
def headers_to_use(self):
'''
Defines features of columns to be used in multiqc table
'''
headers = OrderedDict()
headers['total.reads'] = ... |
def is_iterable(obj):
"""
Are we being asked to look up a list of things, instead of a single thing?
We check for the `__iter__` attribute so that this can cover types that
don't have to be known by this module, such as NumPy arrays.
Strings, however, should be considered as atomic values to look u... | Are we being asked to look up a list of things, instead of a single thing?
We check for the `__iter__` attribute so that this can cover types that
don't have to be known by this module, such as NumPy arrays.
Strings, however, should be considered as atomic values to look up, not
iterables. The same goe... | Below is the the instruction that describes the task:
### Input:
Are we being asked to look up a list of things, instead of a single thing?
We check for the `__iter__` attribute so that this can cover types that
don't have to be known by this module, such as NumPy arrays.
Strings, however, should be co... |
def p_color(self, p):
""" color : css_color
| css_color t_ws
"""
try:
p[0] = Color().fmt(p[1])
if len(p) > 2:
p[0] = [p[0], p[2]]
except ValueError:
self.handle_error('Illegal color ... | color : css_color
| css_color t_ws | Below is the the instruction that describes the task:
### Input:
color : css_color
| css_color t_ws
### Response:
def p_color(self, p):
""" color : css_color
| css_color t_ws
"""
try:... |
def make_node(cls, lineno, s, lower, upper):
""" Creates a node for a string slice. S is the string expression Tree.
Lower and upper are the bounds, if lower & upper are constants, and
s is also constant, then a string constant is returned.
If lower > upper, an empty string is returned.... | Creates a node for a string slice. S is the string expression Tree.
Lower and upper are the bounds, if lower & upper are constants, and
s is also constant, then a string constant is returned.
If lower > upper, an empty string is returned. | Below is the the instruction that describes the task:
### Input:
Creates a node for a string slice. S is the string expression Tree.
Lower and upper are the bounds, if lower & upper are constants, and
s is also constant, then a string constant is returned.
If lower > upper, an empty string ... |
def _run_cromwell(args):
"""Run CWL with Cromwell.
"""
main_file, json_file, project_name = _get_main_and_json(args.directory)
work_dir = utils.safe_makedir(os.path.join(os.getcwd(), "cromwell_work"))
final_dir = utils.safe_makedir(os.path.join(work_dir, "final"))
if args.no_container:
_... | Run CWL with Cromwell. | Below is the the instruction that describes the task:
### Input:
Run CWL with Cromwell.
### Response:
def _run_cromwell(args):
"""Run CWL with Cromwell.
"""
main_file, json_file, project_name = _get_main_and_json(args.directory)
work_dir = utils.safe_makedir(os.path.join(os.getcwd(), "cromwell_work... |
def conversations(self, getsrcdst=None, draw = True, **kargs):
"""Graphes a conversations between sources and destinations and display it
(using graphviz)
getsrcdst: a function that takes an element of the list and return the source and dest
by defaults, return source and dest... | Graphes a conversations between sources and destinations and display it
(using graphviz)
getsrcdst: a function that takes an element of the list and return the source and dest
by defaults, return source and destination IP
if networkx library is available returns a DiGraph, or ... | Below is the the instruction that describes the task:
### Input:
Graphes a conversations between sources and destinations and display it
(using graphviz)
getsrcdst: a function that takes an element of the list and return the source and dest
by defaults, return source and destinati... |
def post_event_unpublish(self, id, **data):
"""
POST /events/:id/unpublish/
Unpublishes an event. In order for a free event to be unpublished, it must not have any pending or completed orders,
even if the event is in the past. In order for a paid event to be unpublished, it must not have... | POST /events/:id/unpublish/
Unpublishes an event. In order for a free event to be unpublished, it must not have any pending or completed orders,
even if the event is in the past. In order for a paid event to be unpublished, it must not have any pending or completed
orders, unless the event has b... | Below is the the instruction that describes the task:
### Input:
POST /events/:id/unpublish/
Unpublishes an event. In order for a free event to be unpublished, it must not have any pending or completed orders,
even if the event is in the past. In order for a paid event to be unpublished, it must not... |
def save_raw(self):
"""
Save the model to a in memory buffer represetation
Returns
-------
a in memory buffer represetation of the model
"""
length = ctypes.c_ulong()
cptr = ctypes.POINTER(ctypes.c_char)()
_check_call(_LIB.XGBoosterGetModelRaw(sel... | Save the model to a in memory buffer represetation
Returns
-------
a in memory buffer represetation of the model | Below is the the instruction that describes the task:
### Input:
Save the model to a in memory buffer represetation
Returns
-------
a in memory buffer represetation of the model
### Response:
def save_raw(self):
"""
Save the model to a in memory buffer represetation
... |
def _acceptpeak(peak, amp, definitive_peaks, spk1, rr_buffer):
"""
Private function intended to insert a new RR interval in the buffer.
----------
Parameters
----------
peak : int
Sample where the peak under analysis is located.
amp : int
Amplitude of the peak under analysis... | Private function intended to insert a new RR interval in the buffer.
----------
Parameters
----------
peak : int
Sample where the peak under analysis is located.
amp : int
Amplitude of the peak under analysis.
definitive_peaks : list
List with the definitive_peaks stored... | Below is the the instruction that describes the task:
### Input:
Private function intended to insert a new RR interval in the buffer.
----------
Parameters
----------
peak : int
Sample where the peak under analysis is located.
amp : int
Amplitude of the peak under analysis.
... |
def get_notebook_object(self, notebook_id):
"""Get the NotebookNode representation of a notebook by notebook_id."""
path = self.find_path(notebook_id)
if not os.path.isfile(path):
raise web.HTTPError(404, u'Notebook does not exist: %s' % notebook_id)
info = os.stat(path)
... | Get the NotebookNode representation of a notebook by notebook_id. | Below is the the instruction that describes the task:
### Input:
Get the NotebookNode representation of a notebook by notebook_id.
### Response:
def get_notebook_object(self, notebook_id):
"""Get the NotebookNode representation of a notebook by notebook_id."""
path = self.find_path(notebook_id)
... |
def visit_Capture(self, node: parsing.Capture) -> [ast.stmt] or ast.expr:
"""Generates python code to capture text consumed by a clause.
#If all clauses can be inlined
self.beginTag('tagname') and clause and self.endTag('tagname')
if not self.beginTag('tagname'):
return Fal... | Generates python code to capture text consumed by a clause.
#If all clauses can be inlined
self.beginTag('tagname') and clause and self.endTag('tagname')
if not self.beginTag('tagname'):
return False
<code for the clause>
if not self.endTag('tagname'):
r... | Below is the the instruction that describes the task:
### Input:
Generates python code to capture text consumed by a clause.
#If all clauses can be inlined
self.beginTag('tagname') and clause and self.endTag('tagname')
if not self.beginTag('tagname'):
return False
<code... |
def notify(self, n: int = 1) -> None:
"""Wake ``n`` waiters."""
waiters = [] # Waiters we plan to run right now.
while n and self._waiters:
waiter = self._waiters.popleft()
if not waiter.done(): # Might have timed out.
n -= 1
waiters.appe... | Wake ``n`` waiters. | Below is the the instruction that describes the task:
### Input:
Wake ``n`` waiters.
### Response:
def notify(self, n: int = 1) -> None:
"""Wake ``n`` waiters."""
waiters = [] # Waiters we plan to run right now.
while n and self._waiters:
waiter = self._waiters.popleft()
... |
def parse_from_file(filename, nodata=False):
"""Parse df message from file.
@filename - path to file
@nodata - do not load data
@return - [binary header, metadata, binary data]
"""
header = None
with open(filename, "rb") as file:
header = read_machine_header(file)
meta_raw ... | Parse df message from file.
@filename - path to file
@nodata - do not load data
@return - [binary header, metadata, binary data] | Below is the the instruction that describes the task:
### Input:
Parse df message from file.
@filename - path to file
@nodata - do not load data
@return - [binary header, metadata, binary data]
### Response:
def parse_from_file(filename, nodata=False):
"""Parse df message from file.
@filename... |
def back_propagation(self, delta_arr):
'''
Back propagation.
Args:
delta_output_arr: Delta.
Returns:
Tuple data.
- decoder's `list` of gradations,
- encoder's `np.ndarray` of Delta,
- encoder's `list` of... | Back propagation.
Args:
delta_output_arr: Delta.
Returns:
Tuple data.
- decoder's `list` of gradations,
- encoder's `np.ndarray` of Delta,
- encoder's `list` of gradations. | Below is the the instruction that describes the task:
### Input:
Back propagation.
Args:
delta_output_arr: Delta.
Returns:
Tuple data.
- decoder's `list` of gradations,
- encoder's `np.ndarray` of Delta,
- encoder's `... |
def chunk(self, maxSize):
"""Splits the `Collection` into _maxSize_ size or smaller `Collections`
# Parameters
_maxSize_ : `int`
> The maximum number of elements in a retuned `Collection`
# Returns
`list [Collection]`
> A list of `Collections` that if all m... | Splits the `Collection` into _maxSize_ size or smaller `Collections`
# Parameters
_maxSize_ : `int`
> The maximum number of elements in a retuned `Collection`
# Returns
`list [Collection]`
> A list of `Collections` that if all merged (`|` operator) would create the... | Below is the the instruction that describes the task:
### Input:
Splits the `Collection` into _maxSize_ size or smaller `Collections`
# Parameters
_maxSize_ : `int`
> The maximum number of elements in a retuned `Collection`
# Returns
`list [Collection]`
> A lis... |
def csrf(request):
"""
Context processor that provides a CSRF token, or the string 'NOTPROVIDED'
if it has not been provided by either a view decorator or the middleware
"""
def _get_val():
token = get_token(request)
if token is None:
# In order to be able to provide debu... | Context processor that provides a CSRF token, or the string 'NOTPROVIDED'
if it has not been provided by either a view decorator or the middleware | Below is the the instruction that describes the task:
### Input:
Context processor that provides a CSRF token, or the string 'NOTPROVIDED'
if it has not been provided by either a view decorator or the middleware
### Response:
def csrf(request):
"""
Context processor that provides a CSRF token, or the s... |
def _codec_can_decode_with_surrogatepass(codec, _cache={}):
"""Returns if a codec supports the surrogatepass error handler when
decoding. Some codecs were broken in Python <3.4
"""
try:
return _cache[codec]
except KeyError:
try:
u"\ud83d".encode(
codec, _... | Returns if a codec supports the surrogatepass error handler when
decoding. Some codecs were broken in Python <3.4 | Below is the the instruction that describes the task:
### Input:
Returns if a codec supports the surrogatepass error handler when
decoding. Some codecs were broken in Python <3.4
### Response:
def _codec_can_decode_with_surrogatepass(codec, _cache={}):
"""Returns if a codec supports the surrogatepass error... |
def intersect(d1, d2):
"""Intersect dictionaries d1 and d2 by key *and* value."""
return dict((k, d1[k]) for k in d1 if k in d2 and d1[k] == d2[k]) | Intersect dictionaries d1 and d2 by key *and* value. | Below is the the instruction that describes the task:
### Input:
Intersect dictionaries d1 and d2 by key *and* value.
### Response:
def intersect(d1, d2):
"""Intersect dictionaries d1 and d2 by key *and* value."""
return dict((k, d1[k]) for k in d1 if k in d2 and d1[k] == d2[k]) |
def _recursive_get(self, key, dic=None):
"""
Gets contents of requirement key recursively so users can search for
specific keys inside nested requirement dicts.
:param key: key or dot separated string of keys to look for.
:param dic: Optional dictionary to use in the search.
... | Gets contents of requirement key recursively so users can search for
specific keys inside nested requirement dicts.
:param key: key or dot separated string of keys to look for.
:param dic: Optional dictionary to use in the search.
If not provided, self._requirements is used.
:re... | Below is the the instruction that describes the task:
### Input:
Gets contents of requirement key recursively so users can search for
specific keys inside nested requirement dicts.
:param key: key or dot separated string of keys to look for.
:param dic: Optional dictionary to use in the sea... |
def _fill(self, direction, limit=None):
"""
Shared function for `pad` and `backfill` to call Cython method.
Parameters
----------
direction : {'ffill', 'bfill'}
Direction passed to underlying Cython function. `bfill` will cause
values to be filled backwar... | Shared function for `pad` and `backfill` to call Cython method.
Parameters
----------
direction : {'ffill', 'bfill'}
Direction passed to underlying Cython function. `bfill` will cause
values to be filled backwards. `ffill` and any other values will
default to... | Below is the the instruction that describes the task:
### Input:
Shared function for `pad` and `backfill` to call Cython method.
Parameters
----------
direction : {'ffill', 'bfill'}
Direction passed to underlying Cython function. `bfill` will cause
values to be fille... |
def defaults(self):
""" component default component
.. Note:: default components is just an indication for user and the
views, except if the Block is required. If required then default is
selected if nothing explisitely selected.
"""
default = self._defaults
... | component default component
.. Note:: default components is just an indication for user and the
views, except if the Block is required. If required then default is
selected if nothing explisitely selected. | Below is the the instruction that describes the task:
### Input:
component default component
.. Note:: default components is just an indication for user and the
views, except if the Block is required. If required then default is
selected if nothing explisitely selected.
### Response... |
def MapFields(function, key=True):
"""
Transformation factory that maps `function` on the values of a row.
It can be applied either to
1. all columns (`key=True`),
2. no column (`key=False`), or
3. a subset of columns by passing a callable, which takes column name and returns `bool`
(same a... | Transformation factory that maps `function` on the values of a row.
It can be applied either to
1. all columns (`key=True`),
2. no column (`key=False`), or
3. a subset of columns by passing a callable, which takes column name and returns `bool`
(same as the parameter `function` in `filter`).
:... | Below is the the instruction that describes the task:
### Input:
Transformation factory that maps `function` on the values of a row.
It can be applied either to
1. all columns (`key=True`),
2. no column (`key=False`), or
3. a subset of columns by passing a callable, which takes column name and retur... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.