code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def profiler(self):
"""
Calculates the core profile for each strain
"""
printtime('Calculating core profiles', self.start)
# Only create the profile if it doesn't exist already
# if not os.path.isfile('{}/profile.txt'.format(self.profilelocation)):
for strain in s... | Calculates the core profile for each strain | Below is the the instruction that describes the task:
### Input:
Calculates the core profile for each strain
### Response:
def profiler(self):
"""
Calculates the core profile for each strain
"""
printtime('Calculating core profiles', self.start)
# Only create the profile if ... |
def get_column_labels(command_name):
'''return dictionary of column labels if available'''
cmd = cmd_reverse_lookup(command_name)
if cmd == 0:
return {}
labels = {}
enum = mavutil.mavlink.enums['MAV_CMD'][cmd]
for col in enum.param.keys():
labels[col] = make_column_label(command_... | return dictionary of column labels if available | Below is the the instruction that describes the task:
### Input:
return dictionary of column labels if available
### Response:
def get_column_labels(command_name):
'''return dictionary of column labels if available'''
cmd = cmd_reverse_lookup(command_name)
if cmd == 0:
return {}
labels = {}... |
def verify_url(url, secret_key, **kwargs):
"""
Verify a signed URL (excluding the domain and scheme).
:param url: URL to sign
:param secret_key: Secret key
:rtype: bool
:raises: URLError
"""
result = urlparse(url)
query_args = MultiValueDict(parse_qs(result.query))
return verif... | Verify a signed URL (excluding the domain and scheme).
:param url: URL to sign
:param secret_key: Secret key
:rtype: bool
:raises: URLError | Below is the the instruction that describes the task:
### Input:
Verify a signed URL (excluding the domain and scheme).
:param url: URL to sign
:param secret_key: Secret key
:rtype: bool
:raises: URLError
### Response:
def verify_url(url, secret_key, **kwargs):
"""
Verify a signed URL (exc... |
def getEngineChangelist(self):
"""
Returns the compatible Perforce changelist identifier for the latest installed version of UE4
"""
# Newer versions of the engine use the key "CompatibleChangelist", older ones use "Changelist"
version = self._getEngineVersionDetails()
if 'CompatibleChangelist' in versio... | Returns the compatible Perforce changelist identifier for the latest installed version of UE4 | Below is the the instruction that describes the task:
### Input:
Returns the compatible Perforce changelist identifier for the latest installed version of UE4
### Response:
def getEngineChangelist(self):
"""
Returns the compatible Perforce changelist identifier for the latest installed version of UE4
"""
... |
def mknfold(dall, nfold, param, seed, evals=(), fpreproc=None):
"""
Make an n-fold list of CVPack from random indices.
"""
evals = list(evals)
np.random.seed(seed)
randidx = np.random.permutation(dall.num_row())
kstep = len(randidx) / nfold
idset = [randidx[(i * kstep): min(len(randidx),... | Make an n-fold list of CVPack from random indices. | Below is the the instruction that describes the task:
### Input:
Make an n-fold list of CVPack from random indices.
### Response:
def mknfold(dall, nfold, param, seed, evals=(), fpreproc=None):
"""
Make an n-fold list of CVPack from random indices.
"""
evals = list(evals)
np.random.seed(seed)
... |
def _pypsa_storage_timeseries(network, timesteps, mode=None):
"""
Timeseries in PyPSA compatible format for storage instances
Parameters
----------
network : Network
The eDisGo grid topology model overall container
timesteps : array_like
Timesteps is an array-like object with en... | Timeseries in PyPSA compatible format for storage instances
Parameters
----------
network : Network
The eDisGo grid topology model overall container
timesteps : array_like
Timesteps is an array-like object with entries of type
:pandas:`pandas.Timestamp<timestamp>` specifying whi... | Below is the the instruction that describes the task:
### Input:
Timeseries in PyPSA compatible format for storage instances
Parameters
----------
network : Network
The eDisGo grid topology model overall container
timesteps : array_like
Timesteps is an array-like object with entries... |
def extract(self, text: str) -> List[Extraction]:
"""
Splits text by sentences.
Args:
text (str): Input text to be extracted.
Returns:
List[Extraction]: the list of extraction or the empty list if there are no matches.
"""
doc = self._parser(tex... | Splits text by sentences.
Args:
text (str): Input text to be extracted.
Returns:
List[Extraction]: the list of extraction or the empty list if there are no matches. | Below is the the instruction that describes the task:
### Input:
Splits text by sentences.
Args:
text (str): Input text to be extracted.
Returns:
List[Extraction]: the list of extraction or the empty list if there are no matches.
### Response:
def extract(self, text: str) ... |
def evaluateR2derivs(Pot,R,z,phi=None,t=0.):
"""
NAME:
evaluateR2derivs
PURPOSE:
convenience function to evaluate a possible sum of potentials
INPUT:
Pot - a potential or list of potentials (dissipative forces in such a list are ignored)
R - cylindrical Galactocentric d... | NAME:
evaluateR2derivs
PURPOSE:
convenience function to evaluate a possible sum of potentials
INPUT:
Pot - a potential or list of potentials (dissipative forces in such a list are ignored)
R - cylindrical Galactocentric distance (can be Quantity)
z - distance above the ... | Below is the the instruction that describes the task:
### Input:
NAME:
evaluateR2derivs
PURPOSE:
convenience function to evaluate a possible sum of potentials
INPUT:
Pot - a potential or list of potentials (dissipative forces in such a list are ignored)
R - cylindrical Gala... |
def references(self, env, object_name, model, assoc_class,
result_class_name, role, result_role, keys_only):
"""Instrument Associations.
All four association-related operations (Associators, AssociatorNames,
References, ReferenceNames) are mapped to this method.
This ... | Instrument Associations.
All four association-related operations (Associators, AssociatorNames,
References, ReferenceNames) are mapped to this method.
This method is a python generator
Keyword arguments:
env -- Provider Environment (pycimmb.ProviderEnvironment)
object_n... | Below is the the instruction that describes the task:
### Input:
Instrument Associations.
All four association-related operations (Associators, AssociatorNames,
References, ReferenceNames) are mapped to this method.
This method is a python generator
Keyword arguments:
env -... |
def editor_multi_agent_example():
"""This editor example shows how to interact with holodeck worlds that have multiple agents.
This is specifically for when working with UE4 directly and not a prebuilt binary.
"""
agent_definitions = [
AgentDefinition("uav0", agents.UavAgent, [Sensors.PIXEL_CAME... | This editor example shows how to interact with holodeck worlds that have multiple agents.
This is specifically for when working with UE4 directly and not a prebuilt binary. | Below is the the instruction that describes the task:
### Input:
This editor example shows how to interact with holodeck worlds that have multiple agents.
This is specifically for when working with UE4 directly and not a prebuilt binary.
### Response:
def editor_multi_agent_example():
"""This editor exampl... |
def derive_signature(key, qs):
"""Derives the signature from the supplied query string using the key."""
key, qs = (key or "", qs or "")
return hmac.new(key.encode(), qs.encode(), hashlib.sha1).hexdigest() | Derives the signature from the supplied query string using the key. | Below is the the instruction that describes the task:
### Input:
Derives the signature from the supplied query string using the key.
### Response:
def derive_signature(key, qs):
"""Derives the signature from the supplied query string using the key."""
key, qs = (key or "", qs or "")
return hmac.new(key... |
def all_departed_units(self):
"""
Collection of all units that were previously part of any relation on
this endpoint but which have since departed.
This collection is persistent and mutable. The departed units will
be kept until they are explicitly removed, to allow for reasona... | Collection of all units that were previously part of any relation on
this endpoint but which have since departed.
This collection is persistent and mutable. The departed units will
be kept until they are explicitly removed, to allow for reasonable
cleanup of units that have left.
... | Below is the the instruction that describes the task:
### Input:
Collection of all units that were previously part of any relation on
this endpoint but which have since departed.
This collection is persistent and mutable. The departed units will
be kept until they are explicitly removed, t... |
def zadd(self, key, score, member, mode, client=None):
"""
Like ZADD, but supports different score update modes, in case the
member already exists in the ZSET:
- "nx": Don't update the score
- "xx": Only update elements that already exist. Never add elements.
- "min": Use... | Like ZADD, but supports different score update modes, in case the
member already exists in the ZSET:
- "nx": Don't update the score
- "xx": Only update elements that already exist. Never add elements.
- "min": Use the smaller of the given and existing score
- "max": Use the large... | Below is the the instruction that describes the task:
### Input:
Like ZADD, but supports different score update modes, in case the
member already exists in the ZSET:
- "nx": Don't update the score
- "xx": Only update elements that already exist. Never add elements.
- "min": Use the s... |
def load_operations_from_docstring(docstring):
"""Return a dictionary of OpenAPI operations parsed from a
a docstring.
"""
doc_data = load_yaml_from_docstring(docstring)
return {
key: val
for key, val in iteritems(doc_data)
if key in PATH_KEYS or key.startswith("x-")
} | Return a dictionary of OpenAPI operations parsed from a
a docstring. | Below is the the instruction that describes the task:
### Input:
Return a dictionary of OpenAPI operations parsed from a
a docstring.
### Response:
def load_operations_from_docstring(docstring):
"""Return a dictionary of OpenAPI operations parsed from a
a docstring.
"""
doc_data = load_yaml_fro... |
def write_transcriptions(utterances: List[Utterance],
tgt_dir: Path, ext: str, lazy: bool) -> None:
""" Write the utterance transcriptions to files in the tgt_dir. Is lazy and
checks if the file already exists.
Args:
utterances: A list of Utterance objects to be written.
... | Write the utterance transcriptions to files in the tgt_dir. Is lazy and
checks if the file already exists.
Args:
utterances: A list of Utterance objects to be written.
tgt_dir: The directory in which to write the text of the utterances,
one file per utterance.
ext: The file ... | Below is the the instruction that describes the task:
### Input:
Write the utterance transcriptions to files in the tgt_dir. Is lazy and
checks if the file already exists.
Args:
utterances: A list of Utterance objects to be written.
tgt_dir: The directory in which to write the text of the u... |
def _detach_process():
"""
Detach daemon process.
Forks the current process into a parent and a detached child. The
child process resides in its own process group, has no controlling
terminal attached and is cleaned up by the init process.
Returns ``True`` for the parent and ``False`` for the ... | Detach daemon process.
Forks the current process into a parent and a detached child. The
child process resides in its own process group, has no controlling
terminal attached and is cleaned up by the init process.
Returns ``True`` for the parent and ``False`` for the child. | Below is the the instruction that describes the task:
### Input:
Detach daemon process.
Forks the current process into a parent and a detached child. The
child process resides in its own process group, has no controlling
terminal attached and is cleaned up by the init process.
Returns ``True`` for... |
def wait_spot_requests_active(ec2, requests, timeout=None, tentative=False):
"""
Wait until no spot request in the given iterator is in the 'open' state or, optionally,
a timeout occurs. Yield spot requests as soon as they leave the 'open' state.
:param Iterator[SpotInstanceRequest] requests:
:par... | Wait until no spot request in the given iterator is in the 'open' state or, optionally,
a timeout occurs. Yield spot requests as soon as they leave the 'open' state.
:param Iterator[SpotInstanceRequest] requests:
:param float timeout: Maximum time in seconds to spend waiting or None to wait forever. If a
... | Below is the the instruction that describes the task:
### Input:
Wait until no spot request in the given iterator is in the 'open' state or, optionally,
a timeout occurs. Yield spot requests as soon as they leave the 'open' state.
:param Iterator[SpotInstanceRequest] requests:
:param float timeout: Ma... |
def get_run_params(self) -> Dict:
"""Return the params to run the celery task."""
params = {}
if self.celery_queue:
params['queue'] = self.celery_queue
if self.timeout:
params['soft_time_limit'] = self.timeout
# We set also a hard time limit that will... | Return the params to run the celery task. | Below is the the instruction that describes the task:
### Input:
Return the params to run the celery task.
### Response:
def get_run_params(self) -> Dict:
"""Return the params to run the celery task."""
params = {}
if self.celery_queue:
params['queue'] = self.celery_queue
... |
def humanTime(seconds):
'''
Convert seconds to something more human-friendly
'''
intervals = ['days', 'hours', 'minutes', 'seconds']
x = deltaTime(seconds=seconds)
return ' '.join('{} {}'.format(getattr(x, k), k) for k in intervals if getattr(x, k)) | Convert seconds to something more human-friendly | Below is the the instruction that describes the task:
### Input:
Convert seconds to something more human-friendly
### Response:
def humanTime(seconds):
'''
Convert seconds to something more human-friendly
'''
intervals = ['days', 'hours', 'minutes', 'seconds']
x = deltaTime(seconds=seconds)
return ' '.... |
def transform(self, X):
'''
Transforms X according to the linear transformation corresponding to
shifting the input eigenvalues to all be at least ``self.min_eig``.
Parameters
----------
X : array, shape [n_test, n]
The test similarities to training points.
... | Transforms X according to the linear transformation corresponding to
shifting the input eigenvalues to all be at least ``self.min_eig``.
Parameters
----------
X : array, shape [n_test, n]
The test similarities to training points.
Returns
-------
Xt :... | Below is the the instruction that describes the task:
### Input:
Transforms X according to the linear transformation corresponding to
shifting the input eigenvalues to all be at least ``self.min_eig``.
Parameters
----------
X : array, shape [n_test, n]
The test similarit... |
def show_key(kwargs=None, call=None):
'''
List the keys available
'''
if call != 'function':
log.error(
'The list_keys function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'keyname' not in kwargs:
log.e... | List the keys available | Below is the the instruction that describes the task:
### Input:
List the keys available
### Response:
def show_key(kwargs=None, call=None):
'''
List the keys available
'''
if call != 'function':
log.error(
'The list_keys function must be called with -f or --function.'
)... |
def Cpig_coeffs(counts):
r'''Computes the ideal-gas polynomial heat capacity coefficients
of an organic compound using the Joback method as a function of
chemical structure only.
.. math::
C_p^{ig} = \sum_i a_i - 37.93 + \left[ \sum_i b_i + 0.210 \right] T
... | r'''Computes the ideal-gas polynomial heat capacity coefficients
of an organic compound using the Joback method as a function of
chemical structure only.
.. math::
C_p^{ig} = \sum_i a_i - 37.93 + \left[ \sum_i b_i + 0.210 \right] T
+ \left[ \sum_i c_i - 3.91 ... | Below is the the instruction that describes the task:
### Input:
r'''Computes the ideal-gas polynomial heat capacity coefficients
of an organic compound using the Joback method as a function of
chemical structure only.
.. math::
C_p^{ig} = \sum_i a_i - 37.93 + \left[... |
def cmd_lsch(self):
"""lsch
List the channels, showing the current one.
"""
names = list(self.fv.get_channel_names())
names.sort()
if len(names) == 0:
self.log("No channels")
return
res = []
cur_ch = self.fv.get_channel_info()
... | lsch
List the channels, showing the current one. | Below is the the instruction that describes the task:
### Input:
lsch
List the channels, showing the current one.
### Response:
def cmd_lsch(self):
"""lsch
List the channels, showing the current one.
"""
names = list(self.fv.get_channel_names())
names.sort()
... |
def set_zerg_client_params(self, server_sockets, use_fallback_socket=None):
"""Zerg mode. Zergs params.
:param str|unicode|list[str|unicode] server_sockets: Attaches zerg to a zerg server.
:param bool use_fallback_socket: Fallback to normal sockets if the zerg server is not available
... | Zerg mode. Zergs params.
:param str|unicode|list[str|unicode] server_sockets: Attaches zerg to a zerg server.
:param bool use_fallback_socket: Fallback to normal sockets if the zerg server is not available | Below is the the instruction that describes the task:
### Input:
Zerg mode. Zergs params.
:param str|unicode|list[str|unicode] server_sockets: Attaches zerg to a zerg server.
:param bool use_fallback_socket: Fallback to normal sockets if the zerg server is not available
### Response:
def set_zerg... |
def plot_featured(*args, **kwargs):
"""
Wrapper for matplotlib.pyplot.plot() / errorbar().
Takes options:
* 'error': if true, use :func:`matplotlib.pyplot.errorbar` instead of :func:`matplotlib.pyplot.plot`. *\*args* and *\*\*kwargs* passed through here.
* 'fig': figure to use.
* 'figlabel': f... | Wrapper for matplotlib.pyplot.plot() / errorbar().
Takes options:
* 'error': if true, use :func:`matplotlib.pyplot.errorbar` instead of :func:`matplotlib.pyplot.plot`. *\*args* and *\*\*kwargs* passed through here.
* 'fig': figure to use.
* 'figlabel': figure label.
* 'legend': legend location.
... | Below is the the instruction that describes the task:
### Input:
Wrapper for matplotlib.pyplot.plot() / errorbar().
Takes options:
* 'error': if true, use :func:`matplotlib.pyplot.errorbar` instead of :func:`matplotlib.pyplot.plot`. *\*args* and *\*\*kwargs* passed through here.
* 'fig': figure to use... |
def supports_version_type(self, version_type):
"""Tests if the given version type is supported.
arg: version_type (osid.type.Type): a version Type
return: (boolean) - ``true`` if the type is supported, ``false``
otherwise
raise: IllegalState - syntax is not a ``VERSI... | Tests if the given version type is supported.
arg: version_type (osid.type.Type): a version Type
return: (boolean) - ``true`` if the type is supported, ``false``
otherwise
raise: IllegalState - syntax is not a ``VERSION``
raise: NullArgument - ``version_type`` is ``... | Below is the the instruction that describes the task:
### Input:
Tests if the given version type is supported.
arg: version_type (osid.type.Type): a version Type
return: (boolean) - ``true`` if the type is supported, ``false``
otherwise
raise: IllegalState - syntax is no... |
def save_config(
self,
cmd="copy running-configuration startup-configuration",
confirm=False,
confirm_response="",
):
"""Saves Config"""
return super(DellForce10SSH, self).save_config(
cmd=cmd, confirm=confirm, confirm_response=confirm_response
) | Saves Config | Below is the the instruction that describes the task:
### Input:
Saves Config
### Response:
def save_config(
self,
cmd="copy running-configuration startup-configuration",
confirm=False,
confirm_response="",
):
"""Saves Config"""
return super(DellForce10SSH, self)... |
def _broadcast_and_set_attrs(self, local_dict):
"""Cast all inputs to correct dimensions.
This method fixes inputs who have different lengths. Namely one input as
an array and others that are scalara or of len-1.
Raises:
Value Error: Multiple length arrays of len>1
... | Cast all inputs to correct dimensions.
This method fixes inputs who have different lengths. Namely one input as
an array and others that are scalara or of len-1.
Raises:
Value Error: Multiple length arrays of len>1 | Below is the the instruction that describes the task:
### Input:
Cast all inputs to correct dimensions.
This method fixes inputs who have different lengths. Namely one input as
an array and others that are scalara or of len-1.
Raises:
Value Error: Multiple length arrays of len>... |
def inv_slots_preferred(self):
"""
List of all available inventory slots in the preferred search order.
Does not include the additional slots from the open window.
1. active slot
2. remainder of the hotbar
3. remainder of the persistent inventory
"""
slot... | List of all available inventory slots in the preferred search order.
Does not include the additional slots from the open window.
1. active slot
2. remainder of the hotbar
3. remainder of the persistent inventory | Below is the the instruction that describes the task:
### Input:
List of all available inventory slots in the preferred search order.
Does not include the additional slots from the open window.
1. active slot
2. remainder of the hotbar
3. remainder of the persistent inventory
### Re... |
def generate(self, x, **kwargs):
"""
Returns the graph for Fast Gradient Method adversarial examples.
:param x: The model's symbolic inputs.
:param kwargs: See `parse_params`
"""
# Parse and save attack-specific parameters
assert self.parse_params(**kwargs)
labels, _nb_classes = self.g... | Returns the graph for Fast Gradient Method adversarial examples.
:param x: The model's symbolic inputs.
:param kwargs: See `parse_params` | Below is the the instruction that describes the task:
### Input:
Returns the graph for Fast Gradient Method adversarial examples.
:param x: The model's symbolic inputs.
:param kwargs: See `parse_params`
### Response:
def generate(self, x, **kwargs):
"""
Returns the graph for Fast Gradient Method a... |
def setup(cls, client_id, client_secret):
"""Configure client in session
"""
cls.client_id = client_id
cls.client_secret = client_secret | Configure client in session | Below is the the instruction that describes the task:
### Input:
Configure client in session
### Response:
def setup(cls, client_id, client_secret):
"""Configure client in session
"""
cls.client_id = client_id
cls.client_secret = client_secret |
def addNamespace(self, namespace, **context):
"""
Creates a new namespace within this database.
:param namespace: <str>
"""
self.connection().addNamespace(namespace, orb.Context(**context)) | Creates a new namespace within this database.
:param namespace: <str> | Below is the the instruction that describes the task:
### Input:
Creates a new namespace within this database.
:param namespace: <str>
### Response:
def addNamespace(self, namespace, **context):
"""
Creates a new namespace within this database.
:param namespace: <str>
"""
... |
def FALSE(classical_reg):
"""
Produce a FALSE instruction.
:param classical_reg: A classical register to modify.
:return: An instruction object representing the equivalent MOVE.
"""
warn("`FALSE a` has been deprecated. Use `MOVE a 0` instead.")
if isinstance(classical_reg, int):
cla... | Produce a FALSE instruction.
:param classical_reg: A classical register to modify.
:return: An instruction object representing the equivalent MOVE. | Below is the the instruction that describes the task:
### Input:
Produce a FALSE instruction.
:param classical_reg: A classical register to modify.
:return: An instruction object representing the equivalent MOVE.
### Response:
def FALSE(classical_reg):
"""
Produce a FALSE instruction.
:param ... |
def wait(self):
""" Waits for the pool to be fully stopped """
while True:
if not self.greenlet_watch:
break
if self.stopping:
gevent.sleep(0.1)
else:
gevent.sleep(1) | Waits for the pool to be fully stopped | Below is the the instruction that describes the task:
### Input:
Waits for the pool to be fully stopped
### Response:
def wait(self):
""" Waits for the pool to be fully stopped """
while True:
if not self.greenlet_watch:
break
if self.stopping:
... |
def parse(bin_payload):
"""
Interpret a block's nulldata back into a SHA256. The first three bytes (2 magic + 1 opcode)
will not be present in bin_payload.
"""
message_hash = hexlify(bin_payload)
if not is_hex( message_hash ):
log.warning("Not a message hash")
return No... | Interpret a block's nulldata back into a SHA256. The first three bytes (2 magic + 1 opcode)
will not be present in bin_payload. | Below is the the instruction that describes the task:
### Input:
Interpret a block's nulldata back into a SHA256. The first three bytes (2 magic + 1 opcode)
will not be present in bin_payload.
### Response:
def parse(bin_payload):
"""
Interpret a block's nulldata back into a SHA256. The first thr... |
def delete_contribution(self, url):
"""Delete the contribution with this identifier
:rtype: bool
:returns: True if the contribution was deleted, False otherwise (eg. if it didn't exist)
"""
# first validate that this is a real contrib
try:
result = self.api_... | Delete the contribution with this identifier
:rtype: bool
:returns: True if the contribution was deleted, False otherwise (eg. if it didn't exist) | Below is the the instruction that describes the task:
### Input:
Delete the contribution with this identifier
:rtype: bool
:returns: True if the contribution was deleted, False otherwise (eg. if it didn't exist)
### Response:
def delete_contribution(self, url):
"""Delete the contribution w... |
def _resolve_squash_cache(self, client):
"""
Currently doing a "squash" basically negates the cache for any subsequent layers.
But we can work around this by A) checking if the cache was successful for the _unsquashed_
version of the image, and B) if so, re-using an older squashed versio... | Currently doing a "squash" basically negates the cache for any subsequent layers.
But we can work around this by A) checking if the cache was successful for the _unsquashed_
version of the image, and B) if so, re-using an older squashed version of the image.
Three ways to do this:
1... | Below is the the instruction that describes the task:
### Input:
Currently doing a "squash" basically negates the cache for any subsequent layers.
But we can work around this by A) checking if the cache was successful for the _unsquashed_
version of the image, and B) if so, re-using an older squashe... |
def discover(name, wait_for_s=60):
"""Discover a service by name
Look for an advert to a named service::
address = nw0.discover("myservice")
:param name: any text
:param wait_for_s: how many seconds to wait before giving up
:returns: the address found or None
"""
_... | Discover a service by name
Look for an advert to a named service::
address = nw0.discover("myservice")
:param name: any text
:param wait_for_s: how many seconds to wait before giving up
:returns: the address found or None | Below is the the instruction that describes the task:
### Input:
Discover a service by name
Look for an advert to a named service::
address = nw0.discover("myservice")
:param name: any text
:param wait_for_s: how many seconds to wait before giving up
:returns: the address ... |
def collect_bin_data(ruptures, sitecol, cmaker, iml4,
truncation_level, n_epsilons, monitor=Monitor()):
"""
:param ruptures: a list of ruptures
:param sitecol: a SiteCollection instance
:param cmaker: a ContextMaker instance
:param iml4: an ArrayWrapper of intensities of shape (... | :param ruptures: a list of ruptures
:param sitecol: a SiteCollection instance
:param cmaker: a ContextMaker instance
:param iml4: an ArrayWrapper of intensities of shape (N, R, M, P)
:param truncation_level: the truncation level
:param n_epsilons: the number of epsilons
:param monitor: a Monitor... | Below is the the instruction that describes the task:
### Input:
:param ruptures: a list of ruptures
:param sitecol: a SiteCollection instance
:param cmaker: a ContextMaker instance
:param iml4: an ArrayWrapper of intensities of shape (N, R, M, P)
:param truncation_level: the truncation level
:p... |
def parse_args():
"""Parse arguments."""
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
description='Diagnose script for checking the current system.')
choices = ['python', 'pip', 'mxnet', 'os', 'hardware', 'network']
for choice in choices:
... | Parse arguments. | Below is the the instruction that describes the task:
### Input:
Parse arguments.
### Response:
def parse_args():
"""Parse arguments."""
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
description='Diagnose script for checking the current system.')
... |
def args(parsed_args, name=None):
"""Interpret parsed args to streams"""
strings = parsed_args.arg_strings(name)
files = [s for s in strings if os.path.isfile(s)]
if files:
streams = [open(f) for f in files]
else:
streams = []
if getattr(parsed_args, 'paste', not files):
... | Interpret parsed args to streams | Below is the the instruction that describes the task:
### Input:
Interpret parsed args to streams
### Response:
def args(parsed_args, name=None):
"""Interpret parsed args to streams"""
strings = parsed_args.arg_strings(name)
files = [s for s in strings if os.path.isfile(s)]
if files:
stream... |
def killCells(self, percent=0.05):
"""
Changes the percentage of cells that are now considered dead. The first
time you call this method a permutation list is set up. Calls change the
number of cells considered dead.
"""
numColumns = numpy.prod(self.getColumnDimensions())
if self.zombiePerm... | Changes the percentage of cells that are now considered dead. The first
time you call this method a permutation list is set up. Calls change the
number of cells considered dead. | Below is the the instruction that describes the task:
### Input:
Changes the percentage of cells that are now considered dead. The first
time you call this method a permutation list is set up. Calls change the
number of cells considered dead.
### Response:
def killCells(self, percent=0.05):
"""
Cha... |
def post(self, request, hook_id):
"""
Process Kik webhook:
1. Get an enabled Kik bot
2. Verify Kik signature
3. Serialize each message
4. For each message create :class:`KikMessage <permabots.models.kik_api.KikMessage>` and :class:`KikUser <permabots.model... | Process Kik webhook:
1. Get an enabled Kik bot
2. Verify Kik signature
3. Serialize each message
4. For each message create :class:`KikMessage <permabots.models.kik_api.KikMessage>` and :class:`KikUser <permabots.models.kik_api.KikUser>`
5. Delay each message ... | Below is the the instruction that describes the task:
### Input:
Process Kik webhook:
1. Get an enabled Kik bot
2. Verify Kik signature
3. Serialize each message
4. For each message create :class:`KikMessage <permabots.models.kik_api.KikMessage>` and :class:`KikUser <... |
def on_close(self, evt):
"""
Pop-up menu and wx.EVT_CLOSE closing event
"""
self.stop() # DoseWatcher
if evt.EventObject is not self: # Avoid deadlocks
self.Close() # wx.Frame
evt.Skip() | Pop-up menu and wx.EVT_CLOSE closing event | Below is the the instruction that describes the task:
### Input:
Pop-up menu and wx.EVT_CLOSE closing event
### Response:
def on_close(self, evt):
"""
Pop-up menu and wx.EVT_CLOSE closing event
"""
self.stop() # DoseWatcher
if evt.EventObject is not self: # Avoid deadlocks
self.Close() # ... |
def versatile_options():
"""return list of options that can be changed at any time (not
only be initialized), however the list might not be entirely up
to date.
The string ' #v ' in the default value indicates a 'versatile'
option that can be changed any time.
"""
... | return list of options that can be changed at any time (not
only be initialized), however the list might not be entirely up
to date.
The string ' #v ' in the default value indicates a 'versatile'
option that can be changed any time. | Below is the the instruction that describes the task:
### Input:
return list of options that can be changed at any time (not
only be initialized), however the list might not be entirely up
to date.
The string ' #v ' in the default value indicates a 'versatile'
option that can be cha... |
def _do_weak_search(self, obj, recursive):
"""Search for an element that looks like *obj* within the node list.
This follows the same rules as :meth:`_do_strong_search` with some
differences. *obj* is treated as a string that might represent any
:class:`.Node`, :class:`.Wikicode`, or co... | Search for an element that looks like *obj* within the node list.
This follows the same rules as :meth:`_do_strong_search` with some
differences. *obj* is treated as a string that might represent any
:class:`.Node`, :class:`.Wikicode`, or combination of the two present
in the node list.... | Below is the the instruction that describes the task:
### Input:
Search for an element that looks like *obj* within the node list.
This follows the same rules as :meth:`_do_strong_search` with some
differences. *obj* is treated as a string that might represent any
:class:`.Node`, :class:`.W... |
def NewFromContent(cls,
content,
urn,
chunk_size=1024,
token=None,
private_key=None,
public_key=None):
"""Alternate constructor for GRRSignedBlob.
Creates a GRRSignedBlob from a content... | Alternate constructor for GRRSignedBlob.
Creates a GRRSignedBlob from a content string by chunking it and signing
each chunk.
Args:
content: The data to stored in the GRRSignedBlob.
urn: The AFF4 URN to create.
chunk_size: Data will be chunked into this size (each chunk is
indiv... | Below is the the instruction that describes the task:
### Input:
Alternate constructor for GRRSignedBlob.
Creates a GRRSignedBlob from a content string by chunking it and signing
each chunk.
Args:
content: The data to stored in the GRRSignedBlob.
urn: The AFF4 URN to create.
chunk_s... |
def _ParseLeak(
self, parser_mediator, cache_directories, msiecf_item, recovered=False):
"""Extract data from a MSIE Cache Files (MSIECF) leak item.
Every item is stored as an event object, one for each timestamp.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
... | Extract data from a MSIE Cache Files (MSIECF) leak item.
Every item is stored as an event object, one for each timestamp.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
cache_directories (list[str]): cache di... | Below is the the instruction that describes the task:
### Input:
Extract data from a MSIE Cache Files (MSIECF) leak item.
Every item is stored as an event object, one for each timestamp.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, suc... |
def sprite(map, sprite, offset_x=None, offset_y=None, cache_buster=True):
"""
Returns the image and background position for use in a single shorthand
property
"""
map = map.render()
sprite_maps = _get_cache('sprite_maps')
sprite_map = sprite_maps.get(map)
sprite_name = String.unquoted(sp... | Returns the image and background position for use in a single shorthand
property | Below is the the instruction that describes the task:
### Input:
Returns the image and background position for use in a single shorthand
property
### Response:
def sprite(map, sprite, offset_x=None, offset_y=None, cache_buster=True):
"""
Returns the image and background position for use in a single sho... |
def xml_to_metrics(xmlstr, object_type):
'''Converts xml response to service bus metrics objects
The xml format for MetricProperties
<entry>
<id>https://sbgm.windows.net/Metrics(\'listeners.active\')</id>
<title/>
<updated>2014-10-09T11:56:50Z</updated>
<author>
<name/>
</au... | Converts xml response to service bus metrics objects
The xml format for MetricProperties
<entry>
<id>https://sbgm.windows.net/Metrics(\'listeners.active\')</id>
<title/>
<updated>2014-10-09T11:56:50Z</updated>
<author>
<name/>
</author>
<content type="application/xml">
<... | Below is the the instruction that describes the task:
### Input:
Converts xml response to service bus metrics objects
The xml format for MetricProperties
<entry>
<id>https://sbgm.windows.net/Metrics(\'listeners.active\')</id>
<title/>
<updated>2014-10-09T11:56:50Z</updated>
<author>
... |
def listen_dataset_events(self, owner_id, project_id, dataset_id):
"""
Authenticate to start using dataset events.
"""
if not self._user_id:
raise AmigoCloudError(self.error_msg['logged_in_websockets'])
url = '/users/%s/projects/%s/datasets/%s/start_websocket_sessio... | Authenticate to start using dataset events. | Below is the the instruction that describes the task:
### Input:
Authenticate to start using dataset events.
### Response:
def listen_dataset_events(self, owner_id, project_id, dataset_id):
"""
Authenticate to start using dataset events.
"""
if not self._user_id:
raise ... |
def _get_action_from_method_and_request_uri(self, method, request_uri):
"""basically used for `rest-json` APIs
You can refer to example from link below
https://github.com/boto/botocore/blob/develop/botocore/data/iot/2015-05-28/service-2.json
"""
# service response class should h... | basically used for `rest-json` APIs
You can refer to example from link below
https://github.com/boto/botocore/blob/develop/botocore/data/iot/2015-05-28/service-2.json | Below is the the instruction that describes the task:
### Input:
basically used for `rest-json` APIs
You can refer to example from link below
https://github.com/boto/botocore/blob/develop/botocore/data/iot/2015-05-28/service-2.json
### Response:
def _get_action_from_method_and_request_uri(self, met... |
def perform(self):
"""
Performs a simple HTTP request against the configured url and returns
true if the response has a 2xx code.
The url can be configured to use https via the "https" boolean flag
in the config, as well as a custom HTTP method via the "method" key.
The... | Performs a simple HTTP request against the configured url and returns
true if the response has a 2xx code.
The url can be configured to use https via the "https" boolean flag
in the config, as well as a custom HTTP method via the "method" key.
The default is to not use https and the GE... | Below is the the instruction that describes the task:
### Input:
Performs a simple HTTP request against the configured url and returns
true if the response has a 2xx code.
The url can be configured to use https via the "https" boolean flag
in the config, as well as a custom HTTP method via ... |
def delete_tag_for_component(user, c_id, tag_id):
"""Delete a tag on a specific component."""
# Todo : check c_id and tag_id exist in db
query = _TABLE_TAGS.delete().where(_TABLE_TAGS.c.tag_id == tag_id and
_TABLE_TAGS.c.component_id == c_id)
try:
flask.g... | Delete a tag on a specific component. | Below is the the instruction that describes the task:
### Input:
Delete a tag on a specific component.
### Response:
def delete_tag_for_component(user, c_id, tag_id):
"""Delete a tag on a specific component."""
# Todo : check c_id and tag_id exist in db
query = _TABLE_TAGS.delete().where(_TABLE_TAGS.c... |
def basic_auth_required(view_func):
"""
A decorator that can be used to protect specific views with HTTP basic
access authentication. Conditional on having BASIC_AUTH_USERNAME and
BASIC_AUTH_PASSWORD set as env vars.
"""
@wraps(view_func)
def wrapper(*args, **kwargs):
if app.config.g... | A decorator that can be used to protect specific views with HTTP basic
access authentication. Conditional on having BASIC_AUTH_USERNAME and
BASIC_AUTH_PASSWORD set as env vars. | Below is the the instruction that describes the task:
### Input:
A decorator that can be used to protect specific views with HTTP basic
access authentication. Conditional on having BASIC_AUTH_USERNAME and
BASIC_AUTH_PASSWORD set as env vars.
### Response:
def basic_auth_required(view_func):
"""
A d... |
def van_enc_2d(x, first_depth, reuse=False):
"""The higher level structure encoder for the VAN.
The high level structure is a vector instead of an image.
Args:
x: The higher level structure to encode.
first_depth: The depth of the first layer. Depth is increased in subsequent
layers.
reuse: To... | The higher level structure encoder for the VAN.
The high level structure is a vector instead of an image.
Args:
x: The higher level structure to encode.
first_depth: The depth of the first layer. Depth is increased in subsequent
layers.
reuse: To reuse in variable scope or not.
Returns:
T... | Below is the the instruction that describes the task:
### Input:
The higher level structure encoder for the VAN.
The high level structure is a vector instead of an image.
Args:
x: The higher level structure to encode.
first_depth: The depth of the first layer. Depth is increased in subsequent
la... |
def _categorize_successor(self, state):
"""
Append state into successor lists.
:param state: a SimState instance
:param target: The target (of the jump/call/ret)
:return: The state
"""
self.all_successors.append(state)
target = state.scratch.target
... | Append state into successor lists.
:param state: a SimState instance
:param target: The target (of the jump/call/ret)
:return: The state | Below is the the instruction that describes the task:
### Input:
Append state into successor lists.
:param state: a SimState instance
:param target: The target (of the jump/call/ret)
:return: The state
### Response:
def _categorize_successor(self, state):
"""
Append state i... |
def _csr_to_sdf(self):
""" Inverse of _sdf_to_csr(). """
self.data = pd.DataFrame(self.data['values'].todense(),
index=self.data['index'],
columns=self.data['columns']).to_sparse() | Inverse of _sdf_to_csr(). | Below is the the instruction that describes the task:
### Input:
Inverse of _sdf_to_csr().
### Response:
def _csr_to_sdf(self):
""" Inverse of _sdf_to_csr(). """
self.data = pd.DataFrame(self.data['values'].todense(),
index=self.data['index'],
... |
def getNumberTLD():
"""
Counting the total number of TLD being processed.
"""
total = 0
for typeTld in TLD.keys():
total+= len(TLD[typeTld])
return total | Counting the total number of TLD being processed. | Below is the the instruction that describes the task:
### Input:
Counting the total number of TLD being processed.
### Response:
def getNumberTLD():
"""
Counting the total number of TLD being processed.
"""
total = 0
for typeTld in TLD.keys():
total+= len(TLD[typeTld])
return total |
def match(self, context, line):
"""Match code lines prefixed with a variety of keywords."""
return line.kind == 'code' and line.partitioned[0] in self._both | Match code lines prefixed with a variety of keywords. | Below is the the instruction that describes the task:
### Input:
Match code lines prefixed with a variety of keywords.
### Response:
def match(self, context, line):
"""Match code lines prefixed with a variety of keywords."""
return line.kind == 'code' and line.partitioned[0] in self._both |
def should_send(self, request):
"""Returns whether or not the request should be sent to the
modules, based on the filters."""
if self.filters.get('whitelist', None):
return request.tree.type in self.filters['whitelist']
elif self.filters.get('blacklist', None):
re... | Returns whether or not the request should be sent to the
modules, based on the filters. | Below is the the instruction that describes the task:
### Input:
Returns whether or not the request should be sent to the
modules, based on the filters.
### Response:
def should_send(self, request):
"""Returns whether or not the request should be sent to the
modules, based on the filters.""... |
def find_one(self, collection, query):
"""
Search a collection for the query provided and return one result. Just
a raw interface to mongo to do any query you want.
Args:
collection: The db collection. See main class documentation.
query: A mongo find query.
... | Search a collection for the query provided and return one result. Just
a raw interface to mongo to do any query you want.
Args:
collection: The db collection. See main class documentation.
query: A mongo find query.
Returns:
pymongo Cursor object with the res... | Below is the the instruction that describes the task:
### Input:
Search a collection for the query provided and return one result. Just
a raw interface to mongo to do any query you want.
Args:
collection: The db collection. See main class documentation.
query: A mongo find q... |
def handle_api_exception(f):
"""
A decorator to catch superset exceptions. Use it after the @api decorator above
so superset exception handler is triggered before the handler for generic exceptions.
"""
def wraps(self, *args, **kwargs):
try:
return f(self, *args, **kwargs)
... | A decorator to catch superset exceptions. Use it after the @api decorator above
so superset exception handler is triggered before the handler for generic exceptions. | Below is the the instruction that describes the task:
### Input:
A decorator to catch superset exceptions. Use it after the @api decorator above
so superset exception handler is triggered before the handler for generic exceptions.
### Response:
def handle_api_exception(f):
"""
A decorator to catch supe... |
def getContextsForExpression(self, body, getFingerprint=None, startIndex=0, maxResults=5, sparsity=1.0):
"""Get semantic contexts for the input expression
Args:
body, ExpressionOperation: The JSON encoded expression to be evaluated (required)
getFingerprint, bool: Configure if th... | Get semantic contexts for the input expression
Args:
body, ExpressionOperation: The JSON encoded expression to be evaluated (required)
getFingerprint, bool: Configure if the fingerprint should be returned as part of the results (optional)
startIndex, int: The start-index for ... | Below is the the instruction that describes the task:
### Input:
Get semantic contexts for the input expression
Args:
body, ExpressionOperation: The JSON encoded expression to be evaluated (required)
getFingerprint, bool: Configure if the fingerprint should be returned as part of the... |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'document_retrieval_strategy'
) and self.document_retrieval_strategy is not None:
_dict[
'document_retrieval_strategy'] = self.document_retrieval_... | Return a json dictionary representing this model. | Below is the the instruction that describes the task:
### Input:
Return a json dictionary representing this model.
### Response:
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'document_retrieval_strategy'
) and self... |
def _validate_int(name, value, limits=(), strip='%'):
'''
Validate the named integer within the supplied limits inclusive and
strip supplied unit characters
'''
comment = ''
# Must be integral
try:
if isinstance(value, string_types):
value = value.strip(' ' + strip)
... | Validate the named integer within the supplied limits inclusive and
strip supplied unit characters | Below is the the instruction that describes the task:
### Input:
Validate the named integer within the supplied limits inclusive and
strip supplied unit characters
### Response:
def _validate_int(name, value, limits=(), strip='%'):
'''
Validate the named integer within the supplied limits inclusive and... |
def build_command(self, action, args=None):
"""Build a SOAP request.
Args:
action (str): the name of an action (a string as specified in the
service description XML file) to be sent.
args (list, optional): Relevant arguments as a list of (name,
va... | Build a SOAP request.
Args:
action (str): the name of an action (a string as specified in the
service description XML file) to be sent.
args (list, optional): Relevant arguments as a list of (name,
value) tuples.
Returns:
tuple: a tup... | Below is the the instruction that describes the task:
### Input:
Build a SOAP request.
Args:
action (str): the name of an action (a string as specified in the
service description XML file) to be sent.
args (list, optional): Relevant arguments as a list of (name,
... |
def request(self, method, path, query=None, content=None):
"""
Sends an HTTP request.
This constructs a full URL, encodes and decodes HTTP bodies, and
handles invalid responses in a pythonic way.
@type method: string
@param method: HTTP method to use
@type path:... | Sends an HTTP request.
This constructs a full URL, encodes and decodes HTTP bodies, and
handles invalid responses in a pythonic way.
@type method: string
@param method: HTTP method to use
@type path: string
@param path: HTTP URL path
@type query: list of two-tup... | Below is the the instruction that describes the task:
### Input:
Sends an HTTP request.
This constructs a full URL, encodes and decodes HTTP bodies, and
handles invalid responses in a pythonic way.
@type method: string
@param method: HTTP method to use
@type path: string
... |
def register_view(self, view_class, *args, **kwargs):
"""Register an admin view on this admin instance.
:param view_class: The view class name passed to the view factory.
:param args: Positional arugments for view class.
:param kwargs: Keyword arguments to view class.
"""
... | Register an admin view on this admin instance.
:param view_class: The view class name passed to the view factory.
:param args: Positional arugments for view class.
:param kwargs: Keyword arguments to view class. | Below is the the instruction that describes the task:
### Input:
Register an admin view on this admin instance.
:param view_class: The view class name passed to the view factory.
:param args: Positional arugments for view class.
:param kwargs: Keyword arguments to view class.
### Response: ... |
def writeInfo(self, location=None, masters=None):
""" Write font into the current instance.
Note: the masters attribute is ignored at the moment.
"""
if self.currentInstance is None:
return
infoElement = ET.Element("info")
if location is not None:
... | Write font into the current instance.
Note: the masters attribute is ignored at the moment. | Below is the the instruction that describes the task:
### Input:
Write font into the current instance.
Note: the masters attribute is ignored at the moment.
### Response:
def writeInfo(self, location=None, masters=None):
""" Write font into the current instance.
Note: the masters at... |
def save_voxel_grid(voxel_grid, file_name):
""" Saves binary voxel grid as a binary file.
The binary file is structured in little-endian unsigned int format.
:param voxel_grid: binary voxel grid
:type voxel_grid: list, tuple
:param file_name: file name to save
:type file_name: str
"""
... | Saves binary voxel grid as a binary file.
The binary file is structured in little-endian unsigned int format.
:param voxel_grid: binary voxel grid
:type voxel_grid: list, tuple
:param file_name: file name to save
:type file_name: str | Below is the the instruction that describes the task:
### Input:
Saves binary voxel grid as a binary file.
The binary file is structured in little-endian unsigned int format.
:param voxel_grid: binary voxel grid
:type voxel_grid: list, tuple
:param file_name: file name to save
:type file_name:... |
def process_ubam(bam, **kwargs):
"""Extracting metrics from unaligned bam format
Extracting lengths
"""
logging.info("Nanoget: Starting to collect statistics from ubam file {}.".format(bam))
samfile = pysam.AlignmentFile(bam, "rb", check_sq=False)
if not samfile.has_index():
pysam.index(... | Extracting metrics from unaligned bam format
Extracting lengths | Below is the the instruction that describes the task:
### Input:
Extracting metrics from unaligned bam format
Extracting lengths
### Response:
def process_ubam(bam, **kwargs):
"""Extracting metrics from unaligned bam format
Extracting lengths
"""
logging.info("Nanoget: Starting to collect stati... |
def _binary_search(f, xmin, xmax, eps=1e-9):
"""Return the largest x such f(x) is True."""
middle = (xmax + xmin) / 2.
while xmax - xmin > eps:
assert xmin < xmax
middle = (xmax + xmin) / 2.
if f(xmax):
return xmax
if not f(xmin):
return xmin
i... | Return the largest x such f(x) is True. | Below is the the instruction that describes the task:
### Input:
Return the largest x such f(x) is True.
### Response:
def _binary_search(f, xmin, xmax, eps=1e-9):
"""Return the largest x such f(x) is True."""
middle = (xmax + xmin) / 2.
while xmax - xmin > eps:
assert xmin < xmax
middl... |
def _loadService(self, servicePath):
"""
Check if an application service can be found at the specified path.
If found, instantiate it and add it to the application service pool.
:param: <str> service file path
:return: <void>
"""
serviceName = ntpath.basename(ser... | Check if an application service can be found at the specified path.
If found, instantiate it and add it to the application service pool.
:param: <str> service file path
:return: <void> | Below is the the instruction that describes the task:
### Input:
Check if an application service can be found at the specified path.
If found, instantiate it and add it to the application service pool.
:param: <str> service file path
:return: <void>
### Response:
def _loadService(self, ser... |
def pushmem(self, data, size):
"""
Push block of memory to front of message, as a new frame.
Returns 0 on success, -1 on error.
"""
return lib.zmsg_pushmem(self._as_parameter_, data, size) | Push block of memory to front of message, as a new frame.
Returns 0 on success, -1 on error. | Below is the the instruction that describes the task:
### Input:
Push block of memory to front of message, as a new frame.
Returns 0 on success, -1 on error.
### Response:
def pushmem(self, data, size):
"""
Push block of memory to front of message, as a new frame.
Returns 0 on success, -1 on error.... |
def parse_uniprot_xml_metadata(sr):
"""Load relevant attributes and dbxrefs from a parsed UniProt XML file in a SeqRecord.
Returns:
dict: All parsed information
"""
# TODO: What about "reviewed" status? and EC number
xref_dbs_to_keep = ['GO', 'KEGG', 'PDB', 'PROSITE', 'Pfam', 'RefSeq']
... | Load relevant attributes and dbxrefs from a parsed UniProt XML file in a SeqRecord.
Returns:
dict: All parsed information | Below is the the instruction that describes the task:
### Input:
Load relevant attributes and dbxrefs from a parsed UniProt XML file in a SeqRecord.
Returns:
dict: All parsed information
### Response:
def parse_uniprot_xml_metadata(sr):
"""Load relevant attributes and dbxrefs from a parsed UniProt... |
def allDayForDate(self,this_date,timeZone=None):
'''
This method determines whether the occurrence lasts the entirety of
a specified day in the specified time zone. If no time zone is specified,
then it uses the default time zone). Also, give a grace period of a few
minutes to ... | This method determines whether the occurrence lasts the entirety of
a specified day in the specified time zone. If no time zone is specified,
then it uses the default time zone). Also, give a grace period of a few
minutes to account for issues with the way events are sometimes entered. | Below is the the instruction that describes the task:
### Input:
This method determines whether the occurrence lasts the entirety of
a specified day in the specified time zone. If no time zone is specified,
then it uses the default time zone). Also, give a grace period of a few
minutes to ... |
def register (self, target):
""" Registers a new virtual target. Checks if there's already registered target, with the same
name, type, project and subvariant properties, and also with the same sources
and equal action. If such target is found it is retured and 'target' is not registered... | Registers a new virtual target. Checks if there's already registered target, with the same
name, type, project and subvariant properties, and also with the same sources
and equal action. If such target is found it is retured and 'target' is not registered.
Otherwise, 'target' is regi... | Below is the the instruction that describes the task:
### Input:
Registers a new virtual target. Checks if there's already registered target, with the same
name, type, project and subvariant properties, and also with the same sources
and equal action. If such target is found it is retured an... |
def csep_periodic(ra, rb, L):
"""Return separation vectors between each pair of the two sets of points.
Parameters
----------
ra, rb: float array-like, shape (n, d) and (m, d) in d dimensions.
Two sets of points.
L: float array, shape (d,)
System lengths.
Returns
-------
... | Return separation vectors between each pair of the two sets of points.
Parameters
----------
ra, rb: float array-like, shape (n, d) and (m, d) in d dimensions.
Two sets of points.
L: float array, shape (d,)
System lengths.
Returns
-------
csep: float array-like, shape (n, m... | Below is the the instruction that describes the task:
### Input:
Return separation vectors between each pair of the two sets of points.
Parameters
----------
ra, rb: float array-like, shape (n, d) and (m, d) in d dimensions.
Two sets of points.
L: float array, shape (d,)
System leng... |
def decode_key(cls, pubkey_content):
"""Decode base64 coded part of the key."""
try:
decoded_key = base64.b64decode(pubkey_content.encode("ascii"))
except (TypeError, binascii.Error):
raise MalformedDataError("Unable to decode the key")
return decoded_key | Decode base64 coded part of the key. | Below is the the instruction that describes the task:
### Input:
Decode base64 coded part of the key.
### Response:
def decode_key(cls, pubkey_content):
"""Decode base64 coded part of the key."""
try:
decoded_key = base64.b64decode(pubkey_content.encode("ascii"))
except (TypeErr... |
def move_in_8(library, session, space, offset, length, extended=False):
"""Moves an 8-bit block of data from the specified address space and offset to local memory.
Corresponds to viMoveIn8* functions of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logic... | Moves an 8-bit block of data from the specified address space and offset to local memory.
Corresponds to viMoveIn8* functions of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param space: Specifies the address space. (Con... | Below is the the instruction that describes the task:
### Input:
Moves an 8-bit block of data from the specified address space and offset to local memory.
Corresponds to viMoveIn8* functions of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identif... |
def get_full_dir_name(self):
"""
Function returns a full dir name
"""
return os.path.join(self.dir_name.get_text(), self.entry_project_name.get_text()) | Function returns a full dir name | Below is the the instruction that describes the task:
### Input:
Function returns a full dir name
### Response:
def get_full_dir_name(self):
"""
Function returns a full dir name
"""
return os.path.join(self.dir_name.get_text(), self.entry_project_name.get_text()) |
def dm_to_sd(dm):
'''
Converts a geographic co-ordinate given in "degrees/minutes" dddmm.mmmm
format (eg, "12319.943281" = 123 degrees, 19.943281 minutes) to a signed
decimal (python float) format
'''
# '12319.943281'
if not dm or dm == '0':
return 0.
d, m = re.match(r'^... | Converts a geographic co-ordinate given in "degrees/minutes" dddmm.mmmm
format (eg, "12319.943281" = 123 degrees, 19.943281 minutes) to a signed
decimal (python float) format | Below is the the instruction that describes the task:
### Input:
Converts a geographic co-ordinate given in "degrees/minutes" dddmm.mmmm
format (eg, "12319.943281" = 123 degrees, 19.943281 minutes) to a signed
decimal (python float) format
### Response:
def dm_to_sd(dm):
'''
Converts a geograph... |
def _get_variable(vid, variables):
"""Retrieve an input variable from our existing pool of options.
"""
if isinstance(vid, six.string_types):
vid = get_base_id(vid)
else:
vid = _get_string_vid(vid)
for v in variables:
if vid == get_base_id(v["id"]):
return copy.de... | Retrieve an input variable from our existing pool of options. | Below is the the instruction that describes the task:
### Input:
Retrieve an input variable from our existing pool of options.
### Response:
def _get_variable(vid, variables):
"""Retrieve an input variable from our existing pool of options.
"""
if isinstance(vid, six.string_types):
vid = get_ba... |
def _default_format(self, occur):
"""Return the default serialization format."""
if self.text or self.children:
return self.start_tag() + "%s" + self.end_tag()
return self.start_tag(empty=True) | Return the default serialization format. | Below is the the instruction that describes the task:
### Input:
Return the default serialization format.
### Response:
def _default_format(self, occur):
"""Return the default serialization format."""
if self.text or self.children:
return self.start_tag() + "%s" + self.end_tag()
... |
def _get_fit_params(self, x, fit_key):
""" Transforms the input parameter to fit parameters for the 7dq2 model.
That is, maps from
x = [q, chiAx, chiAy, chiAz, chiBx, chiBy, chiBz]
fit_params = [np.log(q), chiAx, chiAy, chiHat, chiBx, chiBy, chi_a]
chiHat is defined in Eq.(3) of 1508.07253, but... | Transforms the input parameter to fit parameters for the 7dq2 model.
That is, maps from
x = [q, chiAx, chiAy, chiAz, chiBx, chiBy, chiBz]
fit_params = [np.log(q), chiAx, chiAy, chiHat, chiBx, chiBy, chi_a]
chiHat is defined in Eq.(3) of 1508.07253, but with chiAz and chiBz instead
of chiA and chiB.... | Below is the the instruction that describes the task:
### Input:
Transforms the input parameter to fit parameters for the 7dq2 model.
That is, maps from
x = [q, chiAx, chiAy, chiAz, chiBx, chiBy, chiBz]
fit_params = [np.log(q), chiAx, chiAy, chiHat, chiBx, chiBy, chi_a]
chiHat is defined in Eq.(3) ... |
def renderHTTP(self, context):
"""
Render the wrapped resource if HTTPS is already being used, otherwise
invoke a helper which may generate a redirect.
"""
request = IRequest(context)
if request.isSecure():
renderer = self.wrappedResource
else:
... | Render the wrapped resource if HTTPS is already being used, otherwise
invoke a helper which may generate a redirect. | Below is the the instruction that describes the task:
### Input:
Render the wrapped resource if HTTPS is already being used, otherwise
invoke a helper which may generate a redirect.
### Response:
def renderHTTP(self, context):
"""
Render the wrapped resource if HTTPS is already being used, ... |
def update(self, E=None, **F):
"""
D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
If E present and has a .keys() method, does: for k in E: D[k] = E[k]
If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v
In either case, this is followe... | D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
If E present and has a .keys() method, does: for k in E: D[k] = E[k]
If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v
In either case, this is followed by: for k in F: D[k] = F[k] | Below is the the instruction that describes the task:
### Input:
D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
If E present and has a .keys() method, does: for k in E: D[k] = E[k]
If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v
In either cas... |
def segmentlistdict_fromsearchsummary_out(xmldoc, program = None):
"""
Convenience wrapper for a common case usage of the segmentlistdict
class: searches the process table in xmldoc for occurances of a
program named program, then scans the search summary table for
matching process IDs and constructs a segmentlist... | Convenience wrapper for a common case usage of the segmentlistdict
class: searches the process table in xmldoc for occurances of a
program named program, then scans the search summary table for
matching process IDs and constructs a segmentlistdict object from
the out segments in those rows.
Note: the segmentlis... | Below is the the instruction that describes the task:
### Input:
Convenience wrapper for a common case usage of the segmentlistdict
class: searches the process table in xmldoc for occurances of a
program named program, then scans the search summary table for
matching process IDs and constructs a segmentlistdict... |
def _compute_ll(self):
"""
m._compute_ll() -- [utility] Compute the log-likelihood matrix from the count matrix
"""
self.fracs = []
self.logP = []
self.ll = []
for i in range(self.width):
Dll = {'A': 0, 'C': 0, 'T': 0, 'G': 0}
Df = {... | m._compute_ll() -- [utility] Compute the log-likelihood matrix from the count matrix | Below is the the instruction that describes the task:
### Input:
m._compute_ll() -- [utility] Compute the log-likelihood matrix from the count matrix
### Response:
def _compute_ll(self):
"""
m._compute_ll() -- [utility] Compute the log-likelihood matrix from the count matrix
"""
sel... |
def get_followers(self, auth_secret):
"""Get the follower list of a logged-in user.
Parameters
----------
auth_secret: str
The authentication secret of the logged-in user.
Returns
-------
bool
True if the follower list is successfully obt... | Get the follower list of a logged-in user.
Parameters
----------
auth_secret: str
The authentication secret of the logged-in user.
Returns
-------
bool
True if the follower list is successfully obtained, False otherwise.
result
... | Below is the the instruction that describes the task:
### Input:
Get the follower list of a logged-in user.
Parameters
----------
auth_secret: str
The authentication secret of the logged-in user.
Returns
-------
bool
True if the follower list... |
def adjust_cells(self):
"""Adjust column size based on contents."""
self.resizeColumnsToContents()
fm = self.horizontalHeader().fontMetrics()
names = [fm.width(s.name + ' '*9) for s in self.source_model.shortcuts]
self.setColumnWidth(NAME, max(names))
self.horizonta... | Adjust column size based on contents. | Below is the the instruction that describes the task:
### Input:
Adjust column size based on contents.
### Response:
def adjust_cells(self):
"""Adjust column size based on contents."""
self.resizeColumnsToContents()
fm = self.horizontalHeader().fontMetrics()
names = [fm.width(s.... |
def _check_db_exists(self, instance):
"""
Check if the database we're targeting actually exists
If not then we won't do any checks
This allows the same config to be installed on many servers but fail gracefully
"""
dsn, host, username, password, database, driver = self._... | Check if the database we're targeting actually exists
If not then we won't do any checks
This allows the same config to be installed on many servers but fail gracefully | Below is the the instruction that describes the task:
### Input:
Check if the database we're targeting actually exists
If not then we won't do any checks
This allows the same config to be installed on many servers but fail gracefully
### Response:
def _check_db_exists(self, instance):
"""
... |
def com_google_fonts_check_maxadvancewidth(ttFont):
"""MaxAdvanceWidth is consistent with values in the Hmtx and Hhea tables?"""
hhea_advance_width_max = ttFont['hhea'].advanceWidthMax
hmtx_advance_width_max = None
for g in ttFont['hmtx'].metrics.values():
if hmtx_advance_width_max is None:
hmtx_advan... | MaxAdvanceWidth is consistent with values in the Hmtx and Hhea tables? | Below is the the instruction that describes the task:
### Input:
MaxAdvanceWidth is consistent with values in the Hmtx and Hhea tables?
### Response:
def com_google_fonts_check_maxadvancewidth(ttFont):
"""MaxAdvanceWidth is consistent with values in the Hmtx and Hhea tables?"""
hhea_advance_width_max = ttFont[... |
async def setViewLayers(self, layers, iden=None):
'''
Args:
layers ([str]): A top-down list of of layer guids
iden (str): The view iden ( defaults to default view ).
'''
if iden is None:
iden = self.iden
view = self.views.get(iden)
if ... | Args:
layers ([str]): A top-down list of of layer guids
iden (str): The view iden ( defaults to default view ). | Below is the the instruction that describes the task:
### Input:
Args:
layers ([str]): A top-down list of of layer guids
iden (str): The view iden ( defaults to default view ).
### Response:
async def setViewLayers(self, layers, iden=None):
'''
Args:
layers ([str... |
def to_json(self):
"""
Returns the JSON Representation of the UI extension.
"""
result = super(UIExtension, self).to_json()
result.update({
'extension': self.extension
})
return result | Returns the JSON Representation of the UI extension. | Below is the the instruction that describes the task:
### Input:
Returns the JSON Representation of the UI extension.
### Response:
def to_json(self):
"""
Returns the JSON Representation of the UI extension.
"""
result = super(UIExtension, self).to_json()
result.update({
... |
def settle(
self,
transferred_amount: TokenAmount,
locked_amount: TokenAmount,
locksroot: Locksroot,
partner_transferred_amount: TokenAmount,
partner_locked_amount: TokenAmount,
partner_locksroot: Locksroot,
block_identifier... | Settles the channel. | Below is the the instruction that describes the task:
### Input:
Settles the channel.
### Response:
def settle(
self,
transferred_amount: TokenAmount,
locked_amount: TokenAmount,
locksroot: Locksroot,
partner_transferred_amount: TokenAmount,
p... |
def get_changelog(project_dir=os.curdir, bugtracker_url='', rpm_format=False):
"""
Retrieves the changelog, from the CHANGELOG file (if in a package) or
generates it from the git history. Optionally in rpm-compatible format.
:param project_dir: Path to the git repo of the project.
:type project_dir... | Retrieves the changelog, from the CHANGELOG file (if in a package) or
generates it from the git history. Optionally in rpm-compatible format.
:param project_dir: Path to the git repo of the project.
:type project_dir: str
:param bugtracker_url: Url to the bug tracker for the issues.
:type bugtracke... | Below is the the instruction that describes the task:
### Input:
Retrieves the changelog, from the CHANGELOG file (if in a package) or
generates it from the git history. Optionally in rpm-compatible format.
:param project_dir: Path to the git repo of the project.
:type project_dir: str
:param bugtr... |
def get_queue_settings(self, project_key):
"""
Get queue settings on project
:param project_key: str
:return:
"""
url = 'rest/servicedeskapi/queues/{}'.format(project_key)
return self.get(url, headers=self.experimental_headers) | Get queue settings on project
:param project_key: str
:return: | Below is the the instruction that describes the task:
### Input:
Get queue settings on project
:param project_key: str
:return:
### Response:
def get_queue_settings(self, project_key):
"""
Get queue settings on project
:param project_key: str
:return:
"""
... |
def prepare_duplicate_order_object(manager, origin_volume, iops, tier,
duplicate_size, duplicate_snapshot_size,
volume_type, hourly_billing_flag=False):
"""Prepare the duplicate order to submit to SoftLayer_Product::placeOrder()
:param manag... | Prepare the duplicate order to submit to SoftLayer_Product::placeOrder()
:param manager: The File or Block manager calling this function
:param origin_volume: The origin volume which is being duplicated
:param iops: The IOPS for the duplicate volume (performance)
:param tier: The tier level for the dup... | Below is the the instruction that describes the task:
### Input:
Prepare the duplicate order to submit to SoftLayer_Product::placeOrder()
:param manager: The File or Block manager calling this function
:param origin_volume: The origin volume which is being duplicated
:param iops: The IOPS for the dupli... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.