code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def _salt_to_os_path(path):
'''
Converts a path from the form received via salt master to the OS's native
path format.
'''
return os.path.normpath(path.replace(posixpath.sep, os.path.sep)) | Converts a path from the form received via salt master to the OS's native
path format. | Below is the the instruction that describes the task:
### Input:
Converts a path from the form received via salt master to the OS's native
path format.
### Response:
def _salt_to_os_path(path):
'''
Converts a path from the form received via salt master to the OS's native
path format.
'''
re... |
def export_to(self, appliance, location):
"""Exports the machine to an OVF appliance. See :py:class:`IAppliance` for the
steps required to export VirtualBox machines to OVF.
in appliance of type :class:`IAppliance`
Appliance to export this machine to.
in location of type s... | Exports the machine to an OVF appliance. See :py:class:`IAppliance` for the
steps required to export VirtualBox machines to OVF.
in appliance of type :class:`IAppliance`
Appliance to export this machine to.
in location of type str
The target location.
return d... | Below is the the instruction that describes the task:
### Input:
Exports the machine to an OVF appliance. See :py:class:`IAppliance` for the
steps required to export VirtualBox machines to OVF.
in appliance of type :class:`IAppliance`
Appliance to export this machine to.
in lo... |
def adev_from_qd(self, tau0=1.0, tau=1.0):
""" prefactor for Allan deviation for noise
type defined by (qd, b, tau0)
Colored noise generated with (qd, b, tau0) parameters will
show an Allan variance of:
AVAR = prefactor * h_a * tau^c
where a = b + 2... | prefactor for Allan deviation for noise
type defined by (qd, b, tau0)
Colored noise generated with (qd, b, tau0) parameters will
show an Allan variance of:
AVAR = prefactor * h_a * tau^c
where a = b + 2 is the slope of the frequency PSD.
and h_a... | Below is the the instruction that describes the task:
### Input:
prefactor for Allan deviation for noise
type defined by (qd, b, tau0)
Colored noise generated with (qd, b, tau0) parameters will
show an Allan variance of:
AVAR = prefactor * h_a * tau^c
w... |
def validate_name(err, value, source):
'Tests a manifest name value for trademarks.'
ff_pattern = re.compile('(mozilla|firefox)', re.I)
err.metadata['name'] = value
if ff_pattern.search(value):
err.warning(
('metadata_helpers', '_test_name', 'trademark'),
'Add-on has p... | Tests a manifest name value for trademarks. | Below is the the instruction that describes the task:
### Input:
Tests a manifest name value for trademarks.
### Response:
def validate_name(err, value, source):
'Tests a manifest name value for trademarks.'
ff_pattern = re.compile('(mozilla|firefox)', re.I)
err.metadata['name'] = value
if ff_pa... |
def pkg_list(self):
"""List of packages by repository
"""
options = [
"-l",
"--list"
]
flag = ["--index", "--installed", "--name"]
name = INDEX = installed = False
for arg in self.args[2:]:
if flag[0] == arg:
IND... | List of packages by repository | Below is the the instruction that describes the task:
### Input:
List of packages by repository
### Response:
def pkg_list(self):
"""List of packages by repository
"""
options = [
"-l",
"--list"
]
flag = ["--index", "--installed", "--name"]
na... |
def _createShapelet(self,coeff):
"""
returns a shapelet array out of the coefficients *a, up to order l
:param num_l: order of shapelets
:type num_l: int.
:param coeff: shapelet coefficients
:type coeff: floats
:returns: complex array
:raises: AttributeE... | returns a shapelet array out of the coefficients *a, up to order l
:param num_l: order of shapelets
:type num_l: int.
:param coeff: shapelet coefficients
:type coeff: floats
:returns: complex array
:raises: AttributeError, KeyError | Below is the the instruction that describes the task:
### Input:
returns a shapelet array out of the coefficients *a, up to order l
:param num_l: order of shapelets
:type num_l: int.
:param coeff: shapelet coefficients
:type coeff: floats
:returns: complex array
:ra... |
def _evaluate_one(caller, svtype, size_range, ensemble, truth, data):
"""Compare a ensemble results for a caller against a specific caller and SV type.
"""
def cnv_matches(name):
return cnv_to_event(name, data) == svtype
def is_breakend(name):
return name.startswith("BND")
def in_siz... | Compare a ensemble results for a caller against a specific caller and SV type. | Below is the the instruction that describes the task:
### Input:
Compare a ensemble results for a caller against a specific caller and SV type.
### Response:
def _evaluate_one(caller, svtype, size_range, ensemble, truth, data):
"""Compare a ensemble results for a caller against a specific caller and SV type.
... |
def generate_index(credentials, instance_config, instance_name,
script_dir, genome_file, output_dir, annotation_file=None,
splice_overhang=100,
num_threads=8, chromosome_bin_bits=18,
genome_memory_limit=31000000000,
self_dest... | Generates a STAR index.
Recommended machine type: "n1-highmem-8" (52 GB of RAM, 8 vCPUs)
TODO: docstring | Below is the the instruction that describes the task:
### Input:
Generates a STAR index.
Recommended machine type: "n1-highmem-8" (52 GB of RAM, 8 vCPUs)
TODO: docstring
### Response:
def generate_index(credentials, instance_config, instance_name,
script_dir, genome_file, output_dir, a... |
def is_reseller(self):
"""is the user a reseller"""
return self.role == self.roles.reseller.value and self.state == State.approved | is the user a reseller | Below is the the instruction that describes the task:
### Input:
is the user a reseller
### Response:
def is_reseller(self):
"""is the user a reseller"""
return self.role == self.roles.reseller.value and self.state == State.approved |
def add_trunk_ports(self):
"""SDN Controller enable trunk ports
:rtype: list[tuple[str, str]]
"""
ports = self.attributes.get("{}Enable Full Trunk Ports".format(self.namespace_prefix), None)
return self._parse_ports(ports=ports) | SDN Controller enable trunk ports
:rtype: list[tuple[str, str]] | Below is the the instruction that describes the task:
### Input:
SDN Controller enable trunk ports
:rtype: list[tuple[str, str]]
### Response:
def add_trunk_ports(self):
"""SDN Controller enable trunk ports
:rtype: list[tuple[str, str]]
"""
ports = self.attributes.get("{}E... |
def deluser(name, username, root=None):
'''
Remove a user from the group.
CLI Example:
.. code-block:: bash
salt '*' group.deluser foo bar
Removes a member user 'bar' from a group 'foo'. If group is not present
then returns True.
'''
grp_info = __salt__['group.info'](name)
... | Remove a user from the group.
CLI Example:
.. code-block:: bash
salt '*' group.deluser foo bar
Removes a member user 'bar' from a group 'foo'. If group is not present
then returns True. | Below is the the instruction that describes the task:
### Input:
Remove a user from the group.
CLI Example:
.. code-block:: bash
salt '*' group.deluser foo bar
Removes a member user 'bar' from a group 'foo'. If group is not present
then returns True.
### Response:
def deluser(name, use... |
def point_plane_distance(points,
plane_normal,
plane_origin=[0.0, 0.0, 0.0]):
"""
The minimum perpendicular distance of a point to a plane.
Parameters
-----------
points: (n, 3) float, points in space
plane_normal: (3,) float, normal vecto... | The minimum perpendicular distance of a point to a plane.
Parameters
-----------
points: (n, 3) float, points in space
plane_normal: (3,) float, normal vector
plane_origin: (3,) float, plane origin in space
Returns
------------
distances: (n,) float, distance from point to pl... | Below is the the instruction that describes the task:
### Input:
The minimum perpendicular distance of a point to a plane.
Parameters
-----------
points: (n, 3) float, points in space
plane_normal: (3,) float, normal vector
plane_origin: (3,) float, plane origin in space
Returns
... |
def make_logging_handlers_and_tools(self, multiproc=False):
"""Creates logging handlers and redirects stdout."""
log_stdout = self.log_stdout
if sys.stdout is self._stdout_to_logger:
# If we already redirected stdout we don't neet to redo it again
log_stdout = False
... | Creates logging handlers and redirects stdout. | Below is the the instruction that describes the task:
### Input:
Creates logging handlers and redirects stdout.
### Response:
def make_logging_handlers_and_tools(self, multiproc=False):
"""Creates logging handlers and redirects stdout."""
log_stdout = self.log_stdout
if sys.stdout is self.... |
def Gharagheizi_liquid(T, M, Tb, Pc, omega):
r'''Estimates the thermal conductivity of a liquid as a function of
temperature using the CSP method of Gharagheizi [1]_. A convoluted
method claiming high-accuracy and using only statistically significant
variable following analalysis.
Requires tempera... | r'''Estimates the thermal conductivity of a liquid as a function of
temperature using the CSP method of Gharagheizi [1]_. A convoluted
method claiming high-accuracy and using only statistically significant
variable following analalysis.
Requires temperature, molecular weight, boiling temperature and c... | Below is the the instruction that describes the task:
### Input:
r'''Estimates the thermal conductivity of a liquid as a function of
temperature using the CSP method of Gharagheizi [1]_. A convoluted
method claiming high-accuracy and using only statistically significant
variable following analalysis.
... |
def main():
"""
NAME
common_mean.py
DESCRIPTION
calculates bootstrap statistics to test for common mean
INPUT FORMAT
takes dec/inc as first two columns in two space delimited files
SYNTAX
common_mean.py [command line options]
OPTIONS
-h prints help m... | NAME
common_mean.py
DESCRIPTION
calculates bootstrap statistics to test for common mean
INPUT FORMAT
takes dec/inc as first two columns in two space delimited files
SYNTAX
common_mean.py [command line options]
OPTIONS
-h prints help message and quits
... | Below is the the instruction that describes the task:
### Input:
NAME
common_mean.py
DESCRIPTION
calculates bootstrap statistics to test for common mean
INPUT FORMAT
takes dec/inc as first two columns in two space delimited files
SYNTAX
common_mean.py [command line opti... |
def reindex(
client,
source_index,
target_index,
query=None,
target_client=None,
chunk_size=500,
scroll="5m",
scan_kwargs={},
bulk_kwargs={},
):
"""
Reindex all documents from one index that satisfy a given query
to another, potentially (if `target_client` is specified) ... | Reindex all documents from one index that satisfy a given query
to another, potentially (if `target_client` is specified) on a different cluster.
If you don't specify the query you will reindex all the documents.
Since ``2.3`` a :meth:`~elasticsearch.Elasticsearch.reindex` api is
available as part of e... | Below is the the instruction that describes the task:
### Input:
Reindex all documents from one index that satisfy a given query
to another, potentially (if `target_client` is specified) on a different cluster.
If you don't specify the query you will reindex all the documents.
Since ``2.3`` a :meth:`~e... |
def encrypt(key, message):
'''encrypt leverages KMS encrypt and base64-encode encrypted blob
More info on KMS encrypt API:
https://docs.aws.amazon.com/kms/latest/APIReference/API_encrypt.html
'''
try:
ret = kms.encrypt(KeyId=key, Plaintext=message)
encrypted_data = base64.en... | encrypt leverages KMS encrypt and base64-encode encrypted blob
More info on KMS encrypt API:
https://docs.aws.amazon.com/kms/latest/APIReference/API_encrypt.html | Below is the the instruction that describes the task:
### Input:
encrypt leverages KMS encrypt and base64-encode encrypted blob
More info on KMS encrypt API:
https://docs.aws.amazon.com/kms/latest/APIReference/API_encrypt.html
### Response:
def encrypt(key, message):
'''encrypt leverages KMS e... |
def object_formatter(v, c, m, p):
"""Format object view link."""
endpoint = current_app.config['PIDSTORE_OBJECT_ENDPOINTS'].get(
m.object_type)
if endpoint and m.object_uuid:
return Markup('<a href="{0}">{1}</a>'.format(
url_for(endpoint, id=m.object_uuid),
_('View')... | Format object view link. | Below is the the instruction that describes the task:
### Input:
Format object view link.
### Response:
def object_formatter(v, c, m, p):
"""Format object view link."""
endpoint = current_app.config['PIDSTORE_OBJECT_ENDPOINTS'].get(
m.object_type)
if endpoint and m.object_uuid:
return ... |
def last(self, n=10, by=None, **kwargs):
"""
Alias for .tail().
"""
return self.tail(n=n, by=by, **kwargs) | Alias for .tail(). | Below is the the instruction that describes the task:
### Input:
Alias for .tail().
### Response:
def last(self, n=10, by=None, **kwargs):
"""
Alias for .tail().
"""
return self.tail(n=n, by=by, **kwargs) |
def tuple_in_list_always(main, sub):
"""
>>> main = [('a', 'b', 'c'), ('c', 'd')]
>>> tuple_in_list_always(main, ('a' ,'b', 'c'))
False
>>> tuple_in_list_always(main, ('c', 'd'))
False
>>> tuple_in_list_always(main, ('a', 'c'))
False
>>> tuple_in_list_always(main, ('a'))
False
... | >>> main = [('a', 'b', 'c'), ('c', 'd')]
>>> tuple_in_list_always(main, ('a' ,'b', 'c'))
False
>>> tuple_in_list_always(main, ('c', 'd'))
False
>>> tuple_in_list_always(main, ('a', 'c'))
False
>>> tuple_in_list_always(main, ('a'))
False
>>> tuple_in_list_always(main, ((),))
False... | Below is the the instruction that describes the task:
### Input:
>>> main = [('a', 'b', 'c'), ('c', 'd')]
>>> tuple_in_list_always(main, ('a' ,'b', 'c'))
False
>>> tuple_in_list_always(main, ('c', 'd'))
False
>>> tuple_in_list_always(main, ('a', 'c'))
False
>>> tuple_in_list_always(main,... |
def from_array(array):
"""
Deserialize a new PassportElementErrorFiles from a given dictionary.
:return: new PassportElementErrorFiles instance.
:rtype: PassportElementErrorFiles
"""
if array is None or not array:
return None
# end if
assert_t... | Deserialize a new PassportElementErrorFiles from a given dictionary.
:return: new PassportElementErrorFiles instance.
:rtype: PassportElementErrorFiles | Below is the the instruction that describes the task:
### Input:
Deserialize a new PassportElementErrorFiles from a given dictionary.
:return: new PassportElementErrorFiles instance.
:rtype: PassportElementErrorFiles
### Response:
def from_array(array):
"""
Deserialize a new Passpo... |
def from_origin_axis_angle(origin, axis, angle, angle_in_radians=False):
"""
Generates a SymmOp for a rotation about a given axis through an
origin.
Args:
origin (3x1 array): The origin which the axis passes through.
axis (3x1 array): The axis of rotation in cart... | Generates a SymmOp for a rotation about a given axis through an
origin.
Args:
origin (3x1 array): The origin which the axis passes through.
axis (3x1 array): The axis of rotation in cartesian space. For
example, [1, 0, 0]indicates rotation about x-axis.
... | Below is the the instruction that describes the task:
### Input:
Generates a SymmOp for a rotation about a given axis through an
origin.
Args:
origin (3x1 array): The origin which the axis passes through.
axis (3x1 array): The axis of rotation in cartesian space. For
... |
def get_all_mechs():
"""
Return an :class:`OIDSet` of all the mechanisms supported by the underlying GSSAPI
implementation.
"""
minor_status = ffi.new('OM_uint32[1]')
mech_set = ffi.new('gss_OID_set[1]')
try:
retval = C.gss_indicate_mechs(minor_status, mech_set)
if GSS_ERROR(... | Return an :class:`OIDSet` of all the mechanisms supported by the underlying GSSAPI
implementation. | Below is the the instruction that describes the task:
### Input:
Return an :class:`OIDSet` of all the mechanisms supported by the underlying GSSAPI
implementation.
### Response:
def get_all_mechs():
"""
Return an :class:`OIDSet` of all the mechanisms supported by the underlying GSSAPI
implementatio... |
def add_companion(self, bill_id, session=None, chamber=None):
"""
Associate another bill with this one.
If session isn't set it will be set to self['session'].
"""
companion = {'bill_id': bill_id,
'session': session or self['session'],
'... | Associate another bill with this one.
If session isn't set it will be set to self['session']. | Below is the the instruction that describes the task:
### Input:
Associate another bill with this one.
If session isn't set it will be set to self['session'].
### Response:
def add_companion(self, bill_id, session=None, chamber=None):
"""
Associate another bill with this one.
If s... |
def build_model_columns():
"""Builds a set of wide and deep feature columns."""
# Continuous variable columns
age = tf.feature_column.numeric_column('age')
education_num = tf.feature_column.numeric_column('education_num')
capital_gain = tf.feature_column.numeric_column('capital_gain')
capital_loss = tf.feat... | Builds a set of wide and deep feature columns. | Below is the the instruction that describes the task:
### Input:
Builds a set of wide and deep feature columns.
### Response:
def build_model_columns():
"""Builds a set of wide and deep feature columns."""
# Continuous variable columns
age = tf.feature_column.numeric_column('age')
education_num = tf.featur... |
def generate(self, id_or_uri):
"""
Generates and returns a random range.
Args:
id_or_uri:
ID or URI of range.
Returns:
dict: A dict containing a list with IDs.
"""
uri = self._client.build_uri(id_or_uri) + "/generate"
retu... | Generates and returns a random range.
Args:
id_or_uri:
ID or URI of range.
Returns:
dict: A dict containing a list with IDs. | Below is the the instruction that describes the task:
### Input:
Generates and returns a random range.
Args:
id_or_uri:
ID or URI of range.
Returns:
dict: A dict containing a list with IDs.
### Response:
def generate(self, id_or_uri):
"""
Ge... |
def to_sql(self, app=None, last_known_value_date: Optional[date] = None):
""" Inserts the model into the SQLite3 database associated with Delphi,
for use with the ICM REST API. """
from delphi.apps.rest_api import create_app, db
self.assign_uuids_to_nodes_and_edges()
icm_metada... | Inserts the model into the SQLite3 database associated with Delphi,
for use with the ICM REST API. | Below is the the instruction that describes the task:
### Input:
Inserts the model into the SQLite3 database associated with Delphi,
for use with the ICM REST API.
### Response:
def to_sql(self, app=None, last_known_value_date: Optional[date] = None):
""" Inserts the model into the SQLite3 database... |
def _send_packet(self, packet):
"""Sends <packet> (<dict>) to https://hack.chat."""
encoded = json.dumps(packet)
self.ws.send(encoded) | Sends <packet> (<dict>) to https://hack.chat. | Below is the the instruction that describes the task:
### Input:
Sends <packet> (<dict>) to https://hack.chat.
### Response:
def _send_packet(self, packet):
"""Sends <packet> (<dict>) to https://hack.chat."""
encoded = json.dumps(packet)
self.ws.send(encoded) |
def libvlc_audio_set_volume(p_mi, i_volume):
'''Set current software audio volume.
@param p_mi: media player.
@param i_volume: the volume in percents (0 = mute, 100 = 0dB).
@return: 0 if the volume was set, -1 if it was out of range.
'''
f = _Cfunctions.get('libvlc_audio_set_volume', None) or \
... | Set current software audio volume.
@param p_mi: media player.
@param i_volume: the volume in percents (0 = mute, 100 = 0dB).
@return: 0 if the volume was set, -1 if it was out of range. | Below is the the instruction that describes the task:
### Input:
Set current software audio volume.
@param p_mi: media player.
@param i_volume: the volume in percents (0 = mute, 100 = 0dB).
@return: 0 if the volume was set, -1 if it was out of range.
### Response:
def libvlc_audio_set_volume(p_mi, i_vo... |
def get_custom_views(auth, url,name=None,headers=HEADERS):
"""
function requires no input and returns a list of dictionaries of custom views from an HPE IMC. Optional name
argument will return only the specified view.
:param name: str containing the name of the desired custom view
:return: list of d... | function requires no input and returns a list of dictionaries of custom views from an HPE IMC. Optional name
argument will return only the specified view.
:param name: str containing the name of the desired custom view
:return: list of dictionaties containing attributes of the custom views | Below is the the instruction that describes the task:
### Input:
function requires no input and returns a list of dictionaries of custom views from an HPE IMC. Optional name
argument will return only the specified view.
:param name: str containing the name of the desired custom view
:return: list of dic... |
def _get_default_annual_spacing(nyears):
"""
Returns a default spacing between consecutive ticks for annual data.
"""
if nyears < 11:
(min_spacing, maj_spacing) = (1, 1)
elif nyears < 20:
(min_spacing, maj_spacing) = (1, 2)
elif nyears < 50:
(min_spacing, maj_spacing) = (... | Returns a default spacing between consecutive ticks for annual data. | Below is the the instruction that describes the task:
### Input:
Returns a default spacing between consecutive ticks for annual data.
### Response:
def _get_default_annual_spacing(nyears):
"""
Returns a default spacing between consecutive ticks for annual data.
"""
if nyears < 11:
(min_spac... |
def validate_integer(option, value):
"""Validates that 'value' is an integer (or basestring representation).
"""
if isinstance(value, integer_types):
return value
elif isinstance(value, string_type):
try:
return int(value)
except ValueError:
raise ValueErr... | Validates that 'value' is an integer (or basestring representation). | Below is the the instruction that describes the task:
### Input:
Validates that 'value' is an integer (or basestring representation).
### Response:
def validate_integer(option, value):
"""Validates that 'value' is an integer (or basestring representation).
"""
if isinstance(value, integer_types):
... |
def process_pixels(image_bytes, gray_scale):
"""
Converts byte array observation image into numpy array, re-sizes it,
and optionally converts it to grey scale
:param gray_scale: Whether to convert the image to grayscale.
:param image_bytes: input byte array corresponding to image... | Converts byte array observation image into numpy array, re-sizes it,
and optionally converts it to grey scale
:param gray_scale: Whether to convert the image to grayscale.
:param image_bytes: input byte array corresponding to image
:return: processed numpy array of observation from envir... | Below is the the instruction that describes the task:
### Input:
Converts byte array observation image into numpy array, re-sizes it,
and optionally converts it to grey scale
:param gray_scale: Whether to convert the image to grayscale.
:param image_bytes: input byte array corresponding to i... |
def invoke(tok: str, props: Inputs, opts: InvokeOptions = None) -> Awaitable[Any]:
"""
invoke dynamically invokes the function, tok, which is offered by a provider plugin. The inputs
can be a bag of computed values (Ts or Awaitable[T]s), and the result is a Awaitable[Any] that
resolves when the invoke ... | invoke dynamically invokes the function, tok, which is offered by a provider plugin. The inputs
can be a bag of computed values (Ts or Awaitable[T]s), and the result is a Awaitable[Any] that
resolves when the invoke finishes. | Below is the the instruction that describes the task:
### Input:
invoke dynamically invokes the function, tok, which is offered by a provider plugin. The inputs
can be a bag of computed values (Ts or Awaitable[T]s), and the result is a Awaitable[Any] that
resolves when the invoke finishes.
### Response:
d... |
def profile(name='stats', _stats=stats):
"""Calculates a duration (wall clock time, not the CPU time) and a memory size."""
def _profile(function):
def __profile(*args, **kw):
start_time = timer()
start_memory = _get_memory_usage()
try:
return function... | Calculates a duration (wall clock time, not the CPU time) and a memory size. | Below is the the instruction that describes the task:
### Input:
Calculates a duration (wall clock time, not the CPU time) and a memory size.
### Response:
def profile(name='stats', _stats=stats):
"""Calculates a duration (wall clock time, not the CPU time) and a memory size."""
def _profile(function):
... |
def child_added(self, child):
""" Handle the child added event from the declaration.
This handler will insert the child toolkit widget in the correct.
position. Subclasses which need more control should reimplement this
method.
"""
super(WebComponent, self).child_added(... | Handle the child added event from the declaration.
This handler will insert the child toolkit widget in the correct.
position. Subclasses which need more control should reimplement this
method. | Below is the the instruction that describes the task:
### Input:
Handle the child added event from the declaration.
This handler will insert the child toolkit widget in the correct.
position. Subclasses which need more control should reimplement this
method.
### Response:
def child_added(s... |
def upsert(self, space, t, operations, **kwargs) -> _MethodRet:
"""
Update request coroutine. Performs either insert or update
(depending of either tuple exists or not)
Examples:
.. code-block:: pycon
# upsert does not return anything
... | Update request coroutine. Performs either insert or update
(depending of either tuple exists or not)
Examples:
.. code-block:: pycon
# upsert does not return anything
>>> await conn.upsert('tester', [0, 'hello'],
... ... | Below is the the instruction that describes the task:
### Input:
Update request coroutine. Performs either insert or update
(depending of either tuple exists or not)
Examples:
.. code-block:: pycon
# upsert does not return anything
>>> await con... |
def _days_to_seconds(cls, val, **kwargs):
'''
converts a number of days to seconds
'''
zero_value = kwargs.get('zero_value', 0)
if val is not None:
if val == 0:
return zero_value
return val * 86400
else:
return 'Not Defi... | converts a number of days to seconds | Below is the the instruction that describes the task:
### Input:
converts a number of days to seconds
### Response:
def _days_to_seconds(cls, val, **kwargs):
'''
converts a number of days to seconds
'''
zero_value = kwargs.get('zero_value', 0)
if val is not None:
... |
def path_to_text(self, path):
'''
Transform local PDF file to string.
Args:
path: path to PDF file.
Returns:
string.
'''
rsrcmgr = PDFResourceManager()
retstr = StringIO()
codec = 'utf-8'
laparams = LAParams()
d... | Transform local PDF file to string.
Args:
path: path to PDF file.
Returns:
string. | Below is the the instruction that describes the task:
### Input:
Transform local PDF file to string.
Args:
path: path to PDF file.
Returns:
string.
### Response:
def path_to_text(self, path):
'''
Transform local PDF file to string.
Args:
... |
def selection_error_control(self, form_info):
"""
It controls the selection from the form according
to the operations, and returns an error message
if it does not comply with the rules.
Args:
form_info: Channel or subscriber form from the user
Returns: True ... | It controls the selection from the form according
to the operations, and returns an error message
if it does not comply with the rules.
Args:
form_info: Channel or subscriber form from the user
Returns: True or False
error message | Below is the the instruction that describes the task:
### Input:
It controls the selection from the form according
to the operations, and returns an error message
if it does not comply with the rules.
Args:
form_info: Channel or subscriber form from the user
Returns: Tr... |
def apply(self, config, raise_on_unknown_key=True):
# type: (Dict[str, Any], bool) -> None
"""Apply additional configuration from a dictionary
This will look for dictionary items that exist in the base_config any apply their values on the current
configuration object
"""
... | Apply additional configuration from a dictionary
This will look for dictionary items that exist in the base_config any apply their values on the current
configuration object | Below is the the instruction that describes the task:
### Input:
Apply additional configuration from a dictionary
This will look for dictionary items that exist in the base_config any apply their values on the current
configuration object
### Response:
def apply(self, config, raise_on_unknown_key=... |
def set_default_style(style):
"""Sets default global style to be used by ``prettyprinter.cpprint``.
:param style: the style to set, either subclass of
``pygments.styles.Style`` or one of ``'dark'``, ``'light'``
"""
global default_style
if style == 'dark':
style = default_d... | Sets default global style to be used by ``prettyprinter.cpprint``.
:param style: the style to set, either subclass of
``pygments.styles.Style`` or one of ``'dark'``, ``'light'`` | Below is the the instruction that describes the task:
### Input:
Sets default global style to be used by ``prettyprinter.cpprint``.
:param style: the style to set, either subclass of
``pygments.styles.Style`` or one of ``'dark'``, ``'light'``
### Response:
def set_default_style(style):
"... |
def _post_auth(self):
"""Unregister legacy authentication handlers after successfull
authentication."""
ClientStream._post_auth(self)
if not self.initiator:
self.unset_iq_get_handler("query","jabber:iq:auth")
self.unset_iq_set_handler("query","jabber:iq:auth") | Unregister legacy authentication handlers after successfull
authentication. | Below is the the instruction that describes the task:
### Input:
Unregister legacy authentication handlers after successfull
authentication.
### Response:
def _post_auth(self):
"""Unregister legacy authentication handlers after successfull
authentication."""
ClientStream._post_auth(... |
def File(name, mode='a', chunk_cache_mem_size=1024**2, w0=0.75, n_cache_chunks=None, **kwds):
"""Create h5py File object with cache specification
This function is basically just a wrapper around the usual h5py.File constructor,
but accepts two additional keywords:
Parameters
----------
name : ... | Create h5py File object with cache specification
This function is basically just a wrapper around the usual h5py.File constructor,
but accepts two additional keywords:
Parameters
----------
name : str
mode : str
**kwds : dict (as keywords)
Standard h5py.File arguments, passed to it... | Below is the the instruction that describes the task:
### Input:
Create h5py File object with cache specification
This function is basically just a wrapper around the usual h5py.File constructor,
but accepts two additional keywords:
Parameters
----------
name : str
mode : str
**kwds : ... |
async def get_json(self, url, json_callback=None, **kwargs):
"""Get a URL and return its JSON response.
Args:
url (str): URL to be requested.
json_callback (func): Custom JSON loader function. Defaults
to :meth:`json.loads`.
kwargs (dict): Additional ... | Get a URL and return its JSON response.
Args:
url (str): URL to be requested.
json_callback (func): Custom JSON loader function. Defaults
to :meth:`json.loads`.
kwargs (dict): Additional arguments to pass through to the
request.
Return... | Below is the the instruction that describes the task:
### Input:
Get a URL and return its JSON response.
Args:
url (str): URL to be requested.
json_callback (func): Custom JSON loader function. Defaults
to :meth:`json.loads`.
kwargs (dict): Additional arg... |
def search_payload(self, fields=None, query=None):
"""Create a search query.
Do the following:
1. Generate a search query. By default, all values returned by
:meth:`nailgun.entity_mixins.Entity.get_values` are used. If
``fields`` is specified, only the named values are us... | Create a search query.
Do the following:
1. Generate a search query. By default, all values returned by
:meth:`nailgun.entity_mixins.Entity.get_values` are used. If
``fields`` is specified, only the named values are used.
2. Merge ``query`` in to the generated search quer... | Below is the the instruction that describes the task:
### Input:
Create a search query.
Do the following:
1. Generate a search query. By default, all values returned by
:meth:`nailgun.entity_mixins.Entity.get_values` are used. If
``fields`` is specified, only the named values... |
def do_status(self, line):
'''
Show python packaging configuration status
'''
# Pyrene version
print('{} {}'.format(bold('Pyrene version'), green(get_version())))
# .pip/pip.conf - Pyrene repo name | exists or not
pip_conf = os.path.expanduser('~/.pip/pip.conf')
... | Show python packaging configuration status | Below is the the instruction that describes the task:
### Input:
Show python packaging configuration status
### Response:
def do_status(self, line):
'''
Show python packaging configuration status
'''
# Pyrene version
print('{} {}'.format(bold('Pyrene version'), green(get_ver... |
def _add_stops_to_net(net, stops):
"""
Add nodes to the network from the pandas dataframe describing (a part of the) stops table in the GTFS database.
Parameters
----------
net: networkx.Graph
stops: pandas.DataFrame
"""
for stop in stops.itertuples():
data = {
"lat"... | Add nodes to the network from the pandas dataframe describing (a part of the) stops table in the GTFS database.
Parameters
----------
net: networkx.Graph
stops: pandas.DataFrame | Below is the the instruction that describes the task:
### Input:
Add nodes to the network from the pandas dataframe describing (a part of the) stops table in the GTFS database.
Parameters
----------
net: networkx.Graph
stops: pandas.DataFrame
### Response:
def _add_stops_to_net(net, stops):
""... |
def wrap_socket(socket, certfile, keyfile, password=None):
"""
Wraps an existing TCP socket and returns an SSLSocket object
:param socket: The socket to wrap
:param certfile: The server certificate file
:param keyfile: The server private key file
:param password: Password for the private key fi... | Wraps an existing TCP socket and returns an SSLSocket object
:param socket: The socket to wrap
:param certfile: The server certificate file
:param keyfile: The server private key file
:param password: Password for the private key file (Python >= 3.3)
:return: The wrapped socket
:raise SSLError:... | Below is the the instruction that describes the task:
### Input:
Wraps an existing TCP socket and returns an SSLSocket object
:param socket: The socket to wrap
:param certfile: The server certificate file
:param keyfile: The server private key file
:param password: Password for the private key file... |
def paste(self, *args):
""" Usage: paste([PSMRL], text)
If a pattern is specified, the pattern is clicked first. Doesn't support text paths.
``text`` is pasted as is using the OS paste shortcut (Ctrl+V for Windows/Linux, Cmd+V
for OS X). Note that `paste()` does NOT use special formatti... | Usage: paste([PSMRL], text)
If a pattern is specified, the pattern is clicked first. Doesn't support text paths.
``text`` is pasted as is using the OS paste shortcut (Ctrl+V for Windows/Linux, Cmd+V
for OS X). Note that `paste()` does NOT use special formatting like `type()`. | Below is the the instruction that describes the task:
### Input:
Usage: paste([PSMRL], text)
If a pattern is specified, the pattern is clicked first. Doesn't support text paths.
``text`` is pasted as is using the OS paste shortcut (Ctrl+V for Windows/Linux, Cmd+V
for OS X). Note that `paste... |
def get(self, resource, operation_timeout=None, max_envelope_size=None, locale=None):
"""
resource can be a URL or a ResourceLocator
"""
if isinstance(resource, str):
resource = ResourceLocator(resource)
headers = self._build_headers(resource, Session.GetAction, oper... | resource can be a URL or a ResourceLocator | Below is the the instruction that describes the task:
### Input:
resource can be a URL or a ResourceLocator
### Response:
def get(self, resource, operation_timeout=None, max_envelope_size=None, locale=None):
"""
resource can be a URL or a ResourceLocator
"""
if isinstance(resource, ... |
def resolve_weak_types(storage, debug=False):
"""Reslove weak type rules W1 - W3.
See: http://unicode.org/reports/tr9/#Resolving_Weak_Types
"""
for run in storage['runs']:
prev_strong = prev_type = run['sor']
start, length = run['start'], run['length']
chars = storage['chars']... | Reslove weak type rules W1 - W3.
See: http://unicode.org/reports/tr9/#Resolving_Weak_Types | Below is the the instruction that describes the task:
### Input:
Reslove weak type rules W1 - W3.
See: http://unicode.org/reports/tr9/#Resolving_Weak_Types
### Response:
def resolve_weak_types(storage, debug=False):
"""Reslove weak type rules W1 - W3.
See: http://unicode.org/reports/tr9/#Resolving_We... |
def main(args=None, **kwargs):
"""Run the Tango SDP Master device server."""
LOG.info('Starting %s', __service_id__)
return run([SDPMasterDevice], verbose=True, msg_stream=sys.stdout,
args=args, **kwargs) | Run the Tango SDP Master device server. | Below is the the instruction that describes the task:
### Input:
Run the Tango SDP Master device server.
### Response:
def main(args=None, **kwargs):
"""Run the Tango SDP Master device server."""
LOG.info('Starting %s', __service_id__)
return run([SDPMasterDevice], verbose=True, msg_stream=sys.stdout,
... |
def frequency_cutoff_from_name(name, m1, m2, s1z, s2z):
"""
Returns the result of evaluating the frequency cutoff function
specified by 'name' on a template with given parameters.
Parameters
----------
name : string
Name of the cutoff function
m1 : float or numpy.array
First... | Returns the result of evaluating the frequency cutoff function
specified by 'name' on a template with given parameters.
Parameters
----------
name : string
Name of the cutoff function
m1 : float or numpy.array
First component mass in solar masses
m2 : float or numpy.array
... | Below is the the instruction that describes the task:
### Input:
Returns the result of evaluating the frequency cutoff function
specified by 'name' on a template with given parameters.
Parameters
----------
name : string
Name of the cutoff function
m1 : float or numpy.array
Firs... |
def uniquify(l):
"""
Uniquify a list (skip duplicate items).
"""
result = []
for x in l:
if x not in result:
result.append(x)
return result | Uniquify a list (skip duplicate items). | Below is the the instruction that describes the task:
### Input:
Uniquify a list (skip duplicate items).
### Response:
def uniquify(l):
"""
Uniquify a list (skip duplicate items).
"""
result = []
for x in l:
if x not in result:
result.append(x)
return result |
def update_network_profile(arn=None, name=None, description=None, type=None, uplinkBandwidthBits=None, downlinkBandwidthBits=None, uplinkDelayMs=None, downlinkDelayMs=None, uplinkJitterMs=None, downlinkJitterMs=None, uplinkLossPercent=None, downlinkLossPercent=None):
"""
Updates the network profile with specifi... | Updates the network profile with specific settings.
See also: AWS API Documentation
:example: response = client.update_network_profile(
arn='string',
name='string',
description='string',
type='CURATED'|'PRIVATE',
uplinkBandwidthBits=123,
downlinkBandwidt... | Below is the the instruction that describes the task:
### Input:
Updates the network profile with specific settings.
See also: AWS API Documentation
:example: response = client.update_network_profile(
arn='string',
name='string',
description='string',
type='CURATED'... |
def _storef16(ins):
""" Stores 2º operand content into address of 1st operand.
store16 a, x => *(&a) = x
"""
value = ins.quad[2]
if is_float(value):
val = float(ins.quad[2]) # Immediate?
(de, hl) = f16(val)
q = list(ins.quad)
q[2] = (de << 16) | hl
ins.quad ... | Stores 2º operand content into address of 1st operand.
store16 a, x => *(&a) = x | Below is the the instruction that describes the task:
### Input:
Stores 2º operand content into address of 1st operand.
store16 a, x => *(&a) = x
### Response:
def _storef16(ins):
""" Stores 2º operand content into address of 1st operand.
store16 a, x => *(&a) = x
"""
value = ins.quad[2]
... |
def ReadAllArtifacts(self, cursor=None):
"""Lists all artifacts that are stored in the database."""
cursor.execute("SELECT definition FROM artifacts")
return [_RowToArtifact(row) for row in cursor.fetchall()] | Lists all artifacts that are stored in the database. | Below is the the instruction that describes the task:
### Input:
Lists all artifacts that are stored in the database.
### Response:
def ReadAllArtifacts(self, cursor=None):
"""Lists all artifacts that are stored in the database."""
cursor.execute("SELECT definition FROM artifacts")
return [_RowToArtifa... |
def download_storyitem(self, item: StoryItem, target: str) -> bool:
"""Download one user story.
:param item: Story item, as in story['items'] for story in :meth:`get_stories`
:param target: Replacement for {target} in dirname_pattern and filename_pattern
:return: True if something was d... | Download one user story.
:param item: Story item, as in story['items'] for story in :meth:`get_stories`
:param target: Replacement for {target} in dirname_pattern and filename_pattern
:return: True if something was downloaded, False otherwise, i.e. file was already there | Below is the the instruction that describes the task:
### Input:
Download one user story.
:param item: Story item, as in story['items'] for story in :meth:`get_stories`
:param target: Replacement for {target} in dirname_pattern and filename_pattern
:return: True if something was downloaded,... |
def is_filter_type(target):
# type: (Any) -> Union[bool, Text]
"""
Returns whether the specified object can be registered as a filter.
:return:
Returns ``True`` if the object is a filter.
Otherwise, returns a string indicating why it is not valid.
"""
if not is_class(target):
... | Returns whether the specified object can be registered as a filter.
:return:
Returns ``True`` if the object is a filter.
Otherwise, returns a string indicating why it is not valid. | Below is the the instruction that describes the task:
### Input:
Returns whether the specified object can be registered as a filter.
:return:
Returns ``True`` if the object is a filter.
Otherwise, returns a string indicating why it is not valid.
### Response:
def is_filter_type(target):
# ... |
def _calculate_duration(start_time, finish_time):
"""Calculates how long it took to execute the testcase."""
if not (start_time and finish_time):
return 0
start = datetime.datetime.fromtimestamp(start_time)
finish = datetime.datetime.fromtimestamp(finish_time)
duration = finish - start
... | Calculates how long it took to execute the testcase. | Below is the the instruction that describes the task:
### Input:
Calculates how long it took to execute the testcase.
### Response:
def _calculate_duration(start_time, finish_time):
"""Calculates how long it took to execute the testcase."""
if not (start_time and finish_time):
return 0
start = ... |
def get_runs(self, sort_by=None, sort_direction=None, start=0, limit=None, query={"type": "and", "filters": []}):
"""
Return all runs in the file store.
If a run is corrupt, e.g. missing files, it is skipped.
:param sort_by: NotImplemented
:param sort_direction: NotImplemented... | Return all runs in the file store.
If a run is corrupt, e.g. missing files, it is skipped.
:param sort_by: NotImplemented
:param sort_direction: NotImplemented
:param start: NotImplemented
:param limit: NotImplemented
:param query: NotImplemented
:return: FileS... | Below is the the instruction that describes the task:
### Input:
Return all runs in the file store.
If a run is corrupt, e.g. missing files, it is skipped.
:param sort_by: NotImplemented
:param sort_direction: NotImplemented
:param start: NotImplemented
:param limit: NotIm... |
def exclude(self, other):
"""
Remove coordinates from another region or an array.
If other is an array, will remove coordinates of all
non-zero elements from this region. If other is a region,
will remove any matching coordinates.
Parameters
----------
o... | Remove coordinates from another region or an array.
If other is an array, will remove coordinates of all
non-zero elements from this region. If other is a region,
will remove any matching coordinates.
Parameters
----------
other : ndarray or one region
Regio... | Below is the the instruction that describes the task:
### Input:
Remove coordinates from another region or an array.
If other is an array, will remove coordinates of all
non-zero elements from this region. If other is a region,
will remove any matching coordinates.
Parameters
... |
def validate_url(cls, url):
"""Strip and trailing slash to validate a url
:param url: the url address
:return: the valid url address
:rtype: string
"""
if url is None:
return None
url = url.strip()
while url.endswith('/'):
url = ... | Strip and trailing slash to validate a url
:param url: the url address
:return: the valid url address
:rtype: string | Below is the the instruction that describes the task:
### Input:
Strip and trailing slash to validate a url
:param url: the url address
:return: the valid url address
:rtype: string
### Response:
def validate_url(cls, url):
"""Strip and trailing slash to validate a url
:pa... |
def reactToAMQPMessage(message, sender):
"""
React to given (AMQP) message. `message` is usually expected to be
:py:func:`collections.namedtuple` structure filled with all necessary data.
Args:
message (\*Request class): One of the structures defined in
:mod:`.requests`.
... | React to given (AMQP) message. `message` is usually expected to be
:py:func:`collections.namedtuple` structure filled with all necessary data.
Args:
message (\*Request class): One of the structures defined in
:mod:`.requests`.
sender (fn reference): Reference to function for res... | Below is the the instruction that describes the task:
### Input:
React to given (AMQP) message. `message` is usually expected to be
:py:func:`collections.namedtuple` structure filled with all necessary data.
Args:
message (\*Request class): One of the structures defined in
:mod:`.re... |
def linestrings_intersect(line1, line2):
"""
To valid whether linestrings from geojson are intersected with each other.
reference: http://www.kevlindev.com/gui/math/intersection/Intersection.js
Keyword arguments:
line1 -- first line geojson object
line2 -- second line geojson object
if(lin... | To valid whether linestrings from geojson are intersected with each other.
reference: http://www.kevlindev.com/gui/math/intersection/Intersection.js
Keyword arguments:
line1 -- first line geojson object
line2 -- second line geojson object
if(line1 intersects with other) return intersect point arra... | Below is the the instruction that describes the task:
### Input:
To valid whether linestrings from geojson are intersected with each other.
reference: http://www.kevlindev.com/gui/math/intersection/Intersection.js
Keyword arguments:
line1 -- first line geojson object
line2 -- second line geojson ob... |
def parse(self, stream, media_type=None, parser_context=None):
"""
Parses the incoming bytestream as a multipart encoded form,
and returns a DataAndFiles object.
`.data` will be a `QueryDict` containing all the form parameters.
`.files` will be a `QueryDict` containing all the f... | Parses the incoming bytestream as a multipart encoded form,
and returns a DataAndFiles object.
`.data` will be a `QueryDict` containing all the form parameters.
`.files` will be a `QueryDict` containing all the form files. | Below is the the instruction that describes the task:
### Input:
Parses the incoming bytestream as a multipart encoded form,
and returns a DataAndFiles object.
`.data` will be a `QueryDict` containing all the form parameters.
`.files` will be a `QueryDict` containing all the form files.
###... |
def stop_capture(self, adapter_number):
"""
Stops a packet capture.
:param adapter_number: adapter number
"""
try:
adapter = self._ethernet_adapters[adapter_number]
except KeyError:
raise DockerError("Adapter {adapter_number} doesn't exist on Doc... | Stops a packet capture.
:param adapter_number: adapter number | Below is the the instruction that describes the task:
### Input:
Stops a packet capture.
:param adapter_number: adapter number
### Response:
def stop_capture(self, adapter_number):
"""
Stops a packet capture.
:param adapter_number: adapter number
"""
try:
... |
def save_checkpoint(self, config, population, species_set, generation):
""" Save the current simulation state. """
filename = '{0}{1}'.format(self.filename_prefix, generation)
print("Saving checkpoint to {0}".format(filename))
with gzip.open(filename, 'w', compresslevel=5) as f:
... | Save the current simulation state. | Below is the the instruction that describes the task:
### Input:
Save the current simulation state.
### Response:
def save_checkpoint(self, config, population, species_set, generation):
""" Save the current simulation state. """
filename = '{0}{1}'.format(self.filename_prefix, generation)
p... |
def delay(self, n, start_time):
"""Calculate delay before the next retry.
Args:
n: the number of current attempt. The first attempt should be 1.
start_time: the time when retry started in unix time.
Returns:
Number of seconds to wait before next retry. -1 if retry should give up.
"""... | Calculate delay before the next retry.
Args:
n: the number of current attempt. The first attempt should be 1.
start_time: the time when retry started in unix time.
Returns:
Number of seconds to wait before next retry. -1 if retry should give up. | Below is the the instruction that describes the task:
### Input:
Calculate delay before the next retry.
Args:
n: the number of current attempt. The first attempt should be 1.
start_time: the time when retry started in unix time.
Returns:
Number of seconds to wait before next retry. -1 if... |
def to_utc(a_datetime, keep_utc_tzinfo=False):
"""
Convert a time awared datetime to utc datetime.
:param a_datetime: a timezone awared datetime. (If not, then just returns)
:param keep_utc_tzinfo: whether to retain the utc time zone information.
**中文文档**
将一个带时区的时间转化成UTC时间。而对于UTC时间而言, 有没有时区信息... | Convert a time awared datetime to utc datetime.
:param a_datetime: a timezone awared datetime. (If not, then just returns)
:param keep_utc_tzinfo: whether to retain the utc time zone information.
**中文文档**
将一个带时区的时间转化成UTC时间。而对于UTC时间而言, 有没有时区信息都无所谓了。 | Below is the the instruction that describes the task:
### Input:
Convert a time awared datetime to utc datetime.
:param a_datetime: a timezone awared datetime. (If not, then just returns)
:param keep_utc_tzinfo: whether to retain the utc time zone information.
**中文文档**
将一个带时区的时间转化成UTC时间。而对于UTC时间而... |
def join(self, vals):
"""
Either return the non-list value or raise an Exception.
Arguments:
vals - a list of values to process
"""
if len(vals) == 1:
return vals[0]
raise Exception(
"Too many values for {}:{}".format(self._component_name,... | Either return the non-list value or raise an Exception.
Arguments:
vals - a list of values to process | Below is the the instruction that describes the task:
### Input:
Either return the non-list value or raise an Exception.
Arguments:
vals - a list of values to process
### Response:
def join(self, vals):
"""
Either return the non-list value or raise an Exception.
Arguments:... |
def roll_die(qvm, number_of_sides):
"""
Roll an n-sided quantum die.
"""
die_compiled = qvm.compile(die_program(number_of_sides))
return process_results(qvm.run(die_compiled)) | Roll an n-sided quantum die. | Below is the the instruction that describes the task:
### Input:
Roll an n-sided quantum die.
### Response:
def roll_die(qvm, number_of_sides):
"""
Roll an n-sided quantum die.
"""
die_compiled = qvm.compile(die_program(number_of_sides))
return process_results(qvm.run(die_compiled)) |
def allocate_ids(self, partial_keys):
"""
Allocate IDs for incomplete keys.
.. seealso::
https://cloud.google.com/datastore/docs/reference/rest/v1/projects/allocateIds
:param partial_keys: a list of partial keys.
:type partial_keys: list
:return: a list of f... | Allocate IDs for incomplete keys.
.. seealso::
https://cloud.google.com/datastore/docs/reference/rest/v1/projects/allocateIds
:param partial_keys: a list of partial keys.
:type partial_keys: list
:return: a list of full keys.
:rtype: list | Below is the the instruction that describes the task:
### Input:
Allocate IDs for incomplete keys.
.. seealso::
https://cloud.google.com/datastore/docs/reference/rest/v1/projects/allocateIds
:param partial_keys: a list of partial keys.
:type partial_keys: list
:return: ... |
def readline(self, size=None):
"""
Read one entire line from the file. A trailing newline character is
kept in the string (but may be absent when a file ends with an
incomplete line). If the size argument is present and non-negative, it
is a maximum byte count (including the tr... | Read one entire line from the file. A trailing newline character is
kept in the string (but may be absent when a file ends with an
incomplete line). If the size argument is present and non-negative, it
is a maximum byte count (including the trailing newline) and an
incomplete line may ... | Below is the the instruction that describes the task:
### Input:
Read one entire line from the file. A trailing newline character is
kept in the string (but may be absent when a file ends with an
incomplete line). If the size argument is present and non-negative, it
is a maximum byte count... |
def create_tables(c):
"""create (or recreate) the auto shape type tables"""
# auto_shape_types ---------------------
c.execute(
'DROP TABLE IF EXISTS auto_shape_types'
)
c.execute(
'CREATE TABLE auto_shape_types (\n'
' id integer,\n'
' prst text,\n... | create (or recreate) the auto shape type tables | Below is the the instruction that describes the task:
### Input:
create (or recreate) the auto shape type tables
### Response:
def create_tables(c):
"""create (or recreate) the auto shape type tables"""
# auto_shape_types ---------------------
c.execute(
'DROP TABLE IF EXISTS auto_shape_types'
... |
def edge(s, path, edge, alpha=1.0):
""" Visualization of a single edge between two nodes.
"""
path.moveto(edge.node1.x, edge.node1.y)
if edge.node2.style == BACK:
path.curveto(
edge.node1.x,
edge.node2.y,
edge.node2.x,
edge.node2.y,
... | Visualization of a single edge between two nodes. | Below is the the instruction that describes the task:
### Input:
Visualization of a single edge between two nodes.
### Response:
def edge(s, path, edge, alpha=1.0):
""" Visualization of a single edge between two nodes.
"""
path.moveto(edge.node1.x, edge.node1.y)
if edge.node2.style == BAC... |
def adaptive_set(
self,
reannealing_per=50,
thermostat=0.9,
t_min=0.001,
t_default=1.0
):
'''
Init for Adaptive Simulated Annealing.
Args:
reannealing_per: How often will this model reanneals there per cycles.
thermo... | Init for Adaptive Simulated Annealing.
Args:
reannealing_per: How often will this model reanneals there per cycles.
thermostat: Thermostat.
t_min: The minimum temperature.
t_default: The default temperature. | Below is the the instruction that describes the task:
### Input:
Init for Adaptive Simulated Annealing.
Args:
reannealing_per: How often will this model reanneals there per cycles.
thermostat: Thermostat.
t_min: The minimum temperature.
... |
def getOverlaps(self, inputPattern):
"""
Return the degree of overlap between an input pattern and each category
stored in the classifier. The overlap is computed by computing:
.. code-block:: python
logical_and(inputPattern != 0, trainingPattern != 0).sum()
:param inputPattern: pattern to ... | Return the degree of overlap between an input pattern and each category
stored in the classifier. The overlap is computed by computing:
.. code-block:: python
logical_and(inputPattern != 0, trainingPattern != 0).sum()
:param inputPattern: pattern to check overlap of
:returns: (overlaps, catego... | Below is the the instruction that describes the task:
### Input:
Return the degree of overlap between an input pattern and each category
stored in the classifier. The overlap is computed by computing:
.. code-block:: python
logical_and(inputPattern != 0, trainingPattern != 0).sum()
:param input... |
def setup_address(self, name, address=default, transact={}):
"""
Set up the name to point to the supplied address.
The sender of the transaction must own the name, or
its parent name.
Example: If the caller owns ``parentname.eth`` with no subdomains
and calls this method... | Set up the name to point to the supplied address.
The sender of the transaction must own the name, or
its parent name.
Example: If the caller owns ``parentname.eth`` with no subdomains
and calls this method with ``sub.parentname.eth``,
then ``sub`` will be created as part of thi... | Below is the the instruction that describes the task:
### Input:
Set up the name to point to the supplied address.
The sender of the transaction must own the name, or
its parent name.
Example: If the caller owns ``parentname.eth`` with no subdomains
and calls this method with ``sub.... |
def drawGrid(self, painter, opt, rect, index):
"""
Draws the grid lines for this delegate.
:param painter | <QtGui.QPainter>
opt | <QtGui.QStyleOptionItem>
rect | <QtCore.QRect>
index | <QtGui.QModelIndex>
... | Draws the grid lines for this delegate.
:param painter | <QtGui.QPainter>
opt | <QtGui.QStyleOptionItem>
rect | <QtCore.QRect>
index | <QtGui.QModelIndex> | Below is the the instruction that describes the task:
### Input:
Draws the grid lines for this delegate.
:param painter | <QtGui.QPainter>
opt | <QtGui.QStyleOptionItem>
rect | <QtCore.QRect>
index | <QtGui.QModelIndex>
... |
def log(self, workunit, level, *msg_elements):
"""Log a message.
Each element of msg_elements is either a message string or a (message, detail) pair.
"""
with self._lock:
for reporter in self._reporters.values():
reporter.handle_log(workunit, level, *msg_elements) | Log a message.
Each element of msg_elements is either a message string or a (message, detail) pair. | Below is the the instruction that describes the task:
### Input:
Log a message.
Each element of msg_elements is either a message string or a (message, detail) pair.
### Response:
def log(self, workunit, level, *msg_elements):
"""Log a message.
Each element of msg_elements is either a message string o... |
def echo_percent(self,transferred=1, status=None):
'''Sample usage:
f=lambda x,y:x+y
ldata = range(10)
toBeTransferred = reduce(f,range(10))
import time
progress = ProgressBarUtils("viewbar", toBeTransferred=toBeTransferred, run_sta... | Sample usage:
f=lambda x,y:x+y
ldata = range(10)
toBeTransferred = reduce(f,range(10))
import time
progress = ProgressBarUtils("viewbar", toBeTransferred=toBeTransferred, run_status="正在下载", fin_status="下载完成")
for i in ldata:... | Below is the the instruction that describes the task:
### Input:
Sample usage:
f=lambda x,y:x+y
ldata = range(10)
toBeTransferred = reduce(f,range(10))
import time
progress = ProgressBarUtils("viewbar", toBeTransferred=toBeTransferred, r... |
def parse_keyvalue(self, tup_tree):
"""
Parse a KEYVALUE element and return the keybinding value as a CIM data
type object, based upon the type information in its VALUETYPE and TYPE
attributes, if present.
If TYPE is specified, its value is used to create the corresponding CIM
... | Parse a KEYVALUE element and return the keybinding value as a CIM data
type object, based upon the type information in its VALUETYPE and TYPE
attributes, if present.
If TYPE is specified, its value is used to create the corresponding CIM
data type object. in this case, VALUETYPE is igno... | Below is the the instruction that describes the task:
### Input:
Parse a KEYVALUE element and return the keybinding value as a CIM data
type object, based upon the type information in its VALUETYPE and TYPE
attributes, if present.
If TYPE is specified, its value is used to create the corres... |
def _parse_tokenize(self, rule):
"""Tokenizer for the policy language."""
for token in self._TOKENIZE_RE.split(rule):
# Skip empty tokens
if not token or token.isspace():
continue
# Handle leading parens on the token
clean = token.lstrip(... | Tokenizer for the policy language. | Below is the the instruction that describes the task:
### Input:
Tokenizer for the policy language.
### Response:
def _parse_tokenize(self, rule):
"""Tokenizer for the policy language."""
for token in self._TOKENIZE_RE.split(rule):
# Skip empty tokens
if not token or token.... |
def standardUncertainties(self, sharpness=0.5):
'''
sharpness -> image sharpness // std of Gaussian PSF [px]
returns a list of standard uncertainties for the x and y component:
(1x,2x), (1y, 2y), (intensity:None)
1. px-size-changes(due to deflection)
2. reprojecti... | sharpness -> image sharpness // std of Gaussian PSF [px]
returns a list of standard uncertainties for the x and y component:
(1x,2x), (1y, 2y), (intensity:None)
1. px-size-changes(due to deflection)
2. reprojection error | Below is the the instruction that describes the task:
### Input:
sharpness -> image sharpness // std of Gaussian PSF [px]
returns a list of standard uncertainties for the x and y component:
(1x,2x), (1y, 2y), (intensity:None)
1. px-size-changes(due to deflection)
2. reprojectio... |
def shipping_options(request, country):
"""
Get the shipping options for a given country
"""
qrs = models.ShippingRate.objects.filter(countries__in=[country])
serializer = serializers.ShippingRateSerializer(qrs, many=True)
return Response(
data=serializer.data,
status=status.HTTP... | Get the shipping options for a given country | Below is the the instruction that describes the task:
### Input:
Get the shipping options for a given country
### Response:
def shipping_options(request, country):
"""
Get the shipping options for a given country
"""
qrs = models.ShippingRate.objects.filter(countries__in=[country])
serializer =... |
def update_vertices(self, mask):
"""
Apply a mask to remove or duplicate vertex properties.
"""
if self.uv is not None:
self.uv = self.uv[mask] | Apply a mask to remove or duplicate vertex properties. | Below is the the instruction that describes the task:
### Input:
Apply a mask to remove or duplicate vertex properties.
### Response:
def update_vertices(self, mask):
"""
Apply a mask to remove or duplicate vertex properties.
"""
if self.uv is not None:
self.uv = self.uv... |
def _find_integer_tolerance(epsilon, v_max, min_tol):
"""Find appropriate integer tolerance for gap-filling problems."""
int_tol = min(epsilon / (10 * v_max), 0.1)
min_tol = max(1e-10, min_tol)
if int_tol < min_tol:
eps_lower = min_tol * 10 * v_max
logger.warning(
'When the m... | Find appropriate integer tolerance for gap-filling problems. | Below is the the instruction that describes the task:
### Input:
Find appropriate integer tolerance for gap-filling problems.
### Response:
def _find_integer_tolerance(epsilon, v_max, min_tol):
"""Find appropriate integer tolerance for gap-filling problems."""
int_tol = min(epsilon / (10 * v_max), 0.1)
... |
def pendingTasks(self, *args, **kwargs):
"""
Get Number of Pending Tasks
Get an approximate number of pending tasks for the given `provisionerId`
and `workerType`.
The underlying Azure Storage Queues only promises to give us an estimate.
Furthermore, we cache the result... | Get Number of Pending Tasks
Get an approximate number of pending tasks for the given `provisionerId`
and `workerType`.
The underlying Azure Storage Queues only promises to give us an estimate.
Furthermore, we cache the result in memory for 20 seconds. So consumers
should be no ... | Below is the the instruction that describes the task:
### Input:
Get Number of Pending Tasks
Get an approximate number of pending tasks for the given `provisionerId`
and `workerType`.
The underlying Azure Storage Queues only promises to give us an estimate.
Furthermore, we cache th... |
def _eig_sym(self):
"""
Perform eigendecompositon of the rate matrix and stores the left- and right-
matrices to convert the sequence profiles to the GTR matrix eigenspace
and hence to speed-up the computations.
"""
# eigendecomposition of the rate matrix
tmpp = n... | Perform eigendecompositon of the rate matrix and stores the left- and right-
matrices to convert the sequence profiles to the GTR matrix eigenspace
and hence to speed-up the computations. | Below is the the instruction that describes the task:
### Input:
Perform eigendecompositon of the rate matrix and stores the left- and right-
matrices to convert the sequence profiles to the GTR matrix eigenspace
and hence to speed-up the computations.
### Response:
def _eig_sym(self):
"""
... |
def setInverted(self, state):
"""
Sets whether or not to invert the check state for collapsing.
:param state | <bool>
"""
collapsed = self.isCollapsed()
self._inverted = state
if self.isCollapsible():
self.setCollapsed(collapsed) | Sets whether or not to invert the check state for collapsing.
:param state | <bool> | Below is the the instruction that describes the task:
### Input:
Sets whether or not to invert the check state for collapsing.
:param state | <bool>
### Response:
def setInverted(self, state):
"""
Sets whether or not to invert the check state for collapsing.
... |
def handle_routine(self, que, opts, host, target, mine=False):
'''
Run the routine in a "Thread", put a dict on the queue
'''
opts = copy.deepcopy(opts)
single = Single(
opts,
opts['argv'],
host,
mods=self.mods,
... | Run the routine in a "Thread", put a dict on the queue | Below is the the instruction that describes the task:
### Input:
Run the routine in a "Thread", put a dict on the queue
### Response:
def handle_routine(self, que, opts, host, target, mine=False):
'''
Run the routine in a "Thread", put a dict on the queue
'''
opts = copy.deepcopy(op... |
def save(filepath, obj, on_overwrite = 'ignore'):
"""
Serialize `object` to a file denoted by `filepath`.
Parameters
----------
filepath : str
A filename. If the suffix is `.joblib` and joblib can be
imported, `joblib.dump` is used in place of the regular
pickling mechanisms... | Serialize `object` to a file denoted by `filepath`.
Parameters
----------
filepath : str
A filename. If the suffix is `.joblib` and joblib can be
imported, `joblib.dump` is used in place of the regular
pickling mechanisms; this results in much faster saves by
saving arrays a... | Below is the the instruction that describes the task:
### Input:
Serialize `object` to a file denoted by `filepath`.
Parameters
----------
filepath : str
A filename. If the suffix is `.joblib` and joblib can be
imported, `joblib.dump` is used in place of the regular
pickling mec... |
def ros_q_to_core_q(q_ros):
"""Converts a ROS quaternion vector to an autolab_core quaternion vector."""
q_core = np.array([q_ros[3], q_ros[0], q_ros[1], q_ros[2]])
return q_core | Converts a ROS quaternion vector to an autolab_core quaternion vector. | Below is the the instruction that describes the task:
### Input:
Converts a ROS quaternion vector to an autolab_core quaternion vector.
### Response:
def ros_q_to_core_q(q_ros):
"""Converts a ROS quaternion vector to an autolab_core quaternion vector."""
q_core = np.array([q_ros[3], q_ros[0], q_ros... |
def check_weekday(year, month, day, reverse=False):
"""
Make sure any event day we send back for weekday repeating
events is not a weekend.
"""
d = date(year, month, day)
while d.weekday() in (5, 6):
if reverse:
d -= timedelta(days=1)
else:
d += timedelta(... | Make sure any event day we send back for weekday repeating
events is not a weekend. | Below is the the instruction that describes the task:
### Input:
Make sure any event day we send back for weekday repeating
events is not a weekend.
### Response:
def check_weekday(year, month, day, reverse=False):
"""
Make sure any event day we send back for weekday repeating
events is not a weeke... |
def set_concurrency_options(self, thread_safe=True, handler_thread=True):
"""Set concurrency options for this device server.
Must be called before :meth:`start`.
Parameters
==========
thread_safe : bool
If True, make the server public methods thread safe. Incurs
... | Set concurrency options for this device server.
Must be called before :meth:`start`.
Parameters
==========
thread_safe : bool
If True, make the server public methods thread safe. Incurs
performance overhead.
handler_thread : bool
Can only be ... | Below is the the instruction that describes the task:
### Input:
Set concurrency options for this device server.
Must be called before :meth:`start`.
Parameters
==========
thread_safe : bool
If True, make the server public methods thread safe. Incurs
perform... |
def _decompose_pattern(self, pattern):
"""
Given a path pattern with format declaration, generates a
four-tuple (glob_pattern, regexp pattern, fields, type map)
"""
sep = '~lancet~sep~'
float_codes = ['e','E','f', 'F','g', 'G', 'n']
typecodes = dict([(k,float) for... | Given a path pattern with format declaration, generates a
four-tuple (glob_pattern, regexp pattern, fields, type map) | Below is the the instruction that describes the task:
### Input:
Given a path pattern with format declaration, generates a
four-tuple (glob_pattern, regexp pattern, fields, type map)
### Response:
def _decompose_pattern(self, pattern):
"""
Given a path pattern with format declaration, gener... |
def kmeans(self, maxiter, record_heterogeneity=None, verbose=False):
'''This function runs k-means on given data and initial set of centroids.
maxiter: maximum number of iterations to run.
record_heterogeneity: (optional) a list, to store the history of heterogeneity as function of iterati... | This function runs k-means on given data and initial set of centroids.
maxiter: maximum number of iterations to run.
record_heterogeneity: (optional) a list, to store the history of heterogeneity as function of iterations
if None, do not store the history.
v... | Below is the the instruction that describes the task:
### Input:
This function runs k-means on given data and initial set of centroids.
maxiter: maximum number of iterations to run.
record_heterogeneity: (optional) a list, to store the history of heterogeneity as function of iterations
... |
def rating(self, **kwargs):
"""
This method lets users rate a movie. A valid session id or guest
session id is required.
Args:
session_id: see Authentication.
guest_session_id: see Authentication.
value: Rating value.
Returns:
A d... | This method lets users rate a movie. A valid session id or guest
session id is required.
Args:
session_id: see Authentication.
guest_session_id: see Authentication.
value: Rating value.
Returns:
A dict representation of the JSON returned from the... | Below is the the instruction that describes the task:
### Input:
This method lets users rate a movie. A valid session id or guest
session id is required.
Args:
session_id: see Authentication.
guest_session_id: see Authentication.
value: Rating value.
Ret... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.