code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def create(cls, parent=None, **kwargs):
"""Create an object and return it"""
if parent is None:
raise Exception("Parent class is required")
route = copy(parent.route)
if cls.ID_NAME is not None:
route[cls.ID_NAME] = ""
obj = cls(key=parent.key, route=ro... | Create an object and return it | Below is the the instruction that describes the task:
### Input:
Create an object and return it
### Response:
def create(cls, parent=None, **kwargs):
"""Create an object and return it"""
if parent is None:
raise Exception("Parent class is required")
route = copy(parent.route)
... |
def from_csv(cls, path):
"""
Get box vectors from comma-separated values in file `path`.
The csv file must containt only one line, which in turn can contain
three values (orthogonal vectors) or nine values (triclinic box).
The values should be in nanometers.
Parameters... | Get box vectors from comma-separated values in file `path`.
The csv file must containt only one line, which in turn can contain
three values (orthogonal vectors) or nine values (triclinic box).
The values should be in nanometers.
Parameters
----------
path : str
... | Below is the the instruction that describes the task:
### Input:
Get box vectors from comma-separated values in file `path`.
The csv file must containt only one line, which in turn can contain
three values (orthogonal vectors) or nine values (triclinic box).
The values should be in nanomet... |
def _bucket_events(self, event_iterable):
"""
Convert an iterable of events into an iterable of lists of events
per bucket.
"""
current_bucket_time = None
current_bucket_events = None
for event in event_iterable:
event_bucket_time = self._bucket_time(event[TIMESTAMP_FIELD])
if c... | Convert an iterable of events into an iterable of lists of events
per bucket. | Below is the the instruction that describes the task:
### Input:
Convert an iterable of events into an iterable of lists of events
per bucket.
### Response:
def _bucket_events(self, event_iterable):
"""
Convert an iterable of events into an iterable of lists of events
per bucket.
"""
curre... |
def deliver(self, message, to):
"""
Deliver our message
Arguments:
- `message`: MIMEMultipart
Return: None
Exceptions: None
"""
# Send the message via local SMTP server.
s = smtplib.SMTP(self.host, self.port)
# sendmail function takes 3 a... | Deliver our message
Arguments:
- `message`: MIMEMultipart
Return: None
Exceptions: None | Below is the the instruction that describes the task:
### Input:
Deliver our message
Arguments:
- `message`: MIMEMultipart
Return: None
Exceptions: None
### Response:
def deliver(self, message, to):
"""
Deliver our message
Arguments:
- `message`: M... |
def cfloat64_array_to_numpy(cptr, length):
"""Convert a ctypes double pointer array to a numpy array."""
if isinstance(cptr, ctypes.POINTER(ctypes.c_double)):
return np.fromiter(cptr, dtype=np.float64, count=length)
else:
raise RuntimeError('Expected double pointer') | Convert a ctypes double pointer array to a numpy array. | Below is the the instruction that describes the task:
### Input:
Convert a ctypes double pointer array to a numpy array.
### Response:
def cfloat64_array_to_numpy(cptr, length):
"""Convert a ctypes double pointer array to a numpy array."""
if isinstance(cptr, ctypes.POINTER(ctypes.c_double)):
retur... |
def _fix_slicing_order(self, outer_fields, inner_select, order, inner_table_name):
"""
Apply any necessary fixes to the outer_fields, inner_select, and order
strings due to slicing.
"""
# Using ROW_NUMBER requires an ordering
if order is None:
meta = self.quer... | Apply any necessary fixes to the outer_fields, inner_select, and order
strings due to slicing. | Below is the the instruction that describes the task:
### Input:
Apply any necessary fixes to the outer_fields, inner_select, and order
strings due to slicing.
### Response:
def _fix_slicing_order(self, outer_fields, inner_select, order, inner_table_name):
"""
Apply any necessary fixes to t... |
def convert_to_adjacency_matrix(matrix):
"""
Converts transition matrix into adjacency matrix
:param matrix: The matrix to be converted
:returns: adjacency matrix
"""
for i in range(matrix.shape[0]):
if isspmatrix(matrix):
col = find(matrix[:,i])[2]
else:
... | Converts transition matrix into adjacency matrix
:param matrix: The matrix to be converted
:returns: adjacency matrix | Below is the the instruction that describes the task:
### Input:
Converts transition matrix into adjacency matrix
:param matrix: The matrix to be converted
:returns: adjacency matrix
### Response:
def convert_to_adjacency_matrix(matrix):
"""
Converts transition matrix into adjacency matrix
:p... |
def parse_qs(qs, keep_blank_values=0, strict_parsing=0, keep_attr_order=True):
"""
Kind of like urlparse.parse_qs, except returns an ordered dict.
Also avoids replicating that function's bad habit of overriding the
built-in 'dict' type.
Taken from below with modification:
<https://bitbucket.org... | Kind of like urlparse.parse_qs, except returns an ordered dict.
Also avoids replicating that function's bad habit of overriding the
built-in 'dict' type.
Taken from below with modification:
<https://bitbucket.org/btubbs/thumpy/raw/8cdece404f15/thumpy.py> | Below is the the instruction that describes the task:
### Input:
Kind of like urlparse.parse_qs, except returns an ordered dict.
Also avoids replicating that function's bad habit of overriding the
built-in 'dict' type.
Taken from below with modification:
<https://bitbucket.org/btubbs/thumpy/raw/8cd... |
def get_processing_block_ids(self):
"""Get list of processing block ids using the processing block id"""
# Initialise empty list
_processing_block_ids = []
# Pattern used to search processing block ids
pattern = '*:processing_block:*'
block_ids = self._db.get_ids(patter... | Get list of processing block ids using the processing block id | Below is the the instruction that describes the task:
### Input:
Get list of processing block ids using the processing block id
### Response:
def get_processing_block_ids(self):
"""Get list of processing block ids using the processing block id"""
# Initialise empty list
_processing_block_i... |
def exec_container(self,
asset_url,
algorithm_url,
resource_group_name,
account_name,
account_key,
location,
share_name_input='compute',
... | Prepare a docker image that will run in the cloud, mounting the asset and executing the algorithm.
:param asset_url
:param algorithm_url
:param resource_group_name:
:param account_name:
:param account_key:
:param share_name_input:
:param share_name_output:
... | Below is the the instruction that describes the task:
### Input:
Prepare a docker image that will run in the cloud, mounting the asset and executing the algorithm.
:param asset_url
:param algorithm_url
:param resource_group_name:
:param account_name:
:param account_key:
... |
def _custom_dtype_getter(self, getter, name, shape=None, dtype=DEFAULT_DTYPE,
*args, **kwargs):
"""Creates variables in fp32, then casts to fp16 if necessary.
This function is a custom getter. A custom getter is a function with the
same signature as tf.get_variable, except it has... | Creates variables in fp32, then casts to fp16 if necessary.
This function is a custom getter. A custom getter is a function with the
same signature as tf.get_variable, except it has an additional getter
parameter. Custom getters can be passed as the `custom_getter` parameter of
tf.variable_scope. Then,... | Below is the the instruction that describes the task:
### Input:
Creates variables in fp32, then casts to fp16 if necessary.
This function is a custom getter. A custom getter is a function with the
same signature as tf.get_variable, except it has an additional getter
parameter. Custom getters can be pa... |
def do_NOTIFY(self): # pylint: disable=invalid-name
"""Serve a ``NOTIFY`` request.
A ``NOTIFY`` request will be sent by a Sonos device when a state
variable changes. See the `UPnP Spec §4.3 [pdf]
<http://upnp.org/specs/arch/UPnP-arch
-DeviceArchitecture-v1.1.pdf>`_ for details... | Serve a ``NOTIFY`` request.
A ``NOTIFY`` request will be sent by a Sonos device when a state
variable changes. See the `UPnP Spec §4.3 [pdf]
<http://upnp.org/specs/arch/UPnP-arch
-DeviceArchitecture-v1.1.pdf>`_ for details. | Below is the the instruction that describes the task:
### Input:
Serve a ``NOTIFY`` request.
A ``NOTIFY`` request will be sent by a Sonos device when a state
variable changes. See the `UPnP Spec §4.3 [pdf]
<http://upnp.org/specs/arch/UPnP-arch
-DeviceArchitecture-v1.1.pdf>`_ for de... |
def _check_pillar(kwargs, pillar=None):
'''
Check the pillar for errors, refuse to run the state if there are errors
in the pillar and return the pillar errors
'''
if kwargs.get('force'):
return True
pillar_dict = pillar if pillar is not None else __pillar__
if '_errors' in pillar_di... | Check the pillar for errors, refuse to run the state if there are errors
in the pillar and return the pillar errors | Below is the the instruction that describes the task:
### Input:
Check the pillar for errors, refuse to run the state if there are errors
in the pillar and return the pillar errors
### Response:
def _check_pillar(kwargs, pillar=None):
'''
Check the pillar for errors, refuse to run the state if there ar... |
def tree_line_generator(el, max_lines=None):
"""
Internal generator that iterates through an LXML tree and yields a tuple
per line. In this context, lines are blocks of text separated by <br> tags
or by block elements. The tuples contain the following elements:
- A tuple with the element reference ... | Internal generator that iterates through an LXML tree and yields a tuple
per line. In this context, lines are blocks of text separated by <br> tags
or by block elements. The tuples contain the following elements:
- A tuple with the element reference (element, position) for the start
of the line. The ... | Below is the the instruction that describes the task:
### Input:
Internal generator that iterates through an LXML tree and yields a tuple
per line. In this context, lines are blocks of text separated by <br> tags
or by block elements. The tuples contain the following elements:
- A tuple with the elemen... |
def login(self, password='', captcha='', email_code='', twofactor_code='', language='english'):
"""Attempts web login and returns on a session with cookies set
:param password: password, if it wasn't provided on instance init
:type password: :class:`str`
:param captcha: text reponse fo... | Attempts web login and returns on a session with cookies set
:param password: password, if it wasn't provided on instance init
:type password: :class:`str`
:param captcha: text reponse for captcha challenge
:type captcha: :class:`str`
:param email_code: email code for steam gu... | Below is the the instruction that describes the task:
### Input:
Attempts web login and returns on a session with cookies set
:param password: password, if it wasn't provided on instance init
:type password: :class:`str`
:param captcha: text reponse for captcha challenge
:type cap... |
def pprint2columns(llist, max_length=60):
"""
llist = a list of strings
max_length = if a word is longer than that, for single col display
> prints a list in two columns, taking care of alignment too
"""
if len(llist) == 0:
return None
col_width = max(len(word) for word in llist) +... | llist = a list of strings
max_length = if a word is longer than that, for single col display
> prints a list in two columns, taking care of alignment too | Below is the the instruction that describes the task:
### Input:
llist = a list of strings
max_length = if a word is longer than that, for single col display
> prints a list in two columns, taking care of alignment too
### Response:
def pprint2columns(llist, max_length=60):
"""
llist = a list of s... |
def _get_field(self, extras, field, default=None):
"""
Fetches a field from extras, and returns it. This is some Airflow
magic. The google_cloud_platform hook type adds custom UI elements
to the hook page, which allow admins to specify service_account,
key_path, etc. They get for... | Fetches a field from extras, and returns it. This is some Airflow
magic. The google_cloud_platform hook type adds custom UI elements
to the hook page, which allow admins to specify service_account,
key_path, etc. They get formatted as shown below. | Below is the the instruction that describes the task:
### Input:
Fetches a field from extras, and returns it. This is some Airflow
magic. The google_cloud_platform hook type adds custom UI elements
to the hook page, which allow admins to specify service_account,
key_path, etc. They get forma... |
def update_case_compounds(self, case_obj, build='37'):
"""Update the compounds for a case
Loop over all coding intervals to get coordinates for all potential compound positions.
Update all variants within a gene with a bulk operation.
"""
case_id = case_obj['_id']
# Pos... | Update the compounds for a case
Loop over all coding intervals to get coordinates for all potential compound positions.
Update all variants within a gene with a bulk operation. | Below is the the instruction that describes the task:
### Input:
Update the compounds for a case
Loop over all coding intervals to get coordinates for all potential compound positions.
Update all variants within a gene with a bulk operation.
### Response:
def update_case_compounds(self, case_obj, ... |
def get_comment_group_for_path(self, pathname, default_content_type=None):
"""
Obtains the comment group for a specified pathname.
:param pathname:
The path for which the comment group will be obtained.
:return:
Returns the comment group for the specified pathnam... | Obtains the comment group for a specified pathname.
:param pathname:
The path for which the comment group will be obtained.
:return:
Returns the comment group for the specified pathname
or raises a ``ValueError`` if a content type is not found
or raises a... | Below is the the instruction that describes the task:
### Input:
Obtains the comment group for a specified pathname.
:param pathname:
The path for which the comment group will be obtained.
:return:
Returns the comment group for the specified pathname
or raises a ... |
def as_single_element(self):
"""
Processes the response as a single-element response,
like config_get or system_counters_get.
If there is more then one element in the response or no
elements this raises a ResponseError
"""
if self.as_return_etree is None:
... | Processes the response as a single-element response,
like config_get or system_counters_get.
If there is more then one element in the response or no
elements this raises a ResponseError | Below is the the instruction that describes the task:
### Input:
Processes the response as a single-element response,
like config_get or system_counters_get.
If there is more then one element in the response or no
elements this raises a ResponseError
### Response:
def as_single_element(self... |
def _complete_values(self, symbol = ""):
"""Compiles a list of possible symbols that can hold a value in
place. These consist of local vars, global vars, and functions."""
result = {}
#Also add the subroutines from the module and its dependencies.
moddict = self._generic_filter_e... | Compiles a list of possible symbols that can hold a value in
place. These consist of local vars, global vars, and functions. | Below is the the instruction that describes the task:
### Input:
Compiles a list of possible symbols that can hold a value in
place. These consist of local vars, global vars, and functions.
### Response:
def _complete_values(self, symbol = ""):
"""Compiles a list of possible symbols that can hold a... |
def _construct_axes_dict(self, axes=None, **kwargs):
"""Return an axes dictionary for myself."""
d = {a: self._get_axis(a) for a in (axes or self._AXIS_ORDERS)}
d.update(kwargs)
return d | Return an axes dictionary for myself. | Below is the the instruction that describes the task:
### Input:
Return an axes dictionary for myself.
### Response:
def _construct_axes_dict(self, axes=None, **kwargs):
"""Return an axes dictionary for myself."""
d = {a: self._get_axis(a) for a in (axes or self._AXIS_ORDERS)}
d.update(kwar... |
def shapes(self, simplify=None, predicate=None):
"""
Return geodata as a list of Shapely shapes
:param simplify: Integer or None. Simplify the geometry to a tolerance, in the units of the geometry.
:param predicate: A single-argument function to select which records to include in the ou... | Return geodata as a list of Shapely shapes
:param simplify: Integer or None. Simplify the geometry to a tolerance, in the units of the geometry.
:param predicate: A single-argument function to select which records to include in the output.
:return: A list of Shapely objects | Below is the the instruction that describes the task:
### Input:
Return geodata as a list of Shapely shapes
:param simplify: Integer or None. Simplify the geometry to a tolerance, in the units of the geometry.
:param predicate: A single-argument function to select which records to include in the ou... |
def CSWAP(control, target_1, target_2):
"""Produces a controlled-SWAP gate. This gate conditionally swaps the state of two qubits::
CSWAP = [[1, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0],
... | Produces a controlled-SWAP gate. This gate conditionally swaps the state of two qubits::
CSWAP = [[1, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0],
... | Below is the the instruction that describes the task:
### Input:
Produces a controlled-SWAP gate. This gate conditionally swaps the state of two qubits::
CSWAP = [[1, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0,... |
def eeg_complexity(eeg, sampling_rate, times=None, index=None, include="all", exclude=None, hemisphere="both", central=True, verbose=True, shannon=True, sampen=True, multiscale=True, spectral=True, svd=True, correlation=True, higushi=True, petrosian=True, fisher=True, hurst=True, dfa=True, lyap_r=False, lyap_e=False, n... | Compute complexity indices of epochs or raw object.
DOCS INCOMPLETE :( | Below is the the instruction that describes the task:
### Input:
Compute complexity indices of epochs or raw object.
DOCS INCOMPLETE :(
### Response:
def eeg_complexity(eeg, sampling_rate, times=None, index=None, include="all", exclude=None, hemisphere="both", central=True, verbose=True, shannon=True, sampen=... |
def respond_redirect(self, location='/'):
"""
Respond to the client with a 301 message and redirect them with
a Location header.
:param str location: The new location to redirect the client to.
"""
self.send_response(301)
self.send_header('Content-Length', 0)
self.send_header('Location', location)
se... | Respond to the client with a 301 message and redirect them with
a Location header.
:param str location: The new location to redirect the client to. | Below is the the instruction that describes the task:
### Input:
Respond to the client with a 301 message and redirect them with
a Location header.
:param str location: The new location to redirect the client to.
### Response:
def respond_redirect(self, location='/'):
"""
Respond to the client with a 301 ... |
def create_project(self, name, description):
"""
Create a new project with the specified name and description
:param name: str: name of the project to create
:param description: str: description of the project to create
:return: Project
"""
return self._create_ite... | Create a new project with the specified name and description
:param name: str: name of the project to create
:param description: str: description of the project to create
:return: Project | Below is the the instruction that describes the task:
### Input:
Create a new project with the specified name and description
:param name: str: name of the project to create
:param description: str: description of the project to create
:return: Project
### Response:
def create_project(self,... |
def get_random_string():
""" make a random string, which we can use for bsub job IDs, so that
different jobs do not have the same job IDs.
"""
# set up a random string to associate with the run
hash_string = "%8x" % random.getrandbits(32)
hash_string = hash_string.strip()
# done't ... | make a random string, which we can use for bsub job IDs, so that
different jobs do not have the same job IDs. | Below is the the instruction that describes the task:
### Input:
make a random string, which we can use for bsub job IDs, so that
different jobs do not have the same job IDs.
### Response:
def get_random_string():
""" make a random string, which we can use for bsub job IDs, so that
different jobs do no... |
def extract_upgrade_scripts(self):
"""
Extract the OpenQuake upgrade scripts from the links in the GitHub page
"""
link_pattern = '>\s*{0}\s*<'.format(self.pattern[1:-1])
page = urllib.request.urlopen(self.upgrades_url).read()
for mo in re.finditer(link_pattern, page):
... | Extract the OpenQuake upgrade scripts from the links in the GitHub page | Below is the the instruction that describes the task:
### Input:
Extract the OpenQuake upgrade scripts from the links in the GitHub page
### Response:
def extract_upgrade_scripts(self):
"""
Extract the OpenQuake upgrade scripts from the links in the GitHub page
"""
link_pattern = '>... |
def timedelta_seconds(value: datetime.timedelta) -> int:
"""Return full number of seconds from timedelta.
By default, Python returns only one day seconds, not all timedelta seconds.
:param value: Timedelta instance.
"""
return SECONDS_PER_DAY * value.days + value.seconds | Return full number of seconds from timedelta.
By default, Python returns only one day seconds, not all timedelta seconds.
:param value: Timedelta instance. | Below is the the instruction that describes the task:
### Input:
Return full number of seconds from timedelta.
By default, Python returns only one day seconds, not all timedelta seconds.
:param value: Timedelta instance.
### Response:
def timedelta_seconds(value: datetime.timedelta) -> int:
"""Return... |
def get_type_data(name):
"""Return dictionary representation of type.
Can be used to initialize primordium.type.primitives.Type
"""
name = name.upper()
try:
return {
'authority': 'okapia.net',
'namespace': 'heading',
'identifier': name,
'doma... | Return dictionary representation of type.
Can be used to initialize primordium.type.primitives.Type | Below is the the instruction that describes the task:
### Input:
Return dictionary representation of type.
Can be used to initialize primordium.type.primitives.Type
### Response:
def get_type_data(name):
"""Return dictionary representation of type.
Can be used to initialize primordium.type.primitives... |
def anno_parser(func):
"Look at params (annotated with `Param`) in func and return an `ArgumentParser`"
p = ArgumentParser(description=func.__doc__)
for k,v in inspect.signature(func).parameters.items():
param = func.__annotations__.get(k, Param())
kwargs = param.kwargs
if v.default ... | Look at params (annotated with `Param`) in func and return an `ArgumentParser` | Below is the the instruction that describes the task:
### Input:
Look at params (annotated with `Param`) in func and return an `ArgumentParser`
### Response:
def anno_parser(func):
"Look at params (annotated with `Param`) in func and return an `ArgumentParser`"
p = ArgumentParser(description=func.__doc__)
... |
def set_environment_variable(self, key, val):
""" Sets a variable if that variable is not already set """
if self.get_environment_variable(key) in [None, val]:
self.__dict__['environment_variables'][key] = val
else:
raise Contradiction("Could not set environment variable ... | Sets a variable if that variable is not already set | Below is the the instruction that describes the task:
### Input:
Sets a variable if that variable is not already set
### Response:
def set_environment_variable(self, key, val):
""" Sets a variable if that variable is not already set """
if self.get_environment_variable(key) in [None, val]:
... |
def is50or60(msg, spd_ref, trk_ref, alt_ref):
"""Use reference ground speed and trk to determine BDS50 and DBS60.
Args:
msg (String): 28 bytes hexadecimal message string
spd_ref (float): reference speed (ADS-B ground speed), kts
trk_ref (float): reference track (ADS-B track angle), deg
... | Use reference ground speed and trk to determine BDS50 and DBS60.
Args:
msg (String): 28 bytes hexadecimal message string
spd_ref (float): reference speed (ADS-B ground speed), kts
trk_ref (float): reference track (ADS-B track angle), deg
alt_ref (float): reference altitude (ADS-B al... | Below is the the instruction that describes the task:
### Input:
Use reference ground speed and trk to determine BDS50 and DBS60.
Args:
msg (String): 28 bytes hexadecimal message string
spd_ref (float): reference speed (ADS-B ground speed), kts
trk_ref (float): reference track (ADS-B tr... |
def get(self, id):
"""
Get an by object by unique identifier
:id string id: the bson id of an object
:rtype: JSON
"""
try:
if self.request.headers.get("Id"):
object_ = yield self.client.find_one({self.request.headers.get("Id"): id})
... | Get an by object by unique identifier
:id string id: the bson id of an object
:rtype: JSON | Below is the the instruction that describes the task:
### Input:
Get an by object by unique identifier
:id string id: the bson id of an object
:rtype: JSON
### Response:
def get(self, id):
"""
Get an by object by unique identifier
:id string id: the bson id of an object
... |
def organization_field_show(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/organization_fields#show-organization-field"
api_path = "/api/v2/organization_fields/{id}.json"
api_path = api_path.format(id=id)
return self.call(api_path, **kwargs) | https://developer.zendesk.com/rest_api/docs/core/organization_fields#show-organization-field | Below is the the instruction that describes the task:
### Input:
https://developer.zendesk.com/rest_api/docs/core/organization_fields#show-organization-field
### Response:
def organization_field_show(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/organization_fields#show-organizatio... |
def shift_right(self, times=1):
"""
Finds Location shifted right by 1
:rtype: Location
"""
try:
return Location(self._rank, self._file + times)
except IndexError as e:
raise IndexError(e) | Finds Location shifted right by 1
:rtype: Location | Below is the the instruction that describes the task:
### Input:
Finds Location shifted right by 1
:rtype: Location
### Response:
def shift_right(self, times=1):
"""
Finds Location shifted right by 1
:rtype: Location
"""
try:
return Location(self._rank,... |
def find_le_index(self, k):
'Return last item with a key <= k. Raise ValueError if not found.'
i = bisect_right(self._keys, k)
if i:
return i - 1
raise ValueError('No item found with key at or below: %r' % (k,)) | Return last item with a key <= k. Raise ValueError if not found. | Below is the the instruction that describes the task:
### Input:
Return last item with a key <= k. Raise ValueError if not found.
### Response:
def find_le_index(self, k):
'Return last item with a key <= k. Raise ValueError if not found.'
i = bisect_right(self._keys, k)
if i:
... |
def get_metadata():
"""Get pandas.DataFrame with metadata about the PWM's. Columns:
- PWM_id (id of the PWM - pass to get_pwm_list() for getting the pwm
- info1 - additional information about the motifs
- info2
- consensus: PWM consensus sequence
"""
motifs = _load_motifs()
motif_names... | Get pandas.DataFrame with metadata about the PWM's. Columns:
- PWM_id (id of the PWM - pass to get_pwm_list() for getting the pwm
- info1 - additional information about the motifs
- info2
- consensus: PWM consensus sequence | Below is the the instruction that describes the task:
### Input:
Get pandas.DataFrame with metadata about the PWM's. Columns:
- PWM_id (id of the PWM - pass to get_pwm_list() for getting the pwm
- info1 - additional information about the motifs
- info2
- consensus: PWM consensus sequence
### Respon... |
def clearContents(cls):
"""Clear contents of general pasteboard.
Future enhancement can include specifying which clipboard to clear
Returns: True on success; caller should expect to catch exceptions,
probably from AppKit (ValueError)
"""
log_msg = 'Request to cl... | Clear contents of general pasteboard.
Future enhancement can include specifying which clipboard to clear
Returns: True on success; caller should expect to catch exceptions,
probably from AppKit (ValueError) | Below is the the instruction that describes the task:
### Input:
Clear contents of general pasteboard.
Future enhancement can include specifying which clipboard to clear
Returns: True on success; caller should expect to catch exceptions,
probably from AppKit (ValueError)
### Respon... |
def unpack(self, source: IO):
"""
Read the ConstantPool from the file-like object `source`.
.. note::
Advanced usage only. You will typically never need to call this
method as it will be called for you when loading a ClassFile.
:param source: Any file-like obje... | Read the ConstantPool from the file-like object `source`.
.. note::
Advanced usage only. You will typically never need to call this
method as it will be called for you when loading a ClassFile.
:param source: Any file-like object providing `read()` | Below is the the instruction that describes the task:
### Input:
Read the ConstantPool from the file-like object `source`.
.. note::
Advanced usage only. You will typically never need to call this
method as it will be called for you when loading a ClassFile.
:param source:... |
def compile_theme(theme_id=None):
"""Compiles a theme."""
from engineer.processors import convert_less
from engineer.themes import ThemeManager
if theme_id is None:
themes = ThemeManager.themes().values()
else:
themes = [ThemeManager.theme(theme_id)]
with(indent(2)):
pu... | Compiles a theme. | Below is the the instruction that describes the task:
### Input:
Compiles a theme.
### Response:
def compile_theme(theme_id=None):
"""Compiles a theme."""
from engineer.processors import convert_less
from engineer.themes import ThemeManager
if theme_id is None:
themes = ThemeManager.themes... |
def visit_call(self, node, parent):
"""visit a CallFunc node by returning a fresh instance of it"""
newnode = nodes.Call(node.lineno, node.col_offset, parent)
starargs = _visit_or_none(node, "starargs", self, newnode)
kwargs = _visit_or_none(node, "kwargs", self, newnode)
args = ... | visit a CallFunc node by returning a fresh instance of it | Below is the the instruction that describes the task:
### Input:
visit a CallFunc node by returning a fresh instance of it
### Response:
def visit_call(self, node, parent):
"""visit a CallFunc node by returning a fresh instance of it"""
newnode = nodes.Call(node.lineno, node.col_offset, parent)
... |
def get_beam(header):
"""
Create a :class:`AegeanTools.fits_image.Beam` object from a fits header.
BPA may be missing but will be assumed to be zero.
if BMAJ or BMIN are missing then return None instead of a beam object.
Parameters
----------
header : HDUHeader
The fits header.
... | Create a :class:`AegeanTools.fits_image.Beam` object from a fits header.
BPA may be missing but will be assumed to be zero.
if BMAJ or BMIN are missing then return None instead of a beam object.
Parameters
----------
header : HDUHeader
The fits header.
Returns
-------
beam : ... | Below is the the instruction that describes the task:
### Input:
Create a :class:`AegeanTools.fits_image.Beam` object from a fits header.
BPA may be missing but will be assumed to be zero.
if BMAJ or BMIN are missing then return None instead of a beam object.
Parameters
----------
header : HD... |
def safe_join(base, *paths):
"""
Joins one or more path components to the base path component intelligently.
Returns a normalized, absolute version of the final path.
The final path must be located inside of the base path component (otherwise
a ValueError is raised).
"""
base = base
pat... | Joins one or more path components to the base path component intelligently.
Returns a normalized, absolute version of the final path.
The final path must be located inside of the base path component (otherwise
a ValueError is raised). | Below is the the instruction that describes the task:
### Input:
Joins one or more path components to the base path component intelligently.
Returns a normalized, absolute version of the final path.
The final path must be located inside of the base path component (otherwise
a ValueError is raised).
###... |
def device_characteristics_str(self, indent):
"""Convenience to string method.
"""
s = "{}\n".format(self.label)
s += indent + "MAC Address: {}\n".format(self.mac_addr)
s += indent + "IP Address: {}\n".format(self.ip_addr)
s += indent + "Port: {}\n".format(self.port)
... | Convenience to string method. | Below is the the instruction that describes the task:
### Input:
Convenience to string method.
### Response:
def device_characteristics_str(self, indent):
"""Convenience to string method.
"""
s = "{}\n".format(self.label)
s += indent + "MAC Address: {}\n".format(self.mac_addr)
... |
def set(self, name, value, index=-1):
"""
Assign the ``value`` to the child having the given ``name`` at the ``index`` position
:type name: ``str``
:param name: the child name (e.g. PID)
:type value: an instance of :class:`Element <hl7apy.core.Element>`, a `str` or an instance ... | Assign the ``value`` to the child having the given ``name`` at the ``index`` position
:type name: ``str``
:param name: the child name (e.g. PID)
:type value: an instance of :class:`Element <hl7apy.core.Element>`, a `str` or an instance of
:class:`ElementProxy <hl7apy.core.ElementPr... | Below is the the instruction that describes the task:
### Input:
Assign the ``value`` to the child having the given ``name`` at the ``index`` position
:type name: ``str``
:param name: the child name (e.g. PID)
:type value: an instance of :class:`Element <hl7apy.core.Element>`, a `str` or a... |
def create_perturb_params(countsmat, transmat=None):
'''
Computes transition probabilities and standard errors of the transition probabilities due to
finite sampling using the MSM counts matrix. First, the transition probabilities are computed
by dividing the each element c_ij by the row-sumemd counts... | Computes transition probabilities and standard errors of the transition probabilities due to
finite sampling using the MSM counts matrix. First, the transition probabilities are computed
by dividing the each element c_ij by the row-sumemd counts of row i. THe standard errors are then
computed by first com... | Below is the the instruction that describes the task:
### Input:
Computes transition probabilities and standard errors of the transition probabilities due to
finite sampling using the MSM counts matrix. First, the transition probabilities are computed
by dividing the each element c_ij by the row-sumemd co... |
def _resolve_graph(self, distribution_names=None, leaf_name='x'):
"""Creates a `tuple` of `tuple`s of dependencies.
This function is **experimental**. That said, we encourage its use
and ask that you report problems to `tfprobability@tensorflow.org`.
Args:
distribution_names: `list` of `str` or ... | Creates a `tuple` of `tuple`s of dependencies.
This function is **experimental**. That said, we encourage its use
and ask that you report problems to `tfprobability@tensorflow.org`.
Args:
distribution_names: `list` of `str` or `None` names corresponding to each
of `model` elements. (`None`s ... | Below is the the instruction that describes the task:
### Input:
Creates a `tuple` of `tuple`s of dependencies.
This function is **experimental**. That said, we encourage its use
and ask that you report problems to `tfprobability@tensorflow.org`.
Args:
distribution_names: `list` of `str` or `Non... |
def process_actions(self, actions):
"""Process the actions we want to take
Args:
actions (`list`): List of actions we want to take
Returns:
`list` of notifications
"""
notices = {}
notification_contacts = {}
for action in actions:
... | Process the actions we want to take
Args:
actions (`list`): List of actions we want to take
Returns:
`list` of notifications | Below is the the instruction that describes the task:
### Input:
Process the actions we want to take
Args:
actions (`list`): List of actions we want to take
Returns:
`list` of notifications
### Response:
def process_actions(self, actions):
"""Process the actions we... |
def predict(self, timeseriesX, n, m):
"""
Calculates the dependent timeseries Y for the given parameters
and independent timeseries. (y=m*x + n)
:param TimeSeries timeseriesX: the independent Timeseries.
:param float n: The interception with the x access
that has be... | Calculates the dependent timeseries Y for the given parameters
and independent timeseries. (y=m*x + n)
:param TimeSeries timeseriesX: the independent Timeseries.
:param float n: The interception with the x access
that has been calculated during regression
:param float m: T... | Below is the the instruction that describes the task:
### Input:
Calculates the dependent timeseries Y for the given parameters
and independent timeseries. (y=m*x + n)
:param TimeSeries timeseriesX: the independent Timeseries.
:param float n: The interception with the x access
... |
def _is_pid_running_on_windows(pid):
"""
Check if PID is running for Windows systems
"""
import ctypes.wintypes
kernel32 = ctypes.windll.kernel32
handle = kernel32.OpenProcess(1, 0, pid)
if handle == 0:
return False
exit_code = ctypes.wintypes.DWORD()
ret = kernel32.GetExitC... | Check if PID is running for Windows systems | Below is the the instruction that describes the task:
### Input:
Check if PID is running for Windows systems
### Response:
def _is_pid_running_on_windows(pid):
"""
Check if PID is running for Windows systems
"""
import ctypes.wintypes
kernel32 = ctypes.windll.kernel32
handle = kernel32.Ope... |
def router_fabric_virtual_gateway_address_family_ipv6_gateway_mac_address(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
router = ET.SubElement(config, "router", xmlns="urn:brocade.com:mgmt:brocade-common-def")
fabric_virtual_gateway = ET.SubElement(rou... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def router_fabric_virtual_gateway_address_family_ipv6_gateway_mac_address(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
router = ET.SubElement(config, "rout... |
def get_topology(self):
"""
Get the converted topology ready for JSON encoding
:return: converted topology assembled into a single dict
:rtype: dict
"""
topology = {'name': self._name,
'resources_type': 'local',
'topology': {},
... | Get the converted topology ready for JSON encoding
:return: converted topology assembled into a single dict
:rtype: dict | Below is the the instruction that describes the task:
### Input:
Get the converted topology ready for JSON encoding
:return: converted topology assembled into a single dict
:rtype: dict
### Response:
def get_topology(self):
"""
Get the converted topology ready for JSON encoding
... |
def datastore(self, domain, data_type, mapping=None):
"""Get instance of the DataStore module.
Args:
domain (str): The domain can be either "system", "organization", or "local". When using
"organization" the data store can be accessed by any Application in the entire org,
... | Get instance of the DataStore module.
Args:
domain (str): The domain can be either "system", "organization", or "local". When using
"organization" the data store can be accessed by any Application in the entire org,
while "local" access is restricted to the App writi... | Below is the the instruction that describes the task:
### Input:
Get instance of the DataStore module.
Args:
domain (str): The domain can be either "system", "organization", or "local". When using
"organization" the data store can be accessed by any Application in the entire org... |
def update_avatar(self):
'''更新用户头像'''
def do_update_avatar(info, error=None):
if error or not info:
logger.error('Failed to get user avatar: %s, %s' %
(info, error))
else:
uk, uname, img_path = info
self... | 更新用户头像 | Below is the the instruction that describes the task:
### Input:
更新用户头像
### Response:
def update_avatar(self):
'''更新用户头像'''
def do_update_avatar(info, error=None):
if error or not info:
logger.error('Failed to get user avatar: %s, %s' %
(info... |
def clusterdown_wrapper(func):
"""
Wrapper for CLUSTERDOWN error handling.
If the cluster reports it is down it is assumed that:
- connection_pool was disconnected
- connection_pool was reseted
- refereh_table_asap set to True
It will try 3 times to rerun the command and raises ClusterD... | Wrapper for CLUSTERDOWN error handling.
If the cluster reports it is down it is assumed that:
- connection_pool was disconnected
- connection_pool was reseted
- refereh_table_asap set to True
It will try 3 times to rerun the command and raises ClusterDownException if it continues to fail. | Below is the the instruction that describes the task:
### Input:
Wrapper for CLUSTERDOWN error handling.
If the cluster reports it is down it is assumed that:
- connection_pool was disconnected
- connection_pool was reseted
- refereh_table_asap set to True
It will try 3 times to rerun the c... |
def get_journal_abstracts(self, refresh=True):
"""Return a list of ScopusAbstract objects using ScopusSearch,
but only if belonging to a Journal."""
return [abstract for abstract in self.get_abstracts(refresh=refresh) if
abstract.aggregationType == 'Journal'] | Return a list of ScopusAbstract objects using ScopusSearch,
but only if belonging to a Journal. | Below is the the instruction that describes the task:
### Input:
Return a list of ScopusAbstract objects using ScopusSearch,
but only if belonging to a Journal.
### Response:
def get_journal_abstracts(self, refresh=True):
"""Return a list of ScopusAbstract objects using ScopusSearch,
... |
def _is_in_max_difference(value_1, value_2, max_difference):
''' Helper function to determine the difference of two values that can be np.uints. Works in python and numba mode.
Circumvents numba bug #1653
'''
if value_1 <= value_2:
return value_2 - value_1 <= max_difference
return value_1 - ... | Helper function to determine the difference of two values that can be np.uints. Works in python and numba mode.
Circumvents numba bug #1653 | Below is the the instruction that describes the task:
### Input:
Helper function to determine the difference of two values that can be np.uints. Works in python and numba mode.
Circumvents numba bug #1653
### Response:
def _is_in_max_difference(value_1, value_2, max_difference):
''' Helper function to dete... |
def start_connect(self):
"""Tries to connect to the Heron Server
``loop()`` method needs to be called after this.
"""
Log.debug("In start_connect() of %s" % self._get_classname())
# TODO: specify buffer size, exception handling
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
# when ... | Tries to connect to the Heron Server
``loop()`` method needs to be called after this. | Below is the the instruction that describes the task:
### Input:
Tries to connect to the Heron Server
``loop()`` method needs to be called after this.
### Response:
def start_connect(self):
"""Tries to connect to the Heron Server
``loop()`` method needs to be called after this.
"""
Log.debug(... |
def pdu_to_function_code_or_raise_error(resp_pdu):
""" Parse response PDU and return of :class:`ModbusFunction` or
raise error.
:param resp_pdu: PDU of response.
:return: Subclass of :class:`ModbusFunction` matching the response.
:raises ModbusError: When response contains error code.
"""
f... | Parse response PDU and return of :class:`ModbusFunction` or
raise error.
:param resp_pdu: PDU of response.
:return: Subclass of :class:`ModbusFunction` matching the response.
:raises ModbusError: When response contains error code. | Below is the the instruction that describes the task:
### Input:
Parse response PDU and return of :class:`ModbusFunction` or
raise error.
:param resp_pdu: PDU of response.
:return: Subclass of :class:`ModbusFunction` matching the response.
:raises ModbusError: When response contains error code.
###... |
def fit(self, X, y, cv=None, class_weight='auto'):
""" Fits X to outcomes y, using clf """
# Incorporate error checking such as :
# if isinstance(self.classifier, ScikitClassifier):
# do one thingNone
# otherwiseNone.
self.X = X
self.y = y
self.set_... | Fits X to outcomes y, using clf | Below is the the instruction that describes the task:
### Input:
Fits X to outcomes y, using clf
### Response:
def fit(self, X, y, cv=None, class_weight='auto'):
""" Fits X to outcomes y, using clf """
# Incorporate error checking such as :
# if isinstance(self.classifier, ScikitClassifier... |
def new(cls, settings, *args, **kwargs):
"""
Create a new Cloud instance based on the Settings
"""
logger.debug('Initializing new "%s" Instance object' % settings['CLOUD'])
cloud = settings['CLOUD']
if cloud == 'bare':
self = BareInstance(settings=settings, *a... | Create a new Cloud instance based on the Settings | Below is the the instruction that describes the task:
### Input:
Create a new Cloud instance based on the Settings
### Response:
def new(cls, settings, *args, **kwargs):
"""
Create a new Cloud instance based on the Settings
"""
logger.debug('Initializing new "%s" Instance object' % ... |
def _build_command(self, cmd_1, cmd_2=None,
select=False, select_command=None):
"""
Constructs the complete command.
:param cmd_1: Light command 1.
:param cmd_2: Light command 2.
:param select: If command requires selection.
:param select_command: S... | Constructs the complete command.
:param cmd_1: Light command 1.
:param cmd_2: Light command 2.
:param select: If command requires selection.
:param select_command: Selection command bytes.
:return: The complete command. | Below is the the instruction that describes the task:
### Input:
Constructs the complete command.
:param cmd_1: Light command 1.
:param cmd_2: Light command 2.
:param select: If command requires selection.
:param select_command: Selection command bytes.
:return: The complete ... |
def get_tshark_interfaces(tshark_path=None):
"""
Returns a list of interface numbers from the output tshark -D. Used
internally to capture on multiple interfaces.
"""
parameters = [get_process_path(tshark_path), '-D']
with open(os.devnull, 'w') as null:
tshark_interfaces = subprocess.che... | Returns a list of interface numbers from the output tshark -D. Used
internally to capture on multiple interfaces. | Below is the the instruction that describes the task:
### Input:
Returns a list of interface numbers from the output tshark -D. Used
internally to capture on multiple interfaces.
### Response:
def get_tshark_interfaces(tshark_path=None):
"""
Returns a list of interface numbers from the output tshark -D... |
def remove_threadlocal(self, name):
"""
Args:
name (str | unicode): Remove entry with `name` from current thread's context
"""
with self._lock:
if self._tpayload is not None:
if name in self._tpayload.context:
del self._tpayload... | Args:
name (str | unicode): Remove entry with `name` from current thread's context | Below is the the instruction that describes the task:
### Input:
Args:
name (str | unicode): Remove entry with `name` from current thread's context
### Response:
def remove_threadlocal(self, name):
"""
Args:
name (str | unicode): Remove entry with `name` from current thread'... |
def _update_parent_attachments(self):
""" Tries to update the parent property 'has_attachments' """
try:
self._parent.has_attachments = bool(len(self.__attachments))
except AttributeError:
pass | Tries to update the parent property 'has_attachments' | Below is the the instruction that describes the task:
### Input:
Tries to update the parent property 'has_attachments'
### Response:
def _update_parent_attachments(self):
""" Tries to update the parent property 'has_attachments' """
try:
self._parent.has_attachments = bool(len(self.__at... |
def update_flagfile(flags_path, new_threshold):
"""Updates the flagfile at `flags_path`, changing the value for
`resign_threshold` to `new_threshold`
"""
if abs(new_threshold) > 1:
raise ValueError("Invalid new percentile for resign threshold")
with tf.gfile.GFile(flags_path) as f:
l... | Updates the flagfile at `flags_path`, changing the value for
`resign_threshold` to `new_threshold` | Below is the the instruction that describes the task:
### Input:
Updates the flagfile at `flags_path`, changing the value for
`resign_threshold` to `new_threshold`
### Response:
def update_flagfile(flags_path, new_threshold):
"""Updates the flagfile at `flags_path`, changing the value for
`resign_thres... |
def _from_binary_reparse(cls, binary_stream):
"""See base class."""
''' Reparse type flags - 4
Reparse tag - 4 bits
Reserved - 12 bits
Reparse type - 2 bits
Reparse data length - 2
Padding - 2
'''
#content = cls._REPR.unpack(binary_view[:cls._REPR.size... | See base class. | Below is the the instruction that describes the task:
### Input:
See base class.
### Response:
def _from_binary_reparse(cls, binary_stream):
"""See base class."""
''' Reparse type flags - 4
Reparse tag - 4 bits
Reserved - 12 bits
Reparse type - 2 bits
Reparse dat... |
def stop(self):
'''
Shuts the server down and waits for server thread to join
'''
self._server.shutdown()
self._server.server_close()
self._thread.join()
self.running = False | Shuts the server down and waits for server thread to join | Below is the the instruction that describes the task:
### Input:
Shuts the server down and waits for server thread to join
### Response:
def stop(self):
'''
Shuts the server down and waits for server thread to join
'''
self._server.shutdown()
self._server.server_close()
... |
def _set_internal_compiler_error(self):
"""
Adds the false positive to description and changes severity to low
"""
self.severity = "Low"
self.description_tail += (
" This issue is reported for internal compiler generated code."
)
self.description = "%s... | Adds the false positive to description and changes severity to low | Below is the the instruction that describes the task:
### Input:
Adds the false positive to description and changes severity to low
### Response:
def _set_internal_compiler_error(self):
"""
Adds the false positive to description and changes severity to low
"""
self.severity = "Low"
... |
def unauthorized(cls, errors=None):
"""Shortcut API for HTTP 401 `Unauthorized` response.
Args:
errors (list): Response key/value data.
Returns:
WSResponse Instance.
"""
if cls.expose_status: # pragma: no cover
cls.response.content_type = 'a... | Shortcut API for HTTP 401 `Unauthorized` response.
Args:
errors (list): Response key/value data.
Returns:
WSResponse Instance. | Below is the the instruction that describes the task:
### Input:
Shortcut API for HTTP 401 `Unauthorized` response.
Args:
errors (list): Response key/value data.
Returns:
WSResponse Instance.
### Response:
def unauthorized(cls, errors=None):
"""Shortcut API for HTT... |
def _duplicate_example(self, request):
"""Duplicates the specified example.
Args:
request: A request that should contain 'index'.
Returns:
An empty response.
"""
index = int(request.args.get('index'))
if index >= len(self.examples):
return http_util.Respond(request, {'error':... | Duplicates the specified example.
Args:
request: A request that should contain 'index'.
Returns:
An empty response. | Below is the the instruction that describes the task:
### Input:
Duplicates the specified example.
Args:
request: A request that should contain 'index'.
Returns:
An empty response.
### Response:
def _duplicate_example(self, request):
"""Duplicates the specified example.
Args:
r... |
def write_table_file(self, table_file=None):
"""Write the table to self._table_file"""
if self._table is None:
raise RuntimeError("No table to write")
if table_file is not None:
self._table_file = table_file
if self._table_file is None:
raise RuntimeEr... | Write the table to self._table_file | Below is the the instruction that describes the task:
### Input:
Write the table to self._table_file
### Response:
def write_table_file(self, table_file=None):
"""Write the table to self._table_file"""
if self._table is None:
raise RuntimeError("No table to write")
if table_file... |
def getConnectionInfo(self, wanInterfaceId=1, timeout=1):
"""Execute GetInfo action to get WAN connection information's.
:param int wanInterfaceId: the id of the WAN device
:param float timeout: the timeout to wait for the action to be executed
:return: WAN connection information's.
... | Execute GetInfo action to get WAN connection information's.
:param int wanInterfaceId: the id of the WAN device
:param float timeout: the timeout to wait for the action to be executed
:return: WAN connection information's.
:rtype: ConnectionInfo | Below is the the instruction that describes the task:
### Input:
Execute GetInfo action to get WAN connection information's.
:param int wanInterfaceId: the id of the WAN device
:param float timeout: the timeout to wait for the action to be executed
:return: WAN connection information's.
... |
def validate(self):
"""Dictionary with validation methods as values"""
depr = self._all_deprecated
return dict((key, val[1]) for key, val in
six.iteritems(self.defaultParams)
if key not in depr) | Dictionary with validation methods as values | Below is the the instruction that describes the task:
### Input:
Dictionary with validation methods as values
### Response:
def validate(self):
"""Dictionary with validation methods as values"""
depr = self._all_deprecated
return dict((key, val[1]) for key, val in
six.it... |
def _get_string_match_value(self, string, string_match_type):
"""Gets the match value"""
if string_match_type == Type(**get_type_data('EXACT')):
return string
elif string_match_type == Type(**get_type_data('IGNORECASE')):
return re.compile('^' + string, re.I)
elif... | Gets the match value | Below is the the instruction that describes the task:
### Input:
Gets the match value
### Response:
def _get_string_match_value(self, string, string_match_type):
"""Gets the match value"""
if string_match_type == Type(**get_type_data('EXACT')):
return string
elif string_match_ty... |
def _grow_overlaps(dna, melting_temp, require_even, length_max, overlap_min,
min_exception):
'''Grows equidistant overlaps until they meet specified constraints.
:param dna: Input sequence.
:type dna: coral.DNA
:param melting_temp: Ideal Tm of the overlaps, in degrees C.
:type me... | Grows equidistant overlaps until they meet specified constraints.
:param dna: Input sequence.
:type dna: coral.DNA
:param melting_temp: Ideal Tm of the overlaps, in degrees C.
:type melting_temp: float
:param require_even: Require that the number of oligonucleotides is even.
:type require_even:... | Below is the the instruction that describes the task:
### Input:
Grows equidistant overlaps until they meet specified constraints.
:param dna: Input sequence.
:type dna: coral.DNA
:param melting_temp: Ideal Tm of the overlaps, in degrees C.
:type melting_temp: float
:param require_even: Require... |
def _extract_datasets_to_harvest(cls, report):
"""Extrae de un reporte los datos necesarios para reconocer qué
datasets marcar para cosecha en cualquier generador.
Args:
report (str o list): Reporte (lista de dicts) o path a uno.
Returns:
list: Lista de tuplas c... | Extrae de un reporte los datos necesarios para reconocer qué
datasets marcar para cosecha en cualquier generador.
Args:
report (str o list): Reporte (lista de dicts) o path a uno.
Returns:
list: Lista de tuplas con los títulos de catálogo y dataset de cada
r... | Below is the the instruction that describes the task:
### Input:
Extrae de un reporte los datos necesarios para reconocer qué
datasets marcar para cosecha en cualquier generador.
Args:
report (str o list): Reporte (lista de dicts) o path a uno.
Returns:
list: Lista ... |
def _getCachedValue(obj, relicFunc, resultType):
"""
Retrieves a value from obj.cached (if not None) or calls @relicFunc and
caches the result (of @resultType) int obj.cached.
This is a common implementation for orderG1/G2/Gt and generatotG1/G2/Gt
"""
# If the value has not been previously cac... | Retrieves a value from obj.cached (if not None) or calls @relicFunc and
caches the result (of @resultType) int obj.cached.
This is a common implementation for orderG1/G2/Gt and generatotG1/G2/Gt | Below is the the instruction that describes the task:
### Input:
Retrieves a value from obj.cached (if not None) or calls @relicFunc and
caches the result (of @resultType) int obj.cached.
This is a common implementation for orderG1/G2/Gt and generatotG1/G2/Gt
### Response:
def _getCachedValue(obj, relicF... |
def sem(self, ddof=1):
"""
Compute standard error of the mean of groups, excluding missing values.
For multiple groupings, the result index will be a MultiIndex.
Parameters
----------
ddof : integer, default 1
degrees of freedom
"""
return s... | Compute standard error of the mean of groups, excluding missing values.
For multiple groupings, the result index will be a MultiIndex.
Parameters
----------
ddof : integer, default 1
degrees of freedom | Below is the the instruction that describes the task:
### Input:
Compute standard error of the mean of groups, excluding missing values.
For multiple groupings, the result index will be a MultiIndex.
Parameters
----------
ddof : integer, default 1
degrees of freedom
###... |
def IsAllSpent(self):
"""
Flag indicating if all balance is spend.
Returns:
bool:
"""
for item in self.Items:
if item == CoinState.Confirmed:
return False
return True | Flag indicating if all balance is spend.
Returns:
bool: | Below is the the instruction that describes the task:
### Input:
Flag indicating if all balance is spend.
Returns:
bool:
### Response:
def IsAllSpent(self):
"""
Flag indicating if all balance is spend.
Returns:
bool:
"""
for item in self.Ite... |
def _from_docstring_rst(doc):
"""
format from docstring to ReStructured Text
"""
def format_fn(line, status):
""" format function """
if re_from_data.match(line):
line = re_from_data.sub(r"**\1** ", line)
status["add_line"] = True
line = re_from_defaults... | format from docstring to ReStructured Text | Below is the the instruction that describes the task:
### Input:
format from docstring to ReStructured Text
### Response:
def _from_docstring_rst(doc):
"""
format from docstring to ReStructured Text
"""
def format_fn(line, status):
""" format function """
if re_from_data.match(lin... |
def hash_data(salt, value, hash_alg=None):
"""
Hashes a value together with a salt with the given hash algorithm.
:type salt: str
:type hash_alg: str
:type value: str
:param salt: hash salt
:param hash_alg: the hash algorithm to use (default: SHA512)
:param value: value to hash together... | Hashes a value together with a salt with the given hash algorithm.
:type salt: str
:type hash_alg: str
:type value: str
:param salt: hash salt
:param hash_alg: the hash algorithm to use (default: SHA512)
:param value: value to hash together with the salt
:return: hashed value | Below is the the instruction that describes the task:
### Input:
Hashes a value together with a salt with the given hash algorithm.
:type salt: str
:type hash_alg: str
:type value: str
:param salt: hash salt
:param hash_alg: the hash algorithm to use (default: SHA512)
:param value: value to... |
def listTheExtras(self, deleteAlso):
""" Use ConfigObj's get_extra_values() call to find any extra/unknown
parameters we may have loaded. Return a string similar to findTheLost.
If deleteAlso is True, this will also delete any extra/unknown items.
"""
# get list of extras
... | Use ConfigObj's get_extra_values() call to find any extra/unknown
parameters we may have loaded. Return a string similar to findTheLost.
If deleteAlso is True, this will also delete any extra/unknown items. | Below is the the instruction that describes the task:
### Input:
Use ConfigObj's get_extra_values() call to find any extra/unknown
parameters we may have loaded. Return a string similar to findTheLost.
If deleteAlso is True, this will also delete any extra/unknown items.
### Response:
def listTheE... |
def get_resampled_top_edge(self, angle_var=0.1):
"""
This methods computes a simplified representation of a fault top edge
by removing the points that are not describing a change of direction,
provided a certain tolerance angle.
:param float angle_var:
Number represe... | This methods computes a simplified representation of a fault top edge
by removing the points that are not describing a change of direction,
provided a certain tolerance angle.
:param float angle_var:
Number representing the maximum deviation (in degrees) admitted
without... | Below is the the instruction that describes the task:
### Input:
This methods computes a simplified representation of a fault top edge
by removing the points that are not describing a change of direction,
provided a certain tolerance angle.
:param float angle_var:
Number represe... |
def collect_num(self):
"""获取答案收藏数
:return: 答案收藏数量
:rtype: int
"""
element = self.soup.find("a", {
"data-za-a": "click_answer_collected_count"
})
if element is None:
return 0
else:
return int(element.get_text()) | 获取答案收藏数
:return: 答案收藏数量
:rtype: int | Below is the the instruction that describes the task:
### Input:
获取答案收藏数
:return: 答案收藏数量
:rtype: int
### Response:
def collect_num(self):
"""获取答案收藏数
:return: 答案收藏数量
:rtype: int
"""
element = self.soup.find("a", {
"data-za-a": "click_answer_col... |
def db_optimize(name,
table=None,
**connection_args):
'''
Optimizes the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_optimize dbname
'''
ret = []
if table is None:
# we need to optimize all tables
... | Optimizes the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_optimize dbname | Below is the the instruction that describes the task:
### Input:
Optimizes the full database or just a given table
CLI Example:
.. code-block:: bash
salt '*' mysql.db_optimize dbname
### Response:
def db_optimize(name,
table=None,
**connection_args):
'''
Optim... |
def __dict_invert(self, data):
"""Helper function for merge.
Takes a dictionary whose values are lists and returns a dict with
the elements of each list as keys and the original keys as values.
"""
outdict = {}
for k,lst in data.items():
if isinstance(lst, st... | Helper function for merge.
Takes a dictionary whose values are lists and returns a dict with
the elements of each list as keys and the original keys as values. | Below is the the instruction that describes the task:
### Input:
Helper function for merge.
Takes a dictionary whose values are lists and returns a dict with
the elements of each list as keys and the original keys as values.
### Response:
def __dict_invert(self, data):
"""Helper function f... |
def _find_own_cgroups():
"""
For all subsystems, return the information in which (sub-)cgroup this process is in.
(Each process is in exactly cgroup in each hierarchy.)
@return a generator of tuples (subsystem, cgroup)
"""
try:
with open('/proc/self/cgroup', 'rt') as ownCgroupsFile:
... | For all subsystems, return the information in which (sub-)cgroup this process is in.
(Each process is in exactly cgroup in each hierarchy.)
@return a generator of tuples (subsystem, cgroup) | Below is the the instruction that describes the task:
### Input:
For all subsystems, return the information in which (sub-)cgroup this process is in.
(Each process is in exactly cgroup in each hierarchy.)
@return a generator of tuples (subsystem, cgroup)
### Response:
def _find_own_cgroups():
"""
F... |
def missing(self, field, last=True):
'''
Numeric fields support specific handling for missing fields in a doc.
The missing value can be _last, _first, or a custom value
(that will be used for missing docs as the sort value).
missing('price')
> {"price" : {"missing": "_la... | Numeric fields support specific handling for missing fields in a doc.
The missing value can be _last, _first, or a custom value
(that will be used for missing docs as the sort value).
missing('price')
> {"price" : {"missing": "_last" } }
missing('price',False)
> {"price"... | Below is the the instruction that describes the task:
### Input:
Numeric fields support specific handling for missing fields in a doc.
The missing value can be _last, _first, or a custom value
(that will be used for missing docs as the sort value).
missing('price')
> {"price" : {"mi... |
def Read(self, file_object):
"""Reads dependency definitions.
Args:
file_object (file): file-like object to read from.
Yields:
DependencyDefinition: dependency definition.
"""
config_parser = configparser.RawConfigParser()
# pylint: disable=deprecated-method
# TODO: replace rea... | Reads dependency definitions.
Args:
file_object (file): file-like object to read from.
Yields:
DependencyDefinition: dependency definition. | Below is the the instruction that describes the task:
### Input:
Reads dependency definitions.
Args:
file_object (file): file-like object to read from.
Yields:
DependencyDefinition: dependency definition.
### Response:
def Read(self, file_object):
"""Reads dependency definitions.
Arg... |
def create_environment(self, env_name, version_label=None,
solution_stack_name=None, cname_prefix=None, description=None,
option_settings=None, tier_name='WebServer', tier_type='Standard', tier_version='1.1'):
"""
Creates a new environment
""... | Creates a new environment | Below is the the instruction that describes the task:
### Input:
Creates a new environment
### Response:
def create_environment(self, env_name, version_label=None,
solution_stack_name=None, cname_prefix=None, description=None,
option_settings=None, tier_name='W... |
def _autoinsert_quotes(self, key):
"""Control how to automatically insert quotes in various situations."""
char = {Qt.Key_QuoteDbl: '"', Qt.Key_Apostrophe: '\''}[key]
line_text = self.editor.get_text('sol', 'eol')
line_to_cursor = self.editor.get_text('sol', 'cursor')
cursor = s... | Control how to automatically insert quotes in various situations. | Below is the the instruction that describes the task:
### Input:
Control how to automatically insert quotes in various situations.
### Response:
def _autoinsert_quotes(self, key):
"""Control how to automatically insert quotes in various situations."""
char = {Qt.Key_QuoteDbl: '"', Qt.Key_Apostrophe... |
def key_exists(key_id, region=None, key=None, keyid=None, profile=None):
'''
Check for the existence of a key.
CLI example::
salt myminion boto_kms.key_exists 'alias/mykey'
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
r = {}
try:
key = conn.de... | Check for the existence of a key.
CLI example::
salt myminion boto_kms.key_exists 'alias/mykey' | Below is the the instruction that describes the task:
### Input:
Check for the existence of a key.
CLI example::
salt myminion boto_kms.key_exists 'alias/mykey'
### Response:
def key_exists(key_id, region=None, key=None, keyid=None, profile=None):
'''
Check for the existence of a key.
CL... |
def _collapse_outgroup(tree, taxdicts):
""" collapse outgroup in ete Tree for easier viewing """
## check that all tests have the same outgroup
outg = taxdicts[0]["p4"]
if not all([i["p4"] == outg for i in taxdicts]):
raise Exception("no good")
## prune tree, keep only one sample from ou... | collapse outgroup in ete Tree for easier viewing | Below is the the instruction that describes the task:
### Input:
collapse outgroup in ete Tree for easier viewing
### Response:
def _collapse_outgroup(tree, taxdicts):
""" collapse outgroup in ete Tree for easier viewing """
## check that all tests have the same outgroup
outg = taxdicts[0]["p4"]
if... |
def _shuffled(seq):
"""Deterministically shuffle identically under both py2 + py3."""
fixed_random = random.Random()
if six.PY2: # pragma: no cover (py2)
fixed_random.seed(FIXED_RANDOM_SEED)
else: # pragma: no cover (py3)
fixed_random.seed(FIXED_RANDOM_SEED, version=1)
seq = list(... | Deterministically shuffle identically under both py2 + py3. | Below is the the instruction that describes the task:
### Input:
Deterministically shuffle identically under both py2 + py3.
### Response:
def _shuffled(seq):
"""Deterministically shuffle identically under both py2 + py3."""
fixed_random = random.Random()
if six.PY2: # pragma: no cover (py2)
f... |
def bind(self, fn: Callable[[Any], 'Cont']) -> 'Cont':
r"""Chain continuation passing functions.
Haskell: m >>= k = Cont $ \c -> runCont m $ \a -> runCont (k a) c
"""
return Cont(lambda c: self.run(lambda a: fn(a).run(c))) | r"""Chain continuation passing functions.
Haskell: m >>= k = Cont $ \c -> runCont m $ \a -> runCont (k a) c | Below is the the instruction that describes the task:
### Input:
r"""Chain continuation passing functions.
Haskell: m >>= k = Cont $ \c -> runCont m $ \a -> runCont (k a) c
### Response:
def bind(self, fn: Callable[[Any], 'Cont']) -> 'Cont':
r"""Chain continuation passing functions.
Haske... |
def brpoplpush(self, source, destination, timeout=0):
"""Emulate brpoplpush"""
transfer_item = self.brpop(source, timeout)
if transfer_item is None:
return None
key, val = transfer_item
self.lpush(destination, val)
return val | Emulate brpoplpush | Below is the the instruction that describes the task:
### Input:
Emulate brpoplpush
### Response:
def brpoplpush(self, source, destination, timeout=0):
"""Emulate brpoplpush"""
transfer_item = self.brpop(source, timeout)
if transfer_item is None:
return None
key, val = ... |
def get_agile_board(self, board_id):
"""
Get agile board info by id
:param board_id:
:return:
"""
url = 'rest/agile/1.0/board/{}'.format(str(board_id))
return self.get(url) | Get agile board info by id
:param board_id:
:return: | Below is the the instruction that describes the task:
### Input:
Get agile board info by id
:param board_id:
:return:
### Response:
def get_agile_board(self, board_id):
"""
Get agile board info by id
:param board_id:
:return:
"""
url = 'rest/agile/1.0... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.