code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def excess_drawdown_idx(self, benchmark, method="caer"):
"""Excess drawdown index; TSeries of excess drawdowns.
There are several ways of computing this metric. For highly
volatile returns, the `method` specified will have a
non-negligible effect on the result.
Parameters
... | Excess drawdown index; TSeries of excess drawdowns.
There are several ways of computing this metric. For highly
volatile returns, the `method` specified will have a
non-negligible effect on the result.
Parameters
----------
benchmark : {pd.Series, TSeries, 1d np.ndarra... | Below is the the instruction that describes the task:
### Input:
Excess drawdown index; TSeries of excess drawdowns.
There are several ways of computing this metric. For highly
volatile returns, the `method` specified will have a
non-negligible effect on the result.
Parameters
... |
def get_actors(self):
"""
Returns a list of Actor objects for querying SmartHome devices.
This is currently the only working method for getting temperature data.
"""
devices = self.homeautoswitch("getdevicelistinfos")
xml = ET.fromstring(devices)
actors = []
... | Returns a list of Actor objects for querying SmartHome devices.
This is currently the only working method for getting temperature data. | Below is the the instruction that describes the task:
### Input:
Returns a list of Actor objects for querying SmartHome devices.
This is currently the only working method for getting temperature data.
### Response:
def get_actors(self):
"""
Returns a list of Actor objects for querying Smar... |
def load_info(self):
"""
Parses the JSON object stored at GPJob.info and assigns its metadata to
properties of this GPJob object.
Primarily intended to be called from GPJob.get_info().
"""
self.task_name = self.info['taskName']
self.task_lsid = self.info['taskLsi... | Parses the JSON object stored at GPJob.info and assigns its metadata to
properties of this GPJob object.
Primarily intended to be called from GPJob.get_info(). | Below is the the instruction that describes the task:
### Input:
Parses the JSON object stored at GPJob.info and assigns its metadata to
properties of this GPJob object.
Primarily intended to be called from GPJob.get_info().
### Response:
def load_info(self):
"""
Parses the JSON ob... |
def interrupt(self, interrupt):
"""Perform the shutdown of this server and save the exception."""
self._interrupt = True
self.stop()
self._interrupt = interrupt | Perform the shutdown of this server and save the exception. | Below is the the instruction that describes the task:
### Input:
Perform the shutdown of this server and save the exception.
### Response:
def interrupt(self, interrupt):
"""Perform the shutdown of this server and save the exception."""
self._interrupt = True
self.stop()
self._inter... |
def move_edge_target(self, edge_id, node_a):
"""Moves an edge so that it targets node_a."""
# Grab the edge
edge = self.get_edge(edge_id)
# Remove the edge from the original "target node"
original_target_node_id = edge['vertices'][1]
original_target_node = self.get_node(... | Moves an edge so that it targets node_a. | Below is the the instruction that describes the task:
### Input:
Moves an edge so that it targets node_a.
### Response:
def move_edge_target(self, edge_id, node_a):
"""Moves an edge so that it targets node_a."""
# Grab the edge
edge = self.get_edge(edge_id)
# Remove the edge from t... |
def render_templates(self, templates, filepath=None):
"""Render a collection of :class:`jinja2.Template` objects.
:param templates:
A collection of Templates to render.
:param filepath:
Optional. A file or file-like object to dump the complete template
strea... | Render a collection of :class:`jinja2.Template` objects.
:param templates:
A collection of Templates to render.
:param filepath:
Optional. A file or file-like object to dump the complete template
stream into. Defaults to to ``os.path.join(self.outpath,
t... | Below is the the instruction that describes the task:
### Input:
Render a collection of :class:`jinja2.Template` objects.
:param templates:
A collection of Templates to render.
:param filepath:
Optional. A file or file-like object to dump the complete template
s... |
def ext(external, pillar=None):
'''
.. versionchanged:: 2016.3.6,2016.11.3,2017.7.0
The supported ext_pillar types are now tunable using the
:conf_master:`on_demand_ext_pillar` config option. Earlier releases
used a hard-coded default.
Generate the pillar and apply an explicit exter... | .. versionchanged:: 2016.3.6,2016.11.3,2017.7.0
The supported ext_pillar types are now tunable using the
:conf_master:`on_demand_ext_pillar` config option. Earlier releases
used a hard-coded default.
Generate the pillar and apply an explicit external pillar
external
A single e... | Below is the the instruction that describes the task:
### Input:
.. versionchanged:: 2016.3.6,2016.11.3,2017.7.0
The supported ext_pillar types are now tunable using the
:conf_master:`on_demand_ext_pillar` config option. Earlier releases
used a hard-coded default.
Generate the pillar an... |
def operate(self, vala, valb, oper):
"""Perform operation
args:
vala (mixed): 1st value
valb (mixed): 2nd value
oper (str): operation
returns:
mixed
"""
operation = {
'+': operator.add,
'-': operator.sub,
... | Perform operation
args:
vala (mixed): 1st value
valb (mixed): 2nd value
oper (str): operation
returns:
mixed | Below is the the instruction that describes the task:
### Input:
Perform operation
args:
vala (mixed): 1st value
valb (mixed): 2nd value
oper (str): operation
returns:
mixed
### Response:
def operate(self, vala, valb, oper):
"""Perform operati... |
def _twoByteStringToNum(bytestring, numberOfDecimals=0, signed=False):
"""Convert a two-byte string to a numerical value, possibly scaling it.
Args:
* bytestring (str): A string of length 2.
* numberOfDecimals (int): The number of decimals. Defaults to 0.
* signed (bol): Whether large p... | Convert a two-byte string to a numerical value, possibly scaling it.
Args:
* bytestring (str): A string of length 2.
* numberOfDecimals (int): The number of decimals. Defaults to 0.
* signed (bol): Whether large positive values should be interpreted as negative values.
Returns:
... | Below is the the instruction that describes the task:
### Input:
Convert a two-byte string to a numerical value, possibly scaling it.
Args:
* bytestring (str): A string of length 2.
* numberOfDecimals (int): The number of decimals. Defaults to 0.
* signed (bol): Whether large positive v... |
def generate_run_info():
"""
获取当前运行状态
"""
uptime = datetime.datetime.now() - datetime.datetime.fromtimestamp(glb.run_info.create_time())
memory_usage = glb.run_info.memory_info().rss
msg = '[当前时间] {now:%H:%M:%S}\n[运行时间] {uptime}\n[内存占用] {memory}\n[发送消息] {messages}'.format(
now=datetime.d... | 获取当前运行状态 | Below is the the instruction that describes the task:
### Input:
获取当前运行状态
### Response:
def generate_run_info():
"""
获取当前运行状态
"""
uptime = datetime.datetime.now() - datetime.datetime.fromtimestamp(glb.run_info.create_time())
memory_usage = glb.run_info.memory_info().rss
msg = '[当前时间] {now:%... |
def f_get(self, *args):
"""Returns items handled by the result.
If only a single name is given, a single data item is returned. If several names are
given, a list is returned. For integer inputs the result returns `resultname_X`.
If the result contains only a single entry you can ca... | Returns items handled by the result.
If only a single name is given, a single data item is returned. If several names are
given, a list is returned. For integer inputs the result returns `resultname_X`.
If the result contains only a single entry you can call `f_get()` without arguments.
... | Below is the the instruction that describes the task:
### Input:
Returns items handled by the result.
If only a single name is given, a single data item is returned. If several names are
given, a list is returned. For integer inputs the result returns `resultname_X`.
If the result conta... |
def show_fabric_trunk_info_output_show_trunk_list_trunk_list_groups_trunk_list_group(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_fabric_trunk_info = ET.Element("show_fabric_trunk_info")
config = show_fabric_trunk_info
output = ET.SubElem... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def show_fabric_trunk_info_output_show_trunk_list_trunk_list_groups_trunk_list_group(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_fabric_trunk_info = ... |
def ReduceOpacity(im, opacity):
"""Reduces Opacity.
Returns an image with reduced opacity.
Taken from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/362879
"""
assert opacity >= 0 and opacity <= 1
if isalpha(im):
im = im.copy()
else:
im = im.convert('RGBA')
alp... | Reduces Opacity.
Returns an image with reduced opacity.
Taken from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/362879 | Below is the the instruction that describes the task:
### Input:
Reduces Opacity.
Returns an image with reduced opacity.
Taken from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/362879
### Response:
def ReduceOpacity(im, opacity):
"""Reduces Opacity.
Returns an image with reduced opacit... |
def first_parent(tag, nodename):
"""
Given a beautiful soup tag, look at its parents and return the first
tag name that matches nodename or the list nodename
"""
if nodename is not None and type(nodename) == str:
nodename = [nodename]
return first(list(filter(lambda tag: tag.name in node... | Given a beautiful soup tag, look at its parents and return the first
tag name that matches nodename or the list nodename | Below is the the instruction that describes the task:
### Input:
Given a beautiful soup tag, look at its parents and return the first
tag name that matches nodename or the list nodename
### Response:
def first_parent(tag, nodename):
"""
Given a beautiful soup tag, look at its parents and return the fir... |
def database_exists(url):
"""Check if a database exists.
:param url: A SQLAlchemy engine URL.
Performs backend-specific testing to quickly determine if a database
exists on the server. ::
database_exists('postgres://postgres@localhost/name') #=> False
create_database('postgres://post... | Check if a database exists.
:param url: A SQLAlchemy engine URL.
Performs backend-specific testing to quickly determine if a database
exists on the server. ::
database_exists('postgres://postgres@localhost/name') #=> False
create_database('postgres://postgres@localhost/name')
dat... | Below is the the instruction that describes the task:
### Input:
Check if a database exists.
:param url: A SQLAlchemy engine URL.
Performs backend-specific testing to quickly determine if a database
exists on the server. ::
database_exists('postgres://postgres@localhost/name') #=> False
... |
def _clear_timeouts(self, cache_timeout):
"""
Clear the cache of timed out results.
"""
for key in list(self.timeouts):
if timer() - self.timeouts[key] > cache_timeout:
del self.timeouts[key]
del self.cache[key] | Clear the cache of timed out results. | Below is the the instruction that describes the task:
### Input:
Clear the cache of timed out results.
### Response:
def _clear_timeouts(self, cache_timeout):
"""
Clear the cache of timed out results.
"""
for key in list(self.timeouts):
if timer() - self.timeouts[key] >... |
def _filter_exact(self, term, field_name, field_type, is_not):
"""
Returns a query that matches exactly the un-stemmed term
with positional order.
Assumes term is not a list.
"""
if field_type == 'text' and field_name not in (DJANGO_CT,):
term = '^ %s $' % te... | Returns a query that matches exactly the un-stemmed term
with positional order.
Assumes term is not a list. | Below is the the instruction that describes the task:
### Input:
Returns a query that matches exactly the un-stemmed term
with positional order.
Assumes term is not a list.
### Response:
def _filter_exact(self, term, field_name, field_type, is_not):
"""
Returns a query that matches... |
def interact_gridsearch_result_images(show_result_func, cfgdict_list,
cfglbl_list, cfgresult_list,
score_list=None, fnum=None, figtitle='',
unpack=False, max_plots=25, verbose=True,
... | helper function for visualizing results of gridsearch | Below is the the instruction that describes the task:
### Input:
helper function for visualizing results of gridsearch
### Response:
def interact_gridsearch_result_images(show_result_func, cfgdict_list,
cfglbl_list, cfgresult_list,
score_l... |
def _do_title_string(self,title_items,cycle):
'''
Create title string
Private method that creates a title string for a cycle plot
out of a list of title_items that are cycle attributes and can
be obtained with self.get
Parameters
----------
title_items :... | Create title string
Private method that creates a title string for a cycle plot
out of a list of title_items that are cycle attributes and can
be obtained with self.get
Parameters
----------
title_items : list
A list of cycle attributes.
cycle : scal... | Below is the the instruction that describes the task:
### Input:
Create title string
Private method that creates a title string for a cycle plot
out of a list of title_items that are cycle attributes and can
be obtained with self.get
Parameters
----------
title_item... |
def saturation(self, color, *args):
""" Return the saturation value of a color
args:
color (str): color
raises:
ValueError
returns:
float
"""
if color:
h, l, s = self._hextohls(color)
return s * 100.0
rai... | Return the saturation value of a color
args:
color (str): color
raises:
ValueError
returns:
float | Below is the the instruction that describes the task:
### Input:
Return the saturation value of a color
args:
color (str): color
raises:
ValueError
returns:
float
### Response:
def saturation(self, color, *args):
""" Return the saturation value of... |
def normalize_datum(self, datum):
"""
Convert `datum` into something that umsgpack likes.
:param datum: something that we want to process with umsgpack
:return: a packable version of `datum`
:raises TypeError: if `datum` cannot be packed
This message is called by :meth:... | Convert `datum` into something that umsgpack likes.
:param datum: something that we want to process with umsgpack
:return: a packable version of `datum`
:raises TypeError: if `datum` cannot be packed
This message is called by :meth:`.packb` to recursively normalize
an input val... | Below is the the instruction that describes the task:
### Input:
Convert `datum` into something that umsgpack likes.
:param datum: something that we want to process with umsgpack
:return: a packable version of `datum`
:raises TypeError: if `datum` cannot be packed
This message is c... |
def interpolate(self, target, extent):
""" Move this vector towards the given towards the target by the given
extent. The extent should be between 0 and 1. """
target = cast_anything_to_vector(target)
self += extent * (target - self) | Move this vector towards the given towards the target by the given
extent. The extent should be between 0 and 1. | Below is the the instruction that describes the task:
### Input:
Move this vector towards the given towards the target by the given
extent. The extent should be between 0 and 1.
### Response:
def interpolate(self, target, extent):
""" Move this vector towards the given towards the target by the g... |
def nice(self):
"""Get or set process niceness (priority).
Deprecated, use get_nice() instead.
"""
msg = "this property is deprecated; use Process.get_nice() method instead"
warnings.warn(msg, category=DeprecationWarning, stacklevel=2)
return self.get_nice() | Get or set process niceness (priority).
Deprecated, use get_nice() instead. | Below is the the instruction that describes the task:
### Input:
Get or set process niceness (priority).
Deprecated, use get_nice() instead.
### Response:
def nice(self):
"""Get or set process niceness (priority).
Deprecated, use get_nice() instead.
"""
msg = "this property ... |
def read(self, id, table='reaction'):
""" Return an entire row of a table
Parameters
---------
id: int
row integer
table: str
'reaction', 'publication', 'publication_system', 'reaction_system'
"""
con = self.connection or self._connect()
... | Return an entire row of a table
Parameters
---------
id: int
row integer
table: str
'reaction', 'publication', 'publication_system', 'reaction_system' | Below is the the instruction that describes the task:
### Input:
Return an entire row of a table
Parameters
---------
id: int
row integer
table: str
'reaction', 'publication', 'publication_system', 'reaction_system'
### Response:
def read(self, id, table='re... |
def validate_service(self, request, uid):
"""Validates the specs values from request for the service uid. Returns
a non-translated message if the validation failed."""
result = get_record_value(request, uid, 'result')
if not result:
# No result set for this service, dismiss
... | Validates the specs values from request for the service uid. Returns
a non-translated message if the validation failed. | Below is the the instruction that describes the task:
### Input:
Validates the specs values from request for the service uid. Returns
a non-translated message if the validation failed.
### Response:
def validate_service(self, request, uid):
"""Validates the specs values from request for the service... |
def cleanlines(self):
"""Cleaned code lines.
Implemented cleanups:
* eventually remove method version
* remove docstrings
* remove comments
* remove empty lines
* remove line brackes within brackets
* replace `modelutils` with nothing
... | Cleaned code lines.
Implemented cleanups:
* eventually remove method version
* remove docstrings
* remove comments
* remove empty lines
* remove line brackes within brackets
* replace `modelutils` with nothing
* remove complete lines contain... | Below is the the instruction that describes the task:
### Input:
Cleaned code lines.
Implemented cleanups:
* eventually remove method version
* remove docstrings
* remove comments
* remove empty lines
* remove line brackes within brackets
* replac... |
def _is_level_reference(self, key, axis=0):
"""
Test whether a key is a level reference for a given axis.
To be considered a level reference, `key` must be a string that:
- (axis=0): Matches the name of an index level and does NOT match
a column label.
- (axis=1)... | Test whether a key is a level reference for a given axis.
To be considered a level reference, `key` must be a string that:
- (axis=0): Matches the name of an index level and does NOT match
a column label.
- (axis=1): Matches the name of a column level and does NOT match
... | Below is the the instruction that describes the task:
### Input:
Test whether a key is a level reference for a given axis.
To be considered a level reference, `key` must be a string that:
- (axis=0): Matches the name of an index level and does NOT match
a column label.
- (ax... |
def make_pipeline(context):
"""
Create our pipeline.
"""
# Filter for primary share equities. IsPrimaryShare is a built-in filter.
primary_share = IsPrimaryShare()
# Equities listed as common stock (as opposed to, say, preferred stock).
# 'ST00000001' indicates common stock.
common_sto... | Create our pipeline. | Below is the the instruction that describes the task:
### Input:
Create our pipeline.
### Response:
def make_pipeline(context):
"""
Create our pipeline.
"""
# Filter for primary share equities. IsPrimaryShare is a built-in filter.
primary_share = IsPrimaryShare()
# Equities listed as comm... |
def tensors_equal(tensor1: torch.Tensor, tensor2: torch.Tensor, tolerance: float = 1e-12) -> bool:
"""
A check for tensor equality (by value). We make sure that the tensors have the same shape,
then check all of the entries in the tensor for equality. We additionally allow the input
tensors to be list... | A check for tensor equality (by value). We make sure that the tensors have the same shape,
then check all of the entries in the tensor for equality. We additionally allow the input
tensors to be lists or dictionaries, where we then do the above check on every position in the
list / item in the dictionary.... | Below is the the instruction that describes the task:
### Input:
A check for tensor equality (by value). We make sure that the tensors have the same shape,
then check all of the entries in the tensor for equality. We additionally allow the input
tensors to be lists or dictionaries, where we then do the ab... |
def QueryItems(self, database_or_Container_link, query, options=None, partition_key=None):
"""Queries documents in a collection.
:param str database_or_Container_link:
The link to the database when using partitioning, otherwise link to the document collection.
:param (str or dict) q... | Queries documents in a collection.
:param str database_or_Container_link:
The link to the database when using partitioning, otherwise link to the document collection.
:param (str or dict) query:
:param dict options:
The request options for the request.
:param str... | Below is the the instruction that describes the task:
### Input:
Queries documents in a collection.
:param str database_or_Container_link:
The link to the database when using partitioning, otherwise link to the document collection.
:param (str or dict) query:
:param dict options... |
def _store(self):
"""Returns a storage dictionary understood by the storage service.
Sparse matrices are extracted similar to the :class:`~pypet.parameter.SparseParameter` and
marked with the identifier `__spsp__`.
"""
store_dict = {}
for key in self._data:
... | Returns a storage dictionary understood by the storage service.
Sparse matrices are extracted similar to the :class:`~pypet.parameter.SparseParameter` and
marked with the identifier `__spsp__`. | Below is the the instruction that describes the task:
### Input:
Returns a storage dictionary understood by the storage service.
Sparse matrices are extracted similar to the :class:`~pypet.parameter.SparseParameter` and
marked with the identifier `__spsp__`.
### Response:
def _store(self):
... |
def _process_pth(path, base, file_name):
"""Process a ``.pth`` file similar to site.addpackage(...)."""
pth_path = os.path.abspath(os.path.join(base, file_name))
# This is for `exec` below, as some packages (e.g. virtualenvwrapper)
# assume that `site.addpackage` is running them.
sitedir =... | Process a ``.pth`` file similar to site.addpackage(...). | Below is the the instruction that describes the task:
### Input:
Process a ``.pth`` file similar to site.addpackage(...).
### Response:
def _process_pth(path, base, file_name):
"""Process a ``.pth`` file similar to site.addpackage(...)."""
pth_path = os.path.abspath(os.path.join(base, file_name))
... |
def setLoggedMetrics(self, metricNames):
""" Tell the writer which metrics should be written
Parameters:
-----------------------------------------------------------------------
metricsNames: A list of metric lables to be written
"""
if metricNames is None:
self.__metricNames = set([])
... | Tell the writer which metrics should be written
Parameters:
-----------------------------------------------------------------------
metricsNames: A list of metric lables to be written | Below is the the instruction that describes the task:
### Input:
Tell the writer which metrics should be written
Parameters:
-----------------------------------------------------------------------
metricsNames: A list of metric lables to be written
### Response:
def setLoggedMetrics(self, metricNames)... |
def read_initializer_configuration(self, name, **kwargs): # noqa: E501
"""read_initializer_configuration # noqa: E501
read the specified InitializerConfiguration # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass as... | read_initializer_configuration # noqa: E501
read the specified InitializerConfiguration # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_initializer_configuration(name, async_re... | Below is the the instruction that describes the task:
### Input:
read_initializer_configuration # noqa: E501
read the specified InitializerConfiguration # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
... |
def _handle_message(self, tags, source, command, target, msg):
"""Construct the correct events and handle them
:param tags: the tags of the message
:type tags: :class:`list` of :class:`message.Tag`
:param source: the sender of the message
:type source: :class:`str`
:para... | Construct the correct events and handle them
:param tags: the tags of the message
:type tags: :class:`list` of :class:`message.Tag`
:param source: the sender of the message
:type source: :class:`str`
:param command: the event type
:type command: :class:`str`
:par... | Below is the the instruction that describes the task:
### Input:
Construct the correct events and handle them
:param tags: the tags of the message
:type tags: :class:`list` of :class:`message.Tag`
:param source: the sender of the message
:type source: :class:`str`
:param com... |
def ok_cred_def_id(token: str, issuer_did: str = None) -> bool:
"""
Whether input token looks like a valid credential definition identifier from input issuer DID (default any); i.e.,
<issuer-did>:3:CL:<schema-seq-no>:<cred-def-id-tag> for protocol >= 1.4, or
<issuer-did>:3:CL:<schema-seq-no> for protoco... | Whether input token looks like a valid credential definition identifier from input issuer DID (default any); i.e.,
<issuer-did>:3:CL:<schema-seq-no>:<cred-def-id-tag> for protocol >= 1.4, or
<issuer-did>:3:CL:<schema-seq-no> for protocol == 1.3.
:param token: candidate string
:param issuer_did: issuer ... | Below is the the instruction that describes the task:
### Input:
Whether input token looks like a valid credential definition identifier from input issuer DID (default any); i.e.,
<issuer-did>:3:CL:<schema-seq-no>:<cred-def-id-tag> for protocol >= 1.4, or
<issuer-did>:3:CL:<schema-seq-no> for protocol == 1.... |
def supports_gzip(self, context):
"""
Looks at the RequestContext object and determines if the client
supports gzip encoded content. If the client does, we will send them
to the gzipped version of files that are allowed to be compressed.
Clients without gzip support will be serve... | Looks at the RequestContext object and determines if the client
supports gzip encoded content. If the client does, we will send them
to the gzipped version of files that are allowed to be compressed.
Clients without gzip support will be served the original media. | Below is the the instruction that describes the task:
### Input:
Looks at the RequestContext object and determines if the client
supports gzip encoded content. If the client does, we will send them
to the gzipped version of files that are allowed to be compressed.
Clients without gzip suppor... |
def normpath(path: Optional[str]) -> Optional[str]:
""" Normalizes the path, returns None if the argument is None """
if path is not None:
return os.path.normpath(path) | Normalizes the path, returns None if the argument is None | Below is the the instruction that describes the task:
### Input:
Normalizes the path, returns None if the argument is None
### Response:
def normpath(path: Optional[str]) -> Optional[str]:
""" Normalizes the path, returns None if the argument is None """
if path is not None:
return os.path.normpath... |
def effect_repertoire(self, mechanism, purview):
"""Return the effect repertoire of a mechanism over a purview.
Args:
mechanism (tuple[int]): The mechanism for which to calculate the
effect repertoire.
purview (tuple[int]): The purview over which to calculate the... | Return the effect repertoire of a mechanism over a purview.
Args:
mechanism (tuple[int]): The mechanism for which to calculate the
effect repertoire.
purview (tuple[int]): The purview over which to calculate the
effect repertoire.
Returns:
... | Below is the the instruction that describes the task:
### Input:
Return the effect repertoire of a mechanism over a purview.
Args:
mechanism (tuple[int]): The mechanism for which to calculate the
effect repertoire.
purview (tuple[int]): The purview over which to calc... |
def wait_for_interrupt(self, check_interval=1.0, max_time=None):
"""Run the event loop until we receive a ctrl-c interrupt or max_time passes.
This method will wake up every 1 second by default to check for any
interrupt signals or if the maximum runtime has expired. This can be
set lo... | Run the event loop until we receive a ctrl-c interrupt or max_time passes.
This method will wake up every 1 second by default to check for any
interrupt signals or if the maximum runtime has expired. This can be
set lower for testing purpose to reduce latency but in production
settings... | Below is the the instruction that describes the task:
### Input:
Run the event loop until we receive a ctrl-c interrupt or max_time passes.
This method will wake up every 1 second by default to check for any
interrupt signals or if the maximum runtime has expired. This can be
set lower for... |
def get_marathon_task(
task_name,
inactive=False,
completed=False
):
""" Get a dictionary describing a named marathon task
"""
return get_service_task('marathon', task_name, inactive, completed) | Get a dictionary describing a named marathon task | Below is the the instruction that describes the task:
### Input:
Get a dictionary describing a named marathon task
### Response:
def get_marathon_task(
task_name,
inactive=False,
completed=False
):
""" Get a dictionary describing a named marathon task
"""
return get_service_tas... |
def new_output_file_opt(self, opt, name):
""" Add an option and return a new file handle
"""
fil = File(name)
self.add_output_opt(opt, fil)
return fil | Add an option and return a new file handle | Below is the the instruction that describes the task:
### Input:
Add an option and return a new file handle
### Response:
def new_output_file_opt(self, opt, name):
""" Add an option and return a new file handle
"""
fil = File(name)
self.add_output_opt(opt, fil)
return fil |
def start_web_site_network_trace_operation(
self, resource_group_name, name, duration_in_seconds=None, max_frame_length=None, sas_url=None, custom_headers=None, raw=False, polling=True, **operation_config):
"""Start capturing network packets for the site.
Start capturing network packets for... | Start capturing network packets for the site.
Start capturing network packets for the site.
:param resource_group_name: Name of the resource group to which the
resource belongs.
:type resource_group_name: str
:param name: The name of the web app.
:type name: str
... | Below is the the instruction that describes the task:
### Input:
Start capturing network packets for the site.
Start capturing network packets for the site.
:param resource_group_name: Name of the resource group to which the
resource belongs.
:type resource_group_name: str
... |
def create_ingress_rule(self, app, rule):
"""Create a normalized ingress rule.
Args:
app (str): Application name
rule (dict or int): Allowed Security Group ports and protocols.
Returns:
dict: Contains app, start_port, end_port, protocol, cross_account_env an... | Create a normalized ingress rule.
Args:
app (str): Application name
rule (dict or int): Allowed Security Group ports and protocols.
Returns:
dict: Contains app, start_port, end_port, protocol, cross_account_env and cross_account_vpc_id | Below is the the instruction that describes the task:
### Input:
Create a normalized ingress rule.
Args:
app (str): Application name
rule (dict or int): Allowed Security Group ports and protocols.
Returns:
dict: Contains app, start_port, end_port, protocol, cros... |
def log(self, n=None, template=None):
"""
Run the repository log command
Returns:
str: output of log command (``bzr log -l <n>``)
"""
cmd = ['bzr', 'log']
if n:
cmd.append('-l%d' % n)
return self.sh(cmd, shell=False) | Run the repository log command
Returns:
str: output of log command (``bzr log -l <n>``) | Below is the the instruction that describes the task:
### Input:
Run the repository log command
Returns:
str: output of log command (``bzr log -l <n>``)
### Response:
def log(self, n=None, template=None):
"""
Run the repository log command
Returns:
str: out... |
def run_jobs(delete_completed=False, ignore_errors=False, now=None):
"""Run scheduled jobs.
You may specify a date to be treated as the current time.
"""
if ScheduledJob.objects.filter(status='running'):
raise ValueError('jobs in progress found; aborting')
if now is None:
now = date... | Run scheduled jobs.
You may specify a date to be treated as the current time. | Below is the the instruction that describes the task:
### Input:
Run scheduled jobs.
You may specify a date to be treated as the current time.
### Response:
def run_jobs(delete_completed=False, ignore_errors=False, now=None):
"""Run scheduled jobs.
You may specify a date to be treated as the current ... |
def get_state_transition_function(self):
"""
Returns the transition of the state variables as nested dict in the
case of table type parameter and a nested structure in case of
decision diagram parameter
Example
--------
>>> reader = PomdpXReader('Test_PomdpX.xml'... | Returns the transition of the state variables as nested dict in the
case of table type parameter and a nested structure in case of
decision diagram parameter
Example
--------
>>> reader = PomdpXReader('Test_PomdpX.xml')
>>> reader.get_state_transition_function()
... | Below is the the instruction that describes the task:
### Input:
Returns the transition of the state variables as nested dict in the
case of table type parameter and a nested structure in case of
decision diagram parameter
Example
--------
>>> reader = PomdpXReader('Test_Pom... |
def send_line(self, line, parse_result=True):
"""Submit a raw line of text to the VW instance, returning a
VWResult() object.
If 'parse_result' is False, ignore the result and return None.
"""
self.vw_process.sendline(line) # Send line, along with newline
result = self... | Submit a raw line of text to the VW instance, returning a
VWResult() object.
If 'parse_result' is False, ignore the result and return None. | Below is the the instruction that describes the task:
### Input:
Submit a raw line of text to the VW instance, returning a
VWResult() object.
If 'parse_result' is False, ignore the result and return None.
### Response:
def send_line(self, line, parse_result=True):
"""Submit a raw line of ... |
def send_command_return(self, obj, command, *arguments):
""" Send command and wait for single line output. """
index_command = obj._build_index_command(command, *arguments)
return obj._extract_return(command, self.chassis_list[obj.chassis].sendQuery(index_command)) | Send command and wait for single line output. | Below is the the instruction that describes the task:
### Input:
Send command and wait for single line output.
### Response:
def send_command_return(self, obj, command, *arguments):
""" Send command and wait for single line output. """
index_command = obj._build_index_command(command, *arguments)
... |
def remove_channel(self, channel, *, verbose=True):
"""Remove channel from data.
Parameters
----------
channel : int or str
Channel index or name to remove.
verbose : boolean (optional)
Toggle talkback. Default is True.
"""
channel_index =... | Remove channel from data.
Parameters
----------
channel : int or str
Channel index or name to remove.
verbose : boolean (optional)
Toggle talkback. Default is True. | Below is the the instruction that describes the task:
### Input:
Remove channel from data.
Parameters
----------
channel : int or str
Channel index or name to remove.
verbose : boolean (optional)
Toggle talkback. Default is True.
### Response:
def remove_cha... |
def set_data_dir(path=None, store=None):
"""
Set the top level directory pysat uses to look for data and reload.
Parameters
----------
path : string
valid path to directory pysat uses to look for data
store : bool
if True, store data directory for future runs
"""
import ... | Set the top level directory pysat uses to look for data and reload.
Parameters
----------
path : string
valid path to directory pysat uses to look for data
store : bool
if True, store data directory for future runs | Below is the the instruction that describes the task:
### Input:
Set the top level directory pysat uses to look for data and reload.
Parameters
----------
path : string
valid path to directory pysat uses to look for data
store : bool
if True, store data directory for future runs
###... |
def closenessScores(self, expValues, actValues, fractional=True):
""" See the function description in base.py
"""
expValue = expValues[0]
actValue = actValues[0]
if self.periodic:
expValue = expValue % self.maxval
actValue = actValue % self.maxval
err = abs(expValue - actValue)
... | See the function description in base.py | Below is the the instruction that describes the task:
### Input:
See the function description in base.py
### Response:
def closenessScores(self, expValues, actValues, fractional=True):
""" See the function description in base.py
"""
expValue = expValues[0]
actValue = actValues[0]
if self.perio... |
def create_api_deployment(self):
"""Create API deployment of ENV name."""
try:
self.client.create_deployment(restApiId=self.api_id, stageName=self.env)
self.log.info('Created a deployment resource.')
except botocore.exceptions.ClientError as error:
error_code ... | Create API deployment of ENV name. | Below is the the instruction that describes the task:
### Input:
Create API deployment of ENV name.
### Response:
def create_api_deployment(self):
"""Create API deployment of ENV name."""
try:
self.client.create_deployment(restApiId=self.api_id, stageName=self.env)
self.log.... |
def update_file_ext(filename, ext='txt', sep='.'):
r"""Force the file or path str to end with the indicated extension
Note: a dot (".") is assumed to delimit the extension
>>> from __future__ import unicode_literals
>>> update_file_ext('/home/hobs/extremofile', 'bac')
'/home/hobs/extremofile.bac'
... | r"""Force the file or path str to end with the indicated extension
Note: a dot (".") is assumed to delimit the extension
>>> from __future__ import unicode_literals
>>> update_file_ext('/home/hobs/extremofile', 'bac')
'/home/hobs/extremofile.bac'
>>> update_file_ext('/home/hobs/piano.file/', 'musi... | Below is the the instruction that describes the task:
### Input:
r"""Force the file or path str to end with the indicated extension
Note: a dot (".") is assumed to delimit the extension
>>> from __future__ import unicode_literals
>>> update_file_ext('/home/hobs/extremofile', 'bac')
'/home/hobs/ext... |
def handle_event(self,
event_handler,
event_name,
user_args,
event_timeout=None,
cond=None,
cond_timeout=None):
"""Handle events that don't have registered handlers
In a new thr... | Handle events that don't have registered handlers
In a new thread, poll one event of specified type from its queue and
execute its handler. If no such event exists, the thread waits until
one appears.
Args:
event_handler: Handler for the event, which should take at least
... | Below is the the instruction that describes the task:
### Input:
Handle events that don't have registered handlers
In a new thread, poll one event of specified type from its queue and
execute its handler. If no such event exists, the thread waits until
one appears.
Args:
... |
def close(self):
'''Close the underlying file.
Sets data attribute .closed to True. A closed file cannot be used for
further I/O operations. close() may be called more than once without
error. Some kinds of file objects (for example, opened by popen())
may return an exit status ... | Close the underlying file.
Sets data attribute .closed to True. A closed file cannot be used for
further I/O operations. close() may be called more than once without
error. Some kinds of file objects (for example, opened by popen())
may return an exit status upon closing. | Below is the the instruction that describes the task:
### Input:
Close the underlying file.
Sets data attribute .closed to True. A closed file cannot be used for
further I/O operations. close() may be called more than once without
error. Some kinds of file objects (for example, opened by po... |
def matches_sample(output, target, threshold, is_correct, actual_output):
"""
Check if a sample with the given network output, target output, and threshold
is the classification (is_correct, actual_output) like true positive or false negative
"""
return (bool(output > threshold) ... | Check if a sample with the given network output, target output, and threshold
is the classification (is_correct, actual_output) like true positive or false negative | Below is the the instruction that describes the task:
### Input:
Check if a sample with the given network output, target output, and threshold
is the classification (is_correct, actual_output) like true positive or false negative
### Response:
def matches_sample(output, target, threshold, is_correct, actua... |
def create_exchange(self):
"""
Creates MQ exchange for this channel
Needs to be defined only once.
"""
mq_channel = self._connect_mq()
mq_channel.exchange_declare(exchange=self.code_name,
exchange_type='fanout',
... | Creates MQ exchange for this channel
Needs to be defined only once. | Below is the the instruction that describes the task:
### Input:
Creates MQ exchange for this channel
Needs to be defined only once.
### Response:
def create_exchange(self):
"""
Creates MQ exchange for this channel
Needs to be defined only once.
"""
mq_channel = self... |
def phi_progress(pst,logger=None,filename=None,**kwargs):
""" make plot of phi vs number of model runs - requires
available pestpp .iobj file
Parameters
----------
pst : pyemu.Pst
logger : Logger
if None, a generic one is created. Default is None
filename : s... | make plot of phi vs number of model runs - requires
available pestpp .iobj file
Parameters
----------
pst : pyemu.Pst
logger : Logger
if None, a generic one is created. Default is None
filename : str
PDF filename to save figures to. If None, figures ... | Below is the the instruction that describes the task:
### Input:
make plot of phi vs number of model runs - requires
available pestpp .iobj file
Parameters
----------
pst : pyemu.Pst
logger : Logger
if None, a generic one is created. Default is None
filename ... |
def is_valid(self, request_data, raise_exceptions=False):
"""
Checks if the Logout Request received is valid
:param request_data: Request Data
:type request_data: dict
:param raise_exceptions: Whether to return false on failure or raise an exception
:type raise_exceptions... | Checks if the Logout Request received is valid
:param request_data: Request Data
:type request_data: dict
:param raise_exceptions: Whether to return false on failure or raise an exception
:type raise_exceptions: Boolean
:return: If the Logout Request is or not valid
:rtyp... | Below is the the instruction that describes the task:
### Input:
Checks if the Logout Request received is valid
:param request_data: Request Data
:type request_data: dict
:param raise_exceptions: Whether to return false on failure or raise an exception
:type raise_exceptions: Boolean... |
def logdet(self):
"""
Implements log|K| = - log|D| + n⋅log|C₁|.
Returns
-------
logdet : float
Log-determinant of K.
"""
self._init_svd()
return -log(self._De).sum() + self.G.shape[0] * self.C1.logdet() | Implements log|K| = - log|D| + n⋅log|C₁|.
Returns
-------
logdet : float
Log-determinant of K. | Below is the the instruction that describes the task:
### Input:
Implements log|K| = - log|D| + n⋅log|C₁|.
Returns
-------
logdet : float
Log-determinant of K.
### Response:
def logdet(self):
"""
Implements log|K| = - log|D| + n⋅log|C₁|.
Returns
... |
def _setup_ipc(self):
'''
Setup the IPC pub and sub.
Subscript to the listener IPC
and publish to the device specific IPC.
'''
log.debug('Setting up the server IPC puller to receive from the listener')
self.ctx = zmq.Context()
# subscribe to listener
... | Setup the IPC pub and sub.
Subscript to the listener IPC
and publish to the device specific IPC. | Below is the the instruction that describes the task:
### Input:
Setup the IPC pub and sub.
Subscript to the listener IPC
and publish to the device specific IPC.
### Response:
def _setup_ipc(self):
'''
Setup the IPC pub and sub.
Subscript to the listener IPC
and publ... |
def fit_isochrone(orbit, m0=2E11, b0=1., minimize_kwargs=None):
r"""
Fit the toy Isochrone potential to the sum of the energy residuals relative
to the mean energy by minimizing the function
.. math::
f(m,b) = \sum_i (\frac{1}{2}v_i^2 + \Phi_{\rm iso}(x_i\,|\,m,b) - <E>)^2
TODO: This shou... | r"""
Fit the toy Isochrone potential to the sum of the energy residuals relative
to the mean energy by minimizing the function
.. math::
f(m,b) = \sum_i (\frac{1}{2}v_i^2 + \Phi_{\rm iso}(x_i\,|\,m,b) - <E>)^2
TODO: This should fail if the Hamiltonian associated with the orbit has
a... | Below is the the instruction that describes the task:
### Input:
r"""
Fit the toy Isochrone potential to the sum of the energy residuals relative
to the mean energy by minimizing the function
.. math::
f(m,b) = \sum_i (\frac{1}{2}v_i^2 + \Phi_{\rm iso}(x_i\,|\,m,b) - <E>)^2
TODO: This sho... |
def _MapVowels(cls, string, also_p=False):
"""
Return a copy of ``string`` where characters that exist as keys in
cls._VOWELS have been replaced with the corresponding value. If
also_p is True, this function will also change capital P characters
into a Hebrew character Qof.
... | Return a copy of ``string`` where characters that exist as keys in
cls._VOWELS have been replaced with the corresponding value. If
also_p is True, this function will also change capital P characters
into a Hebrew character Qof. | Below is the the instruction that describes the task:
### Input:
Return a copy of ``string`` where characters that exist as keys in
cls._VOWELS have been replaced with the corresponding value. If
also_p is True, this function will also change capital P characters
into a Hebrew character Qof... |
def _compute_acq(self, x):
"""
Computes the GP-Lower Confidence Bound
"""
m, s = self.model.predict(x)
f_acqu = -m + self.exploration_weight * s
return f_acqu | Computes the GP-Lower Confidence Bound | Below is the the instruction that describes the task:
### Input:
Computes the GP-Lower Confidence Bound
### Response:
def _compute_acq(self, x):
"""
Computes the GP-Lower Confidence Bound
"""
m, s = self.model.predict(x)
f_acqu = -m + self.exploration_weight * s
... |
def perfcounters(infile):
"""
Get a complete list of all measurements.
Args:
infile: The filestream containing all likwid output.
Returns:
A list of all measurements extracted from likwid's file stream.
"""
measurements = []
with open(infile, 'r') as in_file:
read_s... | Get a complete list of all measurements.
Args:
infile: The filestream containing all likwid output.
Returns:
A list of all measurements extracted from likwid's file stream. | Below is the the instruction that describes the task:
### Input:
Get a complete list of all measurements.
Args:
infile: The filestream containing all likwid output.
Returns:
A list of all measurements extracted from likwid's file stream.
### Response:
def perfcounters(infile):
"""
... |
def indent(indent_str=None):
"""
An example indentation ruleset.
"""
def indentation_rule():
inst = Indentator(indent_str)
return {'layout_handlers': {
Indent: inst.layout_handler_indent,
Dedent: inst.layout_handler_dedent,
Newline: inst.layout_handle... | An example indentation ruleset. | Below is the the instruction that describes the task:
### Input:
An example indentation ruleset.
### Response:
def indent(indent_str=None):
"""
An example indentation ruleset.
"""
def indentation_rule():
inst = Indentator(indent_str)
return {'layout_handlers': {
Indent:... |
def process_groupchat_message(self,stanza):
"""
Process <message type="groupchat"/> received from the room.
:Parameters:
- `stanza`: the stanza received.
:Types:
- `stanza`: `Message`
"""
fr=stanza.get_from()
user=self.get_user(fr,True)
... | Process <message type="groupchat"/> received from the room.
:Parameters:
- `stanza`: the stanza received.
:Types:
- `stanza`: `Message` | Below is the the instruction that describes the task:
### Input:
Process <message type="groupchat"/> received from the room.
:Parameters:
- `stanza`: the stanza received.
:Types:
- `stanza`: `Message`
### Response:
def process_groupchat_message(self,stanza):
"""
... |
def LDRD(cpu, dest1, dest2, src, offset=None):
"""Loads double width data from memory."""
assert dest1.type == 'register'
assert dest2.type == 'register'
assert src.type == 'memory'
mem1 = cpu.read_int(src.address(), 32)
mem2 = cpu.read_int(src.address() + 4, 32)
... | Loads double width data from memory. | Below is the the instruction that describes the task:
### Input:
Loads double width data from memory.
### Response:
def LDRD(cpu, dest1, dest2, src, offset=None):
"""Loads double width data from memory."""
assert dest1.type == 'register'
assert dest2.type == 'register'
assert src.ty... |
def GetAllUsers(self, pagination_size=10):
"""Gets all user info from Gitkit server.
Args:
pagination_size: int, how many users should be returned per request.
The account info are retrieved in pagination.
Yields:
A generator to iterate all users.
"""
next_page_token, account... | Gets all user info from Gitkit server.
Args:
pagination_size: int, how many users should be returned per request.
The account info are retrieved in pagination.
Yields:
A generator to iterate all users. | Below is the the instruction that describes the task:
### Input:
Gets all user info from Gitkit server.
Args:
pagination_size: int, how many users should be returned per request.
The account info are retrieved in pagination.
Yields:
A generator to iterate all users.
### Response:
de... |
def is_url(string, allowed_schemes=None):
"""
Check if a string is a valid url.
:param string: String to check.
:param allowed_schemes: List of valid schemes ('http', 'https', 'ftp'...). Default to None (any scheme is valid).
:return: True if url, false otherwise
:rtype: bool
"""
if not... | Check if a string is a valid url.
:param string: String to check.
:param allowed_schemes: List of valid schemes ('http', 'https', 'ftp'...). Default to None (any scheme is valid).
:return: True if url, false otherwise
:rtype: bool | Below is the the instruction that describes the task:
### Input:
Check if a string is a valid url.
:param string: String to check.
:param allowed_schemes: List of valid schemes ('http', 'https', 'ftp'...). Default to None (any scheme is valid).
:return: True if url, false otherwise
:rtype: bool
###... |
def alt40fms(msg):
"""Selected altitude, FMS
Args:
msg (String): 28 bytes hexadecimal message (BDS40) string
Returns:
int: altitude in feet
"""
d = hex2bin(data(msg))
if d[13] == '0':
return None
alt = bin2int(d[14:26]) * 16 # ft
return alt | Selected altitude, FMS
Args:
msg (String): 28 bytes hexadecimal message (BDS40) string
Returns:
int: altitude in feet | Below is the the instruction that describes the task:
### Input:
Selected altitude, FMS
Args:
msg (String): 28 bytes hexadecimal message (BDS40) string
Returns:
int: altitude in feet
### Response:
def alt40fms(msg):
"""Selected altitude, FMS
Args:
msg (String): 28 bytes h... |
def p_mp_setQualifier(p):
"""mp_setQualifier : qualifierDeclaration"""
qualdecl = p[1]
ns = p.parser.handle.default_namespace
if p.parser.verbose:
p.parser.log(
_format("Setting qualifier {0!A}", qualdecl.name))
try:
p.parser.handle.SetQualifier(qualdecl)
except CIMEr... | mp_setQualifier : qualifierDeclaration | Below is the the instruction that describes the task:
### Input:
mp_setQualifier : qualifierDeclaration
### Response:
def p_mp_setQualifier(p):
"""mp_setQualifier : qualifierDeclaration"""
qualdecl = p[1]
ns = p.parser.handle.default_namespace
if p.parser.verbose:
p.parser.log(
... |
def reindex_submitted_analyses(portal):
"""Reindex submitted analyses
"""
logger.info("Reindex submitted analyses")
brains = api.search({}, "bika_analysis_catalog")
total = len(brains)
logger.info("Processing {} analyses".format(total))
for num, brain in enumerate(brains):
# skip a... | Reindex submitted analyses | Below is the the instruction that describes the task:
### Input:
Reindex submitted analyses
### Response:
def reindex_submitted_analyses(portal):
"""Reindex submitted analyses
"""
logger.info("Reindex submitted analyses")
brains = api.search({}, "bika_analysis_catalog")
total = len(brains)
... |
def is_path_python_module(thepath):
"""
Given a path, find out of the path is a python module or is inside
a python module.
"""
thepath = path.normpath(thepath)
if path.isfile(thepath):
base, ext = path.splitext(thepath)
if ext in _py_suffixes:
return True
... | Given a path, find out of the path is a python module or is inside
a python module. | Below is the the instruction that describes the task:
### Input:
Given a path, find out of the path is a python module or is inside
a python module.
### Response:
def is_path_python_module(thepath):
"""
Given a path, find out of the path is a python module or is inside
a python module.
... |
def has_data_file(self, sha1hash): # type: (str) -> bool
"""Confirms the presence of the given file in the RO."""
folder = os.path.join(self.folder, DATA, sha1hash[0:2])
hash_path = os.path.join(folder, sha1hash)
return os.path.isfile(hash_path) | Confirms the presence of the given file in the RO. | Below is the the instruction that describes the task:
### Input:
Confirms the presence of the given file in the RO.
### Response:
def has_data_file(self, sha1hash): # type: (str) -> bool
"""Confirms the presence of the given file in the RO."""
folder = os.path.join(self.folder, DATA, sha1hash[0:2]... |
def query_paths(
service_config: Dict[str, Any],
our_address: Address,
privkey: bytes,
current_block_number: BlockNumber,
token_network_address: Union[TokenNetworkAddress, TokenNetworkID],
route_from: InitiatorAddress,
route_to: TargetAddress,
value: Payme... | Query paths from the PFS.
Send a request to the /paths endpoint of the PFS specified in service_config, and
retry in case of a failed request if it makes sense. | Below is the the instruction that describes the task:
### Input:
Query paths from the PFS.
Send a request to the /paths endpoint of the PFS specified in service_config, and
retry in case of a failed request if it makes sense.
### Response:
def query_paths(
service_config: Dict[str, Any],
o... |
def get_by_name_from(self, root: Account, name: str) -> List[Account]:
""" Searches child accounts by name, starting from the given account """
result = []
if root.name == name:
result.append(root)
for child in root.children:
child_results = self.get_by_name_fro... | Searches child accounts by name, starting from the given account | Below is the the instruction that describes the task:
### Input:
Searches child accounts by name, starting from the given account
### Response:
def get_by_name_from(self, root: Account, name: str) -> List[Account]:
""" Searches child accounts by name, starting from the given account """
result = []... |
def get_repr(self, obj, referent=None):
"""Return an HTML tree block describing the given object."""
objtype = type(obj)
typename = str(objtype.__module__) + "." + objtype.__name__
prettytype = typename.replace("__builtin__.", "")
name = getattr(obj, "__name__", "")
if n... | Return an HTML tree block describing the given object. | Below is the the instruction that describes the task:
### Input:
Return an HTML tree block describing the given object.
### Response:
def get_repr(self, obj, referent=None):
"""Return an HTML tree block describing the given object."""
objtype = type(obj)
typename = str(objtype.__module__) +... |
def export(self, export_auto_config=False):
"""
Export the cluster template for the given cluster. ccluster must have host
templates defined. It cluster does not have host templates defined it will
export host templates based on roles assignment.
@param export_auto_config: Also export auto configur... | Export the cluster template for the given cluster. ccluster must have host
templates defined. It cluster does not have host templates defined it will
export host templates based on roles assignment.
@param export_auto_config: Also export auto configured configs
@return: Return cluster template
@sin... | Below is the the instruction that describes the task:
### Input:
Export the cluster template for the given cluster. ccluster must have host
templates defined. It cluster does not have host templates defined it will
export host templates based on roles assignment.
@param export_auto_config: Also export ... |
def _grab_history(self):
"""Calculate the needed history/changelog changes
Every history heading looks like '1.0 b4 (1972-12-25)'. Extract them,
check if the first one matches the version and whether it has a the
current date.
"""
default_location = None
config =... | Calculate the needed history/changelog changes
Every history heading looks like '1.0 b4 (1972-12-25)'. Extract them,
check if the first one matches the version and whether it has a the
current date. | Below is the the instruction that describes the task:
### Input:
Calculate the needed history/changelog changes
Every history heading looks like '1.0 b4 (1972-12-25)'. Extract them,
check if the first one matches the version and whether it has a the
current date.
### Response:
def _grab_hi... |
def matches(self, other):
"""Do a loose equivalency test suitable for comparing page names.
*other* can be any string-like object, including :class:`.Wikicode`, or
an iterable of these. This operation is symmetric; both sides are
adjusted. Specifically, whitespace and markup is stripped... | Do a loose equivalency test suitable for comparing page names.
*other* can be any string-like object, including :class:`.Wikicode`, or
an iterable of these. This operation is symmetric; both sides are
adjusted. Specifically, whitespace and markup is stripped and the first
letter's case ... | Below is the the instruction that describes the task:
### Input:
Do a loose equivalency test suitable for comparing page names.
*other* can be any string-like object, including :class:`.Wikicode`, or
an iterable of these. This operation is symmetric; both sides are
adjusted. Specifically, w... |
def evaluate_perceptron(ctx, model, corpus):
"""Evaluate performance of Averaged Perceptron POS Tagger."""
click.echo('chemdataextractor.pos.evaluate')
if corpus == 'wsj':
evaluation = wsj_evaluation
sents = list(evaluation.tagged_sents())
for i, wsj_sent in enumerate(sents):
... | Evaluate performance of Averaged Perceptron POS Tagger. | Below is the the instruction that describes the task:
### Input:
Evaluate performance of Averaged Perceptron POS Tagger.
### Response:
def evaluate_perceptron(ctx, model, corpus):
"""Evaluate performance of Averaged Perceptron POS Tagger."""
click.echo('chemdataextractor.pos.evaluate')
if corpus == 'ws... |
def _fix_pooling(pool_type, inputs, new_attr):
"""onnx pooling operator supports asymmetrical padding
Adding pad operator before pooling in mxnet to work with onnx"""
stride = new_attr.get('stride')
kernel = new_attr.get('kernel')
padding = new_attr.get('pad')
p_value = new_attr.get('p_value')
... | onnx pooling operator supports asymmetrical padding
Adding pad operator before pooling in mxnet to work with onnx | Below is the the instruction that describes the task:
### Input:
onnx pooling operator supports asymmetrical padding
Adding pad operator before pooling in mxnet to work with onnx
### Response:
def _fix_pooling(pool_type, inputs, new_attr):
"""onnx pooling operator supports asymmetrical padding
Adding p... |
def high_density_objs(row_obj: CityInfo) -> dict:
"""Color rows with extremely high population density red."""
opts = dict()
if float(pop_density(row_obj)) > EXTREMELY_HIGH_POULATION_DENSITY:
opts[tf.TableFormatter.ROW_OPT_TEXT_COLOR] = tf.TableColors.TEXT_COLOR_RED
return opts | Color rows with extremely high population density red. | Below is the the instruction that describes the task:
### Input:
Color rows with extremely high population density red.
### Response:
def high_density_objs(row_obj: CityInfo) -> dict:
"""Color rows with extremely high population density red."""
opts = dict()
if float(pop_density(row_obj)) > EXTREMELY_H... |
def _render_children(self, contexts, partials):
"""Render the children tokens"""
ret = []
for child in self.children:
ret.append(child._render(contexts, partials))
return EMPTYSTRING.join(ret) | Render the children tokens | Below is the the instruction that describes the task:
### Input:
Render the children tokens
### Response:
def _render_children(self, contexts, partials):
"""Render the children tokens"""
ret = []
for child in self.children:
ret.append(child._render(contexts, partials))
r... |
def calc_qv_v1(self):
"""Calculate the discharge of both forelands after Manning-Strickler.
Required control parameters:
|EKV|
|SKV|
|Gef|
Required flux sequence:
|AV|
|UV|
Calculated flux sequence:
|lstream_fluxes.QV|
Examples:
For appropriate strict... | Calculate the discharge of both forelands after Manning-Strickler.
Required control parameters:
|EKV|
|SKV|
|Gef|
Required flux sequence:
|AV|
|UV|
Calculated flux sequence:
|lstream_fluxes.QV|
Examples:
For appropriate strictly positive values:
... | Below is the the instruction that describes the task:
### Input:
Calculate the discharge of both forelands after Manning-Strickler.
Required control parameters:
|EKV|
|SKV|
|Gef|
Required flux sequence:
|AV|
|UV|
Calculated flux sequence:
|lstream_fluxes.QV|
E... |
def sgc_game(k):
"""
Return a NormalFormGame instance of the 2-player game introduced by
Sandholm, Gilpin, and Conitzer (2005), which has a unique Nash
equilibrium, where each player plays half of the actions with
positive probabilities. Payoffs are normalized so that the minimum
and the maximum... | Return a NormalFormGame instance of the 2-player game introduced by
Sandholm, Gilpin, and Conitzer (2005), which has a unique Nash
equilibrium, where each player plays half of the actions with
positive probabilities. Payoffs are normalized so that the minimum
and the maximum payoffs are 0 and 1, respect... | Below is the the instruction that describes the task:
### Input:
Return a NormalFormGame instance of the 2-player game introduced by
Sandholm, Gilpin, and Conitzer (2005), which has a unique Nash
equilibrium, where each player plays half of the actions with
positive probabilities. Payoffs are normalized... |
def update_author_min_max_date(min_date, max_date, target_author, author_field="author_uuid"):
"""
Get the query to update demography_min_date and demography_max_date of a given author
:param min_date: new demography_min_date
:param max_date: new demography_max_date
:param targe... | Get the query to update demography_min_date and demography_max_date of a given author
:param min_date: new demography_min_date
:param max_date: new demography_max_date
:param target_author: target author to be updated
:param author_field: author field
:return: the query to be e... | Below is the the instruction that describes the task:
### Input:
Get the query to update demography_min_date and demography_max_date of a given author
:param min_date: new demography_min_date
:param max_date: new demography_max_date
:param target_author: target author to be updated
... |
def find_funcdef(source):
"""Find the first FuncDef ast object in source"""
try:
module_node = compile(
source, "<string>", mode="exec", flags=ast.PyCF_ONLY_AST
)
except SyntaxError:
return find_funcdef(fix_lamdaline(source))
for node in ast.walk(module_node):
... | Find the first FuncDef ast object in source | Below is the the instruction that describes the task:
### Input:
Find the first FuncDef ast object in source
### Response:
def find_funcdef(source):
"""Find the first FuncDef ast object in source"""
try:
module_node = compile(
source, "<string>", mode="exec", flags=ast.PyCF_ONLY_AST
... |
def _got_srv(self, addrs):
"""Handle SRV lookup result.
:Parameters:
- `addrs`: properly sorted list of (hostname, port) tuples
"""
with self.lock:
if not addrs:
self._dst_service = None
if self._dst_port:
self.... | Handle SRV lookup result.
:Parameters:
- `addrs`: properly sorted list of (hostname, port) tuples | Below is the the instruction that describes the task:
### Input:
Handle SRV lookup result.
:Parameters:
- `addrs`: properly sorted list of (hostname, port) tuples
### Response:
def _got_srv(self, addrs):
"""Handle SRV lookup result.
:Parameters:
- `addrs`: properly... |
def _file_lists(self, load, form):
'''
Return a dict containing the file lists for files and dirs
'''
if 'env' in load:
# "env" is not supported; Use "saltenv".
load.pop('env')
if not os.path.isdir(self.file_list_cachedir):
try:
... | Return a dict containing the file lists for files and dirs | Below is the the instruction that describes the task:
### Input:
Return a dict containing the file lists for files and dirs
### Response:
def _file_lists(self, load, form):
'''
Return a dict containing the file lists for files and dirs
'''
if 'env' in load:
# "env" is no... |
def __spawn_new_requests(self):
"""Spawn new requests until the max threads option value is reached.
Note:
If no new requests were spawned and there are no requests in progress
the crawler will stop crawling.
"""
self.__should_spawn_new_requests = False
... | Spawn new requests until the max threads option value is reached.
Note:
If no new requests were spawned and there are no requests in progress
the crawler will stop crawling. | Below is the the instruction that describes the task:
### Input:
Spawn new requests until the max threads option value is reached.
Note:
If no new requests were spawned and there are no requests in progress
the crawler will stop crawling.
### Response:
def __spawn_new_requests(self... |
def get_all_projects(url, token, top=HARD_CODED_TOP):
"""
Returns a list of all projects with their collection info from the server. Currently limited functionality to only return the first 1000 projects.
#TODO refactor to add multiple calls to api to retrieve all projects if more exist beyond top.
"""
... | Returns a list of all projects with their collection info from the server. Currently limited functionality to only return the first 1000 projects.
#TODO refactor to add multiple calls to api to retrieve all projects if more exist beyond top. | Below is the the instruction that describes the task:
### Input:
Returns a list of all projects with their collection info from the server. Currently limited functionality to only return the first 1000 projects.
#TODO refactor to add multiple calls to api to retrieve all projects if more exist beyond top.
### R... |
def sort_by_decreasing_count(self):
"""Return a **new** `Vocab` object that is ordered by decreasing count.
The word at index 1 will be most common, the word at index 2 will be
next most common, and so on.
:return: A new vocabulary sorted by decreasing count.
NOTE: UNK will re... | Return a **new** `Vocab` object that is ordered by decreasing count.
The word at index 1 will be most common, the word at index 2 will be
next most common, and so on.
:return: A new vocabulary sorted by decreasing count.
NOTE: UNK will remain at index 0, regardless of its frequency. | Below is the the instruction that describes the task:
### Input:
Return a **new** `Vocab` object that is ordered by decreasing count.
The word at index 1 will be most common, the word at index 2 will be
next most common, and so on.
:return: A new vocabulary sorted by decreasing count.
... |
def showPanelMenu(self, panel, point=None):
"""
Creates the panel menu for this view widget. If no point is supplied,\
then the current cursor position will be used.
:param panel | <XViewPanel>
point | <QPoint> || None
"""
if not sel... | Creates the panel menu for this view widget. If no point is supplied,\
then the current cursor position will be used.
:param panel | <XViewPanel>
point | <QPoint> || None | Below is the the instruction that describes the task:
### Input:
Creates the panel menu for this view widget. If no point is supplied,\
then the current cursor position will be used.
:param panel | <XViewPanel>
point | <QPoint> || None
### Response:
def showPa... |
def set_path(self, path):
'''Sets the listitem's path'''
self._path = path
return self._listitem.setPath(path) | Sets the listitem's path | Below is the the instruction that describes the task:
### Input:
Sets the listitem's path
### Response:
def set_path(self, path):
'''Sets the listitem's path'''
self._path = path
return self._listitem.setPath(path) |
def _create_body(self, name, label=None, cidr=None):
"""
Used to create the dict required to create a network. Accepts either
'label' or 'name' as the keyword parameter for the label attribute.
"""
label = label or name
body = {"network": {
"label": label,... | Used to create the dict required to create a network. Accepts either
'label' or 'name' as the keyword parameter for the label attribute. | Below is the the instruction that describes the task:
### Input:
Used to create the dict required to create a network. Accepts either
'label' or 'name' as the keyword parameter for the label attribute.
### Response:
def _create_body(self, name, label=None, cidr=None):
"""
Used to create the... |
def __unget_service_from_factory(self, bundle, reference, service=None):
# type: (Any, ServiceReference, Any) -> bool
"""
Removes the usage of a a service factory or a prototype
service factory by a bundle
:param bundle: The bundle that used the service
:param reference:... | Removes the usage of a a service factory or a prototype
service factory by a bundle
:param bundle: The bundle that used the service
:param reference: A service reference
:param service: Service instance (for prototype factories)
:return: True if the bundle usage has been removed | Below is the the instruction that describes the task:
### Input:
Removes the usage of a a service factory or a prototype
service factory by a bundle
:param bundle: The bundle that used the service
:param reference: A service reference
:param service: Service instance (for prototype ... |
def plot_density(population, # pylint: disable=too-many-arguments, too-many-locals
bins=100, new_fig=True, subplot=111, levels=None, plane='xy',
colorlabel='Nodes per unit area', labelfontsize=16,
color_map='Reds', no_colorbar=False, threshold=0.01,
n... | Plots the 2d histogram of the center
coordinates of segments in the selected plane. | Below is the the instruction that describes the task:
### Input:
Plots the 2d histogram of the center
coordinates of segments in the selected plane.
### Response:
def plot_density(population, # pylint: disable=too-many-arguments, too-many-locals
bins=100, new_fig=True, subplot=111, levels=... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.