code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def data_received(self, data):
"""Handle received data."""
self._data_buffer += data.decode()
if not self._data_buffer.endswith('\r\n'):
return
data = self._data_buffer
self._data_buffer = '' # clear buffer
for cmd in data.strip().split('\r\n'):
d... | Handle received data. | Below is the the instruction that describes the task:
### Input:
Handle received data.
### Response:
def data_received(self, data):
"""Handle received data."""
self._data_buffer += data.decode()
if not self._data_buffer.endswith('\r\n'):
return
data = self._data_buffer
... |
def _cleanup_closed(self) -> None:
"""Double confirmation for transport close.
Some broken ssl servers may leave socket open without proper close.
"""
if self._cleanup_closed_handle:
self._cleanup_closed_handle.cancel()
for transport in self._cleanup_closed_transport... | Double confirmation for transport close.
Some broken ssl servers may leave socket open without proper close. | Below is the the instruction that describes the task:
### Input:
Double confirmation for transport close.
Some broken ssl servers may leave socket open without proper close.
### Response:
def _cleanup_closed(self) -> None:
"""Double confirmation for transport close.
Some broken ssl servers ... |
def ready(self):
"""Validate config and connect signals."""
super(ElasticAppConfig, self).ready()
_validate_config(settings.get_setting("strict_validation"))
_connect_signals() | Validate config and connect signals. | Below is the the instruction that describes the task:
### Input:
Validate config and connect signals.
### Response:
def ready(self):
"""Validate config and connect signals."""
super(ElasticAppConfig, self).ready()
_validate_config(settings.get_setting("strict_validation"))
_connect_... |
def wait_for_notification(self, notification_class=BaseNotification):
"""Wait for the specified notification to be displayed.
Args:
notification_class (:py:class:`BaseNotification`, optional):
The notification class to wait for. If `None` is specified it
will... | Wait for the specified notification to be displayed.
Args:
notification_class (:py:class:`BaseNotification`, optional):
The notification class to wait for. If `None` is specified it
will wait for any notification to be closed. Defaults to
`BaseNotific... | Below is the the instruction that describes the task:
### Input:
Wait for the specified notification to be displayed.
Args:
notification_class (:py:class:`BaseNotification`, optional):
The notification class to wait for. If `None` is specified it
will wait for an... |
def children(self, **kwargs):
"""Retrieve the children of this `Part` as `Partset`.
When you call the :func:`Part.children()` method without any additional filtering options for the children,
the children are cached to help speed up subsequent calls to retrieve the children. The cached children... | Retrieve the children of this `Part` as `Partset`.
When you call the :func:`Part.children()` method without any additional filtering options for the children,
the children are cached to help speed up subsequent calls to retrieve the children. The cached children are
returned as a list and not a... | Below is the the instruction that describes the task:
### Input:
Retrieve the children of this `Part` as `Partset`.
When you call the :func:`Part.children()` method without any additional filtering options for the children,
the children are cached to help speed up subsequent calls to retrieve the c... |
def check_clean_master(self, commit=False):
"""Perform a sanity check on SCM publishing constraints.
Checks for uncommitted tracked files and ensures we're on an allowed branch configured to push
to an allowed server if `commit` is `True`.
:param bool commit: `True` if a commit is in progress.
:ra... | Perform a sanity check on SCM publishing constraints.
Checks for uncommitted tracked files and ensures we're on an allowed branch configured to push
to an allowed server if `commit` is `True`.
:param bool commit: `True` if a commit is in progress.
:raise TaskError: on failure | Below is the the instruction that describes the task:
### Input:
Perform a sanity check on SCM publishing constraints.
Checks for uncommitted tracked files and ensures we're on an allowed branch configured to push
to an allowed server if `commit` is `True`.
:param bool commit: `True` if a commit is in... |
def recurse(self, full_matrix=False):
"""
recursion to calculate inverse covariance matrix
Parameters
----------
full_matrix : bool, optional
if True, the entire inverse matrix is calculated. otherwise, only the weighing vector.
"""
for n in self.tree... | recursion to calculate inverse covariance matrix
Parameters
----------
full_matrix : bool, optional
if True, the entire inverse matrix is calculated. otherwise, only the weighing vector. | Below is the the instruction that describes the task:
### Input:
recursion to calculate inverse covariance matrix
Parameters
----------
full_matrix : bool, optional
if True, the entire inverse matrix is calculated. otherwise, only the weighing vector.
### Response:
def recurse(... |
def as_json(self, ensure_ascii=False):
"""Property return key-value json-string from __slots__."""
return json.dumps(self.as_dict, ensure_ascii=ensure_ascii) | Property return key-value json-string from __slots__. | Below is the the instruction that describes the task:
### Input:
Property return key-value json-string from __slots__.
### Response:
def as_json(self, ensure_ascii=False):
"""Property return key-value json-string from __slots__."""
return json.dumps(self.as_dict, ensure_ascii=ensure_ascii) |
def fixed_legend_position(self, fixed_legend_position):
"""Sets the fixed_legend_position of this ChartSettings.
Where the fixed legend should be displayed with respect to the chart # noqa: E501
:param fixed_legend_position: The fixed_legend_position of this ChartSettings. # noqa: E501
... | Sets the fixed_legend_position of this ChartSettings.
Where the fixed legend should be displayed with respect to the chart # noqa: E501
:param fixed_legend_position: The fixed_legend_position of this ChartSettings. # noqa: E501
:type: str | Below is the the instruction that describes the task:
### Input:
Sets the fixed_legend_position of this ChartSettings.
Where the fixed legend should be displayed with respect to the chart # noqa: E501
:param fixed_legend_position: The fixed_legend_position of this ChartSettings. # noqa: E501
... |
def align(self, alignment_tool = 'clustalw', gap_opening_penalty = 0.2, ignore_bad_chains = False):
'''If ignore_bad_chains is True then any chains containing all Xs as the sequence will be silently skipped.
The default behavior is to raise a MalformedSequenceException in this case.'''
if len... | If ignore_bad_chains is True then any chains containing all Xs as the sequence will be silently skipped.
The default behavior is to raise a MalformedSequenceException in this case. | Below is the the instruction that describes the task:
### Input:
If ignore_bad_chains is True then any chains containing all Xs as the sequence will be silently skipped.
The default behavior is to raise a MalformedSequenceException in this case.
### Response:
def align(self, alignment_tool = 'clustalw',... |
def is_modified(self):
"""
Returns whether model is modified or not
"""
if len(self.__modified_data__) or len(self.__deleted_fields__):
return True
for value in self.__original_data__.values():
try:
if value.is_modified():
... | Returns whether model is modified or not | Below is the the instruction that describes the task:
### Input:
Returns whether model is modified or not
### Response:
def is_modified(self):
"""
Returns whether model is modified or not
"""
if len(self.__modified_data__) or len(self.__deleted_fields__):
return True
... |
def find_contours(array, level,
fully_connected='low', positive_orientation='low'):
"""Find iso-valued contours in a 2D array for a given level value.
Uses the "marching squares" method to compute a the iso-valued contours of
the input 2D array for a particular level value. Array values a... | Find iso-valued contours in a 2D array for a given level value.
Uses the "marching squares" method to compute a the iso-valued contours of
the input 2D array for a particular level value. Array values are linearly
interpolated to provide better precision for the output contours.
Parameters
-------... | Below is the the instruction that describes the task:
### Input:
Find iso-valued contours in a 2D array for a given level value.
Uses the "marching squares" method to compute a the iso-valued contours of
the input 2D array for a particular level value. Array values are linearly
interpolated to provide ... |
def read_config(cls):
""" Setup :attr:`wasp_launcher.apps.WAppsGlobals.log` configuration. Reads defaults and
override it by a file given via :attr:`WConfigApp.__environment_file_var__` environment variable.
After that configuration files are applied from :attr:`WConfigApp.__environment_dir_var__`
:return: Non... | Setup :attr:`wasp_launcher.apps.WAppsGlobals.log` configuration. Reads defaults and
override it by a file given via :attr:`WConfigApp.__environment_file_var__` environment variable.
After that configuration files are applied from :attr:`WConfigApp.__environment_dir_var__`
:return: None | Below is the the instruction that describes the task:
### Input:
Setup :attr:`wasp_launcher.apps.WAppsGlobals.log` configuration. Reads defaults and
override it by a file given via :attr:`WConfigApp.__environment_file_var__` environment variable.
After that configuration files are applied from :attr:`WConfigApp... |
def mtf_image_transformer_base_imagenet_mp_sp():
"""Model parallel ImageNet parameters."""
hparams = mtf_image_transformer_base_imagenet_mp128()
hparams.mesh_shape = "model:8;batch:4"
hparams.layout = "batch:batch;d_ff:model;num_wblocks:model"
hparams.batch_size = 8
hparams.img_len = 128
hparams.block_len... | Model parallel ImageNet parameters. | Below is the the instruction that describes the task:
### Input:
Model parallel ImageNet parameters.
### Response:
def mtf_image_transformer_base_imagenet_mp_sp():
"""Model parallel ImageNet parameters."""
hparams = mtf_image_transformer_base_imagenet_mp128()
hparams.mesh_shape = "model:8;batch:4"
hparams.... |
def dl_hosted(
self,
token: dict = None,
resource_link: dict = None,
encode_clean: bool = 1,
proxy_url: str = None,
prot: str = "https",
) -> tuple:
"""Download hosted resource.
:param str token: API auth token
:param dict resource_link: link ... | Download hosted resource.
:param str token: API auth token
:param dict resource_link: link dictionary
:param bool encode_clean: option to ensure a clean filename and avoid OS errors
:param str proxy_url: proxy to use to download
:param str prot: https [DEFAULT] or http
... | Below is the the instruction that describes the task:
### Input:
Download hosted resource.
:param str token: API auth token
:param dict resource_link: link dictionary
:param bool encode_clean: option to ensure a clean filename and avoid OS errors
:param str proxy_url: proxy to use t... |
def json_as_html(self):
""" Print out self.json in a nice way. """
# To avoid circular import
from cspreports import utils
formatted_json = utils.format_report(self.json)
return mark_safe("<pre>\n%s</pre>" % escape(formatted_json)) | Print out self.json in a nice way. | Below is the the instruction that describes the task:
### Input:
Print out self.json in a nice way.
### Response:
def json_as_html(self):
""" Print out self.json in a nice way. """
# To avoid circular import
from cspreports import utils
formatted_json = utils.format_report(self.js... |
def infer_process_count(self):
'''Infers the number of CPU cores in the current system, sets the
number of concurrent processes accordingly
'''
try:
self.processes = multiprocessing.cpu_count()
except NotImplementedError:
self._logger.log(
... | Infers the number of CPU cores in the current system, sets the
number of concurrent processes accordingly | Below is the the instruction that describes the task:
### Input:
Infers the number of CPU cores in the current system, sets the
number of concurrent processes accordingly
### Response:
def infer_process_count(self):
'''Infers the number of CPU cores in the current system, sets the
number of... |
def remove_perm(perm, group):
"""
Removes a permission from a group
"""
if not isinstance(perm, Permission):
try:
app_label, codename = perm.split('.', 1)
except ValueError:
raise ValueError("For global permissions, first argument must be in"
... | Removes a permission from a group | Below is the the instruction that describes the task:
### Input:
Removes a permission from a group
### Response:
def remove_perm(perm, group):
"""
Removes a permission from a group
"""
if not isinstance(perm, Permission):
try:
app_label, codename = perm.split('.', 1)
exc... |
def _emit_style_tag(self, tag, markup, body):
"""Write the body of a tag and the tokens that should surround it."""
self._emit(tokens.TagOpenOpen(wiki_markup=markup))
self._emit_text(tag)
self._emit(tokens.TagCloseOpen())
self._emit_all(body)
self._emit(tokens.TagOpenClos... | Write the body of a tag and the tokens that should surround it. | Below is the the instruction that describes the task:
### Input:
Write the body of a tag and the tokens that should surround it.
### Response:
def _emit_style_tag(self, tag, markup, body):
"""Write the body of a tag and the tokens that should surround it."""
self._emit(tokens.TagOpenOpen(wiki_marku... |
def total_length_per_neurite(neurites, neurite_type=NeuriteType.all):
'''Get the path length per neurite in a collection'''
return list(sum(s.length for s in n.iter_sections())
for n in iter_neurites(neurites, filt=is_type(neurite_type))) | Get the path length per neurite in a collection | Below is the the instruction that describes the task:
### Input:
Get the path length per neurite in a collection
### Response:
def total_length_per_neurite(neurites, neurite_type=NeuriteType.all):
'''Get the path length per neurite in a collection'''
return list(sum(s.length for s in n.iter_sections())
... |
def merge(self, merge_id):
"""Get the merge full data"""
path = urijoin(self.base_url,
GitLabClient.PROJECTS, self.owner + '%2F' + self.repository,
GitLabClient.MERGES, merge_id)
response = self.fetch(path)
return response.text | Get the merge full data | Below is the the instruction that describes the task:
### Input:
Get the merge full data
### Response:
def merge(self, merge_id):
"""Get the merge full data"""
path = urijoin(self.base_url,
GitLabClient.PROJECTS, self.owner + '%2F' + self.repository,
G... |
def create_ellipse_mesh(points,**kwargs):
"""Visualize the ellipse by using the mesh of the points."""
import plotly.graph_objs as go
x,y,z = points.T
return (go.Mesh3d(x=x,y=y,z=z,**kwargs),
go.Scatter3d(x=x, y=y, z=z,
marker=dict(size=0.01),
... | Visualize the ellipse by using the mesh of the points. | Below is the the instruction that describes the task:
### Input:
Visualize the ellipse by using the mesh of the points.
### Response:
def create_ellipse_mesh(points,**kwargs):
"""Visualize the ellipse by using the mesh of the points."""
import plotly.graph_objs as go
x,y,z = points.T
return (go.Mes... |
def db(self):
"""
Get a loaded database session
"""
if self.database is NotImplemented:
self.database = Session
return self.database | Get a loaded database session | Below is the the instruction that describes the task:
### Input:
Get a loaded database session
### Response:
def db(self):
"""
Get a loaded database session
"""
if self.database is NotImplemented:
self.database = Session
return self.database |
def timer(module, name, delta, duration_units='milliseconds'):
"""
Record a timing delta:
::
start_time_s = time.time()
do_some_operation()
end_time_s = time.time()
delta_s = end_time_s - start_time_s
delta_ms = delta_s * 1000
timer(__name__, 'my_timer', delt... | Record a timing delta:
::
start_time_s = time.time()
do_some_operation()
end_time_s = time.time()
delta_s = end_time_s - start_time_s
delta_ms = delta_s * 1000
timer(__name__, 'my_timer', delta_ms) | Below is the the instruction that describes the task:
### Input:
Record a timing delta:
::
start_time_s = time.time()
do_some_operation()
end_time_s = time.time()
delta_s = end_time_s - start_time_s
delta_ms = delta_s * 1000
timer(__name__, 'my_timer', delta_ms)
... |
def minimum(station_code):
"""Extreme Minimum Design Temperature for a location.
Degrees in Celcius
Args:
station_code (str): Weather Station Code
Returns:
float degrees Celcius
"""
temp = None
fin = None
try:
fin = open('%s/%s' % (env.WEATHER_DATA_PATH,
... | Extreme Minimum Design Temperature for a location.
Degrees in Celcius
Args:
station_code (str): Weather Station Code
Returns:
float degrees Celcius | Below is the the instruction that describes the task:
### Input:
Extreme Minimum Design Temperature for a location.
Degrees in Celcius
Args:
station_code (str): Weather Station Code
Returns:
float degrees Celcius
### Response:
def minimum(station_code):
"""Extreme Minimum Design ... |
def token_permission_view(token):
"""Show permission garanted to authorized application token."""
scopes = [current_oauth2server.scopes[x] for x in token.scopes]
return render_template(
"invenio_oauth2server/settings/token_permission_view.html",
token=token,
scopes=scopes,
) | Show permission garanted to authorized application token. | Below is the the instruction that describes the task:
### Input:
Show permission garanted to authorized application token.
### Response:
def token_permission_view(token):
"""Show permission garanted to authorized application token."""
scopes = [current_oauth2server.scopes[x] for x in token.scopes]
retu... |
def name_transfer(self, key, new_address, value=None):
""" Check if this name exists and if it does, find the value field
note that update command needs an arg of <new value>.
in case we're simply transferring, need to obtain old value first
"""
key_details = self.name_s... | Check if this name exists and if it does, find the value field
note that update command needs an arg of <new value>.
in case we're simply transferring, need to obtain old value first | Below is the the instruction that describes the task:
### Input:
Check if this name exists and if it does, find the value field
note that update command needs an arg of <new value>.
in case we're simply transferring, need to obtain old value first
### Response:
def name_transfer(self, key, ... |
def recsph(rectan):
"""
Convert from rectangular coordinates to spherical coordinates.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/recrad_c.html
:param rectan: Rectangular coordinates of a point.
:type rectan: 3-Element Array of floats
:return:
Distance from the origin,... | Convert from rectangular coordinates to spherical coordinates.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/recrad_c.html
:param rectan: Rectangular coordinates of a point.
:type rectan: 3-Element Array of floats
:return:
Distance from the origin,
Angle from the posi... | Below is the the instruction that describes the task:
### Input:
Convert from rectangular coordinates to spherical coordinates.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/recrad_c.html
:param rectan: Rectangular coordinates of a point.
:type rectan: 3-Element Array of floats
:return:
... |
def shard_stores(self, index=None, params=None):
"""
Provides store information for shard copies of indices. Store
information reports on which nodes shard copies exist, the shard copy
version, indicating how recent they are, and any exceptions encountered
while opening the shard... | Provides store information for shard copies of indices. Store
information reports on which nodes shard copies exist, the shard copy
version, indicating how recent they are, and any exceptions encountered
while opening the shard index or from earlier engine failure.
`<http://www.elastic.c... | Below is the the instruction that describes the task:
### Input:
Provides store information for shard copies of indices. Store
information reports on which nodes shard copies exist, the shard copy
version, indicating how recent they are, and any exceptions encountered
while opening the shard... |
def branch(self):
'''
:param branch:
Checks out specified branch (tracking if it exists on remote).
If set to ``None``, 'master' will be checked out
:returns:
The current branch
(This could also be 'master (Detatched-Head)' - Be warned)
'''... | :param branch:
Checks out specified branch (tracking if it exists on remote).
If set to ``None``, 'master' will be checked out
:returns:
The current branch
(This could also be 'master (Detatched-Head)' - Be warned) | Below is the the instruction that describes the task:
### Input:
:param branch:
Checks out specified branch (tracking if it exists on remote).
If set to ``None``, 'master' will be checked out
:returns:
The current branch
(This could also be 'master (Detatched-... |
def estimate_column_scales(
self,
X_centered,
row_scales):
"""
column_scale[j] ** 2 =
mean{i in observed[:, j]}{
(X[i, j] - row_center[i] - column_center[j]) ** 2
-------------------------------------------------
... | column_scale[j] ** 2 =
mean{i in observed[:, j]}{
(X[i, j] - row_center[i] - column_center[j]) ** 2
-------------------------------------------------
row_scale[i] ** 2
} | Below is the the instruction that describes the task:
### Input:
column_scale[j] ** 2 =
mean{i in observed[:, j]}{
(X[i, j] - row_center[i] - column_center[j]) ** 2
-------------------------------------------------
row_scale[i] ** 2
}
### Response:
... |
def _print_bits(self,norm=2.3, height=8.0):
"""
m._print_bits(,norm=2.3, height=8.0) -- Print a text-rendering of the Motif Logo
norm -- maximum number of bits to show
height -- number of lines of text to use to render logo
"""
bits = []
tots = []
s... | m._print_bits(,norm=2.3, height=8.0) -- Print a text-rendering of the Motif Logo
norm -- maximum number of bits to show
height -- number of lines of text to use to render logo | Below is the the instruction that describes the task:
### Input:
m._print_bits(,norm=2.3, height=8.0) -- Print a text-rendering of the Motif Logo
norm -- maximum number of bits to show
height -- number of lines of text to use to render logo
### Response:
def _print_bits(self,norm=2.3, height=8.0... |
def despike(df, n1=2, n2=20, block=100, keep=0):
"""
Wild Edit Seabird-like function. Passes with Standard deviation
`n1` and `n2` with window size `block`.
"""
if isinstance(df, pd.Series):
new_df = _despike(df, n1=n1, n2=n2, block=block, keep=keep)
else:
new_df = df.apply(_de... | Wild Edit Seabird-like function. Passes with Standard deviation
`n1` and `n2` with window size `block`. | Below is the the instruction that describes the task:
### Input:
Wild Edit Seabird-like function. Passes with Standard deviation
`n1` and `n2` with window size `block`.
### Response:
def despike(df, n1=2, n2=20, block=100, keep=0):
"""
Wild Edit Seabird-like function. Passes with Standard deviation
... |
def _load(self, **kwargs):
"""Must check if rule actually exists before proceeding with load."""
if self._check_existence_by_collection(
self._meta_data['container'], kwargs['name']):
return super(Rules, self)._load(**kwargs)
msg = 'The rule named, {}, does not exist... | Must check if rule actually exists before proceeding with load. | Below is the the instruction that describes the task:
### Input:
Must check if rule actually exists before proceeding with load.
### Response:
def _load(self, **kwargs):
"""Must check if rule actually exists before proceeding with load."""
if self._check_existence_by_collection(
se... |
def _gather_configs_in(directory):
""" Return list of fully qualified python filenames in the given dir """
try:
return sorted([
os.path.join(directory, fname)
for fname in os.listdir(directory)
if fname.endswith('.py')
])
except OSError:
return [] | Return list of fully qualified python filenames in the given dir | Below is the the instruction that describes the task:
### Input:
Return list of fully qualified python filenames in the given dir
### Response:
def _gather_configs_in(directory):
""" Return list of fully qualified python filenames in the given dir """
try:
return sorted([
os.path.join(d... |
def __send_buffer(self):
"""
Sends the contents of self.__out_buffer to serial device
:return: Number of bytes written
"""
bytes_written = self.serial.write(self.__out_buffer.raw)
if self.DEBUG_MODE:
print("Wrote: '{}'".format(binascii.hexlify(self.__out_buffe... | Sends the contents of self.__out_buffer to serial device
:return: Number of bytes written | Below is the the instruction that describes the task:
### Input:
Sends the contents of self.__out_buffer to serial device
:return: Number of bytes written
### Response:
def __send_buffer(self):
"""
Sends the contents of self.__out_buffer to serial device
:return: Number of bytes wri... |
def rotateInZMat(theta_deg):
"""Rotate a vector theta degrees around the z-axis
Equivalent to yaw left
Rotates the vector in the sense that the x-axis is rotated
towards the y-axis. If looking along the z-axis (which is
not the way you usually look at it), the vector rotates
clockwise.
If... | Rotate a vector theta degrees around the z-axis
Equivalent to yaw left
Rotates the vector in the sense that the x-axis is rotated
towards the y-axis. If looking along the z-axis (which is
not the way you usually look at it), the vector rotates
clockwise.
If sitting on the vector [1,0,0], the ... | Below is the the instruction that describes the task:
### Input:
Rotate a vector theta degrees around the z-axis
Equivalent to yaw left
Rotates the vector in the sense that the x-axis is rotated
towards the y-axis. If looking along the z-axis (which is
not the way you usually look at it), the vect... |
def get_price_id_list(self, package_keyname, item_keynames, core=None):
"""Converts a list of item keynames to a list of price IDs.
This function is used to convert a list of item keynames into
a list of price IDs that are used in the Product_Order verifyOrder()
and placeOrder() functio... | Converts a list of item keynames to a list of price IDs.
This function is used to convert a list of item keynames into
a list of price IDs that are used in the Product_Order verifyOrder()
and placeOrder() functions.
:param str package_keyname: The package associated with the prices
... | Below is the the instruction that describes the task:
### Input:
Converts a list of item keynames to a list of price IDs.
This function is used to convert a list of item keynames into
a list of price IDs that are used in the Product_Order verifyOrder()
and placeOrder() functions.
:... |
def initialize_snapshot(self):
""" Copy the DAG and validate """
logger.debug('Initializing DAG snapshot for job {0}'.format(self.name))
if self.snapshot is not None:
logging.warn("Attempting to initialize DAG snapshot without " +
"first destroying old snapsh... | Copy the DAG and validate | Below is the the instruction that describes the task:
### Input:
Copy the DAG and validate
### Response:
def initialize_snapshot(self):
""" Copy the DAG and validate """
logger.debug('Initializing DAG snapshot for job {0}'.format(self.name))
if self.snapshot is not None:
logging... |
def ipcidr(self, *args):
"""Returns a random address from within the given cidr notation
IPCIDR:cidr
%{IPCIDR:10.0.0.0/8} -> ''
"""
call_args = list(args)
return self.random.choice(IPNetwork(call_args.pop(0))) | Returns a random address from within the given cidr notation
IPCIDR:cidr
%{IPCIDR:10.0.0.0/8} -> '' | Below is the the instruction that describes the task:
### Input:
Returns a random address from within the given cidr notation
IPCIDR:cidr
%{IPCIDR:10.0.0.0/8} -> ''
### Response:
def ipcidr(self, *args):
"""Returns a random address from within the given cidr notation
IPCIDR... |
def serialize(obj, **options):
'''
Serialize Python data to JSON.
:param obj: the data structure to serialize
:param options: options given to lower json/simplejson module.
'''
try:
if 'fp' in options:
return salt.utils.json.dump(obj, _json_module=_json, **options)
... | Serialize Python data to JSON.
:param obj: the data structure to serialize
:param options: options given to lower json/simplejson module. | Below is the the instruction that describes the task:
### Input:
Serialize Python data to JSON.
:param obj: the data structure to serialize
:param options: options given to lower json/simplejson module.
### Response:
def serialize(obj, **options):
'''
Serialize Python data to JSON.
:param obj... |
def verify_recipient(self, recipient):
"""
Verify that I'm the recipient of the assertion
:param recipient: A URI specifying the entity or location to which an
attesting entity can present the assertion.
:return: True/False
"""
if not self.conv_info:
... | Verify that I'm the recipient of the assertion
:param recipient: A URI specifying the entity or location to which an
attesting entity can present the assertion.
:return: True/False | Below is the the instruction that describes the task:
### Input:
Verify that I'm the recipient of the assertion
:param recipient: A URI specifying the entity or location to which an
attesting entity can present the assertion.
:return: True/False
### Response:
def verify_recipient(self,... |
def template(template_name, *, app_key=APP_KEY, encoding='utf-8', status=200):
"""
Decorator compatible with aiohttp_apiset router
"""
def wrapper(func):
@functools.wraps(func)
async def wrapped(*args, **kwargs):
if asyncio.iscoroutinefunction(func):
coro = f... | Decorator compatible with aiohttp_apiset router | Below is the the instruction that describes the task:
### Input:
Decorator compatible with aiohttp_apiset router
### Response:
def template(template_name, *, app_key=APP_KEY, encoding='utf-8', status=200):
"""
Decorator compatible with aiohttp_apiset router
"""
def wrapper(func):
@functool... |
def run(self):
"""Compile libfaketime."""
if sys.platform == "linux" or sys.platform == "linux2":
libname = 'libfaketime.so.1'
libnamemt = 'libfaketimeMT.so.1'
elif sys.platform == "darwin":
libname = 'libfaketime.1.dylib'
libnamemt = 'libfaketimeM... | Compile libfaketime. | Below is the the instruction that describes the task:
### Input:
Compile libfaketime.
### Response:
def run(self):
"""Compile libfaketime."""
if sys.platform == "linux" or sys.platform == "linux2":
libname = 'libfaketime.so.1'
libnamemt = 'libfaketimeMT.so.1'
elif sy... |
def find_root_path(absolute_path, relative_path):
"""
Return the root path of a path relative to an absolute path.
Example:
@param absolute_path: an absolute path that is ended by the specified
relative path.
@param relative_path: a relative path that ends the specified absolute
p... | Return the root path of a path relative to an absolute path.
Example:
@param absolute_path: an absolute path that is ended by the specified
relative path.
@param relative_path: a relative path that ends the specified absolute
path.
@return: the root path of the relative path. | Below is the the instruction that describes the task:
### Input:
Return the root path of a path relative to an absolute path.
Example:
@param absolute_path: an absolute path that is ended by the specified
relative path.
@param relative_path: a relative path that ends the specified absolute
... |
def head(self, display=True, html=None):
"""Return the header stats of this dataset. If in IPython, this will
be formatted to HTML. Otherwise returns a console friendly string"""
# Generate the output
if html:
fmt = ""
# HTML version
fmt += "\n"
... | Return the header stats of this dataset. If in IPython, this will
be formatted to HTML. Otherwise returns a console friendly string | Below is the the instruction that describes the task:
### Input:
Return the header stats of this dataset. If in IPython, this will
be formatted to HTML. Otherwise returns a console friendly string
### Response:
def head(self, display=True, html=None):
"""Return the header stats of this dataset. If ... |
def with_random_weights(cls, options):
"""
Initialize from a list of options with random weights.
The weights assigned to each object are uniformally random
integers between ``1`` and ``len(options)``
Args:
options (list): The list of options of any type this object... | Initialize from a list of options with random weights.
The weights assigned to each object are uniformally random
integers between ``1`` and ``len(options)``
Args:
options (list): The list of options of any type this object
can return with the ``get()`` method.
... | Below is the the instruction that describes the task:
### Input:
Initialize from a list of options with random weights.
The weights assigned to each object are uniformally random
integers between ``1`` and ``len(options)``
Args:
options (list): The list of options of any type t... |
def delete_model(self, **kwargs):
"""Delete model.
Parameters
-----------
kwargs : logging information
Find items to delete, leave it empty to delete all log.
"""
self._fill_project_info(kwargs)
self.db.Model.delete_many(kwargs)
logging.info("... | Delete model.
Parameters
-----------
kwargs : logging information
Find items to delete, leave it empty to delete all log. | Below is the the instruction that describes the task:
### Input:
Delete model.
Parameters
-----------
kwargs : logging information
Find items to delete, leave it empty to delete all log.
### Response:
def delete_model(self, **kwargs):
"""Delete model.
Parameter... |
def get_link_density(node, node_text=None):
"""
Computes the ratio for text in given node and text in links
contained in the node. It is computed from number of
characters in the texts.
:parameter Element node:
HTML element in which links density is computed.
:parameter string node_text... | Computes the ratio for text in given node and text in links
contained in the node. It is computed from number of
characters in the texts.
:parameter Element node:
HTML element in which links density is computed.
:parameter string node_text:
Text content of given node if it was obtained ... | Below is the the instruction that describes the task:
### Input:
Computes the ratio for text in given node and text in links
contained in the node. It is computed from number of
characters in the texts.
:parameter Element node:
HTML element in which links density is computed.
:parameter str... |
def has_valid_padding(value, bits=7):
"""Whether the padding bits are all zero"""
assert bits <= 8
mask = (((1 << (8 - bits)) - 1) << bits)
if isinstance(value, integer_types):
while value:
if value & mask:
return False
v... | Whether the padding bits are all zero | Below is the the instruction that describes the task:
### Input:
Whether the padding bits are all zero
### Response:
def has_valid_padding(value, bits=7):
"""Whether the padding bits are all zero"""
assert bits <= 8
mask = (((1 << (8 - bits)) - 1) << bits)
if isinstance(value, in... |
def _get_first_part_id(self, assessment_id):
"""This session implemenation assumes all items are assigned to the first assessment part"""
if assessment_id not in self._first_part_index:
self._first_part_index[assessment_id] = get_first_part_id_for_assessment(
assessment_id,
... | This session implemenation assumes all items are assigned to the first assessment part | Below is the the instruction that describes the task:
### Input:
This session implemenation assumes all items are assigned to the first assessment part
### Response:
def _get_first_part_id(self, assessment_id):
"""This session implemenation assumes all items are assigned to the first assessment part"""
... |
def set_wsgi_params(self, module=None, callable_name=None, env_strategy=None):
"""Set wsgi related parameters.
:param str|unicode module:
* load .wsgi file as the Python application
* load a WSGI module as the application.
.. note:: The module (sans ``.py``) must be... | Set wsgi related parameters.
:param str|unicode module:
* load .wsgi file as the Python application
* load a WSGI module as the application.
.. note:: The module (sans ``.py``) must be importable, ie. be in ``PYTHONPATH``.
Examples:
* mypackage.... | Below is the the instruction that describes the task:
### Input:
Set wsgi related parameters.
:param str|unicode module:
* load .wsgi file as the Python application
* load a WSGI module as the application.
.. note:: The module (sans ``.py``) must be importable, ie. be i... |
def union(self, *args):
"""
Produce an array that contains the union: each distinct element
from all of the passed-in arrays.
"""
# setobj = set(self.obj)
# for i, v in enumerate(args):
# setobj = setobj + set(args[i])
# return self._wrap(self._clean._... | Produce an array that contains the union: each distinct element
from all of the passed-in arrays. | Below is the the instruction that describes the task:
### Input:
Produce an array that contains the union: each distinct element
from all of the passed-in arrays.
### Response:
def union(self, *args):
"""
Produce an array that contains the union: each distinct element
from all of th... |
def covariance_matrix(self,x,y,names=None,cov=None):
"""build a pyemu.Cov instance from GeoStruct
Parameters
----------
x : (iterable of floats)
x-coordinate locations
y : (iterable of floats)
y-coordinate locations
names : (iterable of str)
... | build a pyemu.Cov instance from GeoStruct
Parameters
----------
x : (iterable of floats)
x-coordinate locations
y : (iterable of floats)
y-coordinate locations
names : (iterable of str)
names of location. If None, cov must not be None. Defaul... | Below is the the instruction that describes the task:
### Input:
build a pyemu.Cov instance from GeoStruct
Parameters
----------
x : (iterable of floats)
x-coordinate locations
y : (iterable of floats)
y-coordinate locations
names : (iterable of str)
... |
def seasonal_subset(dataframe,
months='all'):
'''Get the seasonal data.
Parameters
----------
dataframe : pd.DataFrame
months: int, str
Months to use for statistics, or 'all' for 1-12 (default='all')
'''
if isinstance(months, str) and months == 'all':
mo... | Get the seasonal data.
Parameters
----------
dataframe : pd.DataFrame
months: int, str
Months to use for statistics, or 'all' for 1-12 (default='all') | Below is the the instruction that describes the task:
### Input:
Get the seasonal data.
Parameters
----------
dataframe : pd.DataFrame
months: int, str
Months to use for statistics, or 'all' for 1-12 (default='all')
### Response:
def seasonal_subset(dataframe,
months='a... |
def get_frame_locals(stepback=0):
"""Returns locals dictionary from a given frame.
:param int stepback:
:rtype: dict
"""
with Frame(stepback=stepback) as frame:
locals_dict = frame.f_locals
return locals_dict | Returns locals dictionary from a given frame.
:param int stepback:
:rtype: dict | Below is the the instruction that describes the task:
### Input:
Returns locals dictionary from a given frame.
:param int stepback:
:rtype: dict
### Response:
def get_frame_locals(stepback=0):
"""Returns locals dictionary from a given frame.
:param int stepback:
:rtype: dict
"""
wi... |
def export(self, nidm_version, export_dir):
"""
Create prov entities and activities.
"""
self.add_attributes({
PROV['type']: self.type,
NIDM_DIMENSIONS_IN_VOXELS: json.dumps(self.dimensions.tolist()),
NIDM_NUMBER_OF_DIMENSIONS: self.number_of_dimension... | Create prov entities and activities. | Below is the the instruction that describes the task:
### Input:
Create prov entities and activities.
### Response:
def export(self, nidm_version, export_dir):
"""
Create prov entities and activities.
"""
self.add_attributes({
PROV['type']: self.type,
NIDM_DI... |
async def _setops(self, name, valu, editatom, init=False):
'''
Generate operations to set a property on a node.
'''
prop = self.form.prop(name)
if prop is None:
if self.snap.strict:
raise s_exc.NoSuchProp(name=name)
await self.snap.warn(f... | Generate operations to set a property on a node. | Below is the the instruction that describes the task:
### Input:
Generate operations to set a property on a node.
### Response:
async def _setops(self, name, valu, editatom, init=False):
'''
Generate operations to set a property on a node.
'''
prop = self.form.prop(name)
if ... |
def samplewise_norm(
x, rescale=None, samplewise_center=False, samplewise_std_normalization=False, channel_index=2, epsilon=1e-7
):
"""Normalize an image by rescale, samplewise centering and samplewise centering in order.
Parameters
-----------
x : numpy.array
An image with dimension of... | Normalize an image by rescale, samplewise centering and samplewise centering in order.
Parameters
-----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
rescale : float
Rescaling factor. If None or 0, no rescaling is applied, otherwise we multiply the data... | Below is the the instruction that describes the task:
### Input:
Normalize an image by rescale, samplewise centering and samplewise centering in order.
Parameters
-----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
rescale : float
Rescaling factor. ... |
def _setup_trunk(self, trunk, vlan_id=None):
"""Sets up VLAN trunk and updates the trunk status."""
LOG.info('Binding trunk port: %s.', trunk)
try:
# bind sub_ports to host.
self._trunk_rpc.update_subport_bindings(self._context,
... | Sets up VLAN trunk and updates the trunk status. | Below is the the instruction that describes the task:
### Input:
Sets up VLAN trunk and updates the trunk status.
### Response:
def _setup_trunk(self, trunk, vlan_id=None):
"""Sets up VLAN trunk and updates the trunk status."""
LOG.info('Binding trunk port: %s.', trunk)
try:
# ... |
def clear_input_score_start_range(self):
"""Clears the input score start.
raise: NoAccess - ``Metadata.isRequired()`` or
``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for osid.g... | Clears the input score start.
raise: NoAccess - ``Metadata.isRequired()`` or
``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.* | Below is the the instruction that describes the task:
### Input:
Clears the input score start.
raise: NoAccess - ``Metadata.isRequired()`` or
``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.*
### Response:
def clear_input_score_start... |
def dynamic_presence(self):
"""
Determine presence based on bed heating level and end presence
time reported by the api.
Idea originated from Alex Lee Yuk Cheung SmartThings Code.
"""
# self.heating_stats()
if not self.presence:
if self.heating_leve... | Determine presence based on bed heating level and end presence
time reported by the api.
Idea originated from Alex Lee Yuk Cheung SmartThings Code. | Below is the the instruction that describes the task:
### Input:
Determine presence based on bed heating level and end presence
time reported by the api.
Idea originated from Alex Lee Yuk Cheung SmartThings Code.
### Response:
def dynamic_presence(self):
"""
Determine presence base... |
def print_generated_python(
var_name: str = _PRINT_GENERATED_PY_VAR_NAME, core_ns_name: str = CORE_NS
) -> bool:
"""Return the value of the `*print-generated-python*` dynamic variable."""
ns_sym = sym.Symbol(var_name, ns=core_ns_name)
return (
Maybe(Var.find(ns_sym))
.map(lambda v: v.val... | Return the value of the `*print-generated-python*` dynamic variable. | Below is the the instruction that describes the task:
### Input:
Return the value of the `*print-generated-python*` dynamic variable.
### Response:
def print_generated_python(
var_name: str = _PRINT_GENERATED_PY_VAR_NAME, core_ns_name: str = CORE_NS
) -> bool:
"""Return the value of the `*print-generated-p... |
def _initialize_initial_state_fluents(self):
'''Returns the initial state-fluents instantiated.'''
state_fluents = self.rddl.domain.state_fluents
initializer = self.rddl.instance.init_state
self.initial_state_fluents = self._initialize_pvariables(
state_fluents,
s... | Returns the initial state-fluents instantiated. | Below is the the instruction that describes the task:
### Input:
Returns the initial state-fluents instantiated.
### Response:
def _initialize_initial_state_fluents(self):
'''Returns the initial state-fluents instantiated.'''
state_fluents = self.rddl.domain.state_fluents
initializer = self... |
async def _async_loop(self, urls):
"""Asynchronous internal method used to request multiple URLs
Args:
urls (list): URLs to fetch
Returns:
responses (obj): All URL requests' response coroutines
"""
results = []
async with aiohttp.ClientSession(
... | Asynchronous internal method used to request multiple URLs
Args:
urls (list): URLs to fetch
Returns:
responses (obj): All URL requests' response coroutines | Below is the the instruction that describes the task:
### Input:
Asynchronous internal method used to request multiple URLs
Args:
urls (list): URLs to fetch
Returns:
responses (obj): All URL requests' response coroutines
### Response:
async def _async_loop(self, urls):
... |
def get_option_choices(opt_name, opt_value, default_value, all_choices):
"""
Generate possible choices for the option `opt_name`
limited to `opt_value` value with default value
as `default_value`
"""
choices = []
if isinstance(opt_value, six.string_types):
choices = [opt_value]
... | Generate possible choices for the option `opt_name`
limited to `opt_value` value with default value
as `default_value` | Below is the the instruction that describes the task:
### Input:
Generate possible choices for the option `opt_name`
limited to `opt_value` value with default value
as `default_value`
### Response:
def get_option_choices(opt_name, opt_value, default_value, all_choices):
"""
Generate possible choice... |
def logs(ctx, past, follow, hide_time):
"""Get job logs.
Uses [Caching](/references/polyaxon-cli/#caching)
Examples:
\b
```bash
$ polyaxon job -j 2 logs
```
\b
```bash
$ polyaxon job logs
```
"""
user, project_name, _job = get_job_or_local(ctx.obj.get('project'), ... | Get job logs.
Uses [Caching](/references/polyaxon-cli/#caching)
Examples:
\b
```bash
$ polyaxon job -j 2 logs
```
\b
```bash
$ polyaxon job logs
``` | Below is the the instruction that describes the task:
### Input:
Get job logs.
Uses [Caching](/references/polyaxon-cli/#caching)
Examples:
\b
```bash
$ polyaxon job -j 2 logs
```
\b
```bash
$ polyaxon job logs
```
### Response:
def logs(ctx, past, follow, hide_time):
... |
def split_Text( text, file_name, verbose = True ):
''' Tokenizes the *text* (from *file_name*) into sentences, and if the number of
sentences exceeds *max_sentences*, splits the text into smaller texts.
Returns a list containing the original text (if no splitting was required),
or a list c... | Tokenizes the *text* (from *file_name*) into sentences, and if the number of
sentences exceeds *max_sentences*, splits the text into smaller texts.
Returns a list containing the original text (if no splitting was required),
or a list containing results of the splitting (smaller texts); | Below is the the instruction that describes the task:
### Input:
Tokenizes the *text* (from *file_name*) into sentences, and if the number of
sentences exceeds *max_sentences*, splits the text into smaller texts.
Returns a list containing the original text (if no splitting was required),
o... |
def check_schema(self):
"""Check the schema exists and matches configuration"""
if self.valid_schema:
return
config = self.config
metadata = self.metadata()
if 'current_version' not in metadata:
raise GaugedSchemaError('Gauged schema not found, '
... | Check the schema exists and matches configuration | Below is the the instruction that describes the task:
### Input:
Check the schema exists and matches configuration
### Response:
def check_schema(self):
"""Check the schema exists and matches configuration"""
if self.valid_schema:
return
config = self.config
metadata = s... |
def post_url(self):
"""
Determine which page this post lives on within the topic
and return link to anchor within that page
"""
topic = self.topic
topic_page = topic.post_set.filter(id__lt=self.id).count() / get_paginate_by() + 1
return "{0}page{1}/#post-{2... | Determine which page this post lives on within the topic
and return link to anchor within that page | Below is the the instruction that describes the task:
### Input:
Determine which page this post lives on within the topic
and return link to anchor within that page
### Response:
def post_url(self):
"""
Determine which page this post lives on within the topic
and return link to ... |
def create_app_factory(app_name, config_loader=None,
extension_entry_points=None, extensions=None,
blueprint_entry_points=None, blueprints=None,
converter_entry_points=None, converters=None,
wsgi_factory=None, **app_kwargs):
... | Create a Flask application factory.
The application factory will load Flask extensions and blueprints specified
using both entry points and directly in the arguments. Loading order of
entry points are not guaranteed and can happen in any order.
:param app_name: Flask application name.
:param confi... | Below is the the instruction that describes the task:
### Input:
Create a Flask application factory.
The application factory will load Flask extensions and blueprints specified
using both entry points and directly in the arguments. Loading order of
entry points are not guaranteed and can happen in any ... |
def counter_multi(self, kvs, initial=None, delta=1, ttl=0):
"""Perform counter operations on multiple items
:param kvs: Keys to operate on. See below for more options
:param initial: Initial value to use for all keys.
:param delta: Delta value for all keys.
:param ttl: Expiratio... | Perform counter operations on multiple items
:param kvs: Keys to operate on. See below for more options
:param initial: Initial value to use for all keys.
:param delta: Delta value for all keys.
:param ttl: Expiration value to use for all keys
:return: A :class:`~.MultiResult` ... | Below is the the instruction that describes the task:
### Input:
Perform counter operations on multiple items
:param kvs: Keys to operate on. See below for more options
:param initial: Initial value to use for all keys.
:param delta: Delta value for all keys.
:param ttl: Expiration ... |
def from_file(cls, path=None):
"""Read a config file and instantiate the RCParser.
Create new :class:`configparser.ConfigParser` for the given **path**
and instantiate the :class:`RCParser` with the ConfigParser as
:attr:`config` attribute.
If the **path** doesn't exist, raise ... | Read a config file and instantiate the RCParser.
Create new :class:`configparser.ConfigParser` for the given **path**
and instantiate the :class:`RCParser` with the ConfigParser as
:attr:`config` attribute.
If the **path** doesn't exist, raise :exc:`ConfigFileError`.
Otherwise ... | Below is the the instruction that describes the task:
### Input:
Read a config file and instantiate the RCParser.
Create new :class:`configparser.ConfigParser` for the given **path**
and instantiate the :class:`RCParser` with the ConfigParser as
:attr:`config` attribute.
If the **p... |
def _get_structure(self):
"""
Get the structure we are going to work with.
:return: The structure we have to work with.
:rtype: dict
"""
# We initiate an empty variable which is going to save the location of
# file we are going to download.
structure_fil... | Get the structure we are going to work with.
:return: The structure we have to work with.
:rtype: dict | Below is the the instruction that describes the task:
### Input:
Get the structure we are going to work with.
:return: The structure we have to work with.
:rtype: dict
### Response:
def _get_structure(self):
"""
Get the structure we are going to work with.
:return: The str... |
def log_error(self, callback, error=None):
""" Log the error that occurred when running the given callback. """
print("Uncaught error during callback: {}".format(callback))
print("Error: {}".format(error)) | Log the error that occurred when running the given callback. | Below is the the instruction that describes the task:
### Input:
Log the error that occurred when running the given callback.
### Response:
def log_error(self, callback, error=None):
""" Log the error that occurred when running the given callback. """
print("Uncaught error during callback: {}".form... |
def get(self, *args, **kwargs):
"""
An interface for get requests that handles errors more gracefully to
prevent data loss
"""
try:
req_func = self.session.get if self.session else requests.get
req = req_func(*args, **kwargs)
req.ra... | An interface for get requests that handles errors more gracefully to
prevent data loss | Below is the the instruction that describes the task:
### Input:
An interface for get requests that handles errors more gracefully to
prevent data loss
### Response:
def get(self, *args, **kwargs):
"""
An interface for get requests that handles errors more gracefully to
preven... |
def get_objectives_by_ids(self, objective_ids):
"""Gets an ``ObjectiveList`` corresponding to the given ``IdList``.
In plenary mode, the returned list contains all of the
objectives specified in the ``Id`` list, in the order of the
list, including duplicates, or an error results if an `... | Gets an ``ObjectiveList`` corresponding to the given ``IdList``.
In plenary mode, the returned list contains all of the
objectives specified in the ``Id`` list, in the order of the
list, including duplicates, or an error results if an ``Id`` in
the supplied list is not found or inaccess... | Below is the the instruction that describes the task:
### Input:
Gets an ``ObjectiveList`` corresponding to the given ``IdList``.
In plenary mode, the returned list contains all of the
objectives specified in the ``Id`` list, in the order of the
list, including duplicates, or an error resul... |
def add_ti_txt(self, lines, overwrite=False):
"""Add given TI-TXT string `lines`. Set `overwrite` to ``True`` to
allow already added data to be overwritten.
"""
address = None
eof_found = False
for line in StringIO(lines):
# Abort if data is found after end... | Add given TI-TXT string `lines`. Set `overwrite` to ``True`` to
allow already added data to be overwritten. | Below is the the instruction that describes the task:
### Input:
Add given TI-TXT string `lines`. Set `overwrite` to ``True`` to
allow already added data to be overwritten.
### Response:
def add_ti_txt(self, lines, overwrite=False):
"""Add given TI-TXT string `lines`. Set `overwrite` to ``True`` to... |
def truncate_label(cls, label):
"""
In the case that a label exceeds the max length supported by the engine,
this method is used to construct a deterministic and unique label based on
an md5 hash.
"""
label = hashlib.md5(label.encode('utf-8')).hexdigest()
# trunca... | In the case that a label exceeds the max length supported by the engine,
this method is used to construct a deterministic and unique label based on
an md5 hash. | Below is the the instruction that describes the task:
### Input:
In the case that a label exceeds the max length supported by the engine,
this method is used to construct a deterministic and unique label based on
an md5 hash.
### Response:
def truncate_label(cls, label):
"""
In the ... |
def save_object(self, obj):
"""
Save object to disk as JSON.
Generally shouldn't be called directly.
"""
obj.pre_save(self.jurisdiction.jurisdiction_id)
filename = '{0}_{1}.json'.format(obj._type, obj._id).replace('/', '-')
self.info('save %s %s as %s',... | Save object to disk as JSON.
Generally shouldn't be called directly. | Below is the the instruction that describes the task:
### Input:
Save object to disk as JSON.
Generally shouldn't be called directly.
### Response:
def save_object(self, obj):
"""
Save object to disk as JSON.
Generally shouldn't be called directly.
"""
... |
def notify_all(self):
"""wake all waiting greenlets
:raises:
`RuntimeError` if the underlying lock hasn't been
:meth:`acquired <Lock.acquire>`
"""
if not self._is_owned():
raise RuntimeError("cannot wait on un-acquired lock")
scheduler.state.a... | wake all waiting greenlets
:raises:
`RuntimeError` if the underlying lock hasn't been
:meth:`acquired <Lock.acquire>` | Below is the the instruction that describes the task:
### Input:
wake all waiting greenlets
:raises:
`RuntimeError` if the underlying lock hasn't been
:meth:`acquired <Lock.acquire>`
### Response:
def notify_all(self):
"""wake all waiting greenlets
:raises:
... |
def delete(self, ip_dest, next_hop, **kwargs):
"""Delete a static route
Args:
ip_dest (string): The ip address of the destination in the
form of A.B.C.D/E
next_hop (string): The next hop interface or ip address
**kwargs['next_hop_ip'] (string): The ne... | Delete a static route
Args:
ip_dest (string): The ip address of the destination in the
form of A.B.C.D/E
next_hop (string): The next hop interface or ip address
**kwargs['next_hop_ip'] (string): The next hop address on
destination interface
... | Below is the the instruction that describes the task:
### Input:
Delete a static route
Args:
ip_dest (string): The ip address of the destination in the
form of A.B.C.D/E
next_hop (string): The next hop interface or ip address
**kwargs['next_hop_ip'] (stri... |
def new_post(GITDIRECTORY=CONFIG['output_to'], kind=KINDS['writing']): # pragma: no coverage # noqa
"""
This function should create a template for a new post with a title
read from the user input.
Most other fields should be defaults.
TODO: update this function
"""
title = input("Give the ... | This function should create a template for a new post with a title
read from the user input.
Most other fields should be defaults.
TODO: update this function | Below is the the instruction that describes the task:
### Input:
This function should create a template for a new post with a title
read from the user input.
Most other fields should be defaults.
TODO: update this function
### Response:
def new_post(GITDIRECTORY=CONFIG['output_to'], kind=KINDS['writing... |
def mapReduce(mapFunc, reductionFunc, *iterables, **kwargs):
"""Exectues the :meth:`~scoop.futures.map` function and then applies a
reduction function to its result. The reduction function will cumulatively
merge the results of the map function in order to get a single final value.
This call is blocking... | Exectues the :meth:`~scoop.futures.map` function and then applies a
reduction function to its result. The reduction function will cumulatively
merge the results of the map function in order to get a single final value.
This call is blocking.
:param mapFunc: Any picklable callable object (function or cl... | Below is the the instruction that describes the task:
### Input:
Exectues the :meth:`~scoop.futures.map` function and then applies a
reduction function to its result. The reduction function will cumulatively
merge the results of the map function in order to get a single final value.
This call is blockin... |
def _create_sequences(self):
'''Get all of the Sequences - Rosetta, ATOM, SEQRES, FASTA, UniParc.'''
# Create the Rosetta sequences and the maps from the Rosetta sequences to the ATOM sequences
try:
self.pdb.construct_pdb_to_rosetta_residue_map(self.rosetta_scripts_path, rosetta_dat... | Get all of the Sequences - Rosetta, ATOM, SEQRES, FASTA, UniParc. | Below is the the instruction that describes the task:
### Input:
Get all of the Sequences - Rosetta, ATOM, SEQRES, FASTA, UniParc.
### Response:
def _create_sequences(self):
'''Get all of the Sequences - Rosetta, ATOM, SEQRES, FASTA, UniParc.'''
# Create the Rosetta sequences and the maps from the... |
def _skip_spaces(string, idx):
# type: (str, int) -> int
"""
Retrieves the next non-space character after idx index in the given string
:param string: The string to look into
:param idx: The base search index
:return: The next non-space character index, -1 if not found
"""
i = idx
f... | Retrieves the next non-space character after idx index in the given string
:param string: The string to look into
:param idx: The base search index
:return: The next non-space character index, -1 if not found | Below is the the instruction that describes the task:
### Input:
Retrieves the next non-space character after idx index in the given string
:param string: The string to look into
:param idx: The base search index
:return: The next non-space character index, -1 if not found
### Response:
def _skip_spac... |
def authorize_password(self, client_id, username, password):
"""Authorize to platform as regular user
You must provide a valid client_id (same as web application),
your password and your username. Username and password is not stored in
client but refresh token is stored. The only valid ... | Authorize to platform as regular user
You must provide a valid client_id (same as web application),
your password and your username. Username and password is not stored in
client but refresh token is stored. The only valid scope for this
authorization is "regular_user".
:param ... | Below is the the instruction that describes the task:
### Input:
Authorize to platform as regular user
You must provide a valid client_id (same as web application),
your password and your username. Username and password is not stored in
client but refresh token is stored. The only valid sco... |
def create_topic(self, project, topic, fail_if_exists=False):
"""Creates a Pub/Sub topic, if it does not already exist.
:param project: the GCP project ID in which to create
the topic
:type project: str
:param topic: the Pub/Sub topic name to create; do not
inclu... | Creates a Pub/Sub topic, if it does not already exist.
:param project: the GCP project ID in which to create
the topic
:type project: str
:param topic: the Pub/Sub topic name to create; do not
include the ``projects/{project}/topics/`` prefix.
:type topic: str
... | Below is the the instruction that describes the task:
### Input:
Creates a Pub/Sub topic, if it does not already exist.
:param project: the GCP project ID in which to create
the topic
:type project: str
:param topic: the Pub/Sub topic name to create; do not
include t... |
def set_table_acl(self, table_name, signed_identifiers=None, timeout=None):
'''
Sets stored access policies for the table that may be used with Shared
Access Signatures.
When you set permissions for a table, the existing permissions are replaced.
To update the table’s... | Sets stored access policies for the table that may be used with Shared
Access Signatures.
When you set permissions for a table, the existing permissions are replaced.
To update the table’s permissions, call :func:`~get_table_acl` to fetch
all access policies associated with ... | Below is the the instruction that describes the task:
### Input:
Sets stored access policies for the table that may be used with Shared
Access Signatures.
When you set permissions for a table, the existing permissions are replaced.
To update the table’s permissions, call :func:`~... |
def web_address(self):
"""
Return the url of the web server or None if not running
"""
port = self._current_web_port()
address = self.address or '127.0.0.1'
if port is None:
return None
return 'http://{0}:{1}/'.format(
address if address an... | Return the url of the web server or None if not running | Below is the the instruction that describes the task:
### Input:
Return the url of the web server or None if not running
### Response:
def web_address(self):
"""
Return the url of the web server or None if not running
"""
port = self._current_web_port()
address = self.addres... |
def _from_specs(self, dims, spacing=(1.0,1.0,1.0), origin=(0.0, 0.0, 0.0)):
"""
Create VTK image data directly from numpy arrays. A uniform grid is
defined by the node spacings for each axis (uniform along each
individual axis) and the number of nodes on each axis. These are
rela... | Create VTK image data directly from numpy arrays. A uniform grid is
defined by the node spacings for each axis (uniform along each
individual axis) and the number of nodes on each axis. These are
relative to a specified origin (default is ``(0.0, 0.0, 0.0)``).
Parameters
-------... | Below is the the instruction that describes the task:
### Input:
Create VTK image data directly from numpy arrays. A uniform grid is
defined by the node spacings for each axis (uniform along each
individual axis) and the number of nodes on each axis. These are
relative to a specified origin ... |
def lnlike(self, p):
"""Log-likelihood of model at given parameters
:param p:
mass, log10(age), feh, [distance, A_V (extinction)].
Final two should only be provided if ``self.fit_for_distance``
is ``True``; that is, apparent magnitudes are provided.
... | Log-likelihood of model at given parameters
:param p:
mass, log10(age), feh, [distance, A_V (extinction)].
Final two should only be provided if ``self.fit_for_distance``
is ``True``; that is, apparent magnitudes are provided.
:return:
... | Below is the the instruction that describes the task:
### Input:
Log-likelihood of model at given parameters
:param p:
mass, log10(age), feh, [distance, A_V (extinction)].
Final two should only be provided if ``self.fit_for_distance``
is ``True``; that is, appa... |
def _instructions(self, time: int = 0) -> Iterable[Tuple[int, 'Instruction']]:
"""Iterable for flattening Schedule tree.
Args:
time: Shifted time due to parent
Yields:
Tuple[int, ScheduleComponent]: Tuple containing time `ScheduleComponent` starts
at and... | Iterable for flattening Schedule tree.
Args:
time: Shifted time due to parent
Yields:
Tuple[int, ScheduleComponent]: Tuple containing time `ScheduleComponent` starts
at and the flattened `ScheduleComponent`. | Below is the the instruction that describes the task:
### Input:
Iterable for flattening Schedule tree.
Args:
time: Shifted time due to parent
Yields:
Tuple[int, ScheduleComponent]: Tuple containing time `ScheduleComponent` starts
at and the flattened `Sched... |
def pdf_link(self, link_f, y, Y_metadata=None):
"""
Likelihood function given link(f)
.. math::
\\ln p(y_{i}|\\lambda(f_{i})) = -\\frac{N \\ln 2\\pi}{2} - \\frac{\\ln |K|}{2} - \\frac{(y_{i} - \\lambda(f_{i}))^{T}\\sigma^{-2}(y_{i} - \\lambda(f_{i}))}{2}
:param link_f: late... | Likelihood function given link(f)
.. math::
\\ln p(y_{i}|\\lambda(f_{i})) = -\\frac{N \\ln 2\\pi}{2} - \\frac{\\ln |K|}{2} - \\frac{(y_{i} - \\lambda(f_{i}))^{T}\\sigma^{-2}(y_{i} - \\lambda(f_{i}))}{2}
:param link_f: latent variables link(f)
:type link_f: Nx1 array
:param ... | Below is the the instruction that describes the task:
### Input:
Likelihood function given link(f)
.. math::
\\ln p(y_{i}|\\lambda(f_{i})) = -\\frac{N \\ln 2\\pi}{2} - \\frac{\\ln |K|}{2} - \\frac{(y_{i} - \\lambda(f_{i}))^{T}\\sigma^{-2}(y_{i} - \\lambda(f_{i}))}{2}
:param link_f: lat... |
def set_status(self, status):
"""
Updates the status text
Args:
status (int): The offline/starting/online status of Modis
0: offline, 1: starting, 2: online
"""
text = ""
colour = "#FFFFFF"
if status == 0:
text = "OFFLINE"... | Updates the status text
Args:
status (int): The offline/starting/online status of Modis
0: offline, 1: starting, 2: online | Below is the the instruction that describes the task:
### Input:
Updates the status text
Args:
status (int): The offline/starting/online status of Modis
0: offline, 1: starting, 2: online
### Response:
def set_status(self, status):
"""
Updates the status text
... |
def resample(source_area, data, destination_area,
resampler=None, **kwargs):
"""Do the resampling."""
if 'resampler_class' in kwargs:
import warnings
warnings.warn("'resampler_class' is deprecated, use 'resampler'",
DeprecationWarning)
resampler = kwarg... | Do the resampling. | Below is the the instruction that describes the task:
### Input:
Do the resampling.
### Response:
def resample(source_area, data, destination_area,
resampler=None, **kwargs):
"""Do the resampling."""
if 'resampler_class' in kwargs:
import warnings
warnings.warn("'resampler_clas... |
def main(arguments=None):
"""
*The main function used when ``cl_utils.py`` is run as a single script from the cl, or when installed as a cl command*
"""
# setup the command-line util settings
su = tools(
arguments=arguments,
docString=__doc__,
logLevel="WARNING",
opti... | *The main function used when ``cl_utils.py`` is run as a single script from the cl, or when installed as a cl command* | Below is the the instruction that describes the task:
### Input:
*The main function used when ``cl_utils.py`` is run as a single script from the cl, or when installed as a cl command*
### Response:
def main(arguments=None):
"""
*The main function used when ``cl_utils.py`` is run as a single script from the... |
def find_elements_by_class_name(self, name):
"""
Finds elements by class name.
:Args:
- name: The class name of the elements to find.
:Returns:
- list of WebElement - a list with elements if any was found. An
empty list if not
:Usage:
... | Finds elements by class name.
:Args:
- name: The class name of the elements to find.
:Returns:
- list of WebElement - a list with elements if any was found. An
empty list if not
:Usage:
::
elements = driver.find_elements_by_class_name... | Below is the the instruction that describes the task:
### Input:
Finds elements by class name.
:Args:
- name: The class name of the elements to find.
:Returns:
- list of WebElement - a list with elements if any was found. An
empty list if not
:Usage:
... |
def add_reaction(self, reaction_id):
"""Add reaction to model"""
if reaction_id in self._reaction_set:
return
reaction = self._database.get_reaction(reaction_id)
self._reaction_set.add(reaction_id)
for compound, _ in reaction.compounds:
self._compound_se... | Add reaction to model | Below is the the instruction that describes the task:
### Input:
Add reaction to model
### Response:
def add_reaction(self, reaction_id):
"""Add reaction to model"""
if reaction_id in self._reaction_set:
return
reaction = self._database.get_reaction(reaction_id)
self._... |
def from_json(cls, key):
"""Creates a RFC 7517 JWK from the standard JSON format.
:param key: The RFC 7517 representation of a JWK.
"""
obj = cls()
try:
jkey = json_decode(key)
except Exception as e: # pylint: disable=broad-except
raise InvalidJW... | Creates a RFC 7517 JWK from the standard JSON format.
:param key: The RFC 7517 representation of a JWK. | Below is the the instruction that describes the task:
### Input:
Creates a RFC 7517 JWK from the standard JSON format.
:param key: The RFC 7517 representation of a JWK.
### Response:
def from_json(cls, key):
"""Creates a RFC 7517 JWK from the standard JSON format.
:param key: The RFC 7517... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.