code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def getRfree(self):
'''
Returns an array of size self.AgentCount with self.RfreeNow in every entry.
Parameters
----------
None
Returns
-------
RfreeNow : np.array
Array of size self.AgentCount with risk free interest rate for each agent.
... | Returns an array of size self.AgentCount with self.RfreeNow in every entry.
Parameters
----------
None
Returns
-------
RfreeNow : np.array
Array of size self.AgentCount with risk free interest rate for each agent. | Below is the the instruction that describes the task:
### Input:
Returns an array of size self.AgentCount with self.RfreeNow in every entry.
Parameters
----------
None
Returns
-------
RfreeNow : np.array
Array of size self.AgentCount with risk free inte... |
def get_bin_query_session(self, proxy):
"""Gets the bin query session.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.resource.BinQuerySession) - a ``BinQuerySession``
raise: NullArgument - ``proxy`` is ``null``
raise: OperationFailed - unable to complete request
... | Gets the bin query session.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.resource.BinQuerySession) - a ``BinQuerySession``
raise: NullArgument - ``proxy`` is ``null``
raise: OperationFailed - unable to complete request
raise: Unimplemented - ``supports_bin_query()`... | Below is the the instruction that describes the task:
### Input:
Gets the bin query session.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.resource.BinQuerySession) - a ``BinQuerySession``
raise: NullArgument - ``proxy`` is ``null``
raise: OperationFailed - unable to com... |
def makeStatic():
""" Provide static access to underscore class
"""
p = lambda value: inspect.ismethod(value) or inspect.isfunction(value)
for eachMethod in inspect.getmembers(underscore,
predicate=p):
m = eachMethod[0]
... | Provide static access to underscore class | Below is the the instruction that describes the task:
### Input:
Provide static access to underscore class
### Response:
def makeStatic():
""" Provide static access to underscore class
"""
p = lambda value: inspect.ismethod(value) or inspect.isfunction(value)
for eachMethod in inspe... |
def get_function_in_models(service, operation):
"""refers to definition of API in botocore, and autogenerates function
You can see example of elbv2 from link below.
https://github.com/boto/botocore/blob/develop/botocore/data/elbv2/2015-12-01/service-2.json
"""
client = boto3.client(service)
aw... | refers to definition of API in botocore, and autogenerates function
You can see example of elbv2 from link below.
https://github.com/boto/botocore/blob/develop/botocore/data/elbv2/2015-12-01/service-2.json | Below is the the instruction that describes the task:
### Input:
refers to definition of API in botocore, and autogenerates function
You can see example of elbv2 from link below.
https://github.com/boto/botocore/blob/develop/botocore/data/elbv2/2015-12-01/service-2.json
### Response:
def get_function_in_... |
def yield_pair_energies(self, index1, index2):
"""Yields pairs ((s(r_ij), v(bar{r}_ij))"""
d_1 = 1/self.distances[index1, index2]
if self.charges is not None:
c1 = self.charges[index1]
c2 = self.charges[index2]
yield c1*c2*d_1, 1
if self.dipoles is not... | Yields pairs ((s(r_ij), v(bar{r}_ij)) | Below is the the instruction that describes the task:
### Input:
Yields pairs ((s(r_ij), v(bar{r}_ij))
### Response:
def yield_pair_energies(self, index1, index2):
"""Yields pairs ((s(r_ij), v(bar{r}_ij))"""
d_1 = 1/self.distances[index1, index2]
if self.charges is not None:
c1 ... |
def attribute(self, attribute_id, action='GET', params=None):
"""
Gets the attribute from a Group/Indicator or Victim
Args:
action:
params:
attribute_id:
Returns: attribute json
"""
if params is None:
params = {}
... | Gets the attribute from a Group/Indicator or Victim
Args:
action:
params:
attribute_id:
Returns: attribute json | Below is the the instruction that describes the task:
### Input:
Gets the attribute from a Group/Indicator or Victim
Args:
action:
params:
attribute_id:
Returns: attribute json
### Response:
def attribute(self, attribute_id, action='GET', params=None):
... |
def upload_tree(self):
""" upload_tree: sends processed channel data to server to create tree
Args: None
Returns: link to uploadedchannel
"""
from datetime import datetime
start_time = datetime.now()
root, channel_id = self.add_channel()
self.node_... | upload_tree: sends processed channel data to server to create tree
Args: None
Returns: link to uploadedchannel | Below is the the instruction that describes the task:
### Input:
upload_tree: sends processed channel data to server to create tree
Args: None
Returns: link to uploadedchannel
### Response:
def upload_tree(self):
""" upload_tree: sends processed channel data to server to create tree... |
def get_auth_stdin(refresh_token_filename, manual_login=False):
"""Simple wrapper for :func:`get_auth` that prompts the user using stdin.
Args:
refresh_token_filename (str): Path to file where refresh token will be
cached.
manual_login (bool): If true, prompt user to log in through ... | Simple wrapper for :func:`get_auth` that prompts the user using stdin.
Args:
refresh_token_filename (str): Path to file where refresh token will be
cached.
manual_login (bool): If true, prompt user to log in through a browser
and enter authorization code manually. Defaults t... | Below is the the instruction that describes the task:
### Input:
Simple wrapper for :func:`get_auth` that prompts the user using stdin.
Args:
refresh_token_filename (str): Path to file where refresh token will be
cached.
manual_login (bool): If true, prompt user to log in through a ... |
def foreach(layer, drop_factor=1.0):
"""Map a layer across list items"""
def foreach_fwd(docs, drop=0.0):
sents = []
lengths = []
for doc in docs:
doc_sents = [sent for sent in doc if len(sent)]
subset = [
s for s in doc_sents if numpy.random.rand... | Map a layer across list items | Below is the the instruction that describes the task:
### Input:
Map a layer across list items
### Response:
def foreach(layer, drop_factor=1.0):
"""Map a layer across list items"""
def foreach_fwd(docs, drop=0.0):
sents = []
lengths = []
for doc in docs:
doc_sents = [s... |
def save_video(video, save_path_template):
"""Save frames of the videos into files."""
try:
from PIL import Image # pylint: disable=g-import-not-at-top
except ImportError as e:
tf.logging.warning(
"Showing and saving an image requires PIL library to be "
"installed: %s", e)
raise NotI... | Save frames of the videos into files. | Below is the the instruction that describes the task:
### Input:
Save frames of the videos into files.
### Response:
def save_video(video, save_path_template):
"""Save frames of the videos into files."""
try:
from PIL import Image # pylint: disable=g-import-not-at-top
except ImportError as e:
tf.log... |
def FormatArtifacts(self, artifacts):
"""Formats artifacts to desired output format.
Args:
artifacts (list[ArtifactDefinition]): artifact definitions.
Returns:
str: formatted string of artifact definition.
"""
artifact_definitions = [artifact.AsDict() for artifact in artifacts]
jso... | Formats artifacts to desired output format.
Args:
artifacts (list[ArtifactDefinition]): artifact definitions.
Returns:
str: formatted string of artifact definition. | Below is the the instruction that describes the task:
### Input:
Formats artifacts to desired output format.
Args:
artifacts (list[ArtifactDefinition]): artifact definitions.
Returns:
str: formatted string of artifact definition.
### Response:
def FormatArtifacts(self, artifacts):
"""Form... |
def search_filename(fname, lineno, local_first):
""" Search a filename into the list of the include path.
If local_first is true, it will try first in the current directory of
the file being analyzed.
"""
fname = api.utils.sanitize_filename(fname)
i_path = [CURRENT_DIR] + INCLUDEPATH if local_fi... | Search a filename into the list of the include path.
If local_first is true, it will try first in the current directory of
the file being analyzed. | Below is the the instruction that describes the task:
### Input:
Search a filename into the list of the include path.
If local_first is true, it will try first in the current directory of
the file being analyzed.
### Response:
def search_filename(fname, lineno, local_first):
""" Search a filename into ... |
def read_raster_no_crs(input_file, indexes=None, gdal_opts=None):
"""
Wrapper function around rasterio.open().read().
Parameters
----------
input_file : str
Path to file
indexes : int or list
Band index or list of band indexes to be read.
Returns
-------
MaskedArray... | Wrapper function around rasterio.open().read().
Parameters
----------
input_file : str
Path to file
indexes : int or list
Band index or list of band indexes to be read.
Returns
-------
MaskedArray
Raises
------
FileNotFoundError if file cannot be found. | Below is the the instruction that describes the task:
### Input:
Wrapper function around rasterio.open().read().
Parameters
----------
input_file : str
Path to file
indexes : int or list
Band index or list of band indexes to be read.
Returns
-------
MaskedArray
Rai... |
def solveAgent(agent,verbose):
'''
Solve the dynamic model for one agent type. This function iterates on "cycles"
of an agent's model either a given number of times or until solution convergence
if an infinite horizon model is used (with agent.cycles = 0).
Parameters
----------
agent : Age... | Solve the dynamic model for one agent type. This function iterates on "cycles"
of an agent's model either a given number of times or until solution convergence
if an infinite horizon model is used (with agent.cycles = 0).
Parameters
----------
agent : AgentType
The microeconomic AgentType ... | Below is the the instruction that describes the task:
### Input:
Solve the dynamic model for one agent type. This function iterates on "cycles"
of an agent's model either a given number of times or until solution convergence
if an infinite horizon model is used (with agent.cycles = 0).
Parameters
... |
def write_xspf(f, tuples):
"""send me a list of (artist,title,mp3_url)"""
xml = XmlWriter(f, indentAmount=' ')
xml.prolog()
xml.start('playlist', { 'xmlns': 'http://xspf.org/ns/0/', 'version': '1' })
xml.start('trackList')
for tupe in tuples:
xml.start('track')
xml.elem('creator... | send me a list of (artist,title,mp3_url) | Below is the the instruction that describes the task:
### Input:
send me a list of (artist,title,mp3_url)
### Response:
def write_xspf(f, tuples):
"""send me a list of (artist,title,mp3_url)"""
xml = XmlWriter(f, indentAmount=' ')
xml.prolog()
xml.start('playlist', { 'xmlns': 'http://xspf.org/ns/0... |
def update_positions(self, positions):
'''Update the sphere positions.
'''
sphs_verts = self.sphs_verts_radii.copy()
sphs_verts += positions.reshape(self.n_spheres, 1, 3)
self.tr.update_vertices(sphs_verts)
self.poslist = positions | Update the sphere positions. | Below is the the instruction that describes the task:
### Input:
Update the sphere positions.
### Response:
def update_positions(self, positions):
'''Update the sphere positions.
'''
sphs_verts = self.sphs_verts_radii.copy()
sphs_verts += positions.reshape(self.n_spheres, 1, 3)
... |
def si_parse(value):
'''
Parse a value expressed using SI prefix units to a floating point number.
Parameters
----------
value : str or unicode
Value expressed using SI prefix units (as returned by :func:`si_format`
function).
.. versionchanged:: 1.0
Use unicode string... | Parse a value expressed using SI prefix units to a floating point number.
Parameters
----------
value : str or unicode
Value expressed using SI prefix units (as returned by :func:`si_format`
function).
.. versionchanged:: 1.0
Use unicode string for SI unit to support micro (i.... | Below is the the instruction that describes the task:
### Input:
Parse a value expressed using SI prefix units to a floating point number.
Parameters
----------
value : str or unicode
Value expressed using SI prefix units (as returned by :func:`si_format`
function).
.. versionchan... |
def read_volume_attachment(self, name, **kwargs): # noqa: E501
"""read_volume_attachment # noqa: E501
read the specified VolumeAttachment # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>>... | read_volume_attachment # noqa: E501
read the specified VolumeAttachment # 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_volume_attachment(name, async_req=True)
>>> resu... | Below is the the instruction that describes the task:
### Input:
read_volume_attachment # noqa: E501
read the specified VolumeAttachment # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> threa... |
def bm3_k(p, v0, k0, k0p):
"""
calculate bulk modulus, wrapper for cal_k_bm3
cannot handle uncertainties
:param p: pressure
:param v0: volume at reference conditions
:param k0: bulk modulus at reference conditions
:param k0p: pressure derivative of bulk modulus at different conditions
:... | calculate bulk modulus, wrapper for cal_k_bm3
cannot handle uncertainties
:param p: pressure
:param v0: volume at reference conditions
:param k0: bulk modulus at reference conditions
:param k0p: pressure derivative of bulk modulus at different conditions
:return: bulk modulus at high pressure | Below is the the instruction that describes the task:
### Input:
calculate bulk modulus, wrapper for cal_k_bm3
cannot handle uncertainties
:param p: pressure
:param v0: volume at reference conditions
:param k0: bulk modulus at reference conditions
:param k0p: pressure derivative of bulk modulus... |
def from_fp(self, file_pointer, comment_lead=['c']):
"""
Read a CNF+ formula from a file pointer. A file pointer should be
specified as an argument. The only default argument is
``comment_lead``, which can be used for parsing specific comment
lines.
:... | Read a CNF+ formula from a file pointer. A file pointer should be
specified as an argument. The only default argument is
``comment_lead``, which can be used for parsing specific comment
lines.
:param file_pointer: a file pointer to read the formula from.
:par... | Below is the the instruction that describes the task:
### Input:
Read a CNF+ formula from a file pointer. A file pointer should be
specified as an argument. The only default argument is
``comment_lead``, which can be used for parsing specific comment
lines.
:param fi... |
def get_stackset_ready_accounts(credentials, account_ids, quiet=True):
"""
Verify which AWS accounts have been configured for CloudFormation stack set by attempting to assume the stack set execution role
:param credentials: AWS credentials to use when calling sts:assumerole
:param org_a... | Verify which AWS accounts have been configured for CloudFormation stack set by attempting to assume the stack set execution role
:param credentials: AWS credentials to use when calling sts:assumerole
:param org_account_ids: List of AWS accounts to check for Stackset configuration
... | Below is the the instruction that describes the task:
### Input:
Verify which AWS accounts have been configured for CloudFormation stack set by attempting to assume the stack set execution role
:param credentials: AWS credentials to use when calling sts:assumerole
:param org_account_ids: ... |
def wait_for_provision_state(baremetal_client, node_uuid, provision_state,
loops=10, sleep=1):
"""Wait for a given Provisioning state in Ironic Discoverd
Updating the provisioning state is an async operation, we
need to wait for it to be completed.
:param baremetal_client:... | Wait for a given Provisioning state in Ironic Discoverd
Updating the provisioning state is an async operation, we
need to wait for it to be completed.
:param baremetal_client: Instance of Ironic client
:type baremetal_client: ironicclient.v1.client.Client
:param node_uuid: The Ironic node UUID
... | Below is the the instruction that describes the task:
### Input:
Wait for a given Provisioning state in Ironic Discoverd
Updating the provisioning state is an async operation, we
need to wait for it to be completed.
:param baremetal_client: Instance of Ironic client
:type baremetal_client: ironic... |
def _get_color(self, age):
"""Get the fill color depending on age.
Args:
age (int): The age of the branch/es
Returns:
tuple: (r, g, b)
"""
if age == self.tree.age:
return self.leaf_color
color = self.stem_color
tree = self.tre... | Get the fill color depending on age.
Args:
age (int): The age of the branch/es
Returns:
tuple: (r, g, b) | Below is the the instruction that describes the task:
### Input:
Get the fill color depending on age.
Args:
age (int): The age of the branch/es
Returns:
tuple: (r, g, b)
### Response:
def _get_color(self, age):
"""Get the fill color depending on age.
Args:... |
def replace(self, hour=None, minute=None, second=None, microsecond=None,
tzinfo=True):
"""Return a new time with new values for the specified fields."""
if hour is None:
hour = self.hour
if minute is None:
minute = self.minute
if second is None:
... | Return a new time with new values for the specified fields. | Below is the the instruction that describes the task:
### Input:
Return a new time with new values for the specified fields.
### Response:
def replace(self, hour=None, minute=None, second=None, microsecond=None,
tzinfo=True):
"""Return a new time with new values for the specified fields."""... |
def deregister_image(self, image_id, delete_snapshot=False):
"""
Unregister an AMI.
:type image_id: string
:param image_id: the ID of the Image to unregister
:type delete_snapshot: bool
:param delete_snapshot: Set to True if we should delete the
... | Unregister an AMI.
:type image_id: string
:param image_id: the ID of the Image to unregister
:type delete_snapshot: bool
:param delete_snapshot: Set to True if we should delete the
snapshot associated with an EBS volume
mo... | Below is the the instruction that describes the task:
### Input:
Unregister an AMI.
:type image_id: string
:param image_id: the ID of the Image to unregister
:type delete_snapshot: bool
:param delete_snapshot: Set to True if we should delete the
snap... |
def start_monitor(self, standalone=True):
"""
Run command in a loop and check exit status plus restart process when needed
"""
try:
self.start()
cmdline = shlex.split(self.config.process_to_monitor)
if standalone:
signal.signal(signal.S... | Run command in a loop and check exit status plus restart process when needed | Below is the the instruction that describes the task:
### Input:
Run command in a loop and check exit status plus restart process when needed
### Response:
def start_monitor(self, standalone=True):
"""
Run command in a loop and check exit status plus restart process when needed
"""
... |
def construct_rest_of_worlds_mapping(self, excluded, fp=None):
"""Construct topo mapping file for ``excluded``.
``excluded`` must be a **dictionary** of {"rest-of-world label": ["names", "of", "excluded", "locations"]}``.
Topo mapping has the data format:
.. code-block:: python
... | Construct topo mapping file for ``excluded``.
``excluded`` must be a **dictionary** of {"rest-of-world label": ["names", "of", "excluded", "locations"]}``.
Topo mapping has the data format:
.. code-block:: python
{
'data': [
['location label', ... | Below is the the instruction that describes the task:
### Input:
Construct topo mapping file for ``excluded``.
``excluded`` must be a **dictionary** of {"rest-of-world label": ["names", "of", "excluded", "locations"]}``.
Topo mapping has the data format:
.. code-block:: python
... |
def aggregate(self, query: Optional[dict] = None,
group: Optional[dict] = None,
order_by: Union[None, list, tuple] = None) -> list:
"""return aggregation result based on specified rulez query and group"""
raise NotImplementedError | return aggregation result based on specified rulez query and group | Below is the the instruction that describes the task:
### Input:
return aggregation result based on specified rulez query and group
### Response:
def aggregate(self, query: Optional[dict] = None,
group: Optional[dict] = None,
order_by: Union[None, list, tuple] = None) -> list:
... |
def dispatch(self, request, start_response):
"""Handles dispatch to apiserver handlers.
This typically ends up calling start_response and returning the entire
body of the response.
Args:
request: An ApiRequest, the request from the user.
start_response: A function with semantics defined ... | Handles dispatch to apiserver handlers.
This typically ends up calling start_response and returning the entire
body of the response.
Args:
request: An ApiRequest, the request from the user.
start_response: A function with semantics defined in PEP-333.
Returns:
A string, the body o... | Below is the the instruction that describes the task:
### Input:
Handles dispatch to apiserver handlers.
This typically ends up calling start_response and returning the entire
body of the response.
Args:
request: An ApiRequest, the request from the user.
start_response: A function with s... |
def Remote(path=None, loader=Notebook, **globals):
"""A remote notebook finder. Place a `*` into a url
to generalize the finder. It returns a context manager
"""
class Remote(RemoteMixin, loader):
...
return Remote(path=path, **globals) | A remote notebook finder. Place a `*` into a url
to generalize the finder. It returns a context manager | Below is the the instruction that describes the task:
### Input:
A remote notebook finder. Place a `*` into a url
to generalize the finder. It returns a context manager
### Response:
def Remote(path=None, loader=Notebook, **globals):
"""A remote notebook finder. Place a `*` into a url
to generalize ... |
def update_task_descriptor_content(self, courseid, taskid, content, force_extension=None):
"""
Update the task descriptor with the dict in content
:param courseid: the course id of the course
:param taskid: the task id of the task
:param content: the content to put in the task fi... | Update the task descriptor with the dict in content
:param courseid: the course id of the course
:param taskid: the task id of the task
:param content: the content to put in the task file
:param force_extension: If None, save it the same format. Else, save with the given extension
... | Below is the the instruction that describes the task:
### Input:
Update the task descriptor with the dict in content
:param courseid: the course id of the course
:param taskid: the task id of the task
:param content: the content to put in the task file
:param force_extension: If None... |
def _refine_enc(enc):
'''
Return the properly formatted ssh value for the authorized encryption key
type. ecdsa defaults to 256 bits, must give full ecdsa enc schema string
if using higher enc. If the type is not found, raise CommandExecutionError.
'''
rsa = ['r', 'rsa', 'ssh-rsa']
dss = ['... | Return the properly formatted ssh value for the authorized encryption key
type. ecdsa defaults to 256 bits, must give full ecdsa enc schema string
if using higher enc. If the type is not found, raise CommandExecutionError. | Below is the the instruction that describes the task:
### Input:
Return the properly formatted ssh value for the authorized encryption key
type. ecdsa defaults to 256 bits, must give full ecdsa enc schema string
if using higher enc. If the type is not found, raise CommandExecutionError.
### Response:
def _... |
def rank(keys, axis=semantics.axis_default):
"""where each item is in the pecking order.
Parameters
----------
keys : indexable object
Returns
-------
ndarray, [keys.size], int
unique integers, ranking the sorting order
Notes
-----
we should have that index.sorted[inde... | where each item is in the pecking order.
Parameters
----------
keys : indexable object
Returns
-------
ndarray, [keys.size], int
unique integers, ranking the sorting order
Notes
-----
we should have that index.sorted[index.rank] == keys | Below is the the instruction that describes the task:
### Input:
where each item is in the pecking order.
Parameters
----------
keys : indexable object
Returns
-------
ndarray, [keys.size], int
unique integers, ranking the sorting order
Notes
-----
we should have that ... |
def get_args(node):
"""Return the arguments of a node in the event graph."""
arg_roles = {}
args = node.findall('arg') + \
[node.find('arg1'), node.find('arg2'), node.find('arg3')]
for arg in args:
if arg is not None:
id = arg.attrib.get('id')
if id is not None:
... | Return the arguments of a node in the event graph. | Below is the the instruction that describes the task:
### Input:
Return the arguments of a node in the event graph.
### Response:
def get_args(node):
"""Return the arguments of a node in the event graph."""
arg_roles = {}
args = node.findall('arg') + \
[node.find('arg1'), node.find('arg2'), nod... |
def register_email(request):
'''
Register new email.
'''
user = request.user
serializer = RegisterEmailSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
email = serializer.validated_data['email']
template_config = (
registration_settings.REGISTER_EMAIL_VE... | Register new email. | Below is the the instruction that describes the task:
### Input:
Register new email.
### Response:
def register_email(request):
'''
Register new email.
'''
user = request.user
serializer = RegisterEmailSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
email = ser... |
def get_html_tree(filename_url_or_filelike):
"""From some file path, input stream, or URL, construct and return
an HTML tree.
"""
try:
handler = (
HTTPSHandler
if filename_url_or_filelike.lower().startswith('https')
else HTTPHandler
)
... | From some file path, input stream, or URL, construct and return
an HTML tree. | Below is the the instruction that describes the task:
### Input:
From some file path, input stream, or URL, construct and return
an HTML tree.
### Response:
def get_html_tree(filename_url_or_filelike):
"""From some file path, input stream, or URL, construct and return
an HTML tree.
"""
try... |
def _read_nowait(self, n: int) -> bytes:
""" Read not more than n bytes, or whole buffer is n == -1 """
chunks = []
while self._buffer:
chunk = self._read_nowait_chunk(n)
chunks.append(chunk)
if n != -1:
n -= len(chunk)
if n ==... | Read not more than n bytes, or whole buffer is n == -1 | Below is the the instruction that describes the task:
### Input:
Read not more than n bytes, or whole buffer is n == -1
### Response:
def _read_nowait(self, n: int) -> bytes:
""" Read not more than n bytes, or whole buffer is n == -1 """
chunks = []
while self._buffer:
chunk = ... |
def coupl_model8(self):
""" Variant of toggle switch.
"""
self.Coupl = 0.5*self.Adj_signed
# reduce the value of the coupling of the repressing genes
# otherwise completely unstable solutions are obtained
for x in np.nditer(self.Coupl,op_flags=['readwrite']):
... | Variant of toggle switch. | Below is the the instruction that describes the task:
### Input:
Variant of toggle switch.
### Response:
def coupl_model8(self):
""" Variant of toggle switch.
"""
self.Coupl = 0.5*self.Adj_signed
# reduce the value of the coupling of the repressing genes
# otherwise complete... |
def set_mute(mute_value):
"Browse for mute usages and set value"
all_mutes = ( \
(0x8, 0x9), # LED page
(0x1, 0xA7), # desktop page
(0xb, 0x2f),
)
all_target_usages = [hid.get_full_usage_id(u[0], u[1]) for u in all_mutes]
# usually you'll find and open the target... | Browse for mute usages and set value | Below is the the instruction that describes the task:
### Input:
Browse for mute usages and set value
### Response:
def set_mute(mute_value):
"Browse for mute usages and set value"
all_mutes = ( \
(0x8, 0x9), # LED page
(0x1, 0xA7), # desktop page
(0xb, 0x2f),
)
... |
def stack_template_key_name(blueprint):
"""Given a blueprint, produce an appropriate key name.
Args:
blueprint (:class:`stacker.blueprints.base.Blueprint`): The blueprint
object to create the key from.
Returns:
string: Key name resulting from blueprint.
"""
name = bluep... | Given a blueprint, produce an appropriate key name.
Args:
blueprint (:class:`stacker.blueprints.base.Blueprint`): The blueprint
object to create the key from.
Returns:
string: Key name resulting from blueprint. | Below is the the instruction that describes the task:
### Input:
Given a blueprint, produce an appropriate key name.
Args:
blueprint (:class:`stacker.blueprints.base.Blueprint`): The blueprint
object to create the key from.
Returns:
string: Key name resulting from blueprint.
##... |
def _add_two_way_unqualified_edge(self, u: BaseEntity, v: BaseEntity, relation: str) -> str:
"""Add an unqualified edge both ways."""
self.add_unqualified_edge(v, u, relation)
return self.add_unqualified_edge(u, v, relation) | Add an unqualified edge both ways. | Below is the the instruction that describes the task:
### Input:
Add an unqualified edge both ways.
### Response:
def _add_two_way_unqualified_edge(self, u: BaseEntity, v: BaseEntity, relation: str) -> str:
"""Add an unqualified edge both ways."""
self.add_unqualified_edge(v, u, relation)
r... |
def make_executable(query):
"""make_executable(query) -- give executable permissions to a given file
"""
filename = support.get_file_name(query)
if(os.path.isfile(filename)):
os.system('chmod +x '+filename)
else:
print 'file not found' | make_executable(query) -- give executable permissions to a given file | Below is the the instruction that describes the task:
### Input:
make_executable(query) -- give executable permissions to a given file
### Response:
def make_executable(query):
"""make_executable(query) -- give executable permissions to a given file
"""
filename = support.get_file_name(query)
if(os.path.isfile... |
def version(user=None, host=None, port=None, maintenance_db=None,
password=None, runas=None):
'''
Return the version of a Postgres server.
CLI Example:
.. code-block:: bash
salt '*' postgres.version
'''
query = 'SELECT setting FROM pg_catalog.pg_settings ' \
'W... | Return the version of a Postgres server.
CLI Example:
.. code-block:: bash
salt '*' postgres.version | Below is the the instruction that describes the task:
### Input:
Return the version of a Postgres server.
CLI Example:
.. code-block:: bash
salt '*' postgres.version
### Response:
def version(user=None, host=None, port=None, maintenance_db=None,
password=None, runas=None):
'''
... |
def pruning(self, X, y, cost_mat):
""" Function that prune the decision tree.
Parameters
----------
X : array-like of shape = [n_samples, n_features]
The input samples.
y_true : array indicator matrix
Ground truth (correct) labels.
cost_mat : a... | Function that prune the decision tree.
Parameters
----------
X : array-like of shape = [n_samples, n_features]
The input samples.
y_true : array indicator matrix
Ground truth (correct) labels.
cost_mat : array-like of shape = [n_samples, 4]
... | Below is the the instruction that describes the task:
### Input:
Function that prune the decision tree.
Parameters
----------
X : array-like of shape = [n_samples, n_features]
The input samples.
y_true : array indicator matrix
Ground truth (correct) labels.... |
def __analizar_evento(self, ret):
"Comprueba y extrae el wvento informativo si existen en la respuesta XML"
evt = ret.get('evento')
if evt:
self.Eventos = [evt]
self.Evento = "%(codigo)s: %(descripcion)s" % evt | Comprueba y extrae el wvento informativo si existen en la respuesta XML | Below is the the instruction that describes the task:
### Input:
Comprueba y extrae el wvento informativo si existen en la respuesta XML
### Response:
def __analizar_evento(self, ret):
"Comprueba y extrae el wvento informativo si existen en la respuesta XML"
evt = ret.get('evento')
if evt:
... |
def convert_scope_string_to_expression(scope):
'''**Description**
Internal function to convert a filter string to a filter object to be used with dashboards.
'''
#
# NOTE: The supported grammar is not perfectly aligned with the grammar supported by the Sysdig backend.
... | **Description**
Internal function to convert a filter string to a filter object to be used with dashboards. | Below is the the instruction that describes the task:
### Input:
**Description**
Internal function to convert a filter string to a filter object to be used with dashboards.
### Response:
def convert_scope_string_to_expression(scope):
'''**Description**
Internal function to convert a... |
def _verify_install(desired, new_pkgs, ignore_epoch=False, new_caps=None):
'''
Determine whether or not the installed packages match what was requested in
the SLS file.
'''
ok = []
failed = []
if not new_caps:
new_caps = dict()
for pkgname, pkgver in desired.items():
# Fr... | Determine whether or not the installed packages match what was requested in
the SLS file. | Below is the the instruction that describes the task:
### Input:
Determine whether or not the installed packages match what was requested in
the SLS file.
### Response:
def _verify_install(desired, new_pkgs, ignore_epoch=False, new_caps=None):
'''
Determine whether or not the installed packages match w... |
def post(self, url, post_params=None):
"""
Make an HTTP POST request to the Parser API.
:param url: url to which to make the request
:param post_params: POST data to send along. Expected to be a dict.
"""
post_params['token'] = self.token
params = urlencode(post_... | Make an HTTP POST request to the Parser API.
:param url: url to which to make the request
:param post_params: POST data to send along. Expected to be a dict. | Below is the the instruction that describes the task:
### Input:
Make an HTTP POST request to the Parser API.
:param url: url to which to make the request
:param post_params: POST data to send along. Expected to be a dict.
### Response:
def post(self, url, post_params=None):
"""
Ma... |
def example_reading_spec(self):
"""Return a mix of env and video data fields and decoders."""
video_fields, video_decoders = (
video_utils.VideoProblem.example_reading_spec(self))
env_fields, env_decoders = env_problem.EnvProblem.example_reading_spec(self)
# Remove raw observations field since ... | Return a mix of env and video data fields and decoders. | Below is the the instruction that describes the task:
### Input:
Return a mix of env and video data fields and decoders.
### Response:
def example_reading_spec(self):
"""Return a mix of env and video data fields and decoders."""
video_fields, video_decoders = (
video_utils.VideoProblem.example_read... |
def get_module_by_name(self, modName):
"""
@type modName: int
@param modName:
Name of the module to look for, as returned by L{Module.get_name}.
If two or more modules with the same name are loaded, only one
of the matching modules is returned.
Y... | @type modName: int
@param modName:
Name of the module to look for, as returned by L{Module.get_name}.
If two or more modules with the same name are loaded, only one
of the matching modules is returned.
You can also pass a full pathname to the DLL file.
... | Below is the the instruction that describes the task:
### Input:
@type modName: int
@param modName:
Name of the module to look for, as returned by L{Module.get_name}.
If two or more modules with the same name are loaded, only one
of the matching modules is returned.
... |
def html(self, url, timeout=None):
"""High level method to get http request response in text.
smartly handle the encoding problem.
"""
response = self.get_response(url, timeout=timeout)
if response:
domain = self.get_domain(url)
if domain in self.domain_en... | High level method to get http request response in text.
smartly handle the encoding problem. | Below is the the instruction that describes the task:
### Input:
High level method to get http request response in text.
smartly handle the encoding problem.
### Response:
def html(self, url, timeout=None):
"""High level method to get http request response in text.
smartly handle the encodi... |
def array(self):
"""
The underlying array of shape (N, L, I)
"""
return numpy.array([self[sid].array for sid in sorted(self)]) | The underlying array of shape (N, L, I) | Below is the the instruction that describes the task:
### Input:
The underlying array of shape (N, L, I)
### Response:
def array(self):
"""
The underlying array of shape (N, L, I)
"""
return numpy.array([self[sid].array for sid in sorted(self)]) |
def create_bird_config_files(bird_configuration):
"""Create bird configuration files per IP version.
Creates bird configuration files if they don't exist. It also creates the
directories where we store the history of changes, if this functionality is
enabled.
Arguments:
bird_configuration ... | Create bird configuration files per IP version.
Creates bird configuration files if they don't exist. It also creates the
directories where we store the history of changes, if this functionality is
enabled.
Arguments:
bird_configuration (dict): A dictionary with settings for bird.
Returns... | Below is the the instruction that describes the task:
### Input:
Create bird configuration files per IP version.
Creates bird configuration files if they don't exist. It also creates the
directories where we store the history of changes, if this functionality is
enabled.
Arguments:
bird_co... |
def _make_expanded_field_serializer(
self, name, nested_expand, nested_fields, nested_omit
):
"""
Returns an instance of the dynamically created nested serializer.
"""
field_options = self.expandable_fields[name]
serializer_class = field_options[0]
serializer_... | Returns an instance of the dynamically created nested serializer. | Below is the the instruction that describes the task:
### Input:
Returns an instance of the dynamically created nested serializer.
### Response:
def _make_expanded_field_serializer(
self, name, nested_expand, nested_fields, nested_omit
):
"""
Returns an instance of the dynamically creat... |
def restart_apps_or_services(app_or_service_names=None):
"""Restart any containers associated with Dusty, or associated with
the provided app_or_service_names."""
if app_or_service_names:
log_to_client("Restarting the following apps or services: {}".format(', '.join(app_or_service_names)))
else:... | Restart any containers associated with Dusty, or associated with
the provided app_or_service_names. | Below is the the instruction that describes the task:
### Input:
Restart any containers associated with Dusty, or associated with
the provided app_or_service_names.
### Response:
def restart_apps_or_services(app_or_service_names=None):
"""Restart any containers associated with Dusty, or associated with
... |
def console_output(msg, logging_msg=None):
"""Use instead of print, to clear the status information before printing"""
assert isinstance(msg, bytes)
assert isinstance(logging_msg, bytes) or logging_msg is None
from polysh import remote_dispatcher
remote_dispatcher.log(logging_msg or msg)
if re... | Use instead of print, to clear the status information before printing | Below is the the instruction that describes the task:
### Input:
Use instead of print, to clear the status information before printing
### Response:
def console_output(msg, logging_msg=None):
"""Use instead of print, to clear the status information before printing"""
assert isinstance(msg, bytes)
asser... |
def send_document(self, chat_id, data, reply_to_message_id=None, caption=None, reply_markup=None,
parse_mode=None, disable_notification=None, timeout=None):
"""
Use this method to send general files.
:param chat_id:
:param data:
:param reply_to_message_id:
... | Use this method to send general files.
:param chat_id:
:param data:
:param reply_to_message_id:
:param reply_markup:
:param parse_mode:
:param disable_notification:
:return: API reply. | Below is the the instruction that describes the task:
### Input:
Use this method to send general files.
:param chat_id:
:param data:
:param reply_to_message_id:
:param reply_markup:
:param parse_mode:
:param disable_notification:
:return: API reply.
### Respon... |
def evaluate_dir(sample_dir):
"""Evaluate all recordings in `sample_dir`.
Parameters
----------
sample_dir : string
The path to a directory with *.inkml files.
Returns
-------
list of dictionaries
Each dictionary contains the keys 'filename' and 'results', where
're... | Evaluate all recordings in `sample_dir`.
Parameters
----------
sample_dir : string
The path to a directory with *.inkml files.
Returns
-------
list of dictionaries
Each dictionary contains the keys 'filename' and 'results', where
'results' itself is a list of dictionari... | Below is the the instruction that describes the task:
### Input:
Evaluate all recordings in `sample_dir`.
Parameters
----------
sample_dir : string
The path to a directory with *.inkml files.
Returns
-------
list of dictionaries
Each dictionary contains the keys 'filename' ... |
def _sim_prediction(self, theta, theta_t, Y, scores, h, t_params, simulations):
""" Simulates a h-step ahead mean prediction
Parameters
----------
theta : np.array
The past predicted values
theta_t : np.array
The past local linear trend
Y : np.a... | Simulates a h-step ahead mean prediction
Parameters
----------
theta : np.array
The past predicted values
theta_t : np.array
The past local linear trend
Y : np.array
The past data
scores : np.array
The past scores
... | Below is the the instruction that describes the task:
### Input:
Simulates a h-step ahead mean prediction
Parameters
----------
theta : np.array
The past predicted values
theta_t : np.array
The past local linear trend
Y : np.array
The pa... |
def check_key(self, key):
"""Checks key and add key_prefix."""
return _check_key(key, allow_unicode_keys=self.allow_unicode_keys,
key_prefix=self.key_prefix) | Checks key and add key_prefix. | Below is the the instruction that describes the task:
### Input:
Checks key and add key_prefix.
### Response:
def check_key(self, key):
"""Checks key and add key_prefix."""
return _check_key(key, allow_unicode_keys=self.allow_unicode_keys,
key_prefix=self.key_prefix) |
def cv_compute(self, b, A, B, C, mK, f, m1, m2):
'''
Compute the model (cross-validation step only) for chunk :py:obj:`b`.
'''
A = np.sum([l * a for l, a in zip(self.lam[b], A)
if l is not None], axis=0)
B = np.sum([l * b for l, b in zip(self.lam[b], B)
... | Compute the model (cross-validation step only) for chunk :py:obj:`b`. | Below is the the instruction that describes the task:
### Input:
Compute the model (cross-validation step only) for chunk :py:obj:`b`.
### Response:
def cv_compute(self, b, A, B, C, mK, f, m1, m2):
'''
Compute the model (cross-validation step only) for chunk :py:obj:`b`.
'''
A = n... |
def approx_count_distinct(col, rsd=None):
"""Aggregate function: returns a new :class:`Column` for approximate distinct count of
column `col`.
:param rsd: maximum estimation error allowed (default = 0.05). For rsd < 0.01, it is more
efficient to use :func:`countDistinct`
>>> df.agg(approx_coun... | Aggregate function: returns a new :class:`Column` for approximate distinct count of
column `col`.
:param rsd: maximum estimation error allowed (default = 0.05). For rsd < 0.01, it is more
efficient to use :func:`countDistinct`
>>> df.agg(approx_count_distinct(df.age).alias('distinct_ages')).collec... | Below is the the instruction that describes the task:
### Input:
Aggregate function: returns a new :class:`Column` for approximate distinct count of
column `col`.
:param rsd: maximum estimation error allowed (default = 0.05). For rsd < 0.01, it is more
efficient to use :func:`countDistinct`
>>... |
def media(self):
"""
Combines media of both components and adds a small script that unchecks
the clear box, when a value in any wrapped input is modified.
"""
return self.widget.media + self.checkbox.media + Media(self.Media) | Combines media of both components and adds a small script that unchecks
the clear box, when a value in any wrapped input is modified. | Below is the the instruction that describes the task:
### Input:
Combines media of both components and adds a small script that unchecks
the clear box, when a value in any wrapped input is modified.
### Response:
def media(self):
"""
Combines media of both components and adds a small script... |
def up(force=True, env=None, **kwargs):
"Starts a new experiment"
inventory = os.path.join(os.getcwd(), "hosts")
conf = Configuration.from_dictionnary(provider_conf)
provider = Enos_vagrant(conf)
roles, networks = provider.init()
check_networks(roles, networks)
env["roles"] = roles
env["... | Starts a new experiment | Below is the the instruction that describes the task:
### Input:
Starts a new experiment
### Response:
def up(force=True, env=None, **kwargs):
"Starts a new experiment"
inventory = os.path.join(os.getcwd(), "hosts")
conf = Configuration.from_dictionnary(provider_conf)
provider = Enos_vagrant(conf)
... |
def drop_indexes(self):
"""Delete all indexes for the database"""
LOG.warning("Dropping all indexe")
for collection_name in INDEXES:
LOG.warning("Dropping all indexes for collection name %s", collection_name)
self.db[collection_name].drop_indexes() | Delete all indexes for the database | Below is the the instruction that describes the task:
### Input:
Delete all indexes for the database
### Response:
def drop_indexes(self):
"""Delete all indexes for the database"""
LOG.warning("Dropping all indexe")
for collection_name in INDEXES:
LOG.warning("Dropping all index... |
def to_native_types(self, slicer=None, **kwargs):
"""
Format specified values of `self` and return them.
Parameters
----------
slicer : int, array-like
An indexer into `self` that specifies which values
are used in the formatting process.
kwargs :... | Format specified values of `self` and return them.
Parameters
----------
slicer : int, array-like
An indexer into `self` that specifies which values
are used in the formatting process.
kwargs : dict
Options for specifying how the values should be form... | Below is the the instruction that describes the task:
### Input:
Format specified values of `self` and return them.
Parameters
----------
slicer : int, array-like
An indexer into `self` that specifies which values
are used in the formatting process.
kwargs : ... |
def computeStatistics(tped, tfam, snps):
"""Computes the completion and concordance of each SNPs.
:param tped: a representation of the ``tped``.
:param tfam: a representation of the ``tfam``
:param snps: the position of the duplicated markers in the ``tped``.
:type tped: numpy.array
:type tfam... | Computes the completion and concordance of each SNPs.
:param tped: a representation of the ``tped``.
:param tfam: a representation of the ``tfam``
:param snps: the position of the duplicated markers in the ``tped``.
:type tped: numpy.array
:type tfam: list
:type snps: dict
:returns: a tup... | Below is the the instruction that describes the task:
### Input:
Computes the completion and concordance of each SNPs.
:param tped: a representation of the ``tped``.
:param tfam: a representation of the ``tfam``
:param snps: the position of the duplicated markers in the ``tped``.
:type tped: numpy... |
def send_message(self,body):
"""
Send a message to the room.
:Parameters:
- `body`: the message body.
:Types:
- `body`: `unicode`
"""
m=Message(to_jid=self.room_jid.bare(),stanza_type="groupchat",body=body)
self.manager.stream.send(m) | Send a message to the room.
:Parameters:
- `body`: the message body.
:Types:
- `body`: `unicode` | Below is the the instruction that describes the task:
### Input:
Send a message to the room.
:Parameters:
- `body`: the message body.
:Types:
- `body`: `unicode`
### Response:
def send_message(self,body):
"""
Send a message to the room.
:Parameters:... |
def parse_declaration_expressn_fncall(self, name, params, es):
"""
Parses out cromwell's built-in function calls.
Some of these are special
and need minor adjustments, for example length(), which is equivalent to
python's len() function. Or sub, which is equivalent to re.sub(),... | Parses out cromwell's built-in function calls.
Some of these are special
and need minor adjustments, for example length(), which is equivalent to
python's len() function. Or sub, which is equivalent to re.sub(), but
needs a rearrangement of input variables.
Known to be support... | Below is the the instruction that describes the task:
### Input:
Parses out cromwell's built-in function calls.
Some of these are special
and need minor adjustments, for example length(), which is equivalent to
python's len() function. Or sub, which is equivalent to re.sub(), but
n... |
def push(self, new_scope=None):
"""Create a new scope
:returns: TODO
"""
if new_scope is None:
new_scope = {
"types": {},
"vars": {}
}
self._curr_scope = new_scope
self._dlog("pushing new scope, scope level = {}".fo... | Create a new scope
:returns: TODO | Below is the the instruction that describes the task:
### Input:
Create a new scope
:returns: TODO
### Response:
def push(self, new_scope=None):
"""Create a new scope
:returns: TODO
"""
if new_scope is None:
new_scope = {
"types": {},
... |
def loglike(self):
'''
The summed log-probability of all stochastic variables that depend on
self.stochastics, with self.stochastics removed.
'''
sum = logp_of_set(self.children)
if self.verbose > 2:
print_('\t' + self._id + ' Current log-likelihood ', sum)
... | The summed log-probability of all stochastic variables that depend on
self.stochastics, with self.stochastics removed. | Below is the the instruction that describes the task:
### Input:
The summed log-probability of all stochastic variables that depend on
self.stochastics, with self.stochastics removed.
### Response:
def loglike(self):
'''
The summed log-probability of all stochastic variables that depend on
... |
def _update_search_index(*, instance, index, update_fields):
"""Process index / update search index update actions."""
if not _in_search_queryset(instance=instance, index=index):
logger.debug(
"Object (%r) is not in search queryset, ignoring update.", instance
)
return
t... | Process index / update search index update actions. | Below is the the instruction that describes the task:
### Input:
Process index / update search index update actions.
### Response:
def _update_search_index(*, instance, index, update_fields):
"""Process index / update search index update actions."""
if not _in_search_queryset(instance=instance, index=index... |
def up(self, path, fileobject, upload_callback=None, resume_offset=None):
"Upload a fileobject to path, HTTP POST-ing to up.jottacloud.com, using the JottaCloud API"
"""
*** WHAT DID I DO?: created file
***
POST https://up.jottacloud.com/jfs/**USERNAME**/Jotta/Sync/testFolder/t... | Upload a fileobject to path, HTTP POST-ing to up.jottacloud.com, using the JottaCloud API | Below is the the instruction that describes the task:
### Input:
Upload a fileobject to path, HTTP POST-ing to up.jottacloud.com, using the JottaCloud API
### Response:
def up(self, path, fileobject, upload_callback=None, resume_offset=None):
"Upload a fileobject to path, HTTP POST-ing to up.jottacloud.com... |
def _generate_examples(self, filepaths):
"""Generate CIFAR examples as dicts.
Shared across CIFAR-{10, 100}. Uses self._cifar_info as
configuration.
Args:
filepaths (list[str]): The files to use to generate the data.
Yields:
The cifar examples, as defined in the dataset info features.... | Generate CIFAR examples as dicts.
Shared across CIFAR-{10, 100}. Uses self._cifar_info as
configuration.
Args:
filepaths (list[str]): The files to use to generate the data.
Yields:
The cifar examples, as defined in the dataset info features. | Below is the the instruction that describes the task:
### Input:
Generate CIFAR examples as dicts.
Shared across CIFAR-{10, 100}. Uses self._cifar_info as
configuration.
Args:
filepaths (list[str]): The files to use to generate the data.
Yields:
The cifar examples, as defined in the d... |
def get_variable_grammar(self):
"""
A method that returns variable grammar
"""
# Defining a expression for valid word
word_expr = Word(alphanums + '_' + '-')
word_expr2 = Word(initChars=printables, excludeChars=['{', '}', ',', ' '])
name_expr = Suppress('variable... | A method that returns variable grammar | Below is the the instruction that describes the task:
### Input:
A method that returns variable grammar
### Response:
def get_variable_grammar(self):
"""
A method that returns variable grammar
"""
# Defining a expression for valid word
word_expr = Word(alphanums + '_' + '-'... |
def y(self):
'''
np.array: The grid points in y.
'''
if None not in (self.y_min, self.y_max, self.y_step) and \
self.y_min != self.y_max:
y = np.arange(self.y_min, self.y_max-self.y_step*0.1, self.y_step)
else:
y = np.array([])
retu... | np.array: The grid points in y. | Below is the the instruction that describes the task:
### Input:
np.array: The grid points in y.
### Response:
def y(self):
'''
np.array: The grid points in y.
'''
if None not in (self.y_min, self.y_max, self.y_step) and \
self.y_min != self.y_max:
y = np... |
def add_moveTo(self, x, y):
"""Return a newly created `a:moveTo` subtree with point *(x, y)*.
The new `a:moveTo` element is appended to this `a:path` element.
"""
moveTo = self._add_moveTo()
pt = moveTo._add_pt()
pt.x, pt.y = x, y
return moveTo | Return a newly created `a:moveTo` subtree with point *(x, y)*.
The new `a:moveTo` element is appended to this `a:path` element. | Below is the the instruction that describes the task:
### Input:
Return a newly created `a:moveTo` subtree with point *(x, y)*.
The new `a:moveTo` element is appended to this `a:path` element.
### Response:
def add_moveTo(self, x, y):
"""Return a newly created `a:moveTo` subtree with point *(x, y)... |
def bulk_add(self, item_id, ref_id=None, tags=None,
time=None, title=None, url=None):
"""
Add an item to list
See: https://getpocket.com/developer/docs/v3/modify
:param item_id: int
:param ref_id: tweet_id
:param tags: list of tags
:param time: ti... | Add an item to list
See: https://getpocket.com/developer/docs/v3/modify
:param item_id: int
:param ref_id: tweet_id
:param tags: list of tags
:param time: time of action
:param title: given title
:param url: item url
:return: self for chaining
:rty... | Below is the the instruction that describes the task:
### Input:
Add an item to list
See: https://getpocket.com/developer/docs/v3/modify
:param item_id: int
:param ref_id: tweet_id
:param tags: list of tags
:param time: time of action
:param title: given title
... |
async def parse_release_results(soup):
"""
Parse Releases search pages.
:param soup: The BS4 class object
:return: A list of dictionaries containing a release dictionary. This is the same as the one returned in get_novel.
It contains a Date released, Platform, Ages group and Name.
"""
... | Parse Releases search pages.
:param soup: The BS4 class object
:return: A list of dictionaries containing a release dictionary. This is the same as the one returned in get_novel.
It contains a Date released, Platform, Ages group and Name. | Below is the the instruction that describes the task:
### Input:
Parse Releases search pages.
:param soup: The BS4 class object
:return: A list of dictionaries containing a release dictionary. This is the same as the one returned in get_novel.
It contains a Date released, Platform, Ages group ... |
def delete_agent_cloud(self, agent_cloud_id):
"""DeleteAgentCloud.
[Preview API]
:param int agent_cloud_id:
:rtype: :class:`<TaskAgentCloud> <azure.devops.v5_1.task-agent.models.TaskAgentCloud>`
"""
route_values = {}
if agent_cloud_id is not None:
rout... | DeleteAgentCloud.
[Preview API]
:param int agent_cloud_id:
:rtype: :class:`<TaskAgentCloud> <azure.devops.v5_1.task-agent.models.TaskAgentCloud>` | Below is the the instruction that describes the task:
### Input:
DeleteAgentCloud.
[Preview API]
:param int agent_cloud_id:
:rtype: :class:`<TaskAgentCloud> <azure.devops.v5_1.task-agent.models.TaskAgentCloud>`
### Response:
def delete_agent_cloud(self, agent_cloud_id):
"""DeleteAge... |
def get_scrollbar_value_height(self):
"""Return the value span height of the scrollbar"""
vsb = self.editor.verticalScrollBar()
return vsb.maximum()-vsb.minimum()+vsb.pageStep() | Return the value span height of the scrollbar | Below is the the instruction that describes the task:
### Input:
Return the value span height of the scrollbar
### Response:
def get_scrollbar_value_height(self):
"""Return the value span height of the scrollbar"""
vsb = self.editor.verticalScrollBar()
return vsb.maximum()-vsb.minimum()+vsb... |
def _is_valid_dataset(config_value):
'''Datasets must be of form "project.dataset" or "dataset"
'''
return re.match(
# regex matches: project.table -- OR -- table
r'^' + RE_PROJECT + r'\.' + RE_DS_TABLE + r'$|^' + RE_DS_TABLE + r'$',
config_value,
) | Datasets must be of form "project.dataset" or "dataset" | Below is the the instruction that describes the task:
### Input:
Datasets must be of form "project.dataset" or "dataset"
### Response:
def _is_valid_dataset(config_value):
'''Datasets must be of form "project.dataset" or "dataset"
'''
return re.match(
# regex matches: project.table -- OR -- tab... |
def get_inspector():
"""Reuse inspector"""
global _INSPECTOR
if _INSPECTOR:
return _INSPECTOR
else:
bind = op.get_bind()
_INSPECTOR = sa.engine.reflection.Inspector.from_engine(bind)
return _INSPECTOR | Reuse inspector | Below is the the instruction that describes the task:
### Input:
Reuse inspector
### Response:
def get_inspector():
"""Reuse inspector"""
global _INSPECTOR
if _INSPECTOR:
return _INSPECTOR
else:
bind = op.get_bind()
_INSPECTOR = sa.engine.reflection.Inspector.from_engine(... |
def autoconfig_url_from_preferences():
"""
Get the PAC ``AutoConfigURL`` value from the macOS System Preferences.
This setting is visible as the "URL" field in
System Preferences > Network > Advanced... > Proxies > Automatic Proxy Configuration.
:return: The value from the registry, or None i... | Get the PAC ``AutoConfigURL`` value from the macOS System Preferences.
This setting is visible as the "URL" field in
System Preferences > Network > Advanced... > Proxies > Automatic Proxy Configuration.
:return: The value from the registry, or None if the value isn't configured or available.
N... | Below is the the instruction that describes the task:
### Input:
Get the PAC ``AutoConfigURL`` value from the macOS System Preferences.
This setting is visible as the "URL" field in
System Preferences > Network > Advanced... > Proxies > Automatic Proxy Configuration.
:return: The value from the reg... |
def Vector(self, off):
"""Vector retrieves the start of data of the vector whose offset is
stored at "off" in this object."""
N.enforce_number(off, N.UOffsetTFlags)
off += self.Pos
x = off + self.Get(N.UOffsetTFlags, off)
# data starts after metadata containing the ve... | Vector retrieves the start of data of the vector whose offset is
stored at "off" in this object. | Below is the the instruction that describes the task:
### Input:
Vector retrieves the start of data of the vector whose offset is
stored at "off" in this object.
### Response:
def Vector(self, off):
"""Vector retrieves the start of data of the vector whose offset is
stored at "off" in... |
def message(self, message: Message, rule: Optional[int]) -> None:
"""
Add a message to the appropriate list of messages. If `rule` refers
to a valid id range for a go rule, the message is entered in a list
keyed by the full gorule-{id}. Otherwise, if `rule` is None, or
outside th... | Add a message to the appropriate list of messages. If `rule` refers
to a valid id range for a go rule, the message is entered in a list
keyed by the full gorule-{id}. Otherwise, if `rule` is None, or
outside the id range, then we put this in the catch-all "other"
keyed list of messages. | Below is the the instruction that describes the task:
### Input:
Add a message to the appropriate list of messages. If `rule` refers
to a valid id range for a go rule, the message is entered in a list
keyed by the full gorule-{id}. Otherwise, if `rule` is None, or
outside the id range, then ... |
def iter_items(self, start_key=None, end_key=None, reverse=False):
"""Iterates over the (key, value) items of the associated tree,
in ascending order if reverse is True, iterate in descending order,
reverse defaults to False"""
# optimized iterator (reduced method calls) - faster on CPy... | Iterates over the (key, value) items of the associated tree,
in ascending order if reverse is True, iterate in descending order,
reverse defaults to False | Below is the the instruction that describes the task:
### Input:
Iterates over the (key, value) items of the associated tree,
in ascending order if reverse is True, iterate in descending order,
reverse defaults to False
### Response:
def iter_items(self, start_key=None, end_key=None, reverse=False... |
def as_int_array(self):
"""
Convert self into a regular ndarray of ints.
This is an O(1) operation. It does not copy the underlying data.
"""
return self.view(
type=ndarray,
dtype=unsigned_int_dtype_with_size_in_bytes(self.itemsize),
) | Convert self into a regular ndarray of ints.
This is an O(1) operation. It does not copy the underlying data. | Below is the the instruction that describes the task:
### Input:
Convert self into a regular ndarray of ints.
This is an O(1) operation. It does not copy the underlying data.
### Response:
def as_int_array(self):
"""
Convert self into a regular ndarray of ints.
This is an O(1) ope... |
def parse_GFF_attribute_string(attrStr, extra_return_first_value=False):
"""Parses a GFF attribute string and returns it as a dictionary.
If 'extra_return_first_value' is set, a pair is returned: the dictionary
and the value of the first attribute. This might be useful if this is the
ID.
"""
if... | Parses a GFF attribute string and returns it as a dictionary.
If 'extra_return_first_value' is set, a pair is returned: the dictionary
and the value of the first attribute. This might be useful if this is the
ID. | Below is the the instruction that describes the task:
### Input:
Parses a GFF attribute string and returns it as a dictionary.
If 'extra_return_first_value' is set, a pair is returned: the dictionary
and the value of the first attribute. This might be useful if this is the
ID.
### Response:
def parse_... |
def hicpro_pairing_chart (self):
""" Generate Pairing chart """
# Specify the order of the different possible categories
keys = OrderedDict()
keys['Unique_paired_alignments'] = { 'color': '#005ce6', 'name': 'Uniquely Aligned' }
keys['Low_qual_pairs'] = { 'color': '#b97b35', 'nam... | Generate Pairing chart | Below is the the instruction that describes the task:
### Input:
Generate Pairing chart
### Response:
def hicpro_pairing_chart (self):
""" Generate Pairing chart """
# Specify the order of the different possible categories
keys = OrderedDict()
keys['Unique_paired_alignments'] = { '... |
def read_very_lazy(self):
"""Return any data available in the cooked queue (very lazy).
Raise EOFError if connection closed and no data available.
Return '' if no cooked data available otherwise. Don't block.
"""
buf = self.cookedq.getvalue()
self.cookedq.seek(0)
... | Return any data available in the cooked queue (very lazy).
Raise EOFError if connection closed and no data available.
Return '' if no cooked data available otherwise. Don't block. | Below is the the instruction that describes the task:
### Input:
Return any data available in the cooked queue (very lazy).
Raise EOFError if connection closed and no data available.
Return '' if no cooked data available otherwise. Don't block.
### Response:
def read_very_lazy(self):
"""R... |
def lm_ffinal(freqs, damping_times, modes):
"""Return the maximum f_final of the modes given, with f_final the frequency
at which the amplitude falls to 1/1000 of the peak amplitude
"""
f_max = {}
for lmn in modes:
l, m, nmodes = int(lmn[0]), int(lmn[1]), int(lmn[2])
for n in range(... | Return the maximum f_final of the modes given, with f_final the frequency
at which the amplitude falls to 1/1000 of the peak amplitude | Below is the the instruction that describes the task:
### Input:
Return the maximum f_final of the modes given, with f_final the frequency
at which the amplitude falls to 1/1000 of the peak amplitude
### Response:
def lm_ffinal(freqs, damping_times, modes):
"""Return the maximum f_final of the modes given,... |
def bake(self):
"""
Bake an `ansible-lint` command so it's ready to execute and returns
None.
:return: None
"""
options = self.options
default_exclude_list = options.pop('default_exclude')
options_exclude_list = options.pop('exclude')
excludes = d... | Bake an `ansible-lint` command so it's ready to execute and returns
None.
:return: None | Below is the the instruction that describes the task:
### Input:
Bake an `ansible-lint` command so it's ready to execute and returns
None.
:return: None
### Response:
def bake(self):
"""
Bake an `ansible-lint` command so it's ready to execute and returns
None.
:ret... |
def fabs(x):
"""
Absolute value function
"""
if isinstance(x, UncertainFunction):
mcpts = np.fabs(x._mcpts)
return UncertainFunction(mcpts)
else:
return np.fabs(x) | Absolute value function | Below is the the instruction that describes the task:
### Input:
Absolute value function
### Response:
def fabs(x):
"""
Absolute value function
"""
if isinstance(x, UncertainFunction):
mcpts = np.fabs(x._mcpts)
return UncertainFunction(mcpts)
else:
return np.fabs(x) |
def h2o_median_absolute_error(y_actual, y_predicted):
"""
Median absolute error regression loss
:param y_actual: H2OFrame of actual response.
:param y_predicted: H2OFrame of predicted response.
:returns: median absolute error loss (best is 0.0)
"""
ModelBase._check_targets(y_actual, y_predi... | Median absolute error regression loss
:param y_actual: H2OFrame of actual response.
:param y_predicted: H2OFrame of predicted response.
:returns: median absolute error loss (best is 0.0) | Below is the the instruction that describes the task:
### Input:
Median absolute error regression loss
:param y_actual: H2OFrame of actual response.
:param y_predicted: H2OFrame of predicted response.
:returns: median absolute error loss (best is 0.0)
### Response:
def h2o_median_absolute_error(y_actu... |
def process_payment(self):
'''
Proceed with payment using the payment method selected earlier.
:return: A response having processes the payment.
:rtype: requests.Response
'''
params = {
'__RequestVerificationToken': self.session.cookies,
'method':... | Proceed with payment using the payment method selected earlier.
:return: A response having processes the payment.
:rtype: requests.Response | Below is the the instruction that describes the task:
### Input:
Proceed with payment using the payment method selected earlier.
:return: A response having processes the payment.
:rtype: requests.Response
### Response:
def process_payment(self):
'''
Proceed with payment using the p... |
def draw(self):
'''
Draws samples from the `fake` distribution.
Returns:
`np.ndarray` of samples.
'''
observed_arr = self.noise_sampler.generate()
_ = self.__encoder_decoder_controller.encoder.inference(observed_arr)
arr = self.__encoder_deco... | Draws samples from the `fake` distribution.
Returns:
`np.ndarray` of samples. | Below is the the instruction that describes the task:
### Input:
Draws samples from the `fake` distribution.
Returns:
`np.ndarray` of samples.
### Response:
def draw(self):
'''
Draws samples from the `fake` distribution.
Returns:
`np.ndarray` of sam... |
def set_default_unit_all(self, twig=None, unit=None, **kwargs):
"""
TODO: add documentation
"""
if twig is not None and unit is None:
# then try to support value as the first argument if no matches with twigs
if isinstance(unit, u.Unit) or not isinstance(twig, str... | TODO: add documentation | Below is the the instruction that describes the task:
### Input:
TODO: add documentation
### Response:
def set_default_unit_all(self, twig=None, unit=None, **kwargs):
"""
TODO: add documentation
"""
if twig is not None and unit is None:
# then try to support value as the... |
def on_step_end(self, step, logs={}):
""" Called at end of each step for each callback in callbackList"""
for callback in self.callbacks:
# Check if callback supports the more appropriate `on_step_end` callback.
# If not, fall back to `on_batch_end` to be compatible with built-in... | Called at end of each step for each callback in callbackList | Below is the the instruction that describes the task:
### Input:
Called at end of each step for each callback in callbackList
### Response:
def on_step_end(self, step, logs={}):
""" Called at end of each step for each callback in callbackList"""
for callback in self.callbacks:
# Check i... |
def run(self, calc_bleu=True, epoch=None, iteration=None, eval_path=None,
summary=False, reference_path=None):
"""
Runs translation on test dataset.
:param calc_bleu: if True compares results with reference and computes
BLEU score
:param epoch: index of the curre... | Runs translation on test dataset.
:param calc_bleu: if True compares results with reference and computes
BLEU score
:param epoch: index of the current epoch
:param iteration: index of the current iteration
:param eval_path: path to the file for saving results
:param ... | Below is the the instruction that describes the task:
### Input:
Runs translation on test dataset.
:param calc_bleu: if True compares results with reference and computes
BLEU score
:param epoch: index of the current epoch
:param iteration: index of the current iteration
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.