code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def update(self, calendar_item_update_operation_type=u'SendToAllAndSaveCopy', **kwargs):
"""
Updates an event in Exchange. ::
event = service.calendar().get_event(id='KEY HERE')
event.location = u'New location'
event.update()
If no changes to the event have been made, this method ... | Updates an event in Exchange. ::
event = service.calendar().get_event(id='KEY HERE')
event.location = u'New location'
event.update()
If no changes to the event have been made, this method does nothing.
Notification of the change event is sent to all users. If you wish to just notify ... | Below is the the instruction that describes the task:
### Input:
Updates an event in Exchange. ::
event = service.calendar().get_event(id='KEY HERE')
event.location = u'New location'
event.update()
If no changes to the event have been made, this method does nothing.
Notification ... |
def remove_child_families(self, family_id):
"""Removes all children from a family.
arg: family_id (osid.id.Id): the ``Id`` of a family
raise: NotFound - ``family_id`` not in hierarchy
raise: NullArgument - ``family_id`` is ``null``
raise: OperationFailed - unable to comple... | Removes all children from a family.
arg: family_id (osid.id.Id): the ``Id`` of a family
raise: NotFound - ``family_id`` not in hierarchy
raise: NullArgument - ``family_id`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authoriza... | Below is the the instruction that describes the task:
### Input:
Removes all children from a family.
arg: family_id (osid.id.Id): the ``Id`` of a family
raise: NotFound - ``family_id`` not in hierarchy
raise: NullArgument - ``family_id`` is ``null``
raise: OperationFailed - un... |
def _get(self, key, identity='image'):
"""
Deserializing, prefix wrapper for _get_raw
"""
value = self._get_raw(add_prefix(key, identity))
if not value:
return None
if identity == 'image':
return deserialize_image_file(value)
return dese... | Deserializing, prefix wrapper for _get_raw | Below is the the instruction that describes the task:
### Input:
Deserializing, prefix wrapper for _get_raw
### Response:
def _get(self, key, identity='image'):
"""
Deserializing, prefix wrapper for _get_raw
"""
value = self._get_raw(add_prefix(key, identity))
if not value:... |
def woodbury_vector(self):
"""
Woodbury vector in the gaussian likelihood case only is defined as
$$
(K_{xx} + \Sigma)^{-1}Y
\Sigma := \texttt{Likelihood.variance / Approximate likelihood covariance}
$$
"""
if self._woodbury_vector is None:
sel... | Woodbury vector in the gaussian likelihood case only is defined as
$$
(K_{xx} + \Sigma)^{-1}Y
\Sigma := \texttt{Likelihood.variance / Approximate likelihood covariance}
$$ | Below is the the instruction that describes the task:
### Input:
Woodbury vector in the gaussian likelihood case only is defined as
$$
(K_{xx} + \Sigma)^{-1}Y
\Sigma := \texttt{Likelihood.variance / Approximate likelihood covariance}
$$
### Response:
def woodbury_vector(self):
... |
def set_score(submission_uuid, points_earned, points_possible,
annotation_creator=None, annotation_type=None, annotation_reason=None):
"""Set a score for a particular submission.
Sets the score for a particular submission. This score is calculated
externally to the API.
Args:
sub... | Set a score for a particular submission.
Sets the score for a particular submission. This score is calculated
externally to the API.
Args:
submission_uuid (str): UUID for the submission (must exist).
points_earned (int): The earned points for this submission.
points_possible (int):... | Below is the the instruction that describes the task:
### Input:
Set a score for a particular submission.
Sets the score for a particular submission. This score is calculated
externally to the API.
Args:
submission_uuid (str): UUID for the submission (must exist).
points_earned (int): ... |
def check_connection (self):
"""
Open a telnet connection and try to login. Expected login
label is "login: ", expected password label is "Password: ".
"""
self.url_connection = telnetlib.Telnet(timeout=self.aggregate.config["timeout"])
if log.is_debug(LOG_CHECK):
... | Open a telnet connection and try to login. Expected login
label is "login: ", expected password label is "Password: ". | Below is the the instruction that describes the task:
### Input:
Open a telnet connection and try to login. Expected login
label is "login: ", expected password label is "Password: ".
### Response:
def check_connection (self):
"""
Open a telnet connection and try to login. Expected login
... |
def _find_statements(self):
"""Find the statements in `self.code`.
Produce a sequence of line numbers that start statements. Recurses
into all code objects reachable from `self.code`.
"""
for bp in self.child_parsers():
# Get all of the lineno information from this... | Find the statements in `self.code`.
Produce a sequence of line numbers that start statements. Recurses
into all code objects reachable from `self.code`. | Below is the the instruction that describes the task:
### Input:
Find the statements in `self.code`.
Produce a sequence of line numbers that start statements. Recurses
into all code objects reachable from `self.code`.
### Response:
def _find_statements(self):
"""Find the statements in `se... |
def set_window_title(self):
"""Set window title."""
if DEV is not None:
title = u"Spyder %s (Python %s.%s)" % (__version__,
sys.version_info[0],
sys.version_info[1])
else:
... | Set window title. | Below is the the instruction that describes the task:
### Input:
Set window title.
### Response:
def set_window_title(self):
"""Set window title."""
if DEV is not None:
title = u"Spyder %s (Python %s.%s)" % (__version__,
sys.version... |
def delete(self, file_path, branch, commit_message, **kwargs):
"""Delete a file on the server.
Args:
file_path (str): Path of the file to remove
branch (str): Branch from which the file will be removed
commit_message (str): Commit message for the deletion
... | Delete a file on the server.
Args:
file_path (str): Path of the file to remove
branch (str): Branch from which the file will be removed
commit_message (str): Commit message for the deletion
**kwargs: Extra options to send to the server (e.g. sudo)
Raises... | Below is the the instruction that describes the task:
### Input:
Delete a file on the server.
Args:
file_path (str): Path of the file to remove
branch (str): Branch from which the file will be removed
commit_message (str): Commit message for the deletion
**kw... |
def get(self,id):
'''Return all the semantic tag related to the given tag id
:returns: a semantic tag or None
:rtype: list of ckan.model.semantictag.SemanticTag object
'''
query = meta.Session.query(TagSemanticTag).filter(TagSemanticTag.id==id)
return query.first() | Return all the semantic tag related to the given tag id
:returns: a semantic tag or None
:rtype: list of ckan.model.semantictag.SemanticTag object | Below is the the instruction that describes the task:
### Input:
Return all the semantic tag related to the given tag id
:returns: a semantic tag or None
:rtype: list of ckan.model.semantictag.SemanticTag object
### Response:
def get(self,id):
'''Return all the semantic tag related to the given tag id
:r... |
def serialize(
self,
value, # type: Any
state # type: _ProcessorState
):
# type: (...) -> ET.Element
"""
Serialize the value into a new element object and return the element.
If the omit_empty option was specified and the value is falsey, then t... | Serialize the value into a new element object and return the element.
If the omit_empty option was specified and the value is falsey, then this will return None. | Below is the the instruction that describes the task:
### Input:
Serialize the value into a new element object and return the element.
If the omit_empty option was specified and the value is falsey, then this will return None.
### Response:
def serialize(
self,
value, # type: Any
... |
def install_pkgs(self, offline=False):
"""
TODO: maybe use conda as python package
"""
if not offline and self.pkgs:
self.logger.info("Installing conda packages ...")
cmd = [join(self.anaconda_home, 'bin', 'conda')]
cmd.append('install')
# ... | TODO: maybe use conda as python package | Below is the the instruction that describes the task:
### Input:
TODO: maybe use conda as python package
### Response:
def install_pkgs(self, offline=False):
"""
TODO: maybe use conda as python package
"""
if not offline and self.pkgs:
self.logger.info("Installing conda ... |
def load_clubs(self):
"""Fetches the MAL user clubs page and sets the current user's clubs attributes.
:rtype: :class:`.User`
:return: Current user object.
"""
user_clubs = self.session.session.get(u'http://myanimelist.net/profile/' + utilities.urlencode(self.username) + u'/clubs').text
self.s... | Fetches the MAL user clubs page and sets the current user's clubs attributes.
:rtype: :class:`.User`
:return: Current user object. | Below is the the instruction that describes the task:
### Input:
Fetches the MAL user clubs page and sets the current user's clubs attributes.
:rtype: :class:`.User`
:return: Current user object.
### Response:
def load_clubs(self):
"""Fetches the MAL user clubs page and sets the current user's clubs a... |
def object_info(**kw):
"""Make an object info dict with all fields present."""
infodict = dict(izip_longest(info_fields, [None]))
infodict.update(kw)
return infodict | Make an object info dict with all fields present. | Below is the the instruction that describes the task:
### Input:
Make an object info dict with all fields present.
### Response:
def object_info(**kw):
"""Make an object info dict with all fields present."""
infodict = dict(izip_longest(info_fields, [None]))
infodict.update(kw)
return infodict |
def _find_instance(iname, instance_repo):
"""
Find an instance in the instance repo by iname and return the
index of that instance.
Parameters:
iname: CIMInstancename to find
instance_repo: the instance repo to search
Return (None, None if not found. Other... | Find an instance in the instance repo by iname and return the
index of that instance.
Parameters:
iname: CIMInstancename to find
instance_repo: the instance repo to search
Return (None, None if not found. Otherwise return tuple of
index, instance
R... | Below is the the instruction that describes the task:
### Input:
Find an instance in the instance repo by iname and return the
index of that instance.
Parameters:
iname: CIMInstancename to find
instance_repo: the instance repo to search
Return (None, None if not found... |
def newtons_method(f, x, line_search=1.0, maxiter=1000, tol=1e-16,
cg_iter=None, callback=None):
r"""Newton's method for minimizing a functional.
Notes
-----
This is a general and optimized implementation of Newton's method
for solving the problem:
.. math::
\min f(x... | r"""Newton's method for minimizing a functional.
Notes
-----
This is a general and optimized implementation of Newton's method
for solving the problem:
.. math::
\min f(x)
for a differentiable function
:math:`f: \mathcal{X}\to \mathbb{R}` on a Hilbert space
:math:`\mathcal{X}`... | Below is the the instruction that describes the task:
### Input:
r"""Newton's method for minimizing a functional.
Notes
-----
This is a general and optimized implementation of Newton's method
for solving the problem:
.. math::
\min f(x)
for a differentiable function
:math:`f: ... |
def refresh_content(self, order=None, name=None):
"""
Re-download comments and reset the page index
"""
order = order or self.content.order
url = name or self.content.name
# Hack to allow an order specified in the name by prompt_subreddit() to
# override the curr... | Re-download comments and reset the page index | Below is the the instruction that describes the task:
### Input:
Re-download comments and reset the page index
### Response:
def refresh_content(self, order=None, name=None):
"""
Re-download comments and reset the page index
"""
order = order or self.content.order
url = name... |
def cmp_traj(traj_a, traj_b):
"""
Parameters
----------
traj_a, traj_b: mdtraj.Trajectory
"""
if traj_a is None and traj_b is None:
return True
if traj_a is None and traj_b is not None:
return False
if traj_a is not None and traj_b is None:
return False
equal_... | Parameters
----------
traj_a, traj_b: mdtraj.Trajectory | Below is the the instruction that describes the task:
### Input:
Parameters
----------
traj_a, traj_b: mdtraj.Trajectory
### Response:
def cmp_traj(traj_a, traj_b):
"""
Parameters
----------
traj_a, traj_b: mdtraj.Trajectory
"""
if traj_a is None and traj_b is None:
return T... |
async def asgi_send(self, message: dict) -> None:
"""Called by the ASGI instance to send a message."""
if message["type"] == "websocket.accept" and self.state == ASGIWebsocketState.HANDSHAKE:
headers = build_and_validate_headers(message.get("headers", []))
raise_if_subprotocol_pr... | Called by the ASGI instance to send a message. | Below is the the instruction that describes the task:
### Input:
Called by the ASGI instance to send a message.
### Response:
async def asgi_send(self, message: dict) -> None:
"""Called by the ASGI instance to send a message."""
if message["type"] == "websocket.accept" and self.state == ASGIWebsock... |
def stop_processing(self, warning=True):
"""
Registers the end of a processing operation.
:param warning: Emit warning message.
:type warning: int
:return: Method success.
:rtype: bool
"""
if not self.__is_processing:
warning and LOGGER.warni... | Registers the end of a processing operation.
:param warning: Emit warning message.
:type warning: int
:return: Method success.
:rtype: bool | Below is the the instruction that describes the task:
### Input:
Registers the end of a processing operation.
:param warning: Emit warning message.
:type warning: int
:return: Method success.
:rtype: bool
### Response:
def stop_processing(self, warning=True):
"""
Re... |
def clean_prefix(self):
"""The cleaned up invoke prefix. i.e. mentions are ``@name`` instead of ``<@id>``."""
user = self.context.guild.me if self.context.guild else self.context.bot.user
# this breaks if the prefix mention is not the bot itself but I
# consider this to be an *incredibly... | The cleaned up invoke prefix. i.e. mentions are ``@name`` instead of ``<@id>``. | Below is the the instruction that describes the task:
### Input:
The cleaned up invoke prefix. i.e. mentions are ``@name`` instead of ``<@id>``.
### Response:
def clean_prefix(self):
"""The cleaned up invoke prefix. i.e. mentions are ``@name`` instead of ``<@id>``."""
user = self.context.guild.me i... |
def detect_opensearch(err, package, listed=False):
'Detect, parse, and validate an OpenSearch provider'
# Parse the file.
try:
# Check if it is a file object.
if hasattr(package, 'read'):
srch_prov = parse(package)
else:
# It's not a file object; open it (the... | Detect, parse, and validate an OpenSearch provider | Below is the the instruction that describes the task:
### Input:
Detect, parse, and validate an OpenSearch provider
### Response:
def detect_opensearch(err, package, listed=False):
'Detect, parse, and validate an OpenSearch provider'
# Parse the file.
try:
# Check if it is a file object.
... |
def play(state):
""" Play sound for a given state.
:param state: a State value.
"""
filename = None
if state == SoundService.State.welcome:
filename = "pad_glow_welcome1.wav"
elif state == SoundService.State.goodbye:
filename = "pad_glow_power_off... | Play sound for a given state.
:param state: a State value. | Below is the the instruction that describes the task:
### Input:
Play sound for a given state.
:param state: a State value.
### Response:
def play(state):
""" Play sound for a given state.
:param state: a State value.
"""
filename = None
if state == SoundService.St... |
def put(self, task, args, kwargs):
""" Add a new item to the queue. An item is a task and the
arguments needed to call it.
Do not call this directly, use Task.queue/Task.run instead.
"""
if self.num_threads == 0:
return task(*args, **kwargs)
if self.queue is ... | Add a new item to the queue. An item is a task and the
arguments needed to call it.
Do not call this directly, use Task.queue/Task.run instead. | Below is the the instruction that describes the task:
### Input:
Add a new item to the queue. An item is a task and the
arguments needed to call it.
Do not call this directly, use Task.queue/Task.run instead.
### Response:
def put(self, task, args, kwargs):
""" Add a new item to the queue.... |
def send_file(self, file_name, remote_destination=None, **kwargs):
"""Send a file to a remote host with rsync.
Args:
file_name (str): The relative location of the file on the local
host.
remote_destination (str): The destination for the file on the remote
... | Send a file to a remote host with rsync.
Args:
file_name (str): The relative location of the file on the local
host.
remote_destination (str): The destination for the file on the remote
host. If `None`, will be assumed to be the same as
*... | Below is the the instruction that describes the task:
### Input:
Send a file to a remote host with rsync.
Args:
file_name (str): The relative location of the file on the local
host.
remote_destination (str): The destination for the file on the remote
... |
def Hvap(counts):
r'''Estimates the enthalpy of vaporization of an organic compound at
its normal boiling point using the Joback method as a function of
chemical structure only.
.. math::
\Delta H_{vap} = 15.30 + \sum_i H_{vap,i}
In the abov... | r'''Estimates the enthalpy of vaporization of an organic compound at
its normal boiling point using the Joback method as a function of
chemical structure only.
.. math::
\Delta H_{vap} = 15.30 + \sum_i H_{vap,i}
In the above equation, enthalpy of fu... | Below is the the instruction that describes the task:
### Input:
r'''Estimates the enthalpy of vaporization of an organic compound at
its normal boiling point using the Joback method as a function of
chemical structure only.
.. math::
\Delta H_{vap} = 15.30 + \sum_i... |
def read_crl(crl):
'''
Returns a dict containing details of a certificate revocation list.
Input can be a PEM string or file path.
:depends: - OpenSSL command line tool
csl:
A path or PEM encoded string containing the CSL to read.
CLI Example:
.. code-block:: bash
salt... | Returns a dict containing details of a certificate revocation list.
Input can be a PEM string or file path.
:depends: - OpenSSL command line tool
csl:
A path or PEM encoded string containing the CSL to read.
CLI Example:
.. code-block:: bash
salt '*' x509.read_crl /etc/pki/myc... | Below is the the instruction that describes the task:
### Input:
Returns a dict containing details of a certificate revocation list.
Input can be a PEM string or file path.
:depends: - OpenSSL command line tool
csl:
A path or PEM encoded string containing the CSL to read.
CLI Example:
... |
def parse_arguments(argv):
"""
Parse command line arguments and override local configuration
:params args: Array of command line arguments
"""
parser = argparse.ArgumentParser(description="GNS3 server version {}".format(__version__))
parser.add_argument("-v", "--version", help="show the versio... | Parse command line arguments and override local configuration
:params args: Array of command line arguments | Below is the the instruction that describes the task:
### Input:
Parse command line arguments and override local configuration
:params args: Array of command line arguments
### Response:
def parse_arguments(argv):
"""
Parse command line arguments and override local configuration
:params args: Arr... |
def _validate_calibration_params(strategy='accuracy', min_rate=None,
beta=1.):
"""Ensure that calibration parameters have allowed values"""
if strategy not in ('accuracy', 'f_beta', 'max_tpr',
'max_tnr'):
raise ValueError('Strategy can either be "... | Ensure that calibration parameters have allowed values | Below is the the instruction that describes the task:
### Input:
Ensure that calibration parameters have allowed values
### Response:
def _validate_calibration_params(strategy='accuracy', min_rate=None,
beta=1.):
"""Ensure that calibration parameters have allowed values"""
... |
def run(self, *args):
"""Merge unique identities using a matching algorithm."""
params = self.parser.parse_args(args)
code = self.unify(params.matching, params.sources,
params.fast_matching, params.no_strict,
params.interactive, params.recove... | Merge unique identities using a matching algorithm. | Below is the the instruction that describes the task:
### Input:
Merge unique identities using a matching algorithm.
### Response:
def run(self, *args):
"""Merge unique identities using a matching algorithm."""
params = self.parser.parse_args(args)
code = self.unify(params.matching, param... |
def access_time(self):
"""dfdatetime.DateTimeValues: access time or None if not available."""
timestamp = self._fsapfs_file_entry.get_access_time_as_integer()
return dfdatetime_apfs_time.APFSTime(timestamp=timestamp) | dfdatetime.DateTimeValues: access time or None if not available. | Below is the the instruction that describes the task:
### Input:
dfdatetime.DateTimeValues: access time or None if not available.
### Response:
def access_time(self):
"""dfdatetime.DateTimeValues: access time or None if not available."""
timestamp = self._fsapfs_file_entry.get_access_time_as_integer()
... |
def p_expression_0(self, program):
"""
expression : expression '*' expression
| expression '/' expression
| expression '+' expression
| expression '-' expression
| expression '^' expression
"""
program[0] = n... | expression : expression '*' expression
| expression '/' expression
| expression '+' expression
| expression '-' expression
| expression '^' expression | Below is the the instruction that describes the task:
### Input:
expression : expression '*' expression
| expression '/' expression
| expression '+' expression
| expression '-' expression
| expression '^' expression
### Response:
def p... |
def match(self, selector, index):
"""Match the selector."""
pseudo = None
m = self.re_pseudo_name.match(selector, index)
if m:
name = util.lower(css_unescape(m.group('name')))
pattern = self.patterns.get(name)
if pattern:
pseudo = patt... | Match the selector. | Below is the the instruction that describes the task:
### Input:
Match the selector.
### Response:
def match(self, selector, index):
"""Match the selector."""
pseudo = None
m = self.re_pseudo_name.match(selector, index)
if m:
name = util.lower(css_unescape(m.group('name... |
def trun_emph(trun):
"""Print essential info on"""
if trun["conf"]["VERBOSE"] > 1: # Print environment variables
cij.emph("rnr:CONF {")
for cvar in sorted(trun["conf"].keys()):
cij.emph(" % 16s: %r" % (cvar, trun["conf"][cvar]))
cij.emph("}")
if trun["con... | Print essential info on | Below is the the instruction that describes the task:
### Input:
Print essential info on
### Response:
def trun_emph(trun):
"""Print essential info on"""
if trun["conf"]["VERBOSE"] > 1: # Print environment variables
cij.emph("rnr:CONF {")
for cvar in sorted(trun["conf"].keys(... |
def search(self, term=None, category=None, pages=1, url=search_url,
sort=None, order=None):
"""Search a given URL for torrent results."""
if not self.current_url:
self.current_url = url
if self.current_url == Search.base_url:
# Searching home page so no formatting
results = self._get_results(self.c... | Search a given URL for torrent results. | Below is the the instruction that describes the task:
### Input:
Search a given URL for torrent results.
### Response:
def search(self, term=None, category=None, pages=1, url=search_url,
sort=None, order=None):
"""Search a given URL for torrent results."""
if not self.current_url:
self.current_url = ur... |
def _set_rightMargin(self, value):
"""
value will be an int or float.
Subclasses may override this method.
"""
bounds = self.bounds
if bounds is None:
self.width = value
else:
xMin, yMin, xMax, yMax = bounds
self.width = xMax +... | value will be an int or float.
Subclasses may override this method. | Below is the the instruction that describes the task:
### Input:
value will be an int or float.
Subclasses may override this method.
### Response:
def _set_rightMargin(self, value):
"""
value will be an int or float.
Subclasses may override this method.
"""
bounds ... |
def validate(self, value):
"""Validate value."""
len_ = len(value)
if self.minimum_value is not None and len_ < self.minimum_value:
tpl = "Value '{val}' length is lower than allowed minimum '{min}'."
raise ValidationError(tpl.format(
val=value, min=self.m... | Validate value. | Below is the the instruction that describes the task:
### Input:
Validate value.
### Response:
def validate(self, value):
"""Validate value."""
len_ = len(value)
if self.minimum_value is not None and len_ < self.minimum_value:
tpl = "Value '{val}' length is lower than allowed m... |
def to_script(self, wf_name='wf'):
"""Generated and print the scriptcwl script for the currunt workflow.
Args:
wf_name (str): string used for the WorkflowGenerator object in the
generated script (default: ``wf``).
"""
self._closed()
script = []
... | Generated and print the scriptcwl script for the currunt workflow.
Args:
wf_name (str): string used for the WorkflowGenerator object in the
generated script (default: ``wf``). | Below is the the instruction that describes the task:
### Input:
Generated and print the scriptcwl script for the currunt workflow.
Args:
wf_name (str): string used for the WorkflowGenerator object in the
generated script (default: ``wf``).
### Response:
def to_script(self, wf_... |
def _db_to_python(db_data: dict, table: LdapObjectClass, dn: str) -> LdapObject:
""" Convert a DbDate object to a LdapObject. """
fields = table.get_fields()
python_data = table({
name: field.to_python(db_data[name])
for name, field in fields.items()
if field.db_field
})
pyt... | Convert a DbDate object to a LdapObject. | Below is the the instruction that describes the task:
### Input:
Convert a DbDate object to a LdapObject.
### Response:
def _db_to_python(db_data: dict, table: LdapObjectClass, dn: str) -> LdapObject:
""" Convert a DbDate object to a LdapObject. """
fields = table.get_fields()
python_data = table({
... |
def _classifyState(self, state):
"""
Reclassifies given state.
"""
# Record is before wait period do not classifiy
if state.ROWID < self.getParameter('trainRecords'):
if not state.setByUser:
state.anomalyLabel = []
self._deleteRecordsFromKNN([state])
return
label = K... | Reclassifies given state. | Below is the the instruction that describes the task:
### Input:
Reclassifies given state.
### Response:
def _classifyState(self, state):
"""
Reclassifies given state.
"""
# Record is before wait period do not classifiy
if state.ROWID < self.getParameter('trainRecords'):
if not state.setB... |
def protected_branches():
# type: () -> list[str]
""" Return branches protected by deletion.
By default those are master and devel branches as configured in pelconf.
Returns:
list[str]: Names of important branches that should not be deleted.
"""
master = conf.get('git.master_branch', '... | Return branches protected by deletion.
By default those are master and devel branches as configured in pelconf.
Returns:
list[str]: Names of important branches that should not be deleted. | Below is the the instruction that describes the task:
### Input:
Return branches protected by deletion.
By default those are master and devel branches as configured in pelconf.
Returns:
list[str]: Names of important branches that should not be deleted.
### Response:
def protected_branches():
... |
def saddr(address):
"""Return a string representation for an address.
The *address* paramater can be a pipe name, an IP address tuple, or a
socket address.
The return value is always a ``str`` instance.
"""
if isinstance(address, six.string_types):
return address
elif isinstance(ad... | Return a string representation for an address.
The *address* paramater can be a pipe name, an IP address tuple, or a
socket address.
The return value is always a ``str`` instance. | Below is the the instruction that describes the task:
### Input:
Return a string representation for an address.
The *address* paramater can be a pipe name, an IP address tuple, or a
socket address.
The return value is always a ``str`` instance.
### Response:
def saddr(address):
"""Return a string... |
def clear_lock(self, remote=None, lock_type='update'):
'''
Clear update.lk for all remotes
'''
cleared = []
errors = []
for repo in self.remotes:
if remote:
# Specific remote URL/pattern was passed, ensure that the URL
# matches... | Clear update.lk for all remotes | Below is the the instruction that describes the task:
### Input:
Clear update.lk for all remotes
### Response:
def clear_lock(self, remote=None, lock_type='update'):
'''
Clear update.lk for all remotes
'''
cleared = []
errors = []
for repo in self.remotes:
... |
def _initial_proposal_distribution(self, parameters, theta, size,
default_std=1e-4):
"""
Generate an initial proposal distribution around the point theta.
"""
missing_parameters = set(parameters).difference(theta)
if missing_parameters:
raise ValueError("cann... | Generate an initial proposal distribution around the point theta. | Below is the the instruction that describes the task:
### Input:
Generate an initial proposal distribution around the point theta.
### Response:
def _initial_proposal_distribution(self, parameters, theta, size,
default_std=1e-4):
"""
Generate an initial proposal distribution around the poin... |
def _trj_check_version(self, version, python, force):
"""Checks for version mismatch
Raises a VersionMismatchError if version of loaded trajectory and current pypet version
do not match. In case of `force=True` error is not raised only a warning is emitted.
"""
curr_python = py... | Checks for version mismatch
Raises a VersionMismatchError if version of loaded trajectory and current pypet version
do not match. In case of `force=True` error is not raised only a warning is emitted. | Below is the the instruction that describes the task:
### Input:
Checks for version mismatch
Raises a VersionMismatchError if version of loaded trajectory and current pypet version
do not match. In case of `force=True` error is not raised only a warning is emitted.
### Response:
def _trj_check_ver... |
def getWindows(): #https://sjohannes.wordpress.com/2012/03/23/win32-python-getting-all-window-titles/
"""Return dict: {'window title' : window handle} for all visible windows"""
titles = {}
def foreach_window(hwnd, lparam):
if IsWindowVisible(hwnd):
length = GetWindowTextLength(hwnd)... | Return dict: {'window title' : window handle} for all visible windows | Below is the the instruction that describes the task:
### Input:
Return dict: {'window title' : window handle} for all visible windows
### Response:
def getWindows(): #https://sjohannes.wordpress.com/2012/03/23/win32-python-getting-all-window-titles/
"""Return dict: {'window title' : window handle} for all ... |
def get_project_version_by_name(self, project, version_name):
"""Get a version Resource by its name present on a project.
:param project: ID or key of the project to get versions from
:type project: str
:param version_name: name of the version to search for
:type version_name: s... | Get a version Resource by its name present on a project.
:param project: ID or key of the project to get versions from
:type project: str
:param version_name: name of the version to search for
:type version_name: str
:rtype: Optional[Version] | Below is the the instruction that describes the task:
### Input:
Get a version Resource by its name present on a project.
:param project: ID or key of the project to get versions from
:type project: str
:param version_name: name of the version to search for
:type version_name: str
... |
def update_partition_static_route(self, org_name, part_name,
static_ip_list, vrf_prof=None,
service_node_ip=None):
"""Send static route update requests to DCNM.
:param org_name: name of organization
:param part_name: na... | Send static route update requests to DCNM.
:param org_name: name of organization
:param part_name: name of partition
:static_ip_list: List of static IP addresses
:vrf_prof: VRF Profile
:service_node_ip: Service Node IP address | Below is the the instruction that describes the task:
### Input:
Send static route update requests to DCNM.
:param org_name: name of organization
:param part_name: name of partition
:static_ip_list: List of static IP addresses
:vrf_prof: VRF Profile
:service_node_ip: Service... |
def to_ubyte_array(barray):
"""Returns a c_ubyte_array filled with the given data of a bytearray or bytes"""
bs = (ctypes.c_ubyte * len(barray))()
pack_into('%ds' % len(barray), bs, 0, barray)
return bs | Returns a c_ubyte_array filled with the given data of a bytearray or bytes | Below is the the instruction that describes the task:
### Input:
Returns a c_ubyte_array filled with the given data of a bytearray or bytes
### Response:
def to_ubyte_array(barray):
"""Returns a c_ubyte_array filled with the given data of a bytearray or bytes"""
bs = (ctypes.c_ubyte * len(barray))()
pa... |
def confirm_subscription(self, topic, token,
authenticate_on_unsubscribe=False):
"""
Get properties of a Topic
:type topic: string
:param topic: The ARN of the new topic.
:type token: string
:param token: Short-lived token sent to and endpoi... | Get properties of a Topic
:type topic: string
:param topic: The ARN of the new topic.
:type token: string
:param token: Short-lived token sent to and endpoint during
the Subscribe operation.
:type authenticate_on_unsubscribe: bool
:param authentic... | Below is the the instruction that describes the task:
### Input:
Get properties of a Topic
:type topic: string
:param topic: The ARN of the new topic.
:type token: string
:param token: Short-lived token sent to and endpoint during
the Subscribe operation.
... |
async def modify_otr_status(self, modify_otr_status_request):
"""Enable or disable message history in a conversation."""
response = hangouts_pb2.ModifyOTRStatusResponse()
await self._pb_request('conversations/modifyotrstatus',
modify_otr_status_request, response)
... | Enable or disable message history in a conversation. | Below is the the instruction that describes the task:
### Input:
Enable or disable message history in a conversation.
### Response:
async def modify_otr_status(self, modify_otr_status_request):
"""Enable or disable message history in a conversation."""
response = hangouts_pb2.ModifyOTRStatusRespons... |
def same_col(c):
"""Return True if all Mentions in the given candidate are from the same Col.
:param c: The candidate whose Mentions are being compared
:rtype: boolean
"""
return same_table(c) and all(
is_col_aligned(_to_span(c[i]).sentence, _to_span(c[0]).sentence)
for i in range(l... | Return True if all Mentions in the given candidate are from the same Col.
:param c: The candidate whose Mentions are being compared
:rtype: boolean | Below is the the instruction that describes the task:
### Input:
Return True if all Mentions in the given candidate are from the same Col.
:param c: The candidate whose Mentions are being compared
:rtype: boolean
### Response:
def same_col(c):
"""Return True if all Mentions in the given candidate are ... |
def sendEvents(self, events):
"""Send a Tensor Event to Riemann"""
self.pressure += 1
self.sendString(self.encodeMessage(events)) | Send a Tensor Event to Riemann | Below is the the instruction that describes the task:
### Input:
Send a Tensor Event to Riemann
### Response:
def sendEvents(self, events):
"""Send a Tensor Event to Riemann"""
self.pressure += 1
self.sendString(self.encodeMessage(events)) |
def distb(self, tb=None, file=None):
"""Disassemble a traceback (default: last traceback)."""
if tb is None:
try:
tb = sys.last_traceback
except AttributeError:
raise RuntimeError("no last traceback to disassemble")
while tb.tb_next: tb... | Disassemble a traceback (default: last traceback). | Below is the the instruction that describes the task:
### Input:
Disassemble a traceback (default: last traceback).
### Response:
def distb(self, tb=None, file=None):
"""Disassemble a traceback (default: last traceback)."""
if tb is None:
try:
tb = sys.last_traceback
... |
def _baseattrs(self):
"""A dict of members expressed in literals"""
result = super()._baseattrs
result["params"] = ", ".join(self.parameters)
return result | A dict of members expressed in literals | Below is the the instruction that describes the task:
### Input:
A dict of members expressed in literals
### Response:
def _baseattrs(self):
"""A dict of members expressed in literals"""
result = super()._baseattrs
result["params"] = ", ".join(self.parameters)
return result |
def get_next_image(img_dir):
"""Get the next image in a dir."""
images, current_wall = get_image_dir(img_dir)
images.sort(key=lambda img: [int(x) if x.isdigit() else x
for x in re.split('([0-9]+)', img)])
try:
next_index = images.index(current_wall) + 1
exc... | Get the next image in a dir. | Below is the the instruction that describes the task:
### Input:
Get the next image in a dir.
### Response:
def get_next_image(img_dir):
"""Get the next image in a dir."""
images, current_wall = get_image_dir(img_dir)
images.sort(key=lambda img: [int(x) if x.isdigit() else x
... |
def now_date(str=False):
"""Get the current date."""
if str:
return datetime.datetime.now().strftime("%Y-%m-%d")
return datetime.date.today() | Get the current date. | Below is the the instruction that describes the task:
### Input:
Get the current date.
### Response:
def now_date(str=False):
"""Get the current date."""
if str:
return datetime.datetime.now().strftime("%Y-%m-%d")
return datetime.date.today() |
def migrate_database(adapter):
"""Migrate an old loqusdb instance to 1.0
Args:
adapter
Returns:
nr_updated(int): Number of variants that where updated
"""
all_variants = adapter.get_variants()
nr_variants = all_variants.count()
nr_updated = 0
with progressb... | Migrate an old loqusdb instance to 1.0
Args:
adapter
Returns:
nr_updated(int): Number of variants that where updated | Below is the the instruction that describes the task:
### Input:
Migrate an old loqusdb instance to 1.0
Args:
adapter
Returns:
nr_updated(int): Number of variants that where updated
### Response:
def migrate_database(adapter):
"""Migrate an old loqusdb instance to 1.0
... |
def _create_content_element(self, content, data_property_value):
"""
Create a element to show the content.
:param content: The text content of element.
:type content: str
:param data_property_value: The value of custom attribute used to
identi... | Create a element to show the content.
:param content: The text content of element.
:type content: str
:param data_property_value: The value of custom attribute used to
identify the fix.
:type data_property_value: str
:return: The element to sh... | Below is the the instruction that describes the task:
### Input:
Create a element to show the content.
:param content: The text content of element.
:type content: str
:param data_property_value: The value of custom attribute used to
identify the fix.
... |
def stationary_distributions(self, max_iter=200, tol=1e-5):
r"""
Compute the moments of the stationary distributions of :math:`x_t` and
:math:`y_t` if possible. Computation is by iteration, starting from
the initial conditions self.mu_0 and self.Sigma_0
Parameters
-----... | r"""
Compute the moments of the stationary distributions of :math:`x_t` and
:math:`y_t` if possible. Computation is by iteration, starting from
the initial conditions self.mu_0 and self.Sigma_0
Parameters
----------
max_iter : scalar(int), optional(default=200)
... | Below is the the instruction that describes the task:
### Input:
r"""
Compute the moments of the stationary distributions of :math:`x_t` and
:math:`y_t` if possible. Computation is by iteration, starting from
the initial conditions self.mu_0 and self.Sigma_0
Parameters
----... |
def is_fw_present(self, fw_id):
"""Returns if firewall index by ID is present in dictionary. """
if self.fw_id is None or self.fw_id != fw_id:
return False
else:
return True | Returns if firewall index by ID is present in dictionary. | Below is the the instruction that describes the task:
### Input:
Returns if firewall index by ID is present in dictionary.
### Response:
def is_fw_present(self, fw_id):
"""Returns if firewall index by ID is present in dictionary. """
if self.fw_id is None or self.fw_id != fw_id:
return ... |
def _validate_pos(df):
"""Validates the returned positional object
"""
assert isinstance(df, pd.DataFrame)
assert ["seqname", "position", "strand"] == df.columns.tolist()
assert df.position.dtype == np.dtype("int64")
assert df.strand.dtype == np.dtype("O")
assert df.seqname.dtype == np.dtype... | Validates the returned positional object | Below is the the instruction that describes the task:
### Input:
Validates the returned positional object
### Response:
def _validate_pos(df):
"""Validates the returned positional object
"""
assert isinstance(df, pd.DataFrame)
assert ["seqname", "position", "strand"] == df.columns.tolist()
asse... |
def main():
"""
Computational Genomics Lab, Genomics Institute, UC Santa Cruz
Toil BWA pipeline
Alignment of fastq reads via BWA-kit
General usage:
1. Type "toil-bwa generate" to create an editable manifest and config in the current working directory.
2. Parameterize the pipeline by editin... | Computational Genomics Lab, Genomics Institute, UC Santa Cruz
Toil BWA pipeline
Alignment of fastq reads via BWA-kit
General usage:
1. Type "toil-bwa generate" to create an editable manifest and config in the current working directory.
2. Parameterize the pipeline by editing the config.
3. Fil... | Below is the the instruction that describes the task:
### Input:
Computational Genomics Lab, Genomics Institute, UC Santa Cruz
Toil BWA pipeline
Alignment of fastq reads via BWA-kit
General usage:
1. Type "toil-bwa generate" to create an editable manifest and config in the current working director... |
def _configure_nodes(self, nodes):
"""Parse and set up the given nodes.
:param nodes: nodes used to create the continuum (see doc for format).
"""
if isinstance(nodes, str):
nodes = [nodes]
elif not isinstance(nodes, (dict, list)):
raise ValueError(
... | Parse and set up the given nodes.
:param nodes: nodes used to create the continuum (see doc for format). | Below is the the instruction that describes the task:
### Input:
Parse and set up the given nodes.
:param nodes: nodes used to create the continuum (see doc for format).
### Response:
def _configure_nodes(self, nodes):
"""Parse and set up the given nodes.
:param nodes: nodes used to creat... |
def fromvars(cls, dataset, batch_size, train=None, **kwargs):
"""Create a Batch directly from a number of Variables."""
batch = cls()
batch.batch_size = batch_size
batch.dataset = dataset
batch.fields = dataset.fields.keys()
for k, v in kwargs.items():
setattr... | Create a Batch directly from a number of Variables. | Below is the the instruction that describes the task:
### Input:
Create a Batch directly from a number of Variables.
### Response:
def fromvars(cls, dataset, batch_size, train=None, **kwargs):
"""Create a Batch directly from a number of Variables."""
batch = cls()
batch.batch_size = batch_s... |
def per_distro_data(self):
"""
Return download data by distro name and version.
:return: dict of cache data; keys are datetime objects, values are
dict of distro name/version (str) to count (int).
:rtype: dict
"""
ret = {}
for cache_date in self.cache_d... | Return download data by distro name and version.
:return: dict of cache data; keys are datetime objects, values are
dict of distro name/version (str) to count (int).
:rtype: dict | Below is the the instruction that describes the task:
### Input:
Return download data by distro name and version.
:return: dict of cache data; keys are datetime objects, values are
dict of distro name/version (str) to count (int).
:rtype: dict
### Response:
def per_distro_data(self):
... |
def _init_nodes(self, config):
""" Gathers dependency sets onto _nodes """
if not isinstance(config, dict):
raise TypeError('"config" must be a dictionary')
for (name, conf) in six.iteritems(config):
args = [] if 'args' not in conf else conf['args']
kwargs = ... | Gathers dependency sets onto _nodes | Below is the the instruction that describes the task:
### Input:
Gathers dependency sets onto _nodes
### Response:
def _init_nodes(self, config):
""" Gathers dependency sets onto _nodes """
if not isinstance(config, dict):
raise TypeError('"config" must be a dictionary')
for (n... |
def guest_start(self, userid):
"""Power on a virtual machine.
:param str userid: the id of the virtual machine to be power on
:returns: None
"""
action = "start guest '%s'" % userid
with zvmutils.log_and_reraise_sdkbase_error(action):
self._vmops.guest_start... | Power on a virtual machine.
:param str userid: the id of the virtual machine to be power on
:returns: None | Below is the the instruction that describes the task:
### Input:
Power on a virtual machine.
:param str userid: the id of the virtual machine to be power on
:returns: None
### Response:
def guest_start(self, userid):
"""Power on a virtual machine.
:param str userid: the id of the... |
def submit_form_id(self, id_):
"""
Submit the form with given id (used to disambiguate between multiple
forms).
"""
form = ElementSelector(
world.browser,
str('id("{id}")'.format(id=id_)),
)
assert form, "Cannot find a form with ID '{}' on the page.".format(id_)
form.subm... | Submit the form with given id (used to disambiguate between multiple
forms). | Below is the the instruction that describes the task:
### Input:
Submit the form with given id (used to disambiguate between multiple
forms).
### Response:
def submit_form_id(self, id_):
"""
Submit the form with given id (used to disambiguate between multiple
forms).
"""
form = ElementSelec... |
def move_detections(label, dy, dx):
"""
Move detections in direction dx, dy.
:param label: The label dict containing all detection lists.
:param dy: The delta in y direction as a number.
:param dx: The delta in x direction as a number.
:return:
"""
for k in label.keys():
if k.st... | Move detections in direction dx, dy.
:param label: The label dict containing all detection lists.
:param dy: The delta in y direction as a number.
:param dx: The delta in x direction as a number.
:return: | Below is the the instruction that describes the task:
### Input:
Move detections in direction dx, dy.
:param label: The label dict containing all detection lists.
:param dy: The delta in y direction as a number.
:param dx: The delta in x direction as a number.
:return:
### Response:
def move_detec... |
def console_progress_callback(current, maximum, message=None):
"""Simple console based callback implementation for tests.
:param current: Current progress.
:type current: int
:param maximum: Maximum range (point at which task is complete.
:type maximum: int
:param mess... | Simple console based callback implementation for tests.
:param current: Current progress.
:type current: int
:param maximum: Maximum range (point at which task is complete.
:type maximum: int
:param message: Optional message dictionary to containing content
we can ... | Below is the the instruction that describes the task:
### Input:
Simple console based callback implementation for tests.
:param current: Current progress.
:type current: int
:param maximum: Maximum range (point at which task is complete.
:type maximum: int
:param message: ... |
def __fetch_issue_messages(self, issue_id):
"""Get messages of an issue"""
for messages_raw in self.client.issue_collection(issue_id, "messages"):
messages = json.loads(messages_raw)
for msg in messages['entries']:
msg['owner_data'] = self.__fetch_user_data('{OW... | Get messages of an issue | Below is the the instruction that describes the task:
### Input:
Get messages of an issue
### Response:
def __fetch_issue_messages(self, issue_id):
"""Get messages of an issue"""
for messages_raw in self.client.issue_collection(issue_id, "messages"):
messages = json.loads(messages_raw)... |
def approve(self, template_address, account):
"""
Approve a template already proposed. The account needs to be owner of the templateManager
contract to be able of approve the template.
:param template_address: Address of the template contract, str
:param account: account approvi... | Approve a template already proposed. The account needs to be owner of the templateManager
contract to be able of approve the template.
:param template_address: Address of the template contract, str
:param account: account approving the template, Account
:return: bool | Below is the the instruction that describes the task:
### Input:
Approve a template already proposed. The account needs to be owner of the templateManager
contract to be able of approve the template.
:param template_address: Address of the template contract, str
:param account: account appr... |
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: SyncMapItemContext for this SyncMapItemInstance
:rtype: twilio.rest.preview.sync.service.sync_map... | Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: SyncMapItemContext for this SyncMapItemInstance
:rtype: twilio.rest.preview.sync.service.sync_map.sync_map_item.SyncMapItemContext | Below is the the instruction that describes the task:
### Input:
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: SyncMapItemContext for this SyncMapItemInstance
:rtype: twilio.res... |
def get_pan(self, coord='data'):
"""Get pan positions.
Parameters
----------
coord : {'data', 'wcs'}
Indicates whether the pan positions are returned in
data or WCS space.
Returns
-------
positions : tuple
X and Y positions, i... | Get pan positions.
Parameters
----------
coord : {'data', 'wcs'}
Indicates whether the pan positions are returned in
data or WCS space.
Returns
-------
positions : tuple
X and Y positions, in that order. | Below is the the instruction that describes the task:
### Input:
Get pan positions.
Parameters
----------
coord : {'data', 'wcs'}
Indicates whether the pan positions are returned in
data or WCS space.
Returns
-------
positions : tuple
... |
def get_footerReference(self, type_):
"""Return footerReference element of *type_* or None if not present."""
path = "./w:footerReference[@w:type='%s']" % WD_HEADER_FOOTER.to_xml(type_)
footerReferences = self.xpath(path)
if not footerReferences:
return None
return fo... | Return footerReference element of *type_* or None if not present. | Below is the the instruction that describes the task:
### Input:
Return footerReference element of *type_* or None if not present.
### Response:
def get_footerReference(self, type_):
"""Return footerReference element of *type_* or None if not present."""
path = "./w:footerReference[@w:type='%s']" %... |
def netmiko_args(optional_args):
"""Check for Netmiko arguments that were passed in as NAPALM optional arguments.
Return a dictionary of these optional args that will be passed into the Netmiko
ConnectHandler call.
"""
fields = py23_compat.argspec(BaseConnection.__init__)
args = fields[0]
... | Check for Netmiko arguments that were passed in as NAPALM optional arguments.
Return a dictionary of these optional args that will be passed into the Netmiko
ConnectHandler call. | Below is the the instruction that describes the task:
### Input:
Check for Netmiko arguments that were passed in as NAPALM optional arguments.
Return a dictionary of these optional args that will be passed into the Netmiko
ConnectHandler call.
### Response:
def netmiko_args(optional_args):
"""Check f... |
def triples(self, (s, p, o), context=None):
"""
Returns all triples in the current store.
"""
named_graph = _get_named_graph(context)
query_sets = _get_query_sets_for_object(o)
filter_parameters = dict()
if named_graph is not None:
filter_parameters['... | Returns all triples in the current store. | Below is the the instruction that describes the task:
### Input:
Returns all triples in the current store.
### Response:
def triples(self, (s, p, o), context=None):
"""
Returns all triples in the current store.
"""
named_graph = _get_named_graph(context)
query_sets = _get_qu... |
def getargnames(argspecs, with_unbox=False):
"""Resembles list of arg-names as would be seen in a function signature, including
var-args, var-keywords and keyword-only args.
"""
# todo: We can maybe make use of inspect.formatargspec
args = argspecs.args
vargs = argspecs.varargs
try:
... | Resembles list of arg-names as would be seen in a function signature, including
var-args, var-keywords and keyword-only args. | Below is the the instruction that describes the task:
### Input:
Resembles list of arg-names as would be seen in a function signature, including
var-args, var-keywords and keyword-only args.
### Response:
def getargnames(argspecs, with_unbox=False):
"""Resembles list of arg-names as would be seen in a func... |
def get(self, robj, r=None, pr=None, timeout=None, basic_quorum=None,
notfound_ok=None, head_only=False):
"""
Fetches an object.
"""
raise NotImplementedError | Fetches an object. | Below is the the instruction that describes the task:
### Input:
Fetches an object.
### Response:
def get(self, robj, r=None, pr=None, timeout=None, basic_quorum=None,
notfound_ok=None, head_only=False):
"""
Fetches an object.
"""
raise NotImplementedError |
def _validate(self, data):
"""Helper to run validators on the field data."""
errors = {}
# if the validator is not enabled, return the empty error dict
if not self._enabled:
return errors
for field in self.validators:
field_errors = []
for... | Helper to run validators on the field data. | Below is the the instruction that describes the task:
### Input:
Helper to run validators on the field data.
### Response:
def _validate(self, data):
"""Helper to run validators on the field data."""
errors = {}
# if the validator is not enabled, return the empty error dict
if not... |
def count_documents(self, filter, session=None, **kwargs):
"""Count the number of documents in this collection.
The :meth:`count_documents` method is supported in a transaction.
All optional parameters should be passed as keyword arguments
to this method. Valid options include:
... | Count the number of documents in this collection.
The :meth:`count_documents` method is supported in a transaction.
All optional parameters should be passed as keyword arguments
to this method. Valid options include:
- `skip` (int): The number of matching documents to skip before
... | Below is the the instruction that describes the task:
### Input:
Count the number of documents in this collection.
The :meth:`count_documents` method is supported in a transaction.
All optional parameters should be passed as keyword arguments
to this method. Valid options include:
... |
def delete_mountpoints(self, paths=None, folder_ids=None):
"""
:param folder_ids: list of ids
:param path: list of folder's paths
"""
self.delete_folders(paths=paths, folder_ids=folder_ids, f_type='link') | :param folder_ids: list of ids
:param path: list of folder's paths | Below is the the instruction that describes the task:
### Input:
:param folder_ids: list of ids
:param path: list of folder's paths
### Response:
def delete_mountpoints(self, paths=None, folder_ids=None):
"""
:param folder_ids: list of ids
:param path: list of folder's paths
... |
async def listen(host, port, onlink, ssl=None):
'''
Listen on the given host/port and fire onlink(Link).
Returns a server object that contains the listening sockets
'''
async def onconn(reader, writer):
link = await Link.anit(reader, writer)
link.schedCoro(onlink(link))
server ... | Listen on the given host/port and fire onlink(Link).
Returns a server object that contains the listening sockets | Below is the the instruction that describes the task:
### Input:
Listen on the given host/port and fire onlink(Link).
Returns a server object that contains the listening sockets
### Response:
async def listen(host, port, onlink, ssl=None):
'''
Listen on the given host/port and fire onlink(Link).
... |
def get_providing_power_source_type(self):
"""
Looks through all power supplies in POWER_SUPPLY_PATH.
If there is an AC adapter online returns POWER_TYPE_AC.
If there is a discharging battery, returns POWER_TYPE_BATTERY.
Since the order of supplies is arbitrary, whatever found fi... | Looks through all power supplies in POWER_SUPPLY_PATH.
If there is an AC adapter online returns POWER_TYPE_AC.
If there is a discharging battery, returns POWER_TYPE_BATTERY.
Since the order of supplies is arbitrary, whatever found first is returned. | Below is the the instruction that describes the task:
### Input:
Looks through all power supplies in POWER_SUPPLY_PATH.
If there is an AC adapter online returns POWER_TYPE_AC.
If there is a discharging battery, returns POWER_TYPE_BATTERY.
Since the order of supplies is arbitrary, whatever fo... |
def classify_coincident(st_vals, coincident):
r"""Determine if coincident parameters are "unused".
.. note::
This is a helper for :func:`surface_intersections`.
In the case that ``coincident`` is :data:`True`, then we'll have two
sets of parameters :math:`(s_1, t_1)` and :math:`(s_2, t_2)`.
... | r"""Determine if coincident parameters are "unused".
.. note::
This is a helper for :func:`surface_intersections`.
In the case that ``coincident`` is :data:`True`, then we'll have two
sets of parameters :math:`(s_1, t_1)` and :math:`(s_2, t_2)`.
If one of :math:`s1 < s2` or :math:`t1 < t2` is... | Below is the the instruction that describes the task:
### Input:
r"""Determine if coincident parameters are "unused".
.. note::
This is a helper for :func:`surface_intersections`.
In the case that ``coincident`` is :data:`True`, then we'll have two
sets of parameters :math:`(s_1, t_1)` and :ma... |
def main():
"""
NAME
agm_magic.py
DESCRIPTION
converts Micromag agm files to magic format
SYNTAX
agm_magic.py [-h] [command line options]
OPTIONS
-usr USER: identify user, default is "" - put in quotation marks!
-bak: this is a IRM backfield curve
... | NAME
agm_magic.py
DESCRIPTION
converts Micromag agm files to magic format
SYNTAX
agm_magic.py [-h] [command line options]
OPTIONS
-usr USER: identify user, default is "" - put in quotation marks!
-bak: this is a IRM backfield curve
-f FILE, specify input... | Below is the the instruction that describes the task:
### Input:
NAME
agm_magic.py
DESCRIPTION
converts Micromag agm files to magic format
SYNTAX
agm_magic.py [-h] [command line options]
OPTIONS
-usr USER: identify user, default is "" - put in quotation marks!
... |
def add_missing_price_information_message(request, item):
"""
Add a message to the Django messages store indicating that we failed to retrieve price information about an item.
:param request: The current request.
:param item: The item for which price information is missing. Example: a program title, or... | Add a message to the Django messages store indicating that we failed to retrieve price information about an item.
:param request: The current request.
:param item: The item for which price information is missing. Example: a program title, or a course. | Below is the the instruction that describes the task:
### Input:
Add a message to the Django messages store indicating that we failed to retrieve price information about an item.
:param request: The current request.
:param item: The item for which price information is missing. Example: a program title, or ... |
def background_thread():
"""Example of how to send server generated events to clients."""
count = 0
while True:
socketio.sleep(10)
count += 1
socketio.emit('my_response',
{'data': 'Server generated event', 'count': count},
namespace='/test'... | Example of how to send server generated events to clients. | Below is the the instruction that describes the task:
### Input:
Example of how to send server generated events to clients.
### Response:
def background_thread():
"""Example of how to send server generated events to clients."""
count = 0
while True:
socketio.sleep(10)
count += 1
... |
def responsive_sleep(self, seconds, wait_reason=''):
"""Sleep for the specified number of seconds, logging every
'wait_log_interval' seconds with progress info."""
for x in range(int(seconds)):
if (self.config.wait_log_interval and
not x % self.config.wait_log_interva... | Sleep for the specified number of seconds, logging every
'wait_log_interval' seconds with progress info. | Below is the the instruction that describes the task:
### Input:
Sleep for the specified number of seconds, logging every
'wait_log_interval' seconds with progress info.
### Response:
def responsive_sleep(self, seconds, wait_reason=''):
"""Sleep for the specified number of seconds, logging every
... |
def login_create(login, new_login_password=None, new_login_domain='', new_login_roles=None, new_login_options=None, **kwargs):
'''
Creates a new login. Does not update password of existing logins. For
Windows authentication, provide ``new_login_domain``. For SQL Server
authentication, prvide ``new_lo... | Creates a new login. Does not update password of existing logins. For
Windows authentication, provide ``new_login_domain``. For SQL Server
authentication, prvide ``new_login_password``. Since hashed passwords are
*varbinary* values, if the ``new_login_password`` is 'int / long', it will
be considere... | Below is the the instruction that describes the task:
### Input:
Creates a new login. Does not update password of existing logins. For
Windows authentication, provide ``new_login_domain``. For SQL Server
authentication, prvide ``new_login_password``. Since hashed passwords are
*varbinary* values, if... |
def _item_keys_match(crypto_config, item1, item2):
# type: (CryptoConfig, Dict, Dict) -> Bool
"""Determines whether the values in the primary and sort keys (if they exist) are the same
:param CryptoConfig crypto_config: CryptoConfig used in encrypting the given items
:param dict item1: The first item t... | Determines whether the values in the primary and sort keys (if they exist) are the same
:param CryptoConfig crypto_config: CryptoConfig used in encrypting the given items
:param dict item1: The first item to compare
:param dict item2: The second item to compare
:return: Bool response, True if the key a... | Below is the the instruction that describes the task:
### Input:
Determines whether the values in the primary and sort keys (if they exist) are the same
:param CryptoConfig crypto_config: CryptoConfig used in encrypting the given items
:param dict item1: The first item to compare
:param dict item2: The... |
def get_summary(config, bugnumber):
"""return a summary for this bug/issue. If it can't be found,
return None."""
bugzilla_url_regex = re.compile(
re.escape("https://bugzilla.mozilla.org/show_bug.cgi?id=") + r"(\d+)$"
)
# The user could have pasted in a bugzilla ID or a bugzilla URL
if... | return a summary for this bug/issue. If it can't be found,
return None. | Below is the the instruction that describes the task:
### Input:
return a summary for this bug/issue. If it can't be found,
return None.
### Response:
def get_summary(config, bugnumber):
"""return a summary for this bug/issue. If it can't be found,
return None."""
bugzilla_url_regex = re.compile(
... |
def dehydrate_point(value):
""" Dehydrator for Point data.
:param value:
:type value: Point
:return:
"""
dim = len(value)
if dim == 2:
return Structure(b"X", value.srid, *value)
elif dim == 3:
return Structure(b"Y", value.srid, *value)
else:
raise ValueError(... | Dehydrator for Point data.
:param value:
:type value: Point
:return: | Below is the the instruction that describes the task:
### Input:
Dehydrator for Point data.
:param value:
:type value: Point
:return:
### Response:
def dehydrate_point(value):
""" Dehydrator for Point data.
:param value:
:type value: Point
:return:
"""
dim = len(value)
if ... |
def p_InDecrement(p):
'''
InDecrement : INDECREMENT Expression
| Expression INDECREMENT
'''
from .helper import isString
if isString(p[1]):
p[0] = InDecrement(p[1], p[2], False)
else:
p[0] = InDecrement(p[2], p[1], True) | InDecrement : INDECREMENT Expression
| Expression INDECREMENT | Below is the the instruction that describes the task:
### Input:
InDecrement : INDECREMENT Expression
| Expression INDECREMENT
### Response:
def p_InDecrement(p):
'''
InDecrement : INDECREMENT Expression
| Expression INDECREMENT
'''
from .helper import isString
i... |
def _browse(c):
"""
Open build target's index.html in a browser (using 'open').
"""
index = join(c.sphinx.target, c.sphinx.target_file)
c.run("open {0}".format(index)) | Open build target's index.html in a browser (using 'open'). | Below is the the instruction that describes the task:
### Input:
Open build target's index.html in a browser (using 'open').
### Response:
def _browse(c):
"""
Open build target's index.html in a browser (using 'open').
"""
index = join(c.sphinx.target, c.sphinx.target_file)
c.run("open {0}".for... |
def summary(self, title=None, complexity=False):
"""
Generates a summary.
:param title: optional title
:type title: str
:param complexity: whether to print the complexity information as well
:type complexity: bool
:return: the summary
:rtype: str
... | Generates a summary.
:param title: optional title
:type title: str
:param complexity: whether to print the complexity information as well
:type complexity: bool
:return: the summary
:rtype: str | Below is the the instruction that describes the task:
### Input:
Generates a summary.
:param title: optional title
:type title: str
:param complexity: whether to print the complexity information as well
:type complexity: bool
:return: the summary
:rtype: str
### Resp... |
def extract_iface_name_from_path(path, name):
"""
Extract the 'real' interface name from the path name. Basically this
puts the '@' back in the name in place of the underscore, where the name
contains a '.' or contains 'macvtap' or 'macvlan'.
Examples:
+------------------+-----------------+
... | Extract the 'real' interface name from the path name. Basically this
puts the '@' back in the name in place of the underscore, where the name
contains a '.' or contains 'macvtap' or 'macvlan'.
Examples:
+------------------+-----------------+
| real name | path name |
+===========... | Below is the the instruction that describes the task:
### Input:
Extract the 'real' interface name from the path name. Basically this
puts the '@' back in the name in place of the underscore, where the name
contains a '.' or contains 'macvtap' or 'macvlan'.
Examples:
+------------------+---------... |
def start(self):
"""Start the subscriber.
"""
def _get_addr_loop(service, timeout):
"""Try to get the address of *service* until for *timeout* seconds.
"""
then = datetime.now() + timedelta(seconds=timeout)
while datetime.now() < then:
... | Start the subscriber. | Below is the the instruction that describes the task:
### Input:
Start the subscriber.
### Response:
def start(self):
"""Start the subscriber.
"""
def _get_addr_loop(service, timeout):
"""Try to get the address of *service* until for *timeout* seconds.
"""
... |
def profile(self):
"""
Buffered result of :meth:`build_profile`
"""
if self._profile is None:
self._profile = self.build_profile()
return self._profile | Buffered result of :meth:`build_profile` | Below is the the instruction that describes the task:
### Input:
Buffered result of :meth:`build_profile`
### Response:
def profile(self):
"""
Buffered result of :meth:`build_profile`
"""
if self._profile is None:
self._profile = self.build_profile()
return self.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.