code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def _set_amz_headers(self):
"""
Sets x-amz-* error response fields from response headers.
"""
if self._response.headers:
# keeping x-amz-id-2 as part of amz_host_id.
if 'x-amz-id-2' in self._response.headers:
self.host_id = self._response.headers['... | Sets x-amz-* error response fields from response headers. | Below is the the instruction that describes the task:
### Input:
Sets x-amz-* error response fields from response headers.
### Response:
def _set_amz_headers(self):
"""
Sets x-amz-* error response fields from response headers.
"""
if self._response.headers:
# keeping x-a... |
def _build_likelihood(self):
"""
Construct a tensorflow function to compute the bound on the marginal
likelihood.
"""
pX = DiagonalGaussian(self.X_mean, self.X_var)
num_inducing = len(self.feature)
psi0 = tf.reduce_sum(expectation(pX, self.kern))
psi1 = e... | Construct a tensorflow function to compute the bound on the marginal
likelihood. | Below is the the instruction that describes the task:
### Input:
Construct a tensorflow function to compute the bound on the marginal
likelihood.
### Response:
def _build_likelihood(self):
"""
Construct a tensorflow function to compute the bound on the marginal
likelihood.
"... |
def list(self, request, project):
''' Routing to /api/project/{project}/seta/job-priorities/
This API can potentially have these consumers:
* Buildbot
* build_system_type=buildbot
* priority=5
* format=json
* TaskCluster (Gecko decision ... | Routing to /api/project/{project}/seta/job-priorities/
This API can potentially have these consumers:
* Buildbot
* build_system_type=buildbot
* priority=5
* format=json
* TaskCluster (Gecko decision task)
* build_system_type=taskcl... | Below is the the instruction that describes the task:
### Input:
Routing to /api/project/{project}/seta/job-priorities/
This API can potentially have these consumers:
* Buildbot
* build_system_type=buildbot
* priority=5
* format=json
* TaskC... |
def compress_dir(path, compression="gz"):
"""
Recursively compresses all files in a directory. Note that this
compresses all files singly, i.e., it does not create a tar archive. For
that, just use Python tarfile class.
Args:
path (str): Path to parent directory.
compression (str): ... | Recursively compresses all files in a directory. Note that this
compresses all files singly, i.e., it does not create a tar archive. For
that, just use Python tarfile class.
Args:
path (str): Path to parent directory.
compression (str): A compression mode. Valid options are "gz" or
... | Below is the the instruction that describes the task:
### Input:
Recursively compresses all files in a directory. Note that this
compresses all files singly, i.e., it does not create a tar archive. For
that, just use Python tarfile class.
Args:
path (str): Path to parent directory.
comp... |
def soft_triplet_loss(anchor, positive, negative, extra=True, scope="soft_triplet_loss"):
r"""Loss for triplet networks as described in the paper:
`Deep Metric Learning using Triplet Network
<https://arxiv.org/abs/1412.6622>`_ by Hoffer et al.
It is a softmax loss using :math:`(anchor-positive)^2` and
... | r"""Loss for triplet networks as described in the paper:
`Deep Metric Learning using Triplet Network
<https://arxiv.org/abs/1412.6622>`_ by Hoffer et al.
It is a softmax loss using :math:`(anchor-positive)^2` and
:math:`(anchor-negative)^2` as logits.
Args:
anchor (tf.Tensor): anchor featu... | Below is the the instruction that describes the task:
### Input:
r"""Loss for triplet networks as described in the paper:
`Deep Metric Learning using Triplet Network
<https://arxiv.org/abs/1412.6622>`_ by Hoffer et al.
It is a softmax loss using :math:`(anchor-positive)^2` and
:math:`(anchor-negati... |
def get(self):
"""
Return the HTTP code status.
:return: The matched and formatted status code.
:rtype: str|int|None
"""
if PyFunceble.HTTP_CODE["active"]:
# The http status code extraction is activated.
# We get the http status code.
... | Return the HTTP code status.
:return: The matched and formatted status code.
:rtype: str|int|None | Below is the the instruction that describes the task:
### Input:
Return the HTTP code status.
:return: The matched and formatted status code.
:rtype: str|int|None
### Response:
def get(self):
"""
Return the HTTP code status.
:return: The matched and formatted status code.
... |
def set_linked_probs(self, linked_statements):
"""Sets the belief probabilities for a list of linked INDRA Statements.
The list of LinkedStatement objects is assumed to come from the
MechanismLinker. The belief probability of the inferred Statement is
assigned the joint probability of i... | Sets the belief probabilities for a list of linked INDRA Statements.
The list of LinkedStatement objects is assumed to come from the
MechanismLinker. The belief probability of the inferred Statement is
assigned the joint probability of its source Statements.
Parameters
--------... | Below is the the instruction that describes the task:
### Input:
Sets the belief probabilities for a list of linked INDRA Statements.
The list of LinkedStatement objects is assumed to come from the
MechanismLinker. The belief probability of the inferred Statement is
assigned the joint proba... |
def default(self, obj):
"""Default object encoder function
Args:
obj (:obj:`Any`): Object to be serialized
Returns:
JSON string
"""
if isinstance(obj, datetime):
return obj.isoformat()
if issubclass(obj.__class__, Enum.__class__):
... | Default object encoder function
Args:
obj (:obj:`Any`): Object to be serialized
Returns:
JSON string | Below is the the instruction that describes the task:
### Input:
Default object encoder function
Args:
obj (:obj:`Any`): Object to be serialized
Returns:
JSON string
### Response:
def default(self, obj):
"""Default object encoder function
Args:
... |
def __execute_cmd(name, cmd):
'''
Execute Riak commands
'''
return __salt__['cmd.run_all'](
'{0} {1}'.format(salt.utils.path.which(name), cmd)
) | Execute Riak commands | Below is the the instruction that describes the task:
### Input:
Execute Riak commands
### Response:
def __execute_cmd(name, cmd):
'''
Execute Riak commands
'''
return __salt__['cmd.run_all'](
'{0} {1}'.format(salt.utils.path.which(name), cmd)
) |
def execute(command, detach=False):
"""
Runs a command in background. No output is retrieved. Useful for running GUI
applications that would block click events.
:param command: A string or a list of strings containing the name and
arguments of the program.
:param detach: If set to `True` the p... | Runs a command in background. No output is retrieved. Useful for running GUI
applications that would block click events.
:param command: A string or a list of strings containing the name and
arguments of the program.
:param detach: If set to `True` the program will be executed using the
`i3-msg` ... | Below is the the instruction that describes the task:
### Input:
Runs a command in background. No output is retrieved. Useful for running GUI
applications that would block click events.
:param command: A string or a list of strings containing the name and
arguments of the program.
:param detach: I... |
def maybe_curry(maybe_fn, first_arg) -> 'Function | Any':
"""
If maybe_fn is a function, curries it and passes in first_arg. Otherwise
returns maybe_fn.
"""
if not callable(maybe_fn):
return maybe_fn
return tz.curry(maybe_fn)(first_arg) | If maybe_fn is a function, curries it and passes in first_arg. Otherwise
returns maybe_fn. | Below is the the instruction that describes the task:
### Input:
If maybe_fn is a function, curries it and passes in first_arg. Otherwise
returns maybe_fn.
### Response:
def maybe_curry(maybe_fn, first_arg) -> 'Function | Any':
"""
If maybe_fn is a function, curries it and passes in first_arg. Otherwis... |
def Cube(x, a, b, c, d):
"""Third order polynomial
Inputs:
-------
``x``: independent variable
``a``: coefficient of the third-order term
``b``: coefficient of the second-order term
``c``: coefficient of the first-order term
``d``: additive constant
Formula:
... | Third order polynomial
Inputs:
-------
``x``: independent variable
``a``: coefficient of the third-order term
``b``: coefficient of the second-order term
``c``: coefficient of the first-order term
``d``: additive constant
Formula:
--------
``a*x^3 + b*x^... | Below is the the instruction that describes the task:
### Input:
Third order polynomial
Inputs:
-------
``x``: independent variable
``a``: coefficient of the third-order term
``b``: coefficient of the second-order term
``c``: coefficient of the first-order term
``d``... |
def start(self, s):
# type: (Optional[Type[Nonterminal]]) -> None
"""
Set start symbol of the grammar.
:param s: Start symbol to set.
:raise NonterminalDoesNotExistsException: If the start symbol is not in nonterminals.
"""
if s is not None and s not in self.nonte... | Set start symbol of the grammar.
:param s: Start symbol to set.
:raise NonterminalDoesNotExistsException: If the start symbol is not in nonterminals. | Below is the the instruction that describes the task:
### Input:
Set start symbol of the grammar.
:param s: Start symbol to set.
:raise NonterminalDoesNotExistsException: If the start symbol is not in nonterminals.
### Response:
def start(self, s):
# type: (Optional[Type[Nonterminal]]) -> N... |
def encryption_key(self, alg, **kwargs):
"""
Return an encryption key as per
http://openid.net/specs/openid-connect-core-1_0.html#Encryption
:param alg: encryption algorithm
:param kwargs:
:return: encryption key as byte string
"""
if not self.key:
... | Return an encryption key as per
http://openid.net/specs/openid-connect-core-1_0.html#Encryption
:param alg: encryption algorithm
:param kwargs:
:return: encryption key as byte string | Below is the the instruction that describes the task:
### Input:
Return an encryption key as per
http://openid.net/specs/openid-connect-core-1_0.html#Encryption
:param alg: encryption algorithm
:param kwargs:
:return: encryption key as byte string
### Response:
def encryption_key(s... |
def getVC(self):
"""
Variance componenrs
"""
_Cr = decompose_GxE(self.full['Cr'])
RV = {}
for key in list(_Cr.keys()):
RV['var_%s' % key] = sp.array([var_CoXX(_Cr[key], self.Xr)])
RV['var_c'] = self.full['var_c']
RV['var_n'] = self.full['var_n... | Variance componenrs | Below is the the instruction that describes the task:
### Input:
Variance componenrs
### Response:
def getVC(self):
"""
Variance componenrs
"""
_Cr = decompose_GxE(self.full['Cr'])
RV = {}
for key in list(_Cr.keys()):
RV['var_%s' % key] = sp.array([var_Co... |
def options(self, parser, env=None):
"""
Adds command-line options for this plugin.
"""
if env is None:
env = os.environ
env_opt_name = 'NOSE_%s' % self.__dest_opt_name.upper()
parser.add_option("--%s" % self.__opt_name,
dest=self.__d... | Adds command-line options for this plugin. | Below is the the instruction that describes the task:
### Input:
Adds command-line options for this plugin.
### Response:
def options(self, parser, env=None):
"""
Adds command-line options for this plugin.
"""
if env is None:
env = os.environ
env_opt_name = 'NOSE... |
def block_sep1(self, Y):
r"""Separate variable into component corresponding to
:math:`\mathbf{y}_1` in :math:`\mathbf{y}\;\;`.
"""
# This method is overridden because we have to change the
# mechanism for combining the Y0 and Y1 blocks into a single
# array (see comment ... | r"""Separate variable into component corresponding to
:math:`\mathbf{y}_1` in :math:`\mathbf{y}\;\;`. | Below is the the instruction that describes the task:
### Input:
r"""Separate variable into component corresponding to
:math:`\mathbf{y}_1` in :math:`\mathbf{y}\;\;`.
### Response:
def block_sep1(self, Y):
r"""Separate variable into component corresponding to
:math:`\mathbf{y}_1` in :math:`... |
def alignment(job, ids, input_args, sample):
"""
Runs BWA and then Bamsort on the supplied fastqs for this sample
Input1: Toil Job instance
Input2: jobstore id dictionary
Input3: Input arguments dictionary
Input4: Sample tuple -- contains uuid and urls for the sample
"""
uuid, urls = sa... | Runs BWA and then Bamsort on the supplied fastqs for this sample
Input1: Toil Job instance
Input2: jobstore id dictionary
Input3: Input arguments dictionary
Input4: Sample tuple -- contains uuid and urls for the sample | Below is the the instruction that describes the task:
### Input:
Runs BWA and then Bamsort on the supplied fastqs for this sample
Input1: Toil Job instance
Input2: jobstore id dictionary
Input3: Input arguments dictionary
Input4: Sample tuple -- contains uuid and urls for the sample
### Response:
... |
def getTotalDiscountedBulkPrice(self):
"""Compute total discounted corporate bulk price
"""
price = self.getDiscountedCorporatePrice()
vat = self.getVAT()
price = price and price or 0
vat = vat and vat or 0
return float(price) + (float(price) * float(vat)) / 100 | Compute total discounted corporate bulk price | Below is the the instruction that describes the task:
### Input:
Compute total discounted corporate bulk price
### Response:
def getTotalDiscountedBulkPrice(self):
"""Compute total discounted corporate bulk price
"""
price = self.getDiscountedCorporatePrice()
vat = self.getVAT()
... |
def _wrap_chunks(self, chunks):
"""_wrap_chunks(chunks : [string]) -> [string]
Wrap a sequence of text chunks and return a list of lines of
length 'self.width' or less. (If 'break_long_words' is false,
some lines may be longer than this.) Chunks correspond roughly
to words and... | _wrap_chunks(chunks : [string]) -> [string]
Wrap a sequence of text chunks and return a list of lines of
length 'self.width' or less. (If 'break_long_words' is false,
some lines may be longer than this.) Chunks correspond roughly
to words and the whitespace between them: each chunk is... | Below is the the instruction that describes the task:
### Input:
_wrap_chunks(chunks : [string]) -> [string]
Wrap a sequence of text chunks and return a list of lines of
length 'self.width' or less. (If 'break_long_words' is false,
some lines may be longer than this.) Chunks correspond ro... |
def validate_current_versions(self): # type: () -> bool
"""
Can a version be found? Are all versions currently the same? Are they valid sem ver?
:return:
"""
versions = self.all_current_versions()
for _, version in versions.items():
if "Invalid Semantic Versi... | Can a version be found? Are all versions currently the same? Are they valid sem ver?
:return: | Below is the the instruction that describes the task:
### Input:
Can a version be found? Are all versions currently the same? Are they valid sem ver?
:return:
### Response:
def validate_current_versions(self): # type: () -> bool
"""
Can a version be found? Are all versions currently the sa... |
def start_ppp_link(self):
'''startup the link'''
cmd = ['pppd']
cmd.extend(self.command)
(self.pid, self.ppp_fd) = pty.fork()
if self.pid == 0:
os.execvp("pppd", cmd)
raise RuntimeError("pppd exited")
if self.ppp_fd == -1:
print("Failed... | startup the link | Below is the the instruction that describes the task:
### Input:
startup the link
### Response:
def start_ppp_link(self):
'''startup the link'''
cmd = ['pppd']
cmd.extend(self.command)
(self.pid, self.ppp_fd) = pty.fork()
if self.pid == 0:
os.execvp("pppd", cmd)
... |
def parseCommandLineArguments():
"""
Set up command line parsing.
"""
parser = argparse.ArgumentParser(description="Calculate parallax error for given G and (V-I)")
parser.add_argument("gmag", help="G-band magnitude of source", type=float)
parser.add_argument("vmini", help="(V-I) colour of source", type=flo... | Set up command line parsing. | Below is the the instruction that describes the task:
### Input:
Set up command line parsing.
### Response:
def parseCommandLineArguments():
"""
Set up command line parsing.
"""
parser = argparse.ArgumentParser(description="Calculate parallax error for given G and (V-I)")
parser.add_argument("gmag", help... |
def get_by_index(self, index):
"""Returns a Volume or Disk by its index."""
try:
return self[index]
except KeyError:
for v in self.get_volumes():
if v.index == str(index):
return v
raise KeyError(index) | Returns a Volume or Disk by its index. | Below is the the instruction that describes the task:
### Input:
Returns a Volume or Disk by its index.
### Response:
def get_by_index(self, index):
"""Returns a Volume or Disk by its index."""
try:
return self[index]
except KeyError:
for v in self.get_volumes():
... |
def _getW(self):
"""
Gets a value of `w` for use in generating a pattern.
"""
w = self._w
if type(w) is list:
return w[self._random.getUInt32(len(w))]
else:
return w | Gets a value of `w` for use in generating a pattern. | Below is the the instruction that describes the task:
### Input:
Gets a value of `w` for use in generating a pattern.
### Response:
def _getW(self):
"""
Gets a value of `w` for use in generating a pattern.
"""
w = self._w
if type(w) is list:
return w[self._random.getUInt32(len(w))]
e... |
def _start_new_cdx_file(self):
'''Create and set current CDX file.'''
self._cdx_filename = '{0}.cdx'.format(self._prefix_filename)
if not self._params.appending:
wpull.util.truncate_file(self._cdx_filename)
self._write_cdx_header()
elif not os.path.exists(self._c... | Create and set current CDX file. | Below is the the instruction that describes the task:
### Input:
Create and set current CDX file.
### Response:
def _start_new_cdx_file(self):
'''Create and set current CDX file.'''
self._cdx_filename = '{0}.cdx'.format(self._prefix_filename)
if not self._params.appending:
wpul... |
def process_deltadir(delta_dir, org_lengths, logger=None):
"""Returns a tuple of ANIm results for .deltas in passed directory.
- delta_dir - path to the directory containing .delta files
- org_lengths - dictionary of total sequence lengths, keyed by sequence
Returns the following pandas dataframes in ... | Returns a tuple of ANIm results for .deltas in passed directory.
- delta_dir - path to the directory containing .delta files
- org_lengths - dictionary of total sequence lengths, keyed by sequence
Returns the following pandas dataframes in an ANIResults object;
query sequences are rows, subject sequen... | Below is the the instruction that describes the task:
### Input:
Returns a tuple of ANIm results for .deltas in passed directory.
- delta_dir - path to the directory containing .delta files
- org_lengths - dictionary of total sequence lengths, keyed by sequence
Returns the following pandas dataframes ... |
def text_log_errors(self, request, project, pk=None):
"""
Gets a list of steps associated with this job
"""
try:
job = Job.objects.get(repository__name=project,
id=pk)
except Job.DoesNotExist:
return Response("No job with ... | Gets a list of steps associated with this job | Below is the the instruction that describes the task:
### Input:
Gets a list of steps associated with this job
### Response:
def text_log_errors(self, request, project, pk=None):
"""
Gets a list of steps associated with this job
"""
try:
job = Job.objects.get(repository_... |
def internal_classpath(cls, targets, classpath_products, confs=('default',)):
"""Return the list of internal classpath entries for a classpath covering all `targets`.
Any classpath entries contributed by external dependencies will be omitted.
:param targets: Targets to build an aggregated classpath for.
... | Return the list of internal classpath entries for a classpath covering all `targets`.
Any classpath entries contributed by external dependencies will be omitted.
:param targets: Targets to build an aggregated classpath for.
:param ClasspathProducts classpath_products: Product containing classpath elements... | Below is the the instruction that describes the task:
### Input:
Return the list of internal classpath entries for a classpath covering all `targets`.
Any classpath entries contributed by external dependencies will be omitted.
:param targets: Targets to build an aggregated classpath for.
:param Classp... |
def crud_permission_name(model, action, convert=True):
"""Returns permission name using Django naming convention: app_label.action_object.
If `convert` is True, `create` and `update` actions would be renamed
to `add` and `change`.
"""
app_label = model._meta.app_label
model_lower = model.__name... | Returns permission name using Django naming convention: app_label.action_object.
If `convert` is True, `create` and `update` actions would be renamed
to `add` and `change`. | Below is the the instruction that describes the task:
### Input:
Returns permission name using Django naming convention: app_label.action_object.
If `convert` is True, `create` and `update` actions would be renamed
to `add` and `change`.
### Response:
def crud_permission_name(model, action, convert=True):... |
def _gc_prop(s, length):
"""Get proportion of GC from a string
Parameters
----------
s : str
Arbitrary string
Returns
-------
x : float
GC proportion.
"""
gc = sum(map(s.count, ["c", "g"]))
return gc / length | Get proportion of GC from a string
Parameters
----------
s : str
Arbitrary string
Returns
-------
x : float
GC proportion. | Below is the the instruction that describes the task:
### Input:
Get proportion of GC from a string
Parameters
----------
s : str
Arbitrary string
Returns
-------
x : float
GC proportion.
### Response:
def _gc_prop(s, length):
"""Get... |
def main():
"""
A CLI application for performing factory calibration of an Opentrons robot
Instructions:
- Robot must be set up with two 300ul or 50ul single-channel pipettes
installed on the right-hand and left-hand mount.
- Put a GEB 300ul tip onto the pipette.
- Use the... | A CLI application for performing factory calibration of an Opentrons robot
Instructions:
- Robot must be set up with two 300ul or 50ul single-channel pipettes
installed on the right-hand and left-hand mount.
- Put a GEB 300ul tip onto the pipette.
- Use the arrow keys to jog the r... | Below is the the instruction that describes the task:
### Input:
A CLI application for performing factory calibration of an Opentrons robot
Instructions:
- Robot must be set up with two 300ul or 50ul single-channel pipettes
installed on the right-hand and left-hand mount.
- Put a GEB ... |
def get_internal_project(
self,
timeout: float = 1
) -> typing.Union['projects.Project', None]:
"""
Attempts to return the internally loaded project. This function
prevents race condition issues where projects are loaded via threads
because the internal loop w... | Attempts to return the internally loaded project. This function
prevents race condition issues where projects are loaded via threads
because the internal loop will try to continuously load the internal
project until it is available or until the timeout is reached.
:param timeout:
... | Below is the the instruction that describes the task:
### Input:
Attempts to return the internally loaded project. This function
prevents race condition issues where projects are loaded via threads
because the internal loop will try to continuously load the internal
project until it is avail... |
async def on_message(message):
"""The on_message event handler for this module
Args:
message (discord.Message): Input message
"""
# Simplify message info
server = message.server
author = message.author
channel = message.channel
content = message.content
data = datatools.ge... | The on_message event handler for this module
Args:
message (discord.Message): Input message | Below is the the instruction that describes the task:
### Input:
The on_message event handler for this module
Args:
message (discord.Message): Input message
### Response:
async def on_message(message):
"""The on_message event handler for this module
Args:
message (discord.Message): In... |
def forwarder(frontend, backend):
"""Simple pub/sub forwarder
:param int frontend: fontend zeromq port
:param int backend: backend zeromq port
"""
try:
context = zmq.Context()
front_sub = context.socket(zmq.SUB)
front_sub.bind("tcp://*:%d" % frontend)
front_sub.set... | Simple pub/sub forwarder
:param int frontend: fontend zeromq port
:param int backend: backend zeromq port | Below is the the instruction that describes the task:
### Input:
Simple pub/sub forwarder
:param int frontend: fontend zeromq port
:param int backend: backend zeromq port
### Response:
def forwarder(frontend, backend):
"""Simple pub/sub forwarder
:param int frontend: fontend zeromq port
:para... |
def execute_lines(self, lines):
"""
Execute a set of lines as multiple command
lines: multiple lines of text to be executed as single commands
"""
for line in lines.splitlines():
stripped_line = line.strip()
if stripped_line.startswith('#'):
... | Execute a set of lines as multiple command
lines: multiple lines of text to be executed as single commands | Below is the the instruction that describes the task:
### Input:
Execute a set of lines as multiple command
lines: multiple lines of text to be executed as single commands
### Response:
def execute_lines(self, lines):
"""
Execute a set of lines as multiple command
lines: multipl... |
def _encode(self, value, path_from_root):
"""Normalize, compress, and encode sub-objects for backend storage.
value: Object to encode.
path_from_root: `tuple` of key strings from the top-level summary to the
current `value`.
Returns:
A new tree of dict's with la... | Normalize, compress, and encode sub-objects for backend storage.
value: Object to encode.
path_from_root: `tuple` of key strings from the top-level summary to the
current `value`.
Returns:
A new tree of dict's with large objects replaced with dictionaries
wi... | Below is the the instruction that describes the task:
### Input:
Normalize, compress, and encode sub-objects for backend storage.
value: Object to encode.
path_from_root: `tuple` of key strings from the top-level summary to the
current `value`.
Returns:
A new tree o... |
def customize_grammar_rules(self, tokens, customize):
"""The base grammar we start out for a Python version even with the
subclassing is, well, is pretty base. And we want it that way: lean and
mean so that parsing will go faster.
Here, we add additional grammar rules based on specific... | The base grammar we start out for a Python version even with the
subclassing is, well, is pretty base. And we want it that way: lean and
mean so that parsing will go faster.
Here, we add additional grammar rules based on specific instructions
that are in the instruction/token stream. I... | Below is the the instruction that describes the task:
### Input:
The base grammar we start out for a Python version even with the
subclassing is, well, is pretty base. And we want it that way: lean and
mean so that parsing will go faster.
Here, we add additional grammar rules based on spec... |
def get_absolute_path(some_path):
"""
This function will return an appropriate absolute path for the path it is
given. If the input is absolute, it will return unmodified; if the input is
relative, it will be rendered as relative to the current working directory.
"""
if os.path.isabs(some_path):... | This function will return an appropriate absolute path for the path it is
given. If the input is absolute, it will return unmodified; if the input is
relative, it will be rendered as relative to the current working directory. | Below is the the instruction that describes the task:
### Input:
This function will return an appropriate absolute path for the path it is
given. If the input is absolute, it will return unmodified; if the input is
relative, it will be rendered as relative to the current working directory.
### Response:
de... |
def create_protocol(name, **kwargs):
"""
Returns an instance of the protocol with the given name.
:type name: str
:param name: The name of the protocol.
:rtype: Protocol
:return: An instance of the protocol.
"""
cls = protocol_map.get(name)
if not cls:
raise ValueError('Un... | Returns an instance of the protocol with the given name.
:type name: str
:param name: The name of the protocol.
:rtype: Protocol
:return: An instance of the protocol. | Below is the the instruction that describes the task:
### Input:
Returns an instance of the protocol with the given name.
:type name: str
:param name: The name of the protocol.
:rtype: Protocol
:return: An instance of the protocol.
### Response:
def create_protocol(name, **kwargs):
"""
R... |
def from_json(cls, data):
"""Decode a JSON string and inflate a node instance."""
# Decode JSON string
assert isinstance(data, str)
data = json.loads(data)
assert isinstance(data, dict)
return cls.from_dict(data) | Decode a JSON string and inflate a node instance. | Below is the the instruction that describes the task:
### Input:
Decode a JSON string and inflate a node instance.
### Response:
def from_json(cls, data):
"""Decode a JSON string and inflate a node instance."""
# Decode JSON string
assert isinstance(data, str)
data = json.loads(data... |
def _fill(self, values):
"""Add extra values to fill the line"""
if not self._previous_line:
self._previous_line = values
return super(StackedLine, self)._fill(values)
new_values = values + list(reversed(self._previous_line))
self._previous_line = values
r... | Add extra values to fill the line | Below is the the instruction that describes the task:
### Input:
Add extra values to fill the line
### Response:
def _fill(self, values):
"""Add extra values to fill the line"""
if not self._previous_line:
self._previous_line = values
return super(StackedLine, self)._fill(va... |
def parse_selfsm(self, f):
""" Go through selfSM file and create a dictionary with the sample name as a key, """
#create a dictionary to populate from this sample's file
parsed_data = dict()
# set a empty variable which denotes if the headers have been read
headers = None
# for each line in the file
for l... | Go through selfSM file and create a dictionary with the sample name as a key, | Below is the the instruction that describes the task:
### Input:
Go through selfSM file and create a dictionary with the sample name as a key,
### Response:
def parse_selfsm(self, f):
""" Go through selfSM file and create a dictionary with the sample name as a key, """
#create a dictionary to populate from thi... |
def reset_handler(self, cmd):
"""Process a ResetCommand."""
self.cmd_counts[cmd.name] += 1
if cmd.ref.startswith('refs/tags/'):
self.lightweight_tags += 1
else:
if cmd.from_ is not None:
self.reftracker.track_heads_for_ref(
cmd.... | Process a ResetCommand. | Below is the the instruction that describes the task:
### Input:
Process a ResetCommand.
### Response:
def reset_handler(self, cmd):
"""Process a ResetCommand."""
self.cmd_counts[cmd.name] += 1
if cmd.ref.startswith('refs/tags/'):
self.lightweight_tags += 1
else:
... |
def map(self, absolute_address, region_id, related_function_address=None):
"""
Add a mapping between an absolute address and a region ID. If this is a stack region map, all stack regions
beyond (lower than) this newly added regions will be discarded.
:param absolute_address: ... | Add a mapping between an absolute address and a region ID. If this is a stack region map, all stack regions
beyond (lower than) this newly added regions will be discarded.
:param absolute_address: An absolute memory address.
:param region_id: ID of the memory region... | Below is the the instruction that describes the task:
### Input:
Add a mapping between an absolute address and a region ID. If this is a stack region map, all stack regions
beyond (lower than) this newly added regions will be discarded.
:param absolute_address: An absolute memory address... |
def get_file_diff(tree, files_to_diff):
""" get_file_diff: Download files from nodes
Args:
tree (ChannelManager): manager to handle communication to Kolibri Studio
Returns: list of files that are not on Kolibri Studio
"""
# Determine which files have not yet been uploaded to the ... | get_file_diff: Download files from nodes
Args:
tree (ChannelManager): manager to handle communication to Kolibri Studio
Returns: list of files that are not on Kolibri Studio | Below is the the instruction that describes the task:
### Input:
get_file_diff: Download files from nodes
Args:
tree (ChannelManager): manager to handle communication to Kolibri Studio
Returns: list of files that are not on Kolibri Studio
### Response:
def get_file_diff(tree, files_to_d... |
def encodeIntoArray(self, input, output, learn=True):
""" See method description in base.py """
if input is not None and not isinstance(input, numbers.Number):
raise TypeError(
"Expected a scalar input but got input of type %s" % type(input))
if type(input) is float and math.isnan(input):
... | See method description in base.py | Below is the the instruction that describes the task:
### Input:
See method description in base.py
### Response:
def encodeIntoArray(self, input, output, learn=True):
""" See method description in base.py """
if input is not None and not isinstance(input, numbers.Number):
raise TypeError(
... |
def _InnerAppendData(self, prev_col_values, data, col_index):
"""Inner function to assist LoadData."""
# We first check that col_index has not exceeded the columns size
if col_index >= len(self.__columns):
raise DataTableException("The data does not match description, too deep")
# Dealing with th... | Inner function to assist LoadData. | Below is the the instruction that describes the task:
### Input:
Inner function to assist LoadData.
### Response:
def _InnerAppendData(self, prev_col_values, data, col_index):
"""Inner function to assist LoadData."""
# We first check that col_index has not exceeded the columns size
if col_index >= len(... |
def read_rle(file_obj, header, bit_width, debug_logging):
"""Read a run-length encoded run from the given fo with the given header and bit_width.
The count is determined from the header and the width is used to grab the
value that's repeated. Yields the value repeated count times.
"""
count = heade... | Read a run-length encoded run from the given fo with the given header and bit_width.
The count is determined from the header and the width is used to grab the
value that's repeated. Yields the value repeated count times. | Below is the the instruction that describes the task:
### Input:
Read a run-length encoded run from the given fo with the given header and bit_width.
The count is determined from the header and the width is used to grab the
value that's repeated. Yields the value repeated count times.
### Response:
def re... |
def handleMethodCallMessage(self, msg):
"""
Handles DBus MethodCall messages on behalf of the DBus Connection and
dispatches them to the appropriate exported object
"""
if (
msg.interface == 'org.freedesktop.DBus.Peer'
and msg.member == 'Ping'
):
... | Handles DBus MethodCall messages on behalf of the DBus Connection and
dispatches them to the appropriate exported object | Below is the the instruction that describes the task:
### Input:
Handles DBus MethodCall messages on behalf of the DBus Connection and
dispatches them to the appropriate exported object
### Response:
def handleMethodCallMessage(self, msg):
"""
Handles DBus MethodCall messages on behalf of t... |
def getEditorBinary(self, cmdVersion=False):
"""
Determines the location of the UE4Editor binary
"""
return os.path.join(self.getEngineRoot(), 'Engine', 'Binaries', self.getPlatformIdentifier(), 'UE4Editor' + self._editorPathSuffix(cmdVersion)) | Determines the location of the UE4Editor binary | Below is the the instruction that describes the task:
### Input:
Determines the location of the UE4Editor binary
### Response:
def getEditorBinary(self, cmdVersion=False):
"""
Determines the location of the UE4Editor binary
"""
return os.path.join(self.getEngineRoot(), 'Engine', 'Binaries', self.getPlatfor... |
def cardinality(self):
'''
Obtain the cardinality string.
Example: '1C' for a conditional link with a single instance [0..1]
'MC' for a link with any number of instances [0..*]
'M' for a more than one instance [1..*]
'M' for a link wi... | Obtain the cardinality string.
Example: '1C' for a conditional link with a single instance [0..1]
'MC' for a link with any number of instances [0..*]
'M' for a more than one instance [1..*]
'M' for a link with exactly one instance [1] | Below is the the instruction that describes the task:
### Input:
Obtain the cardinality string.
Example: '1C' for a conditional link with a single instance [0..1]
'MC' for a link with any number of instances [0..*]
'M' for a more than one instance [1..*]
... |
def dataframe_from_excel(path, sheetname=0, header=0, skiprows=None): # , parse_dates=False):
"""Thin wrapper for pandas.io.excel.read_excel() that accepts a file path and sheet index/name
Arguments:
path (str): file or folder to retrieve CSV files and `pandas.DataFrame`s from
ext (str): file name... | Thin wrapper for pandas.io.excel.read_excel() that accepts a file path and sheet index/name
Arguments:
path (str): file or folder to retrieve CSV files and `pandas.DataFrame`s from
ext (str): file name extension (to filter files by)
date_parser (function): if the MultiIndex can be interpretted as... | Below is the the instruction that describes the task:
### Input:
Thin wrapper for pandas.io.excel.read_excel() that accepts a file path and sheet index/name
Arguments:
path (str): file or folder to retrieve CSV files and `pandas.DataFrame`s from
ext (str): file name extension (to filter files by)
... |
def main():
"""Function to add or substract the temperature effect to data in a tomodir
"""
options = handle_options()
# read in temperature and resistivity data
tempdata = readin_temp(options.temp_file)
magdata = readin_rho(options.filename,
options.rhofile,
... | Function to add or substract the temperature effect to data in a tomodir | Below is the the instruction that describes the task:
### Input:
Function to add or substract the temperature effect to data in a tomodir
### Response:
def main():
"""Function to add or substract the temperature effect to data in a tomodir
"""
options = handle_options()
# read in temperature and r... |
def _CheckIsLink(self, file_entry):
"""Checks the is_link find specification.
Args:
file_entry (FileEntry): file entry.
Returns:
bool: True if the file entry matches the find specification, False if not.
"""
if definitions.FILE_ENTRY_TYPE_LINK not in self._file_entry_types:
retur... | Checks the is_link find specification.
Args:
file_entry (FileEntry): file entry.
Returns:
bool: True if the file entry matches the find specification, False if not. | Below is the the instruction that describes the task:
### Input:
Checks the is_link find specification.
Args:
file_entry (FileEntry): file entry.
Returns:
bool: True if the file entry matches the find specification, False if not.
### Response:
def _CheckIsLink(self, file_entry):
"""Checks... |
def remove(self):
""" Remove the directory. """
lib.gp_camera_folder_remove_dir(
self._cam._cam, self.parent.path.encode(), self.name.encode(),
self._cam._ctx) | Remove the directory. | Below is the the instruction that describes the task:
### Input:
Remove the directory.
### Response:
def remove(self):
""" Remove the directory. """
lib.gp_camera_folder_remove_dir(
self._cam._cam, self.parent.path.encode(), self.name.encode(),
self._cam._ctx) |
def eventloop(self, *args, **kwargs):
"""
Hand crafted event loop, with only one event possible : exit
More events ( and signals ) can be added later, after converting to asyncio.
"""
# Setting status
status = None
# Starting the clock
start = time.time(... | Hand crafted event loop, with only one event possible : exit
More events ( and signals ) can be added later, after converting to asyncio. | Below is the the instruction that describes the task:
### Input:
Hand crafted event loop, with only one event possible : exit
More events ( and signals ) can be added later, after converting to asyncio.
### Response:
def eventloop(self, *args, **kwargs):
"""
Hand crafted event loop, with on... |
def axes(self):
"""
Returns all the axes that have been defined for this chart.
:return [<projexui.widgets.xchart.XChartAxis>, ..]
"""
out = self._axes[:]
if self._horizontalAxis:
out.append(self._horizontalAxis)
if self._vertical... | Returns all the axes that have been defined for this chart.
:return [<projexui.widgets.xchart.XChartAxis>, ..] | Below is the the instruction that describes the task:
### Input:
Returns all the axes that have been defined for this chart.
:return [<projexui.widgets.xchart.XChartAxis>, ..]
### Response:
def axes(self):
"""
Returns all the axes that have been defined for this chart.
... |
def make_prior(num_topics, initial_value):
"""Create the prior distribution.
Args:
num_topics: Number of topics.
initial_value: The starting value for the prior parameters.
Returns:
prior: A `callable` that returns a `tf.distribution.Distribution`
instance, the prior distribution.
prior_... | Create the prior distribution.
Args:
num_topics: Number of topics.
initial_value: The starting value for the prior parameters.
Returns:
prior: A `callable` that returns a `tf.distribution.Distribution`
instance, the prior distribution.
prior_variables: A `list` of `Variable` objects, the t... | Below is the the instruction that describes the task:
### Input:
Create the prior distribution.
Args:
num_topics: Number of topics.
initial_value: The starting value for the prior parameters.
Returns:
prior: A `callable` that returns a `tf.distribution.Distribution`
instance, the prior dis... |
def install_from_exchange():
''' Install from experiment exchange. '''
parser = argparse.ArgumentParser(
description='Download experiment from the psiturk.org experiment\
exchange (http://psiturk.org/ee).'
)
parser.add_argument(
'exp_id', metavar='exp_id', type=str, help='the id ... | Install from experiment exchange. | Below is the the instruction that describes the task:
### Input:
Install from experiment exchange.
### Response:
def install_from_exchange():
''' Install from experiment exchange. '''
parser = argparse.ArgumentParser(
description='Download experiment from the psiturk.org experiment\
exchang... |
def get_term(self, ontology, iri):
"""Gets the data for a given term
:param str ontology: The name of the ontology
:param str iri: The IRI of a term
:rtype: dict
"""
url = self.ontology_term_fmt.format(ontology, iri)
response = requests.get(url)
return r... | Gets the data for a given term
:param str ontology: The name of the ontology
:param str iri: The IRI of a term
:rtype: dict | Below is the the instruction that describes the task:
### Input:
Gets the data for a given term
:param str ontology: The name of the ontology
:param str iri: The IRI of a term
:rtype: dict
### Response:
def get_term(self, ontology, iri):
"""Gets the data for a given term
:... |
def _sorted_keys_items(dobj):
"""Return dictionary items sorted by key."""
keys = sorted(dobj.keys())
for key in keys:
yield key, dobj[key] | Return dictionary items sorted by key. | Below is the the instruction that describes the task:
### Input:
Return dictionary items sorted by key.
### Response:
def _sorted_keys_items(dobj):
"""Return dictionary items sorted by key."""
keys = sorted(dobj.keys())
for key in keys:
yield key, dobj[key] |
def airwires(board, showgui=0):
'search for airwires in eagle board'
board = Path(board).expand().abspath()
file_out = tempfile.NamedTemporaryFile(suffix='.txt', delete=0)
file_out.close()
ulp = ulp_templ.replace('FILE_NAME', file_out.name)
file_ulp = tempfile.NamedTemporaryFile(suffix='.ulp'... | search for airwires in eagle board | Below is the the instruction that describes the task:
### Input:
search for airwires in eagle board
### Response:
def airwires(board, showgui=0):
'search for airwires in eagle board'
board = Path(board).expand().abspath()
file_out = tempfile.NamedTemporaryFile(suffix='.txt', delete=0)
file_out.clo... |
def to_latex(self, buf=None, upper_triangle=True, **kwargs):
"""Render a DataFrame to a tabular environment table.
You can splice this into a LaTeX document.
Requires ``\\usepackage{booktabs}``.
Wrapper around the :meth:`pandas.DataFrame.to_latex` method.
"""
out = self.... | Render a DataFrame to a tabular environment table.
You can splice this into a LaTeX document.
Requires ``\\usepackage{booktabs}``.
Wrapper around the :meth:`pandas.DataFrame.to_latex` method. | Below is the the instruction that describes the task:
### Input:
Render a DataFrame to a tabular environment table.
You can splice this into a LaTeX document.
Requires ``\\usepackage{booktabs}``.
Wrapper around the :meth:`pandas.DataFrame.to_latex` method.
### Response:
def to_latex(self, ... |
def get_client_identity_from_certificate(certificate):
"""
Given an X.509 certificate, extract and return the client identity.
"""
client_ids = get_common_names_from_certificate(certificate)
if len(client_ids) > 0:
if len(client_ids) > 1:
raise exceptions.PermissionDenied(
... | Given an X.509 certificate, extract and return the client identity. | Below is the the instruction that describes the task:
### Input:
Given an X.509 certificate, extract and return the client identity.
### Response:
def get_client_identity_from_certificate(certificate):
"""
Given an X.509 certificate, extract and return the client identity.
"""
client_ids = get_comm... |
def conditionally_inline_policies(role_name, sr_entry):
"""
If 'policies' key lists the filename prefixes of policies to bind to the role,
load them from the expected path and inline them onto the role
Args:
role_name: name of the role to attach the policies to
sr_entry: service registry entry
"""
s... | If 'policies' key lists the filename prefixes of policies to bind to the role,
load them from the expected path and inline them onto the role
Args:
role_name: name of the role to attach the policies to
sr_entry: service registry entry | Below is the the instruction that describes the task:
### Input:
If 'policies' key lists the filename prefixes of policies to bind to the role,
load them from the expected path and inline them onto the role
Args:
role_name: name of the role to attach the policies to
sr_entry: service registry entry
### ... |
def difference_update(self, values):
'''Remove an iterable of *values* from the set.'''
d = self.value_pickler.dumps
return self.cache.remove(tuple((d(v) for v in values))) | Remove an iterable of *values* from the set. | Below is the the instruction that describes the task:
### Input:
Remove an iterable of *values* from the set.
### Response:
def difference_update(self, values):
'''Remove an iterable of *values* from the set.'''
d = self.value_pickler.dumps
return self.cache.remove(tuple((d(v) for v in v... |
def json_safe(string, content_type='application/octet-stream'):
"""Returns JSON-safe version of `string`.
If `string` is a Unicode string or a valid UTF-8, it is returned unmodified,
as it can safely be encoded to JSON string.
If `string` contains raw/binary data, it is Base64-encoded, formatted and
... | Returns JSON-safe version of `string`.
If `string` is a Unicode string or a valid UTF-8, it is returned unmodified,
as it can safely be encoded to JSON string.
If `string` contains raw/binary data, it is Base64-encoded, formatted and
returned according to "data" URL scheme (RFC2397). Since JSON is not... | Below is the the instruction that describes the task:
### Input:
Returns JSON-safe version of `string`.
If `string` is a Unicode string or a valid UTF-8, it is returned unmodified,
as it can safely be encoded to JSON string.
If `string` contains raw/binary data, it is Base64-encoded, formatted and
... |
def size_to_content(self, get_font_metrics_fn):
""" Size the canvas item to the proper width, the maximum of any label. """
new_sizing = self.copy_sizing()
new_sizing.minimum_width = 0
new_sizing.maximum_width = 0
axes = self.__axes
if axes and axes.is_valid:
... | Size the canvas item to the proper width, the maximum of any label. | Below is the the instruction that describes the task:
### Input:
Size the canvas item to the proper width, the maximum of any label.
### Response:
def size_to_content(self, get_font_metrics_fn):
""" Size the canvas item to the proper width, the maximum of any label. """
new_sizing = self.copy_sizin... |
def process_raw_data(cls, raw_data):
"""Create a new model using raw API response."""
properties = raw_data.get("properties", {})
bgp_peers = []
for raw_content in properties.get("bgpPeers", []):
raw_content["parentResourceID"] = raw_data["resourceId"]
raw_conten... | Create a new model using raw API response. | Below is the the instruction that describes the task:
### Input:
Create a new model using raw API response.
### Response:
def process_raw_data(cls, raw_data):
"""Create a new model using raw API response."""
properties = raw_data.get("properties", {})
bgp_peers = []
for raw_content... |
def create_milestones(self, project_id, milestones):
"""
With this function you can create multiple milestones in a single
request. See the "create" function for a description of the individual
fields in the milestone.
"""
path = '/projects/%u/milestones/create' % project... | With this function you can create multiple milestones in a single
request. See the "create" function for a description of the individual
fields in the milestone. | Below is the the instruction that describes the task:
### Input:
With this function you can create multiple milestones in a single
request. See the "create" function for a description of the individual
fields in the milestone.
### Response:
def create_milestones(self, project_id, milestones):
... |
def parse_known2func(self, args=None, func=None):
"""Parse the command line arguments to the setup function
This method parses the given command line arguments to the function
used in the :meth:`setup_args` method to setup up this parser
Parameters
----------
args: list... | Parse the command line arguments to the setup function
This method parses the given command line arguments to the function
used in the :meth:`setup_args` method to setup up this parser
Parameters
----------
args: list
The list of command line arguments
func:... | Below is the the instruction that describes the task:
### Input:
Parse the command line arguments to the setup function
This method parses the given command line arguments to the function
used in the :meth:`setup_args` method to setup up this parser
Parameters
----------
ar... |
def get_sample_size(self, key=None):
""" Returns the number of samples in the input data
@ In, key, an optional 2-tuple specifying a min-max id pair
used for determining which partition size should be
returned. If not specified then the size of the entire data
set... | Returns the number of samples in the input data
@ In, key, an optional 2-tuple specifying a min-max id pair
used for determining which partition size should be
returned. If not specified then the size of the entire data
set will be returned.
@ Out, an integer ... | Below is the the instruction that describes the task:
### Input:
Returns the number of samples in the input data
@ In, key, an optional 2-tuple specifying a min-max id pair
used for determining which partition size should be
returned. If not specified then the size of the entire ... |
def Create(self, body, path, type, id, initial_headers, options=None):
"""Creates a Azure Cosmos resource and returns it.
:param dict body:
:param str path:
:param str type:
:param str id:
:param dict initial_headers:
:param dict options:
The request ... | Creates a Azure Cosmos resource and returns it.
:param dict body:
:param str path:
:param str type:
:param str id:
:param dict initial_headers:
:param dict options:
The request options for the request.
:return:
The created Azure Cosmos re... | Below is the the instruction that describes the task:
### Input:
Creates a Azure Cosmos resource and returns it.
:param dict body:
:param str path:
:param str type:
:param str id:
:param dict initial_headers:
:param dict options:
The request options for t... |
def change_password(self, auth_secret, old_password, new_password):
"""Change the user password.
Parameters
----------
auth_secret: str
The authentication secret which will be used for user authentication.
old_password: str
The old password before the cha... | Change the user password.
Parameters
----------
auth_secret: str
The authentication secret which will be used for user authentication.
old_password: str
The old password before the change.
new_password: str
The new password after the change.
... | Below is the the instruction that describes the task:
### Input:
Change the user password.
Parameters
----------
auth_secret: str
The authentication secret which will be used for user authentication.
old_password: str
The old password before the change.
... |
def get_audio_duration(self):
"""
Return item audio duration
"""
decoder = timeside.core.get_processor('file_decoder')(
uri=self.get_uri())
return decoder.uri_total_duration | Return item audio duration | Below is the the instruction that describes the task:
### Input:
Return item audio duration
### Response:
def get_audio_duration(self):
"""
Return item audio duration
"""
decoder = timeside.core.get_processor('file_decoder')(
uri=self.get_uri())
return decoder.ur... |
def stop(self, nowait=False):
"""Stop the listener.
This asks the thread to terminate, and then waits for it to do so.
Note that if you don't call this before your application exits, there
may be some records still left on the queue, which won't be processed.
If nowait is False ... | Stop the listener.
This asks the thread to terminate, and then waits for it to do so.
Note that if you don't call this before your application exits, there
may be some records still left on the queue, which won't be processed.
If nowait is False then thread will handle remaining items i... | Below is the the instruction that describes the task:
### Input:
Stop the listener.
This asks the thread to terminate, and then waits for it to do so.
Note that if you don't call this before your application exits, there
may be some records still left on the queue, which won't be processed.... |
def is_single_class():
"""Returns True if only a single class is being run or some tests within a single class"""
ret = False
counts = get_counts()
if counts["classes"] < 1 and counts["modules"] < 1:
ret = counts["tests"] > 0
else:
ret = counts["classes"] <= 1 and counts["modules"] <... | Returns True if only a single class is being run or some tests within a single class | Below is the the instruction that describes the task:
### Input:
Returns True if only a single class is being run or some tests within a single class
### Response:
def is_single_class():
"""Returns True if only a single class is being run or some tests within a single class"""
ret = False
counts = get_... |
def distance_matrix(self, leaf_labels=False):
'''Return a distance matrix (2D dictionary) of the leaves of this ``Tree``
Args:
``leaf_labels`` (``bool``): ``True`` to have keys be labels of leaf ``Node`` objects, otherwise ``False`` to have keys be ``Node`` objects
Returns:
... | Return a distance matrix (2D dictionary) of the leaves of this ``Tree``
Args:
``leaf_labels`` (``bool``): ``True`` to have keys be labels of leaf ``Node`` objects, otherwise ``False`` to have keys be ``Node`` objects
Returns:
``dict``: Distance matrix (2D dictionary) of the lea... | Below is the the instruction that describes the task:
### Input:
Return a distance matrix (2D dictionary) of the leaves of this ``Tree``
Args:
``leaf_labels`` (``bool``): ``True`` to have keys be labels of leaf ``Node`` objects, otherwise ``False`` to have keys be ``Node`` objects
Retu... |
def string_stats(strs, valid_chars='012346789', left_pad='0', right_pad='', strip=True):
""" Count the occurrence of a category of valid characters within an iterable of serial/model no, etc """
if left_pad is None:
left_pad = ''.join(c for c in rex.ASCII_CHARACTERS if c not in valid_chars)
if right... | Count the occurrence of a category of valid characters within an iterable of serial/model no, etc | Below is the the instruction that describes the task:
### Input:
Count the occurrence of a category of valid characters within an iterable of serial/model no, etc
### Response:
def string_stats(strs, valid_chars='012346789', left_pad='0', right_pad='', strip=True):
""" Count the occurrence of a category of val... |
def disable_bool_icon(
fieldname: str,
model) -> Callable[[Any], bool]:
"""
Disable boolean icons for a Django ModelAdmin field.
The '_meta' attribute is present on Django model classes and instances.
model_class: ``Union[Model, Type[Model]]``
... only the type checker in Py3.5 is ... | Disable boolean icons for a Django ModelAdmin field.
The '_meta' attribute is present on Django model classes and instances.
model_class: ``Union[Model, Type[Model]]``
... only the type checker in Py3.5 is broken; see ``files.py`` | Below is the the instruction that describes the task:
### Input:
Disable boolean icons for a Django ModelAdmin field.
The '_meta' attribute is present on Django model classes and instances.
model_class: ``Union[Model, Type[Model]]``
... only the type checker in Py3.5 is broken; see ``files.py``
### Re... |
def get_tetrahedra_relative_grid_address(microzone_lattice):
"""Returns relative (differences of) grid addresses from the central
Parameter
---------
microzone_lattice : ndarray or list of list
column vectors of parallel piped microzone lattice, i.e.,
microzone_lattice = np.linalg.inv(c... | Returns relative (differences of) grid addresses from the central
Parameter
---------
microzone_lattice : ndarray or list of list
column vectors of parallel piped microzone lattice, i.e.,
microzone_lattice = np.linalg.inv(cell.get_cell()) / mesh | Below is the the instruction that describes the task:
### Input:
Returns relative (differences of) grid addresses from the central
Parameter
---------
microzone_lattice : ndarray or list of list
column vectors of parallel piped microzone lattice, i.e.,
microzone_lattice = np.linalg.inv(... |
def stop(self):
"""Stop internal color pattern playing
"""
if ( self.dev == None ): return ''
buf = [REPORT_ID, ord('p'), 0, 0, 0, 0, 0, 0, 0]
return self.write(buf); | Stop internal color pattern playing | Below is the the instruction that describes the task:
### Input:
Stop internal color pattern playing
### Response:
def stop(self):
"""Stop internal color pattern playing
"""
if ( self.dev == None ): return ''
buf = [REPORT_ID, ord('p'), 0, 0, 0, 0, 0, 0, 0]
return self.write... |
def _replace_tables(self, soup, v_separator=' | ', h_separator='-'):
"""Replaces <table> elements with its ASCII equivalent.
"""
tables = self._parse_tables(soup)
v_sep_len = len(v_separator)
v_left_sep = v_separator.lstrip()
for t in tables:
html = ''
... | Replaces <table> elements with its ASCII equivalent. | Below is the the instruction that describes the task:
### Input:
Replaces <table> elements with its ASCII equivalent.
### Response:
def _replace_tables(self, soup, v_separator=' | ', h_separator='-'):
"""Replaces <table> elements with its ASCII equivalent.
"""
tables = self._parse_tables(so... |
def reverse_file(infile, outfile):
'''Reverse the content of infile, write to outfile.
Both infile and outfile are filenames or filepaths.
'''
with open(infile, 'rb') as inf:
with open(outfile, 'wb') as outf:
reverse_fd(inf, outf) | Reverse the content of infile, write to outfile.
Both infile and outfile are filenames or filepaths. | Below is the the instruction that describes the task:
### Input:
Reverse the content of infile, write to outfile.
Both infile and outfile are filenames or filepaths.
### Response:
def reverse_file(infile, outfile):
'''Reverse the content of infile, write to outfile.
Both infile and outfile are filename... |
def submission_to_json(self, task, data, debug, reloading=False, replace=False, tags={}):
""" Converts a submission to json (keeps only needed fields) """
if "ssh_host" in data:
return json.dumps({'status': "waiting", 'text': "<b>SSH server active</b>",
'ssh_h... | Converts a submission to json (keeps only needed fields) | Below is the the instruction that describes the task:
### Input:
Converts a submission to json (keeps only needed fields)
### Response:
def submission_to_json(self, task, data, debug, reloading=False, replace=False, tags={}):
""" Converts a submission to json (keeps only needed fields) """
if "ssh... |
def install_from_arguments(self, arguments, **kw):
"""
Download, unpack, build and install the specified requirements.
This function is a simple wrapper for :func:`get_requirements()`,
:func:`install_requirements()` and :func:`cleanup_temporary_directories()`
that implements the... | Download, unpack, build and install the specified requirements.
This function is a simple wrapper for :func:`get_requirements()`,
:func:`install_requirements()` and :func:`cleanup_temporary_directories()`
that implements the default behavior of the pip accelerator. If you're
extending o... | Below is the the instruction that describes the task:
### Input:
Download, unpack, build and install the specified requirements.
This function is a simple wrapper for :func:`get_requirements()`,
:func:`install_requirements()` and :func:`cleanup_temporary_directories()`
that implements the d... |
def _symlink_to_workdir(data, key):
"""For CWL support, symlink files into a working directory if in read-only imports.
"""
orig_file = tz.get_in(key, data)
if orig_file and not orig_file.startswith(dd.get_work_dir(data)):
variantcaller = genotype.get_variantcaller(data, require_bam=False)
... | For CWL support, symlink files into a working directory if in read-only imports. | Below is the the instruction that describes the task:
### Input:
For CWL support, symlink files into a working directory if in read-only imports.
### Response:
def _symlink_to_workdir(data, key):
"""For CWL support, symlink files into a working directory if in read-only imports.
"""
orig_file = tz.get_... |
def start(endpoint='data.logentries.com',
port=10000,
token=None,
tag='salt/engines/logentries'):
'''
Listen to salt events and forward them to Logentries
'''
if __opts__.get('id').endswith('_master'):
event_bus = salt.utils.event.get_master_event(
__opt... | Listen to salt events and forward them to Logentries | Below is the the instruction that describes the task:
### Input:
Listen to salt events and forward them to Logentries
### Response:
def start(endpoint='data.logentries.com',
port=10000,
token=None,
tag='salt/engines/logentries'):
'''
Listen to salt events and forward them to L... |
def switch_domain(self, domain):
"""
Switch from one domain to another. You can call session.login() with
a domain key value to log directly into the domain of choice or alternatively
switch from domain to domain. The user must have permissions to the domain or
unauthorized will ... | Switch from one domain to another. You can call session.login() with
a domain key value to log directly into the domain of choice or alternatively
switch from domain to domain. The user must have permissions to the domain or
unauthorized will be returned. In addition, when switching domains, you... | Below is the the instruction that describes the task:
### Input:
Switch from one domain to another. You can call session.login() with
a domain key value to log directly into the domain of choice or alternatively
switch from domain to domain. The user must have permissions to the domain or
un... |
def restart(self, timeout=300, config_callback=None):
"""Restart each member of the replica set."""
for member_id in self.server_map:
host = self.server_map[member_id]
server_id = self._servers.host_to_server_id(host)
server = self._servers._storage[server_id]
... | Restart each member of the replica set. | Below is the the instruction that describes the task:
### Input:
Restart each member of the replica set.
### Response:
def restart(self, timeout=300, config_callback=None):
"""Restart each member of the replica set."""
for member_id in self.server_map:
host = self.server_map[member_id]
... |
def email_address(user=None):
"""Return random e-mail address in a hopefully imaginary domain.
If `user` is ``None`` :py:func:`~user_name()` will be used. Otherwise it
will be lowercased and will have spaces replaced with ``_``.
Domain name is created using :py:func:`~domain_name()`.
"""
if no... | Return random e-mail address in a hopefully imaginary domain.
If `user` is ``None`` :py:func:`~user_name()` will be used. Otherwise it
will be lowercased and will have spaces replaced with ``_``.
Domain name is created using :py:func:`~domain_name()`. | Below is the the instruction that describes the task:
### Input:
Return random e-mail address in a hopefully imaginary domain.
If `user` is ``None`` :py:func:`~user_name()` will be used. Otherwise it
will be lowercased and will have spaces replaced with ``_``.
Domain name is created using :py:func:`~d... |
def _remove_persistent_module(mod, comment):
'''
Remove module from configuration file. If comment is true only comment line
where module is.
'''
conf = _get_modules_conf()
mod_name = _strip_module_name(mod)
if not mod_name or mod_name not in mod_list(True):
return set()
escape_m... | Remove module from configuration file. If comment is true only comment line
where module is. | Below is the the instruction that describes the task:
### Input:
Remove module from configuration file. If comment is true only comment line
where module is.
### Response:
def _remove_persistent_module(mod, comment):
'''
Remove module from configuration file. If comment is true only comment line
wh... |
def run_state_estimation(data, clusters, dist='Poiss', reps=1, **kwargs):
"""
Runs state estimation for multiple initializations, returning the result with the highest log-likelihood. All the arguments are passed to the underlying state estimation functions (poisson_estimate_state, nb_estimate_state, zip_estima... | Runs state estimation for multiple initializations, returning the result with the highest log-likelihood. All the arguments are passed to the underlying state estimation functions (poisson_estimate_state, nb_estimate_state, zip_estimate_state).
Args:
data (array): genes x cells
clusters (int): numb... | Below is the the instruction that describes the task:
### Input:
Runs state estimation for multiple initializations, returning the result with the highest log-likelihood. All the arguments are passed to the underlying state estimation functions (poisson_estimate_state, nb_estimate_state, zip_estimate_state).
A... |
def _push_configs_to_nvram(self):
"""
Push the startup-config and private-config content to the NVRAM.
"""
startup_config_content = self.startup_config_content
if startup_config_content:
nvram_file = self._nvram_file()
try:
if not os.path.... | Push the startup-config and private-config content to the NVRAM. | Below is the the instruction that describes the task:
### Input:
Push the startup-config and private-config content to the NVRAM.
### Response:
def _push_configs_to_nvram(self):
"""
Push the startup-config and private-config content to the NVRAM.
"""
startup_config_content = self.s... |
def _initTables(self, cursor, deleteOldVersions, recreate):
""" Initialize tables, if needed
Parameters:
----------------------------------------------------------------
cursor: SQL cursor
deleteOldVersions: if true, delete any old versions of the DB left
on... | Initialize tables, if needed
Parameters:
----------------------------------------------------------------
cursor: SQL cursor
deleteOldVersions: if true, delete any old versions of the DB left
on the server
recreate: if true, recreate the database ... | Below is the the instruction that describes the task:
### Input:
Initialize tables, if needed
Parameters:
----------------------------------------------------------------
cursor: SQL cursor
deleteOldVersions: if true, delete any old versions of the DB left
o... |
def set_lineno(self, lineno, override=False):
"""Set the line numbers of the node and children."""
todo = deque([self])
while todo:
node = todo.popleft()
if 'lineno' in node.attributes:
if node.lineno is None or override:
node.lineno = ... | Set the line numbers of the node and children. | Below is the the instruction that describes the task:
### Input:
Set the line numbers of the node and children.
### Response:
def set_lineno(self, lineno, override=False):
"""Set the line numbers of the node and children."""
todo = deque([self])
while todo:
node = todo.popleft()... |
def age(self):
"""
Get the age of the PID file.
"""
# Created timestamp
created = self.created()
# Age in seconds / minutes / hours / days
age_secs = time() - created
age_mins = 0 if (age_secs < 60) else (age_secs / 60)
age_hour... | Get the age of the PID file. | Below is the the instruction that describes the task:
### Input:
Get the age of the PID file.
### Response:
def age(self):
"""
Get the age of the PID file.
"""
# Created timestamp
created = self.created()
# Age in seconds / minutes / hours / days
... |
def nearest_keys(self, key):
"""Find the nearest_keys (l2 distance) thanks to a cKDTree query"""
if not isinstance(key, tuple):
_key = (key,)
if self.__stale:
self.generate_tree()
d, idx = self.__tree.query(
_key, self.k_neighbors, distance_upper_bound... | Find the nearest_keys (l2 distance) thanks to a cKDTree query | Below is the the instruction that describes the task:
### Input:
Find the nearest_keys (l2 distance) thanks to a cKDTree query
### Response:
def nearest_keys(self, key):
"""Find the nearest_keys (l2 distance) thanks to a cKDTree query"""
if not isinstance(key, tuple):
_key = (key,)
... |
def tag_instances_on_cluster(cluster_name, project='cwc'):
"""Adds project tag to untagged instances in a given cluster.
Parameters
----------
cluster_name : str
The name of the AWS ECS cluster in which running instances
should be tagged.
project : str
The name of the projec... | Adds project tag to untagged instances in a given cluster.
Parameters
----------
cluster_name : str
The name of the AWS ECS cluster in which running instances
should be tagged.
project : str
The name of the project to tag instances with. | Below is the the instruction that describes the task:
### Input:
Adds project tag to untagged instances in a given cluster.
Parameters
----------
cluster_name : str
The name of the AWS ECS cluster in which running instances
should be tagged.
project : str
The name of the pro... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.