code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def _path_to_baton_json(self, path: str) -> Dict:
"""
Converts a path to the type of iRODS entity the mapper deals with, to its JSON representation.
:param path: the path to convert
:return: the JSON representation of the path
"""
entity = self._create_entity_with_path(pa... | Converts a path to the type of iRODS entity the mapper deals with, to its JSON representation.
:param path: the path to convert
:return: the JSON representation of the path | Below is the the instruction that describes the task:
### Input:
Converts a path to the type of iRODS entity the mapper deals with, to its JSON representation.
:param path: the path to convert
:return: the JSON representation of the path
### Response:
def _path_to_baton_json(self, path: str) -> Dic... |
def view_task_risk(token, dstore):
"""
Display info about a given risk task. Here are a few examples of usage::
$ oq show task_risk:0 # the fastest task
$ oq show task_risk:-1 # the slowest task
"""
[key] = dstore['task_info']
data = dstore['task_info/' + key].value
data.sort(order=... | Display info about a given risk task. Here are a few examples of usage::
$ oq show task_risk:0 # the fastest task
$ oq show task_risk:-1 # the slowest task | Below is the the instruction that describes the task:
### Input:
Display info about a given risk task. Here are a few examples of usage::
$ oq show task_risk:0 # the fastest task
$ oq show task_risk:-1 # the slowest task
### Response:
def view_task_risk(token, dstore):
"""
Display info about a... |
def from_dict(data, ctx):
"""
Instantiate a new OrderBook from a dict (generally from loading a JSON
response). The data used to instantiate the OrderBook is a shallow copy
of the dict passed in, with any complex child types instantiated
appropriately.
"""
data =... | Instantiate a new OrderBook from a dict (generally from loading a JSON
response). The data used to instantiate the OrderBook is a shallow copy
of the dict passed in, with any complex child types instantiated
appropriately. | Below is the the instruction that describes the task:
### Input:
Instantiate a new OrderBook from a dict (generally from loading a JSON
response). The data used to instantiate the OrderBook is a shallow copy
of the dict passed in, with any complex child types instantiated
appropriately.
### ... |
def save(self, filething=None):
"""Save changes to a file.
If no filename is given, the one most recently loaded is used.
Tags are always written at the end of the file, and include
a header and a footer.
"""
fileobj = filething.fileobj
data = _APEv2Data(fileo... | Save changes to a file.
If no filename is given, the one most recently loaded is used.
Tags are always written at the end of the file, and include
a header and a footer. | Below is the the instruction that describes the task:
### Input:
Save changes to a file.
If no filename is given, the one most recently loaded is used.
Tags are always written at the end of the file, and include
a header and a footer.
### Response:
def save(self, filething=None):
... |
def row(*args, **kwargs):
""" Create a row of Bokeh Layout objects. Forces all objects to
have the same sizing_mode, which is required for complex layouts to work.
Args:
children (list of :class:`~bokeh.models.layouts.LayoutDOM` ): A list of instances for
the row. Can be any of the foll... | Create a row of Bokeh Layout objects. Forces all objects to
have the same sizing_mode, which is required for complex layouts to work.
Args:
children (list of :class:`~bokeh.models.layouts.LayoutDOM` ): A list of instances for
the row. Can be any of the following - :class:`~bokeh.models.plot... | Below is the the instruction that describes the task:
### Input:
Create a row of Bokeh Layout objects. Forces all objects to
have the same sizing_mode, which is required for complex layouts to work.
Args:
children (list of :class:`~bokeh.models.layouts.LayoutDOM` ): A list of instances for
... |
def get(cls, community_id, with_deleted=False):
"""Get a community."""
q = cls.query.filter_by(id=community_id)
if not with_deleted:
q = q.filter(cls.deleted_at.is_(None))
return q.one_or_none() | Get a community. | Below is the the instruction that describes the task:
### Input:
Get a community.
### Response:
def get(cls, community_id, with_deleted=False):
"""Get a community."""
q = cls.query.filter_by(id=community_id)
if not with_deleted:
q = q.filter(cls.deleted_at.is_(None))
ret... |
def AskFileForSave(message=None, savedFileName=None, version=None, defaultLocation=None, dialogOptionFlags=None, location=None, clientName=None, windowTitle=None, actionButtonLabel=None, cancelButtonLabel=None, preferenceKey=None, popupExtension=None, eventProc=None, fileType=None, fileCreator=None, wanted=None, multip... | Original doc: Display a dialog asking the user for a filename to save to.
wanted is the return type wanted: FSSpec, FSRef, unicode or string (default)
the other arguments can be looked up in Apple's Navigation Services documentation | Below is the the instruction that describes the task:
### Input:
Original doc: Display a dialog asking the user for a filename to save to.
wanted is the return type wanted: FSSpec, FSRef, unicode or string (default)
the other arguments can be looked up in Apple's Navigation Services documentation
### Respo... |
def _get_data_files(self):
"""
Override of build_py.get_data_files that includes out of tree configs.
These are currently hardcoded to include everything in
../shared-data/robot-data, which will move to
opentrons/config/shared-data
"""
files = super()._get_data_f... | Override of build_py.get_data_files that includes out of tree configs.
These are currently hardcoded to include everything in
../shared-data/robot-data, which will move to
opentrons/config/shared-data | Below is the the instruction that describes the task:
### Input:
Override of build_py.get_data_files that includes out of tree configs.
These are currently hardcoded to include everything in
../shared-data/robot-data, which will move to
opentrons/config/shared-data
### Response:
def _get_d... |
def iterstraight(self, raw):
"""Iterator that undoes the effect of filtering, and yields
each row in serialised format (as a sequence of bytes).
Assumes input is straightlaced. `raw` should be an iterable
that yields the raw bytes in chunks of arbitrary size.
"""
# leng... | Iterator that undoes the effect of filtering, and yields
each row in serialised format (as a sequence of bytes).
Assumes input is straightlaced. `raw` should be an iterable
that yields the raw bytes in chunks of arbitrary size. | Below is the the instruction that describes the task:
### Input:
Iterator that undoes the effect of filtering, and yields
each row in serialised format (as a sequence of bytes).
Assumes input is straightlaced. `raw` should be an iterable
that yields the raw bytes in chunks of arbitrary size... |
def handle_dpad(self):
"""Gets the state of the virtual dpad."""
# pylint: disable=no-member
x_raw = self.microbit.accelerometer.get_x()
y_raw = self.microbit.accelerometer.get_y()
minus_sens = self.sensitivity * -1
if x_raw < minus_sens:
x_state = ('Absolute'... | Gets the state of the virtual dpad. | Below is the the instruction that describes the task:
### Input:
Gets the state of the virtual dpad.
### Response:
def handle_dpad(self):
"""Gets the state of the virtual dpad."""
# pylint: disable=no-member
x_raw = self.microbit.accelerometer.get_x()
y_raw = self.microbit.accelerom... |
def lookup_discrete(x, xs, ys):
"""
Intermediate values take on the value associated with the next lower x-coordinate (also called a step-wise function). The last two points of a discrete graphical function must have the same y value.
Out-of-range values are the same as the closest endpoint (i.e, no extrapo... | Intermediate values take on the value associated with the next lower x-coordinate (also called a step-wise function). The last two points of a discrete graphical function must have the same y value.
Out-of-range values are the same as the closest endpoint (i.e, no extrapolation is performed). | Below is the the instruction that describes the task:
### Input:
Intermediate values take on the value associated with the next lower x-coordinate (also called a step-wise function). The last two points of a discrete graphical function must have the same y value.
Out-of-range values are the same as the closest ... |
def _depth_first_search(set_tasks, current_task, visited):
"""
This dfs checks why tasks are still pending.
"""
visited.add(current_task)
if current_task in set_tasks["still_pending_not_ext"]:
upstream_failure = False
upstream_missing_dependency = False
upstream_run_by_other_... | This dfs checks why tasks are still pending. | Below is the the instruction that describes the task:
### Input:
This dfs checks why tasks are still pending.
### Response:
def _depth_first_search(set_tasks, current_task, visited):
"""
This dfs checks why tasks are still pending.
"""
visited.add(current_task)
if current_task in set_tasks["sti... |
def request_response(self):
"""Verify that a card is still present and get its operating mode.
The Request Response command returns the current operating
state of the card. The operating state changes with the
authentication process, a card is in Mode 0 after power-up or
a Polli... | Verify that a card is still present and get its operating mode.
The Request Response command returns the current operating
state of the card. The operating state changes with the
authentication process, a card is in Mode 0 after power-up or
a Polling command, transitions to Mode 1 with ... | Below is the the instruction that describes the task:
### Input:
Verify that a card is still present and get its operating mode.
The Request Response command returns the current operating
state of the card. The operating state changes with the
authentication process, a card is in Mode 0 aft... |
def _compute_term_3(self, C, mag, R):
"""
(a12 + a13.*M + a14.*M.*M + a15.*M.*M.*M).*(d(r).^2)
"""
return (
(C['a12'] + C['a13'] * mag + C['a14'] * np.power(mag, 2) +
C['a15'] * np.power(mag, 3)) * np.power(R, 2)
) | (a12 + a13.*M + a14.*M.*M + a15.*M.*M.*M).*(d(r).^2) | Below is the the instruction that describes the task:
### Input:
(a12 + a13.*M + a14.*M.*M + a15.*M.*M.*M).*(d(r).^2)
### Response:
def _compute_term_3(self, C, mag, R):
"""
(a12 + a13.*M + a14.*M.*M + a15.*M.*M.*M).*(d(r).^2)
"""
return (
(C['a12'] + C['a13'] * mag + C[... |
def size(f, unit='B', fileStore=None):
"""
Returns the size of a file in bytes.
:param f: Filename
:param unit: Return the byte size in these units (gigabytes, etc.).
:return:
"""
divisor = return_bytes(unit)
fileID = process_infile(f, fileStore)[0]
return fileID.size / divisor | Returns the size of a file in bytes.
:param f: Filename
:param unit: Return the byte size in these units (gigabytes, etc.).
:return: | Below is the the instruction that describes the task:
### Input:
Returns the size of a file in bytes.
:param f: Filename
:param unit: Return the byte size in these units (gigabytes, etc.).
:return:
### Response:
def size(f, unit='B', fileStore=None):
"""
Returns the size of a file in bytes.
... |
def _add_right(self, d):
'''
Adds the provided domino to the right end of the board.
:param Domino d: domino to add
:return: None
:raises EndsMismatchException: if the values do not match
'''
if not self:
self._left = d.first
self._right =... | Adds the provided domino to the right end of the board.
:param Domino d: domino to add
:return: None
:raises EndsMismatchException: if the values do not match | Below is the the instruction that describes the task:
### Input:
Adds the provided domino to the right end of the board.
:param Domino d: domino to add
:return: None
:raises EndsMismatchException: if the values do not match
### Response:
def _add_right(self, d):
'''
Adds th... |
def add_edge(self, x, y, label=None):
"""Add an edge from distribution *x* to distribution *y* with the given
*label*.
:type x: :class:`distutils2.database.InstalledDistribution` or
:class:`distutils2.database.EggInfoDistribution`
:type y: :class:`distutils2.database.In... | Add an edge from distribution *x* to distribution *y* with the given
*label*.
:type x: :class:`distutils2.database.InstalledDistribution` or
:class:`distutils2.database.EggInfoDistribution`
:type y: :class:`distutils2.database.InstalledDistribution` or
:class:`... | Below is the the instruction that describes the task:
### Input:
Add an edge from distribution *x* to distribution *y* with the given
*label*.
:type x: :class:`distutils2.database.InstalledDistribution` or
:class:`distutils2.database.EggInfoDistribution`
:type y: :class:`di... |
def _join_i8_wrapper(joinf, dtype, with_indexers=True):
"""
Create the join wrapper methods.
"""
from pandas.core.arrays.datetimelike import DatetimeLikeArrayMixin
@staticmethod
def wrapper(left, right):
if isinstance(left, (np.ndarray, ABCIndex, ABCSeries,
... | Create the join wrapper methods. | Below is the the instruction that describes the task:
### Input:
Create the join wrapper methods.
### Response:
def _join_i8_wrapper(joinf, dtype, with_indexers=True):
"""
Create the join wrapper methods.
"""
from pandas.core.arrays.datetimelike import DatetimeLikeArrayMixin
... |
def _add_qasm_reset(self, qubit):
"""Apply a reset instruction to a qubit.
Args:
qubit (int): the qubit being rest
This is done by doing a simulating a measurement
outcome and projecting onto the outcome state while
renormalizing.
"""
# get measure o... | Apply a reset instruction to a qubit.
Args:
qubit (int): the qubit being rest
This is done by doing a simulating a measurement
outcome and projecting onto the outcome state while
renormalizing. | Below is the the instruction that describes the task:
### Input:
Apply a reset instruction to a qubit.
Args:
qubit (int): the qubit being rest
This is done by doing a simulating a measurement
outcome and projecting onto the outcome state while
renormalizing.
### Respons... |
def update_progress(opts, progress, progress_iter, out):
'''
Update the progress iterator for the given outputter
'''
# Look up the outputter
try:
progress_outputter = salt.loader.outputters(opts)[out]
except KeyError: # Outputter is not loaded
log.warning('Progress outputter no... | Update the progress iterator for the given outputter | Below is the the instruction that describes the task:
### Input:
Update the progress iterator for the given outputter
### Response:
def update_progress(opts, progress, progress_iter, out):
'''
Update the progress iterator for the given outputter
'''
# Look up the outputter
try:
progress... |
def __insert_cluster(self, cluster):
"""!
@brief Insert cluster to the list (sorted queue) in line with sequence order (distance).
@param[in] cluster (cure_cluster): Cluster that should be inserted.
"""
for index in range(len(self.__queue)):
... | !
@brief Insert cluster to the list (sorted queue) in line with sequence order (distance).
@param[in] cluster (cure_cluster): Cluster that should be inserted. | Below is the the instruction that describes the task:
### Input:
!
@brief Insert cluster to the list (sorted queue) in line with sequence order (distance).
@param[in] cluster (cure_cluster): Cluster that should be inserted.
### Response:
def __insert_cluster(self, cluster):
"""... |
def get_second_pass_opts_peakrms(self):
"""
Set the adjustment gain based on chosen option and mean/max volume,
return the matching ffmpeg volume filter.
"""
normalization_type = self.media_file.ffmpeg_normalize.normalization_type
target_level = self.media_file.ffmpeg_nor... | Set the adjustment gain based on chosen option and mean/max volume,
return the matching ffmpeg volume filter. | Below is the the instruction that describes the task:
### Input:
Set the adjustment gain based on chosen option and mean/max volume,
return the matching ffmpeg volume filter.
### Response:
def get_second_pass_opts_peakrms(self):
"""
Set the adjustment gain based on chosen option and mean/ma... |
def parse_esmtp_extensions(message: str) -> Tuple[Dict[str, str], List[str]]:
"""
Parse an EHLO response from the server into a dict of {extension: params}
and a list of auth method names.
It might look something like:
220 size.does.matter.af.MIL (More ESMTP than Crappysoft!)
EHLO he... | Parse an EHLO response from the server into a dict of {extension: params}
and a list of auth method names.
It might look something like:
220 size.does.matter.af.MIL (More ESMTP than Crappysoft!)
EHLO heaven.af.mil
250-size.does.matter.af.MIL offers FIFTEEN extensions:
250-8... | Below is the the instruction that describes the task:
### Input:
Parse an EHLO response from the server into a dict of {extension: params}
and a list of auth method names.
It might look something like:
220 size.does.matter.af.MIL (More ESMTP than Crappysoft!)
EHLO heaven.af.mil
... |
def runcode(self, code):
"""
Override L{code.InteractiveConsole.runcode} to run the code in a
transaction unless the local C{autocommit} is currently set to a true
value.
"""
if not self.locals.get('autocommit', None):
return self.locals['db'].transact(code.In... | Override L{code.InteractiveConsole.runcode} to run the code in a
transaction unless the local C{autocommit} is currently set to a true
value. | Below is the the instruction that describes the task:
### Input:
Override L{code.InteractiveConsole.runcode} to run the code in a
transaction unless the local C{autocommit} is currently set to a true
value.
### Response:
def runcode(self, code):
"""
Override L{code.InteractiveConsol... |
def prepare_model(module: Union[types.ModuleType, str],
timestep: PeriodABC.ConstrArg = None):
"""Prepare and return the model of the given module.
In usual HydPy projects, each hydrological model instance is prepared
in an individual control file. This allows for "polluting" the
nam... | Prepare and return the model of the given module.
In usual HydPy projects, each hydrological model instance is prepared
in an individual control file. This allows for "polluting" the
namespace with different model attributes. There is no danger of
name conflicts, as long as no other (wildcard) import... | Below is the the instruction that describes the task:
### Input:
Prepare and return the model of the given module.
In usual HydPy projects, each hydrological model instance is prepared
in an individual control file. This allows for "polluting" the
namespace with different model attributes. There is n... |
def _CollapseStrings(elided):
"""Collapses strings and chars on a line to simple "" or '' blocks.
We nix strings first so we're not fooled by text like '"http://"'
Args:
elided: The line being processed.
Returns:
The line with collapsed strings.
"""
if _RE_PATTERN_INCLUDE.match(el... | Collapses strings and chars on a line to simple "" or '' blocks.
We nix strings first so we're not fooled by text like '"http://"'
Args:
elided: The line being processed.
Returns:
The line with collapsed strings. | Below is the the instruction that describes the task:
### Input:
Collapses strings and chars on a line to simple "" or '' blocks.
We nix strings first so we're not fooled by text like '"http://"'
Args:
elided: The line being processed.
Returns:
The line with collapsed strings.
### Respons... |
def matches_ordering(self, other):
"""
Compares the magnetic orderings of one structure with another.
:param other: Structure
:return (bool):
"""
a = CollinearMagneticStructureAnalyzer(
self.structure, overwrite_magmom_mode="normalize"
).get_structure... | Compares the magnetic orderings of one structure with another.
:param other: Structure
:return (bool): | Below is the the instruction that describes the task:
### Input:
Compares the magnetic orderings of one structure with another.
:param other: Structure
:return (bool):
### Response:
def matches_ordering(self, other):
"""
Compares the magnetic orderings of one structure with another.... |
def _get_pltdotstrs(self, hdrgos_usr, **kws):
"""Plot GO DAGs for each group found under a specfied header GO."""
import datetime
import timeit
dotstrs_all = []
tic = timeit.default_timer()
# Loop through GO groups. Each group of GOs is formed under a single "header GO"
... | Plot GO DAGs for each group found under a specfied header GO. | Below is the the instruction that describes the task:
### Input:
Plot GO DAGs for each group found under a specfied header GO.
### Response:
def _get_pltdotstrs(self, hdrgos_usr, **kws):
"""Plot GO DAGs for each group found under a specfied header GO."""
import datetime
import timeit
... |
def package_finder(argv):
"""Return a PackageFinder respecting command-line options.
:arg argv: Everything after the subcommand
"""
# We instantiate an InstallCommand and then use some of its private
# machinery--its arg parser--for our own purposes, like a virus. This
# approach is portable a... | Return a PackageFinder respecting command-line options.
:arg argv: Everything after the subcommand | Below is the the instruction that describes the task:
### Input:
Return a PackageFinder respecting command-line options.
:arg argv: Everything after the subcommand
### Response:
def package_finder(argv):
"""Return a PackageFinder respecting command-line options.
:arg argv: Everything after the subcom... |
def _get_format_from_document(self, token, document):
""" Returns a QTextCharFormat for token by
"""
code, html = self._formatter._format_lines([(token, u'dummy')]).next()
self._document.setHtml(html)
return QtGui.QTextCursor(self._document).charFormat() | Returns a QTextCharFormat for token by | Below is the the instruction that describes the task:
### Input:
Returns a QTextCharFormat for token by
### Response:
def _get_format_from_document(self, token, document):
""" Returns a QTextCharFormat for token by
"""
code, html = self._formatter._format_lines([(token, u'dummy')]).next()
... |
def _read_configfile(self):
"""Read the config file and store it (when valid)"""
rc = self.config_filename
if not os.path.isabs(rc):
rc = os.path.join(os.path.expanduser('~'), self.config_filename)
# If there is a setup.cfg in the package, parse it
files = [f for f in... | Read the config file and store it (when valid) | Below is the the instruction that describes the task:
### Input:
Read the config file and store it (when valid)
### Response:
def _read_configfile(self):
"""Read the config file and store it (when valid)"""
rc = self.config_filename
if not os.path.isabs(rc):
rc = os.path.join(os... |
def group_systems(self, group_name, systems):
"""
Adds an array of systems to specified group
Args:
group_name: Display name of group
systems: Array of {'machine_id': machine_id}
"""
api_group_id = None
headers = {'Content-Type': 'application/json... | Adds an array of systems to specified group
Args:
group_name: Display name of group
systems: Array of {'machine_id': machine_id} | Below is the the instruction that describes the task:
### Input:
Adds an array of systems to specified group
Args:
group_name: Display name of group
systems: Array of {'machine_id': machine_id}
### Response:
def group_systems(self, group_name, systems):
"""
Adds an ... |
def set_select(self, selector, updates):
''' Update objects that match a given selector with the specified
attribute/value updates.
Args:
selector (JSON-like) :
updates (dict) :
Returns:
None
'''
for obj in self.select(selector):
... | Update objects that match a given selector with the specified
attribute/value updates.
Args:
selector (JSON-like) :
updates (dict) :
Returns:
None | Below is the the instruction that describes the task:
### Input:
Update objects that match a given selector with the specified
attribute/value updates.
Args:
selector (JSON-like) :
updates (dict) :
Returns:
None
### Response:
def set_select(self, select... |
def node_version():
"""Get node version."""
version = check_output(('node', '--version'))
return tuple(int(x) for x in version.strip()[1:].split(b'.')) | Get node version. | Below is the the instruction that describes the task:
### Input:
Get node version.
### Response:
def node_version():
"""Get node version."""
version = check_output(('node', '--version'))
return tuple(int(x) for x in version.strip()[1:].split(b'.')) |
def _match_datetime_pattern(self, tokens):
"""
Match the datetime pattern at the beginning of the token list.
There are several formats that this method needs to understand
and distinguish between (see MongoDB's SERVER-7965):
ctime-pre2.4 Wed Dec 31 19:00:00
ctime ... | Match the datetime pattern at the beginning of the token list.
There are several formats that this method needs to understand
and distinguish between (see MongoDB's SERVER-7965):
ctime-pre2.4 Wed Dec 31 19:00:00
ctime Wed Dec 31 19:00:00.000
iso8601-utc 1970-01... | Below is the the instruction that describes the task:
### Input:
Match the datetime pattern at the beginning of the token list.
There are several formats that this method needs to understand
and distinguish between (see MongoDB's SERVER-7965):
ctime-pre2.4 Wed Dec 31 19:00:00
ct... |
def addReadGroupSet(self):
"""
Adds a new ReadGroupSet into this repo.
"""
self._openRepo()
dataset = self._repo.getDatasetByName(self._args.datasetName)
dataUrl = self._args.dataFile
indexFile = self._args.indexFile
parsed = urlparse.urlparse(dataUrl)
... | Adds a new ReadGroupSet into this repo. | Below is the the instruction that describes the task:
### Input:
Adds a new ReadGroupSet into this repo.
### Response:
def addReadGroupSet(self):
"""
Adds a new ReadGroupSet into this repo.
"""
self._openRepo()
dataset = self._repo.getDatasetByName(self._args.datasetName)
... |
def execute(self, sql, *args, **kwargs):
"""Executes an SQL INSERT/UPDATE/DELETE query with the given parameters and returns the number of affected rows.
:param sql: statement to execute
:param args: parameters iterable
:param kwargs: parameters iterable
:return: number of affec... | Executes an SQL INSERT/UPDATE/DELETE query with the given parameters and returns the number of affected rows.
:param sql: statement to execute
:param args: parameters iterable
:param kwargs: parameters iterable
:return: number of affected rows
:rtype: int | Below is the the instruction that describes the task:
### Input:
Executes an SQL INSERT/UPDATE/DELETE query with the given parameters and returns the number of affected rows.
:param sql: statement to execute
:param args: parameters iterable
:param kwargs: parameters iterable
:return... |
def check_condition(condition, defined_variables):
""" Checks a single rule condition - the condition will be made up of
variables, values, and the comparison operator. The defined_variables
object must have a variable defined for any variables in this condition.
"""
name, op, value = condition['nam... | Checks a single rule condition - the condition will be made up of
variables, values, and the comparison operator. The defined_variables
object must have a variable defined for any variables in this condition. | Below is the the instruction that describes the task:
### Input:
Checks a single rule condition - the condition will be made up of
variables, values, and the comparison operator. The defined_variables
object must have a variable defined for any variables in this condition.
### Response:
def check_condition... |
def parse_args():
"""
Parse the command line arguments
"""
parser = argparse.ArgumentParser(description = "Generate secrets for YubiKeys using YubiHSM",
add_help=True,
formatter_class = argparse.ArgumentDefaultsHelpFormatter,
... | Parse the command line arguments | Below is the the instruction that describes the task:
### Input:
Parse the command line arguments
### Response:
def parse_args():
"""
Parse the command line arguments
"""
parser = argparse.ArgumentParser(description = "Generate secrets for YubiKeys using YubiHSM",
... |
def _format_syslog_config(cmd_ret):
'''
Helper function to format the stdout from the get_syslog_config function.
cmd_ret
The return dictionary that comes from a cmd.run_all call.
'''
ret_dict = {'success': cmd_ret['retcode'] == 0}
if cmd_ret['retcode'] != 0:
ret_dict['message'... | Helper function to format the stdout from the get_syslog_config function.
cmd_ret
The return dictionary that comes from a cmd.run_all call. | Below is the the instruction that describes the task:
### Input:
Helper function to format the stdout from the get_syslog_config function.
cmd_ret
The return dictionary that comes from a cmd.run_all call.
### Response:
def _format_syslog_config(cmd_ret):
'''
Helper function to format the stdou... |
def create_mv_rule(tensorprod_rule, dim):
"""Convert tensor product rule into a multivariate quadrature generator."""
def mv_rule(order, sparse=False, part=None):
"""
Multidimensional integration rule.
Args:
order (int, numpy.ndarray) : order of integration rule. If numpy.nd... | Convert tensor product rule into a multivariate quadrature generator. | Below is the the instruction that describes the task:
### Input:
Convert tensor product rule into a multivariate quadrature generator.
### Response:
def create_mv_rule(tensorprod_rule, dim):
"""Convert tensor product rule into a multivariate quadrature generator."""
def mv_rule(order, sparse=False, part=No... |
def draw_patch(data, obj):
"""Return the PGFPlots code for patches.
"""
# Gather the draw options.
data, draw_options = mypath.get_draw_options(
data,
obj,
obj.get_edgecolor(),
obj.get_facecolor(),
obj.get_linestyle(),
obj.get_linewidth(),
)
if is... | Return the PGFPlots code for patches. | Below is the the instruction that describes the task:
### Input:
Return the PGFPlots code for patches.
### Response:
def draw_patch(data, obj):
"""Return the PGFPlots code for patches.
"""
# Gather the draw options.
data, draw_options = mypath.get_draw_options(
data,
obj,
ob... |
def append(self, value, new_name=False):
"""
Append a new array to the list
Parameters
----------
value: InteractiveBase
The data object to append to this list
%(ArrayList.rename.parameters.new_name)s
Raises
------
%(ArrayList.rename.... | Append a new array to the list
Parameters
----------
value: InteractiveBase
The data object to append to this list
%(ArrayList.rename.parameters.new_name)s
Raises
------
%(ArrayList.rename.raises)s
See Also
--------
list.appe... | Below is the the instruction that describes the task:
### Input:
Append a new array to the list
Parameters
----------
value: InteractiveBase
The data object to append to this list
%(ArrayList.rename.parameters.new_name)s
Raises
------
%(ArrayList... |
def set_created_date(self, date=None):
"""
Set the created date of a IOC to the current date.
User may specify the date they want to set as well.
:param date: Date value to set the created date to. This should be in the xsdDate form.
This defaults to the current date if it is ... | Set the created date of a IOC to the current date.
User may specify the date they want to set as well.
:param date: Date value to set the created date to. This should be in the xsdDate form.
This defaults to the current date if it is not provided.
xsdDate form: YYYY-MM-DDTHH:MM:SS
... | Below is the the instruction that describes the task:
### Input:
Set the created date of a IOC to the current date.
User may specify the date they want to set as well.
:param date: Date value to set the created date to. This should be in the xsdDate form.
This defaults to the current date... |
def reducing(reducer, init=UNSET):
"""Create a reducing transducer with the given reducer.
Args:
reducer: A two-argument function which will be used to combine the
partial cumulative result in the first argument with the next
item from the input stream in the second argument.
... | Create a reducing transducer with the given reducer.
Args:
reducer: A two-argument function which will be used to combine the
partial cumulative result in the first argument with the next
item from the input stream in the second argument.
Returns: A reducing transducer: A singl... | Below is the the instruction that describes the task:
### Input:
Create a reducing transducer with the given reducer.
Args:
reducer: A two-argument function which will be used to combine the
partial cumulative result in the first argument with the next
item from the input stream... |
def bb(self,*args,**kwargs):
"""
NAME:
bb
PURPOSE:
return Galactic latitude
INPUT:
t - (optional) time at which to get bb (can be Quantity)
obs=[X,Y,Z] - (optional) position of observer (in kpc; entries can be Quantity)
(defau... | NAME:
bb
PURPOSE:
return Galactic latitude
INPUT:
t - (optional) time at which to get bb (can be Quantity)
obs=[X,Y,Z] - (optional) position of observer (in kpc; entries can be Quantity)
(default=[8.0,0.,0.]) OR Orbit object that corresponds ... | Below is the the instruction that describes the task:
### Input:
NAME:
bb
PURPOSE:
return Galactic latitude
INPUT:
t - (optional) time at which to get bb (can be Quantity)
obs=[X,Y,Z] - (optional) position of observer (in kpc; entries can be Quantity... |
def from_jsonld(cls, data, __reference__=None, __source__=None):
"""Instantiate a JSON-LD class from data."""
if isinstance(data, cls):
return data
if not isinstance(data, dict):
raise ValueError(data)
if '@type' in data:
type_ = tuple(sorted(data['@... | Instantiate a JSON-LD class from data. | Below is the the instruction that describes the task:
### Input:
Instantiate a JSON-LD class from data.
### Response:
def from_jsonld(cls, data, __reference__=None, __source__=None):
"""Instantiate a JSON-LD class from data."""
if isinstance(data, cls):
return data
if not isins... |
def patch(patch_inspect=True):
"""
Main entry point for patching the ``collections.abc`` and ``inspect``
standard library modules.
"""
PATCHED['collections.abc.Generator'] = _collections_abc.Generator = Generator
PATCHED['collections.abc.Coroutine'] = _collections_abc.Coroutine = Coroutine
P... | Main entry point for patching the ``collections.abc`` and ``inspect``
standard library modules. | Below is the the instruction that describes the task:
### Input:
Main entry point for patching the ``collections.abc`` and ``inspect``
standard library modules.
### Response:
def patch(patch_inspect=True):
"""
Main entry point for patching the ``collections.abc`` and ``inspect``
standard library mo... |
def onca(word, max_length=4, zero_pad=True):
"""Return the Oxford Name Compression Algorithm (ONCA) code for a word.
This is a wrapper for :py:meth:`ONCA.encode`.
Parameters
----------
word : str
The word to transform
max_length : int
The maximum length (default 5) of the code ... | Return the Oxford Name Compression Algorithm (ONCA) code for a word.
This is a wrapper for :py:meth:`ONCA.encode`.
Parameters
----------
word : str
The word to transform
max_length : int
The maximum length (default 5) of the code to return
zero_pad : bool
Pad the end of... | Below is the the instruction that describes the task:
### Input:
Return the Oxford Name Compression Algorithm (ONCA) code for a word.
This is a wrapper for :py:meth:`ONCA.encode`.
Parameters
----------
word : str
The word to transform
max_length : int
The maximum length (defaul... |
def table_groupbyagg(table_name):
"""
Perform a groupby on a table and return an aggregation on a single column.
This depends on some request parameters in the URL.
"column" and "agg" must always be present, and one of "by" or "level"
must be present. "column" is the table column on which aggregati... | Perform a groupby on a table and return an aggregation on a single column.
This depends on some request parameters in the URL.
"column" and "agg" must always be present, and one of "by" or "level"
must be present. "column" is the table column on which aggregation will
be performed, "agg" is the aggrega... | Below is the the instruction that describes the task:
### Input:
Perform a groupby on a table and return an aggregation on a single column.
This depends on some request parameters in the URL.
"column" and "agg" must always be present, and one of "by" or "level"
must be present. "column" is the table co... |
def _clean_kwargs(self, kwargs, fn):
'''
Remove unexpected keyword arguments from the
set of received keyword arguments.
'''
# Do not do the cleaning if server config
# doesnt ask to ignore
if not self.server.IGNORE_UNEXPECTED_KWARGS:
return kwargs
... | Remove unexpected keyword arguments from the
set of received keyword arguments. | Below is the the instruction that describes the task:
### Input:
Remove unexpected keyword arguments from the
set of received keyword arguments.
### Response:
def _clean_kwargs(self, kwargs, fn):
'''
Remove unexpected keyword arguments from the
set of received keyword arguments.
... |
def fit(self, X, y=None):
"""Compute the probabilistic Shared Response Model
Parameters
----------
X : list of 2D arrays, element i has shape=[voxels_i, samples]
Each element in the list contains the fMRI data of one subject.
y : not used
"""
logger... | Compute the probabilistic Shared Response Model
Parameters
----------
X : list of 2D arrays, element i has shape=[voxels_i, samples]
Each element in the list contains the fMRI data of one subject.
y : not used | Below is the the instruction that describes the task:
### Input:
Compute the probabilistic Shared Response Model
Parameters
----------
X : list of 2D arrays, element i has shape=[voxels_i, samples]
Each element in the list contains the fMRI data of one subject.
y : not... |
def VcardFieldsEqual(field1, field2):
"""Handle comparing vCard fields where inputs are lists of components.
Handle parameters? Are any used aside from 'TYPE'?
Note: force cast to string to compare sub-objects like Name and Address
"""
field1_vals = set([ str(f.value) for f in field1 ])
field2... | Handle comparing vCard fields where inputs are lists of components.
Handle parameters? Are any used aside from 'TYPE'?
Note: force cast to string to compare sub-objects like Name and Address | Below is the the instruction that describes the task:
### Input:
Handle comparing vCard fields where inputs are lists of components.
Handle parameters? Are any used aside from 'TYPE'?
Note: force cast to string to compare sub-objects like Name and Address
### Response:
def VcardFieldsEqual(field1, field2... |
def from_tokens(cls, path:PathOrStr, trn_tok:Collection[Collection[str]], trn_lbls:Collection[Union[int,float]],
val_tok:Collection[Collection[str]], val_lbls:Collection[Union[int,float]], vocab:Vocab=None,
tst_tok:Collection[Collection[str]]=None, classes:Collection[Any]=None, max_voc... | Create a `TextDataBunch` from tokens and labels. `kwargs` are passed to the dataloader creation. | Below is the the instruction that describes the task:
### Input:
Create a `TextDataBunch` from tokens and labels. `kwargs` are passed to the dataloader creation.
### Response:
def from_tokens(cls, path:PathOrStr, trn_tok:Collection[Collection[str]], trn_lbls:Collection[Union[int,float]],
val_tok:C... |
def _do(name, fun, path=None):
'''
Invoke a function in the lxc module with no args
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
'''
host = find_guest(name, quiet=True, path=path)
if not host:
return False
... | Invoke a function in the lxc module with no args
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0 | Below is the the instruction that describes the task:
### Input:
Invoke a function in the lxc module with no args
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
### Response:
def _do(name, fun, path=None):
'''
Invoke a funct... |
def start(self, value: typing.Union[float, typing.Tuple[float, float]]) -> None:
"""Set the end property in relative coordinates.
End may be a float when graphic is an Interval or a tuple (y, x) when graphic is a Line."""
... | Set the end property in relative coordinates.
End may be a float when graphic is an Interval or a tuple (y, x) when graphic is a Line. | Below is the the instruction that describes the task:
### Input:
Set the end property in relative coordinates.
End may be a float when graphic is an Interval or a tuple (y, x) when graphic is a Line.
### Response:
def start(self, value: typing.Union[float, typing.Tuple[float, float]]) -> None:
"""... |
def effective_bounds(self):
"""
Effective process bounds required to initialize inputs.
Process bounds sometimes have to be larger, because all intersecting process
tiles have to be covered as well.
"""
return snap_bounds(
bounds=clip_bounds(bounds=self.init_... | Effective process bounds required to initialize inputs.
Process bounds sometimes have to be larger, because all intersecting process
tiles have to be covered as well. | Below is the the instruction that describes the task:
### Input:
Effective process bounds required to initialize inputs.
Process bounds sometimes have to be larger, because all intersecting process
tiles have to be covered as well.
### Response:
def effective_bounds(self):
"""
Effe... |
def _swap(self, class1, class2, a):
"""evaluate cost of moving a from class1 to class2"""
ss1 = self._ss(class1)
ss2 = self._ss(class2)
tss1 = ss1 + ss2
class1c = copy.copy(class1)
class2c = copy.copy(class2)
class1c.remove(a)
class2c.append(a)
ss1... | evaluate cost of moving a from class1 to class2 | Below is the the instruction that describes the task:
### Input:
evaluate cost of moving a from class1 to class2
### Response:
def _swap(self, class1, class2, a):
"""evaluate cost of moving a from class1 to class2"""
ss1 = self._ss(class1)
ss2 = self._ss(class2)
tss1 = ss1 + ss2
... |
def fromPy(cls, val, typeObj, vldMask=None):
"""
:param val: value of python type int or None
:param typeObj: instance of Integer
:param vldMask: None vldMask is resolved from val,
if is 0 value is invalidated
if is 1 value has to be valid
"""
asse... | :param val: value of python type int or None
:param typeObj: instance of Integer
:param vldMask: None vldMask is resolved from val,
if is 0 value is invalidated
if is 1 value has to be valid | Below is the the instruction that describes the task:
### Input:
:param val: value of python type int or None
:param typeObj: instance of Integer
:param vldMask: None vldMask is resolved from val,
if is 0 value is invalidated
if is 1 value has to be valid
### Response:
def f... |
def exchange_code(self, code, redirect_uri):
"""
Exchanges code for token/s
"""
token = requests.post(GOOGLE_OAUTH2_TOKEN_URL, data=dict(
code=code,
redirect_uri=redirect_uri,
grant_type='authorization_code',
client_id=self.client_id,
... | Exchanges code for token/s | Below is the the instruction that describes the task:
### Input:
Exchanges code for token/s
### Response:
def exchange_code(self, code, redirect_uri):
"""
Exchanges code for token/s
"""
token = requests.post(GOOGLE_OAUTH2_TOKEN_URL, data=dict(
code=code,
red... |
def _get_conn(socket=DEFAULT_SOCKET_URL):
'''
Get connection to haproxy socket.
'''
assert os.path.exists(socket), '{0} does not exist.'.format(socket)
issock = os.stat(socket).st_mode
assert stat.S_ISSOCK(issock), '{0} is not a socket.'.format(socket)
ha_conn = haproxy.conn.HaPConn(socket)
... | Get connection to haproxy socket. | Below is the the instruction that describes the task:
### Input:
Get connection to haproxy socket.
### Response:
def _get_conn(socket=DEFAULT_SOCKET_URL):
'''
Get connection to haproxy socket.
'''
assert os.path.exists(socket), '{0} does not exist.'.format(socket)
issock = os.stat(socket).st_mo... |
def _setup_config_from_kwargs(kwargs):
"""Setup config commands for conda."""
cmd_list = ['--json', '--force']
if 'file' in kwargs:
cmd_list.extend(['--file', kwargs['file']])
if 'system' in kwargs:
cmd_list.append('--system')
return cmd_list | Setup config commands for conda. | Below is the the instruction that describes the task:
### Input:
Setup config commands for conda.
### Response:
def _setup_config_from_kwargs(kwargs):
"""Setup config commands for conda."""
cmd_list = ['--json', '--force']
if 'file' in kwargs:
cmd_list.extend(['--file', kwargs[... |
def _get_reparse_data(path):
'''
Retrieves the reparse point data structure for the given path.
If the path is not a reparse point, None is returned.
See http://msdn.microsoft.com/en-us/library/ff552012.aspx for details on the
REPARSE_DATA_BUFFER structure returned.
'''
# ensure paths are ... | Retrieves the reparse point data structure for the given path.
If the path is not a reparse point, None is returned.
See http://msdn.microsoft.com/en-us/library/ff552012.aspx for details on the
REPARSE_DATA_BUFFER structure returned. | Below is the the instruction that describes the task:
### Input:
Retrieves the reparse point data structure for the given path.
If the path is not a reparse point, None is returned.
See http://msdn.microsoft.com/en-us/library/ff552012.aspx for details on the
REPARSE_DATA_BUFFER structure returned.
###... |
def get_file_privilege(self, source):
'''Get privileges of a local file'''
try:
return str(oct(os.stat(source).st_mode)[-3:])
except Exception as e:
raise Failure('Could not get stat for %s, error_message = %s', source, e) | Get privileges of a local file | Below is the the instruction that describes the task:
### Input:
Get privileges of a local file
### Response:
def get_file_privilege(self, source):
'''Get privileges of a local file'''
try:
return str(oct(os.stat(source).st_mode)[-3:])
except Exception as e:
raise Failure('Could not get sta... |
def build_msg_fmtstr2(lbl, length, invert_rate, backspace):
r"""
Args:
lbl (str):
invert_rate (bool):
backspace (bool):
Returns:
str: msg_fmtstr_time
CommandLine:
python -m utool.util_progress --exec-ProgressIter.build_msg_fmt... | r"""
Args:
lbl (str):
invert_rate (bool):
backspace (bool):
Returns:
str: msg_fmtstr_time
CommandLine:
python -m utool.util_progress --exec-ProgressIter.build_msg_fmtstr2
Setup:
>>> from utool.util_progress import... | Below is the the instruction that describes the task:
### Input:
r"""
Args:
lbl (str):
invert_rate (bool):
backspace (bool):
Returns:
str: msg_fmtstr_time
CommandLine:
python -m utool.util_progress --exec-ProgressIter.build_msg_fm... |
def create_shared(self, name, ref):
""" For the app backends to create the GLShared object.
Parameters
----------
name : str
The name.
ref : object
The reference.
"""
if self._shared is not None:
raise RuntimeError('Can only se... | For the app backends to create the GLShared object.
Parameters
----------
name : str
The name.
ref : object
The reference. | Below is the the instruction that describes the task:
### Input:
For the app backends to create the GLShared object.
Parameters
----------
name : str
The name.
ref : object
The reference.
### Response:
def create_shared(self, name, ref):
""" For the ... |
def generate_url(self, bucket=None, asset_key=None, asset_url=None, operations=['identity'], secure=True):
"""
Given an S3 key and bucket/URL, perform given image operations on an image and return the URL.
"""
if len(operations) < 1:
raise OperationError('You didn\'t provide ... | Given an S3 key and bucket/URL, perform given image operations on an image and return the URL. | Below is the the instruction that describes the task:
### Input:
Given an S3 key and bucket/URL, perform given image operations on an image and return the URL.
### Response:
def generate_url(self, bucket=None, asset_key=None, asset_url=None, operations=['identity'], secure=True):
"""
Given an S3 ke... |
def do_load(self, args: argparse.Namespace) -> None:
"""Run commands in script file that is encoded as either ASCII or UTF-8 text"""
expanded_path = os.path.abspath(os.path.expanduser(args.script_path))
# Make sure the path exists and we can access it
if not os.path.exists(expanded_path... | Run commands in script file that is encoded as either ASCII or UTF-8 text | Below is the the instruction that describes the task:
### Input:
Run commands in script file that is encoded as either ASCII or UTF-8 text
### Response:
def do_load(self, args: argparse.Namespace) -> None:
"""Run commands in script file that is encoded as either ASCII or UTF-8 text"""
expanded_path... |
def to_before_bank(self):
"""
Change the current :class:`Bank` for the before bank. If the current
bank is the first, the current bank is will be the last bank.
The current pedalboard will be the first pedalboard of the new current bank
**if it contains any pedalboard**, else wi... | Change the current :class:`Bank` for the before bank. If the current
bank is the first, the current bank is will be the last bank.
The current pedalboard will be the first pedalboard of the new current bank
**if it contains any pedalboard**, else will be ``None``.
.. warning::
... | Below is the the instruction that describes the task:
### Input:
Change the current :class:`Bank` for the before bank. If the current
bank is the first, the current bank is will be the last bank.
The current pedalboard will be the first pedalboard of the new current bank
**if it contains an... |
def decorated(self, decorators, classfuncdef):
"""decorated: decorators (classdef | funcdef)"""
classfuncdef.at_locs = list(map(lambda x: x[0], decorators))
classfuncdef.decorator_list = list(map(lambda x: x[1], decorators))
classfuncdef.loc = classfuncdef.loc.join(decorators[0][0])
... | decorated: decorators (classdef | funcdef) | Below is the the instruction that describes the task:
### Input:
decorated: decorators (classdef | funcdef)
### Response:
def decorated(self, decorators, classfuncdef):
"""decorated: decorators (classdef | funcdef)"""
classfuncdef.at_locs = list(map(lambda x: x[0], decorators))
classfuncdef... |
def remove_rows_matching(df, column, match):
"""
Return a ``DataFrame`` with rows where `column` values match `match` are removed.
The selected `column` series of values from the supplied Pandas ``DataFrame`` is compared
to `match`, and those rows that match are removed from the DataFrame.
:param ... | Return a ``DataFrame`` with rows where `column` values match `match` are removed.
The selected `column` series of values from the supplied Pandas ``DataFrame`` is compared
to `match`, and those rows that match are removed from the DataFrame.
:param df: Pandas ``DataFrame``
:param column: Column indexe... | Below is the the instruction that describes the task:
### Input:
Return a ``DataFrame`` with rows where `column` values match `match` are removed.
The selected `column` series of values from the supplied Pandas ``DataFrame`` is compared
to `match`, and those rows that match are removed from the DataFrame.
... |
def get_field_names(self):
"""
Builds a list of the field names for all tables and joined tables by calling
``get_field_names()`` on each table
:return: list of field names
:rtype: list of str
"""
field_names = []
for table in self.tables:
fie... | Builds a list of the field names for all tables and joined tables by calling
``get_field_names()`` on each table
:return: list of field names
:rtype: list of str | Below is the the instruction that describes the task:
### Input:
Builds a list of the field names for all tables and joined tables by calling
``get_field_names()`` on each table
:return: list of field names
:rtype: list of str
### Response:
def get_field_names(self):
"""
Bu... |
def login(credentials=None, app_name=None, services=None, client_id=None, make_clients=True,
clear_old_tokens=False, token_dir=DEFAULT_CRED_PATH, **kwargs):
"""Log in to Globus services
Arguments:
credentials (str or dict): A string filename, string JSON, or dictionary
with cr... | Log in to Globus services
Arguments:
credentials (str or dict): A string filename, string JSON, or dictionary
with credential and config information.
By default, looks in ``~/mdf/credentials/globus_login.json``.
Contains ``app_name``, ``services``, and ``clie... | Below is the the instruction that describes the task:
### Input:
Log in to Globus services
Arguments:
credentials (str or dict): A string filename, string JSON, or dictionary
with credential and config information.
By default, looks in ``~/mdf/credentials/globus_login.js... |
def _eval_meta_as_summary(meta):
"""some crude heuristics for now
most are implemented on bot-side
with domain whitelists"""
if meta == '':
return False
if len(meta)>500:
return False
if 'login' in meta.lower():
return False
return True | some crude heuristics for now
most are implemented on bot-side
with domain whitelists | Below is the the instruction that describes the task:
### Input:
some crude heuristics for now
most are implemented on bot-side
with domain whitelists
### Response:
def _eval_meta_as_summary(meta):
"""some crude heuristics for now
most are implemented on bot-side
with domain whitelists"""
... |
def polygon_filter_add(self, filt):
"""Associate a Polygon Filter with this instance
Parameters
----------
filt: int or instance of `PolygonFilter`
The polygon filter to add
"""
if not isinstance(filt, (PolygonFilter, int, float)):
msg = "`filt` m... | Associate a Polygon Filter with this instance
Parameters
----------
filt: int or instance of `PolygonFilter`
The polygon filter to add | Below is the the instruction that describes the task:
### Input:
Associate a Polygon Filter with this instance
Parameters
----------
filt: int or instance of `PolygonFilter`
The polygon filter to add
### Response:
def polygon_filter_add(self, filt):
"""Associate a Polyg... |
def rename_directory(self, relativePath, newName, raiseError=True, ntrials=3):
"""
Rename a directory in the repository. It insures renaming the directory in the system.
:Parameters:
#. relativePath (string): The relative to the repository path of
the directory to be ... | Rename a directory in the repository. It insures renaming the directory in the system.
:Parameters:
#. relativePath (string): The relative to the repository path of
the directory to be renamed.
#. newName (string): The new directory name.
#. raiseError (boolea... | Below is the the instruction that describes the task:
### Input:
Rename a directory in the repository. It insures renaming the directory in the system.
:Parameters:
#. relativePath (string): The relative to the repository path of
the directory to be renamed.
#. newNam... |
def essential_precursors_not_in_biomass(model, reaction):
u"""
Return a list of essential precursors missing from the biomass reaction.
There are universal components of life that make up the biomass of all
known organisms. These include all proteinogenic amino acids, deoxy- and
ribonucleotides, wa... | u"""
Return a list of essential precursors missing from the biomass reaction.
There are universal components of life that make up the biomass of all
known organisms. These include all proteinogenic amino acids, deoxy- and
ribonucleotides, water and a range of metabolic cofactors.
Parameters
--... | Below is the the instruction that describes the task:
### Input:
u"""
Return a list of essential precursors missing from the biomass reaction.
There are universal components of life that make up the biomass of all
known organisms. These include all proteinogenic amino acids, deoxy- and
ribonucleoti... |
def read_length_adjust(self, analysistype):
"""
Trim the reads to the correct length using reformat.sh
:param analysistype: current analysis type. Will be either 'simulated' or 'sampled'
"""
logging.info('Trimming {at} reads'.format(at=analysistype))
for sample in self.me... | Trim the reads to the correct length using reformat.sh
:param analysistype: current analysis type. Will be either 'simulated' or 'sampled' | Below is the the instruction that describes the task:
### Input:
Trim the reads to the correct length using reformat.sh
:param analysistype: current analysis type. Will be either 'simulated' or 'sampled'
### Response:
def read_length_adjust(self, analysistype):
"""
Trim the reads to the cor... |
def build_input_partitions(cls, name='inputTablePartitions', input_name='input'):
"""
Build an input table partition parameter
:param name: parameter name
:type name: str
:param input_name: bind input port name
:param input_name: str
:return: input description
... | Build an input table partition parameter
:param name: parameter name
:type name: str
:param input_name: bind input port name
:param input_name: str
:return: input description
:rtype: ParamDef | Below is the the instruction that describes the task:
### Input:
Build an input table partition parameter
:param name: parameter name
:type name: str
:param input_name: bind input port name
:param input_name: str
:return: input description
:rtype: ParamDef
### Respon... |
def issued_at(self):
"""Time when access token was requested, as seconds since epoch.
Note:
Accessing this property when there wasn't any request attempts
will return current time.
Returns:
int
"""
issued_at = self._issued_at
if issue... | Time when access token was requested, as seconds since epoch.
Note:
Accessing this property when there wasn't any request attempts
will return current time.
Returns:
int | Below is the the instruction that describes the task:
### Input:
Time when access token was requested, as seconds since epoch.
Note:
Accessing this property when there wasn't any request attempts
will return current time.
Returns:
int
### Response:
def issued_a... |
def vb_machine_exists(name):
'''
Checks in with the hypervisor to see if the machine with the given name is known
@param name:
@type name:
@return:
@rtype:
'''
try:
vbox = vb_get_box()
vbox.findMachine(name)
return True
except Exception as e:
if isinst... | Checks in with the hypervisor to see if the machine with the given name is known
@param name:
@type name:
@return:
@rtype: | Below is the the instruction that describes the task:
### Input:
Checks in with the hypervisor to see if the machine with the given name is known
@param name:
@type name:
@return:
@rtype:
### Response:
def vb_machine_exists(name):
'''
Checks in with the hypervisor to see if the machine with... |
def save_monomial_index(filename, monomial_index):
"""Save a monomial dictionary for debugging purposes.
:param filename: The name of the file to save to.
:type filename: str.
:param monomial_index: The monomial index of the SDP relaxation.
:type monomial_index: dict of :class:`sympy.core.expr.Expr... | Save a monomial dictionary for debugging purposes.
:param filename: The name of the file to save to.
:type filename: str.
:param monomial_index: The monomial index of the SDP relaxation.
:type monomial_index: dict of :class:`sympy.core.expr.Expr`. | Below is the the instruction that describes the task:
### Input:
Save a monomial dictionary for debugging purposes.
:param filename: The name of the file to save to.
:type filename: str.
:param monomial_index: The monomial index of the SDP relaxation.
:type monomial_index: dict of :class:`sympy.cor... |
def _set_error_log(self, config, level, debug=False):
""" Configure error logs
"""
error_handler = self._get_param(
'global',
'log.error_handler',
config,
'syslog'
)
# log format for syslog
syslog_formatter = logging.Fo... | Configure error logs | Below is the the instruction that describes the task:
### Input:
Configure error logs
### Response:
def _set_error_log(self, config, level, debug=False):
""" Configure error logs
"""
error_handler = self._get_param(
'global',
'log.error_handler',
config,
... |
def list2dict(lst):
"""Takes a list of (key,value) pairs and turns it into a dict."""
dic = {}
for k,v in lst: dic[k] = v
return dic | Takes a list of (key,value) pairs and turns it into a dict. | Below is the the instruction that describes the task:
### Input:
Takes a list of (key,value) pairs and turns it into a dict.
### Response:
def list2dict(lst):
"""Takes a list of (key,value) pairs and turns it into a dict."""
dic = {}
for k,v in lst: dic[k] = v
return dic |
def aliased_slot_name(self, slot: SLOT_OR_SLOTNAME) -> str:
""" Return the overloaded slot name -- the alias if one exists otherwise the actual name
@param slot: either a slot name or a definition
@return: overloaded name
"""
if isinstance(slot, str):
slot = self.sch... | Return the overloaded slot name -- the alias if one exists otherwise the actual name
@param slot: either a slot name or a definition
@return: overloaded name | Below is the the instruction that describes the task:
### Input:
Return the overloaded slot name -- the alias if one exists otherwise the actual name
@param slot: either a slot name or a definition
@return: overloaded name
### Response:
def aliased_slot_name(self, slot: SLOT_OR_SLOTNAME) -> str:
... |
def infer(self, rows, headers=1, confidence=0.75):
"""https://github.com/frictionlessdata/tableschema-py#schema
"""
# Get headers
if isinstance(headers, int):
headers_row = headers
while True:
headers_row -= 1
headers = rows.pop(0)... | https://github.com/frictionlessdata/tableschema-py#schema | Below is the the instruction that describes the task:
### Input:
https://github.com/frictionlessdata/tableschema-py#schema
### Response:
def infer(self, rows, headers=1, confidence=0.75):
"""https://github.com/frictionlessdata/tableschema-py#schema
"""
# Get headers
if isinstance(h... |
def _parallel_downloader(voxforge_url, archive_dir, total, counter):
"""Generate a function to download a file based on given parameters
This works by currying the above given arguments into a closure
in the form of the following function.
:param voxforge_url: the base voxforge URL
:param archive_d... | Generate a function to download a file based on given parameters
This works by currying the above given arguments into a closure
in the form of the following function.
:param voxforge_url: the base voxforge URL
:param archive_dir: the location to store the downloaded file
:param total: the ... | Below is the the instruction that describes the task:
### Input:
Generate a function to download a file based on given parameters
This works by currying the above given arguments into a closure
in the form of the following function.
:param voxforge_url: the base voxforge URL
:param archive_dir: th... |
def extract_code_from_args(args):
"""
Extracts the access code from the arguments dictionary (given back
from github)
"""
if args is None:
raise_error("Couldn't extract GitHub authentication code "
"from response")
# TODO: Is there a case where the length of the erro... | Extracts the access code from the arguments dictionary (given back
from github) | Below is the the instruction that describes the task:
### Input:
Extracts the access code from the arguments dictionary (given back
from github)
### Response:
def extract_code_from_args(args):
"""
Extracts the access code from the arguments dictionary (given back
from github)
"""
if args is... |
def get_low_battery_warning_level(self):
"""
Returns warning according to GetSystemPowerStatus().BatteryLifeTime/BatteryLifePercent
@raise WindowsError if any underlying error occures.
"""
power_status = SYSTEM_POWER_STATUS()
if not GetSystemPowerStatus(pointer(power_sta... | Returns warning according to GetSystemPowerStatus().BatteryLifeTime/BatteryLifePercent
@raise WindowsError if any underlying error occures. | Below is the the instruction that describes the task:
### Input:
Returns warning according to GetSystemPowerStatus().BatteryLifeTime/BatteryLifePercent
@raise WindowsError if any underlying error occures.
### Response:
def get_low_battery_warning_level(self):
"""
Returns warning according ... |
def restore_renamed_serializable_attributes(self):
"""Hook for the future if attributes have been renamed. The old
attribute names will have been restored in the __dict__.update in
__setstate__, so this routine should move attribute values to their new
names.
"""
if hasat... | Hook for the future if attributes have been renamed. The old
attribute names will have been restored in the __dict__.update in
__setstate__, so this routine should move attribute values to their new
names. | Below is the the instruction that describes the task:
### Input:
Hook for the future if attributes have been renamed. The old
attribute names will have been restored in the __dict__.update in
__setstate__, so this routine should move attribute values to their new
names.
### Response:
def re... |
def create_branding(self, params):
"""
Create a new branding
@params: An array of params (all params are optional)
- layout: Default color for all application widgets (hex code)
- text: Default text color for all application widgets (hex code)
- application_te... | Create a new branding
@params: An array of params (all params are optional)
- layout: Default color for all application widgets (hex code)
- text: Default text color for all application widgets (hex code)
- application_texts: A dict with the new text values
- sign... | Below is the the instruction that describes the task:
### Input:
Create a new branding
@params: An array of params (all params are optional)
- layout: Default color for all application widgets (hex code)
- text: Default text color for all application widgets (hex code)
- ... |
def connect(self, params):
"""Connect to the specified AP."""
self._logger.info("iface '%s' connects to AP: '%s'",
self.name(), params.ssid)
self._wifi_ctrl.connect(self._raw_obj, params) | Connect to the specified AP. | Below is the the instruction that describes the task:
### Input:
Connect to the specified AP.
### Response:
def connect(self, params):
"""Connect to the specified AP."""
self._logger.info("iface '%s' connects to AP: '%s'",
self.name(), params.ssid)
self._wifi_ctr... |
def setMaxSpeed(self, edgeID, speed):
"""setMaxSpeed(string, double) -> None
Set a new maximum speed (in m/s) for all lanes of the edge.
"""
self._connection._sendDoubleCmd(
tc.CMD_SET_EDGE_VARIABLE, tc.VAR_MAXSPEED, edgeID, speed) | setMaxSpeed(string, double) -> None
Set a new maximum speed (in m/s) for all lanes of the edge. | Below is the the instruction that describes the task:
### Input:
setMaxSpeed(string, double) -> None
Set a new maximum speed (in m/s) for all lanes of the edge.
### Response:
def setMaxSpeed(self, edgeID, speed):
"""setMaxSpeed(string, double) -> None
Set a new maximum speed (in m/s) for ... |
def scatter(x,Ns,start):
"""
Sample a baseband digital communications waveform at the symbol spacing.
Parameters
----------
x : ndarray of the input digital comm signal
Ns : number of samples per symbol (bit)
start : the array index to start the sampling
Returns
-------
xI : nd... | Sample a baseband digital communications waveform at the symbol spacing.
Parameters
----------
x : ndarray of the input digital comm signal
Ns : number of samples per symbol (bit)
start : the array index to start the sampling
Returns
-------
xI : ndarray of the real part of x following... | Below is the the instruction that describes the task:
### Input:
Sample a baseband digital communications waveform at the symbol spacing.
Parameters
----------
x : ndarray of the input digital comm signal
Ns : number of samples per symbol (bit)
start : the array index to start the sampling
... |
def _collapseMsg(self, msg):
"""
Take msg, which is a dictionary of lists of output chunks, and
concatenate all the chunks into a single string
"""
retval = {}
for logname in msg:
data = u""
for m in msg[logname]:
m = bytes2unicode(... | Take msg, which is a dictionary of lists of output chunks, and
concatenate all the chunks into a single string | Below is the the instruction that describes the task:
### Input:
Take msg, which is a dictionary of lists of output chunks, and
concatenate all the chunks into a single string
### Response:
def _collapseMsg(self, msg):
"""
Take msg, which is a dictionary of lists of output chunks, and
... |
def update_preferences_by_category(self, category, communication_channel_id, notification_preferences_frequency):
"""
Update preferences by category.
Change the preferences for multiple notifications based on the category for a single communication channel
"""
path = {}
... | Update preferences by category.
Change the preferences for multiple notifications based on the category for a single communication channel | Below is the the instruction that describes the task:
### Input:
Update preferences by category.
Change the preferences for multiple notifications based on the category for a single communication channel
### Response:
def update_preferences_by_category(self, category, communication_channel_id, notificat... |
def forall(self, method):
"""
IT IS EXPECTED THE method ACCEPTS (value, coord, cube), WHERE
value - VALUE FOUND AT ELEMENT
coord - THE COORDINATES OF THE ELEMENT (PLEASE, READ ONLY)
cube - THE WHOLE CUBE, FOR USE IN WINDOW FUNCTIONS
"""
for c in self._all_combos()... | IT IS EXPECTED THE method ACCEPTS (value, coord, cube), WHERE
value - VALUE FOUND AT ELEMENT
coord - THE COORDINATES OF THE ELEMENT (PLEASE, READ ONLY)
cube - THE WHOLE CUBE, FOR USE IN WINDOW FUNCTIONS | Below is the the instruction that describes the task:
### Input:
IT IS EXPECTED THE method ACCEPTS (value, coord, cube), WHERE
value - VALUE FOUND AT ELEMENT
coord - THE COORDINATES OF THE ELEMENT (PLEASE, READ ONLY)
cube - THE WHOLE CUBE, FOR USE IN WINDOW FUNCTIONS
### Response:
def foral... |
def QA_indicator_WR(DataFrame, N, N1):
'威廉指标'
HIGH = DataFrame['high']
LOW = DataFrame['low']
CLOSE = DataFrame['close']
WR1 = 100 * (HHV(HIGH, N) - CLOSE) / (HHV(HIGH, N) - LLV(LOW, N))
WR2 = 100 * (HHV(HIGH, N1) - CLOSE) / (HHV(HIGH, N1) - LLV(LOW, N1))
DICT = {'WR1': WR1, 'WR2': WR2}
... | 威廉指标 | Below is the the instruction that describes the task:
### Input:
威廉指标
### Response:
def QA_indicator_WR(DataFrame, N, N1):
'威廉指标'
HIGH = DataFrame['high']
LOW = DataFrame['low']
CLOSE = DataFrame['close']
WR1 = 100 * (HHV(HIGH, N) - CLOSE) / (HHV(HIGH, N) - LLV(LOW, N))
WR2 = 100 * (HHV(HIG... |
def save(self, name):
"""
Copy the contents of the temporary file somewhere else. Finalizes prior to saving.
:param name: File path.
:type name: unicode | str
"""
self.finalize()
with open(name, 'wb+') as f:
buf = self._fileobj.read()
whil... | Copy the contents of the temporary file somewhere else. Finalizes prior to saving.
:param name: File path.
:type name: unicode | str | Below is the the instruction that describes the task:
### Input:
Copy the contents of the temporary file somewhere else. Finalizes prior to saving.
:param name: File path.
:type name: unicode | str
### Response:
def save(self, name):
"""
Copy the contents of the temporary file some... |
def pairwise_tukey(dv=None, between=None, data=None, alpha=.05,
tail='two-sided', effsize='hedges'):
'''Pairwise Tukey-HSD post-hoc test.
Parameters
----------
dv : string
Name of column containing the dependant variable.
between: string
Name of column containing ... | Pairwise Tukey-HSD post-hoc test.
Parameters
----------
dv : string
Name of column containing the dependant variable.
between: string
Name of column containing the between factor.
data : pandas DataFrame
DataFrame
alpha : float
Significance level
tail : strin... | Below is the the instruction that describes the task:
### Input:
Pairwise Tukey-HSD post-hoc test.
Parameters
----------
dv : string
Name of column containing the dependant variable.
between: string
Name of column containing the between factor.
data : pandas DataFrame
Da... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.