code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def load_string(self, string_data, share_name, directory_name, file_name, **kwargs):
"""
Upload a string to Azure File Share.
:param string_data: String to load.
:type string_data: str
:param share_name: Name of the share.
:type share_name: str
:param directory_n... | Upload a string to Azure File Share.
:param string_data: String to load.
:type string_data: str
:param share_name: Name of the share.
:type share_name: str
:param directory_name: Name of the directory.
:type directory_name: str
:param file_name: Name of the file.... | Below is the the instruction that describes the task:
### Input:
Upload a string to Azure File Share.
:param string_data: String to load.
:type string_data: str
:param share_name: Name of the share.
:type share_name: str
:param directory_name: Name of the directory.
... |
def get_max_id(cls, session):
"""Get the current max value of the ``id`` column.
When creating and storing ORM objects in bulk, :mod:`sqlalchemy` does not automatically
generate an incrementing primary key ``id``. To do this manually, one needs to know the
current max ``id``. For ORM ob... | Get the current max value of the ``id`` column.
When creating and storing ORM objects in bulk, :mod:`sqlalchemy` does not automatically
generate an incrementing primary key ``id``. To do this manually, one needs to know the
current max ``id``. For ORM object classes that are derived from other ... | Below is the the instruction that describes the task:
### Input:
Get the current max value of the ``id`` column.
When creating and storing ORM objects in bulk, :mod:`sqlalchemy` does not automatically
generate an incrementing primary key ``id``. To do this manually, one needs to know the
cu... |
def ok(prompt='OK ', loc={}, glo={}, cmd=""):
'''
Invoke the peforth interpreter.
An statement: peforth.ok(prompt='OK ', loc=locals(), glo=globals(), cmd="")
is like a breakpoint. The prompt indicates which breakpoint it is if there are
many. Arguments loc (locals) and glo (globals) along with the... | Invoke the peforth interpreter.
An statement: peforth.ok(prompt='OK ', loc=locals(), glo=globals(), cmd="")
is like a breakpoint. The prompt indicates which breakpoint it is if there are
many. Arguments loc (locals) and glo (globals) along with the prompt are the
debuggee's informations that is packe... | Below is the the instruction that describes the task:
### Input:
Invoke the peforth interpreter.
An statement: peforth.ok(prompt='OK ', loc=locals(), glo=globals(), cmd="")
is like a breakpoint. The prompt indicates which breakpoint it is if there are
many. Arguments loc (locals) and glo (globals) alo... |
def create_prod_build(self, *args, **kwargs):
"""
Create a production build
:param git_uri: str, URI of git repository
:param git_ref: str, reference to commit
:param git_branch: str, branch name
:param user: str, user name
:param component: str, not used anymore... | Create a production build
:param git_uri: str, URI of git repository
:param git_ref: str, reference to commit
:param git_branch: str, branch name
:param user: str, user name
:param component: str, not used anymore
:param target: str, koji target
:param architectu... | Below is the the instruction that describes the task:
### Input:
Create a production build
:param git_uri: str, URI of git repository
:param git_ref: str, reference to commit
:param git_branch: str, branch name
:param user: str, user name
:param component: str, not used anym... |
def fill_taxid2asscs(taxid2asscs_usr, taxid2asscs_ret):
"""Fill user taxid2asscs for backward compatibility."""
for taxid, ab_ret in taxid2asscs_ret.items():
taxid2asscs_usr[taxid]['ID2GOs'] = ab_ret['ID2GOs']
taxid2asscs_usr[taxid]['GO2IDs'] = ab_ret['GO2IDs'] | Fill user taxid2asscs for backward compatibility. | Below is the the instruction that describes the task:
### Input:
Fill user taxid2asscs for backward compatibility.
### Response:
def fill_taxid2asscs(taxid2asscs_usr, taxid2asscs_ret):
"""Fill user taxid2asscs for backward compatibility."""
for taxid, ab_ret in taxid2asscs_ret.items():
... |
def get_entry(self, entry_name, key):
"""Returns cache entry parameter value by its name.
:param str|unicode entry_name:
:param key:
:return:
"""
return self.cache[entry_name].get(key, False) | Returns cache entry parameter value by its name.
:param str|unicode entry_name:
:param key:
:return: | Below is the the instruction that describes the task:
### Input:
Returns cache entry parameter value by its name.
:param str|unicode entry_name:
:param key:
:return:
### Response:
def get_entry(self, entry_name, key):
"""Returns cache entry parameter value by its name.
:pa... |
def appendPath(self, path):
"""
Appends the inputted path to the end of the sys.path variable,
provided the path does not already exist in it.
:param path
:type str
:return bool: success
"""
# normalize the path
pat... | Appends the inputted path to the end of the sys.path variable,
provided the path does not already exist in it.
:param path
:type str
:return bool: success | Below is the the instruction that describes the task:
### Input:
Appends the inputted path to the end of the sys.path variable,
provided the path does not already exist in it.
:param path
:type str
:return bool: success
### Response:
def appendPath(s... |
def error(self, message):
"""error(message: string)
Prints a usage message incorporating the message to stderr and
exits.
If you override this in a subclass, it should not return -- it
should either exit or raise an exception.
"""
self.print_usage(_sys.... | error(message: string)
Prints a usage message incorporating the message to stderr and
exits.
If you override this in a subclass, it should not return -- it
should either exit or raise an exception. | Below is the the instruction that describes the task:
### Input:
error(message: string)
Prints a usage message incorporating the message to stderr and
exits.
If you override this in a subclass, it should not return -- it
should either exit or raise an exception.
### Response:... |
def expressionToAST(ex):
"""Take an expression tree made out of expressions.ExpressionNode,
and convert to an AST tree.
This is necessary as ExpressionNode overrides many methods to act
like a number.
"""
return ASTNode(ex.astType, ex.astKind, ex.value,
[expressionToAST(c) fo... | Take an expression tree made out of expressions.ExpressionNode,
and convert to an AST tree.
This is necessary as ExpressionNode overrides many methods to act
like a number. | Below is the the instruction that describes the task:
### Input:
Take an expression tree made out of expressions.ExpressionNode,
and convert to an AST tree.
This is necessary as ExpressionNode overrides many methods to act
like a number.
### Response:
def expressionToAST(ex):
"""Take an expression... |
def holm(pvals, alpha=.05):
"""P-values correction with Holm method.
Parameters
----------
pvals : array_like
Array of p-values of the individual tests.
alpha : float
Error rate (= alpha level).
Returns
-------
reject : array, bool
True if a hypothesis is reject... | P-values correction with Holm method.
Parameters
----------
pvals : array_like
Array of p-values of the individual tests.
alpha : float
Error rate (= alpha level).
Returns
-------
reject : array, bool
True if a hypothesis is rejected, False if not
pvals_correcte... | Below is the the instruction that describes the task:
### Input:
P-values correction with Holm method.
Parameters
----------
pvals : array_like
Array of p-values of the individual tests.
alpha : float
Error rate (= alpha level).
Returns
-------
reject : array, bool
... |
def is_integer_array(val):
"""
Checks whether a variable is a numpy integer array.
Parameters
----------
val
The variable to check.
Returns
-------
bool
True if the variable is a numpy integer array. Otherwise False.
"""
return is_np_array(val) and issubclass(v... | Checks whether a variable is a numpy integer array.
Parameters
----------
val
The variable to check.
Returns
-------
bool
True if the variable is a numpy integer array. Otherwise False. | Below is the the instruction that describes the task:
### Input:
Checks whether a variable is a numpy integer array.
Parameters
----------
val
The variable to check.
Returns
-------
bool
True if the variable is a numpy integer array. Otherwise False.
### Response:
def is_i... |
def parse_poi_query(north, south, east, west, amenities=None, timeout=180, maxsize=''):
"""
Parse the Overpass QL query based on the list of amenities.
Parameters
----------
north : float
Northernmost coordinate from bounding box of the search area.
south : float
Southernmo... | Parse the Overpass QL query based on the list of amenities.
Parameters
----------
north : float
Northernmost coordinate from bounding box of the search area.
south : float
Southernmost coordinate from bounding box of the search area.
east : float
Easternmost coordinate ... | Below is the the instruction that describes the task:
### Input:
Parse the Overpass QL query based on the list of amenities.
Parameters
----------
north : float
Northernmost coordinate from bounding box of the search area.
south : float
Southernmost coordinate from bounding box... |
def compile(self, model):
"""Compile this file into a SensorGraph.
You must have preivously called parse_file to parse a
sensor graph file into statements that are then executed
by this command to build a sensor graph.
The results are stored in self.sensor_graph and can be
... | Compile this file into a SensorGraph.
You must have preivously called parse_file to parse a
sensor graph file into statements that are then executed
by this command to build a sensor graph.
The results are stored in self.sensor_graph and can be
inspected before running optimiza... | Below is the the instruction that describes the task:
### Input:
Compile this file into a SensorGraph.
You must have preivously called parse_file to parse a
sensor graph file into statements that are then executed
by this command to build a sensor graph.
The results are stored in s... |
def connect(cls, resource):
"""Connect to this Region's endpoint.
Returns a connection object pointing to the endpoint associated
to the received resource.
"""
import boto
return boto.s3.connect_to_region(cls.get_region(resource)) | Connect to this Region's endpoint.
Returns a connection object pointing to the endpoint associated
to the received resource. | Below is the the instruction that describes the task:
### Input:
Connect to this Region's endpoint.
Returns a connection object pointing to the endpoint associated
to the received resource.
### Response:
def connect(cls, resource):
"""Connect to this Region's endpoint.
Returns a c... |
def make_requests_session():
"""
:returns: requests session
:rtype: :class:`requests.Session`
"""
session = requests.Session()
version = __import__('steam').__version__
ua = "python-steam/{0} {1}".format(version,
session.headers['User-Agent'])
session.hea... | :returns: requests session
:rtype: :class:`requests.Session` | Below is the the instruction that describes the task:
### Input:
:returns: requests session
:rtype: :class:`requests.Session`
### Response:
def make_requests_session():
"""
:returns: requests session
:rtype: :class:`requests.Session`
"""
session = requests.Session()
version = __import_... |
def can_cloak_as(user, other_user):
"""
Returns true if `user` can cloak as `other_user`
"""
# check to see if the user is allowed to do this
can_cloak = False
try:
can_cloak = user.can_cloak_as(other_user)
except AttributeError as e:
try:
can_cloak = user.is_staf... | Returns true if `user` can cloak as `other_user` | Below is the the instruction that describes the task:
### Input:
Returns true if `user` can cloak as `other_user`
### Response:
def can_cloak_as(user, other_user):
"""
Returns true if `user` can cloak as `other_user`
"""
# check to see if the user is allowed to do this
can_cloak = False
try... |
def trigger_dag(args):
"""
Creates a dag run for the specified dag
:param args:
:return:
"""
log = LoggingMixin().log
try:
message = api_client.trigger_dag(dag_id=args.dag_id,
run_id=args.run_id,
conf=a... | Creates a dag run for the specified dag
:param args:
:return: | Below is the the instruction that describes the task:
### Input:
Creates a dag run for the specified dag
:param args:
:return:
### Response:
def trigger_dag(args):
"""
Creates a dag run for the specified dag
:param args:
:return:
"""
log = LoggingMixin().log
try:
message... |
def _add_escape_character_for_quote_prime_character(self, text):
"""
Fix for https://github.com/openatx/facebook-wda/issues/33
Returns:
string with properly formated quotes, or non changed text
"""
if text is not None:
if "'" in text:
return text... | Fix for https://github.com/openatx/facebook-wda/issues/33
Returns:
string with properly formated quotes, or non changed text | Below is the the instruction that describes the task:
### Input:
Fix for https://github.com/openatx/facebook-wda/issues/33
Returns:
string with properly formated quotes, or non changed text
### Response:
def _add_escape_character_for_quote_prime_character(self, text):
"""
Fix fo... |
def create_paste(self, content):
"""Create a raw paste of the given content.
Returns a URL to the paste, or raises a ``pasteraw.Error`` if something
tragic happens instead.
"""
r = requests.post(
self.endpoint + '/pastes',
data={'content': content},
... | Create a raw paste of the given content.
Returns a URL to the paste, or raises a ``pasteraw.Error`` if something
tragic happens instead. | Below is the the instruction that describes the task:
### Input:
Create a raw paste of the given content.
Returns a URL to the paste, or raises a ``pasteraw.Error`` if something
tragic happens instead.
### Response:
def create_paste(self, content):
"""Create a raw paste of the given conten... |
def _splice_index(*key):
"""
Utility for key management in dig/dug
If first elem of key list contains an index[], spread it out as a second
numeric index.
>>> _splice_index('abc[0]', 'def')
('abc', 0, 'def')
>>> _splice_index('abc[a]', 'def')
('abc[a]', 'def')
>>> _splice_index('ab... | Utility for key management in dig/dug
If first elem of key list contains an index[], spread it out as a second
numeric index.
>>> _splice_index('abc[0]', 'def')
('abc', 0, 'def')
>>> _splice_index('abc[a]', 'def')
('abc[a]', 'def')
>>> _splice_index('abc[200]', 'def')
('abc', 200, 'def... | Below is the the instruction that describes the task:
### Input:
Utility for key management in dig/dug
If first elem of key list contains an index[], spread it out as a second
numeric index.
>>> _splice_index('abc[0]', 'def')
('abc', 0, 'def')
>>> _splice_index('abc[a]', 'def')
('abc[a]', ... |
def getPIDStatus(jobStoreName):
"""
Determine the status of a process with a particular pid.
Checks to see if a process exists or not.
:return: A string indicating the status of the PID of the workflow as stored in the jobstore.
:rtype: str
"""
try:
... | Determine the status of a process with a particular pid.
Checks to see if a process exists or not.
:return: A string indicating the status of the PID of the workflow as stored in the jobstore.
:rtype: str | Below is the the instruction that describes the task:
### Input:
Determine the status of a process with a particular pid.
Checks to see if a process exists or not.
:return: A string indicating the status of the PID of the workflow as stored in the jobstore.
:rtype: str
### Response:
def g... |
def find_interface_by_mac(self, **kwargs):
"""Find the interface through which a MAC can be reached.
Args:
mac_address (str): A MAC address in 'xx:xx:xx:xx:xx:xx' format.
Returns:
list[dict]: a list of mac table data.
Raises:
KeyError: if `mac_addre... | Find the interface through which a MAC can be reached.
Args:
mac_address (str): A MAC address in 'xx:xx:xx:xx:xx:xx' format.
Returns:
list[dict]: a list of mac table data.
Raises:
KeyError: if `mac_address` is not specified.
Examples:
>... | Below is the the instruction that describes the task:
### Input:
Find the interface through which a MAC can be reached.
Args:
mac_address (str): A MAC address in 'xx:xx:xx:xx:xx:xx' format.
Returns:
list[dict]: a list of mac table data.
Raises:
KeyError... |
def transpose(self):
"""Create a transpose of this matrix."""
ma4 = Matrix4(self.get_col(0),
self.get_col(1),
self.get_col(2),
self.get_col(3))
return ma4 | Create a transpose of this matrix. | Below is the the instruction that describes the task:
### Input:
Create a transpose of this matrix.
### Response:
def transpose(self):
"""Create a transpose of this matrix."""
ma4 = Matrix4(self.get_col(0),
self.get_col(1),
self.get_col(2),
... |
def auth_none(self, username):
"""
Try to authenticate to the server using no authentication at all.
This will almost always fail. It may be useful for determining the
list of authentication types supported by the server, by catching the
L{BadAuthenticationType} exception raised... | Try to authenticate to the server using no authentication at all.
This will almost always fail. It may be useful for determining the
list of authentication types supported by the server, by catching the
L{BadAuthenticationType} exception raised.
@param username: the username to authent... | Below is the the instruction that describes the task:
### Input:
Try to authenticate to the server using no authentication at all.
This will almost always fail. It may be useful for determining the
list of authentication types supported by the server, by catching the
L{BadAuthenticationType... |
def visit_UnaryOp(self, node):
""" Update range with given unary operation.
>>> import gast as ast
>>> from pythran import passmanager, backend
>>> node = ast.parse('''
... def foo():
... a = 2
... c = -a
... d = ~a
... f = +a
... | Update range with given unary operation.
>>> import gast as ast
>>> from pythran import passmanager, backend
>>> node = ast.parse('''
... def foo():
... a = 2
... c = -a
... d = ~a
... f = +a
... e = not a''')
>>> pm = ... | Below is the the instruction that describes the task:
### Input:
Update range with given unary operation.
>>> import gast as ast
>>> from pythran import passmanager, backend
>>> node = ast.parse('''
... def foo():
... a = 2
... c = -a
... d = ~a
... |
def split_quantities(data, units='units', magnitude='magnitude',
list_of_dicts=False):
""" split pint.Quantity objects into <unit,magnitude> pairs
Parameters
----------
data : dict
units : str
name for units key
magnitude : str
name for magnitude key
lis... | split pint.Quantity objects into <unit,magnitude> pairs
Parameters
----------
data : dict
units : str
name for units key
magnitude : str
name for magnitude key
list_of_dicts: bool
treat list of dicts as additional branches
Examples
--------
>>> from pprint i... | Below is the the instruction that describes the task:
### Input:
split pint.Quantity objects into <unit,magnitude> pairs
Parameters
----------
data : dict
units : str
name for units key
magnitude : str
name for magnitude key
list_of_dicts: bool
treat list of dicts as... |
def _decode_module_id(self, module_id):
"""
decode module id to string
based on @antirez moduleTypeNameByID function from redis/src/module.c
:param module_id: 64bit integer
:return: string
"""
name = [''] * 9
module_id >>= 10
for i in reversed(rang... | decode module id to string
based on @antirez moduleTypeNameByID function from redis/src/module.c
:param module_id: 64bit integer
:return: string | Below is the the instruction that describes the task:
### Input:
decode module id to string
based on @antirez moduleTypeNameByID function from redis/src/module.c
:param module_id: 64bit integer
:return: string
### Response:
def _decode_module_id(self, module_id):
"""
decode ... |
def any_i18n(*args):
""" Return True if any argument appears to be an i18n string. """
for a in args:
if a is not None and not isinstance(a, str):
return True
return False | Return True if any argument appears to be an i18n string. | Below is the the instruction that describes the task:
### Input:
Return True if any argument appears to be an i18n string.
### Response:
def any_i18n(*args):
""" Return True if any argument appears to be an i18n string. """
for a in args:
if a is not None and not isinstance(a, str):
... |
def routers_updated(self, context, routers, operation=None, data=None,
shuffle_agents=False):
"""Notify cfg agents about configuration changes to routers.
This includes operations performed on the router like when a
router interface is added or removed.
"""
... | Notify cfg agents about configuration changes to routers.
This includes operations performed on the router like when a
router interface is added or removed. | Below is the the instruction that describes the task:
### Input:
Notify cfg agents about configuration changes to routers.
This includes operations performed on the router like when a
router interface is added or removed.
### Response:
def routers_updated(self, context, routers, operation=None, da... |
def getDigitalMaximum(self, chn=None):
"""
Returns the maximum digital value of signal edfsignal.
Parameters
----------
chn : int
channel number
Examples
--------
>>> import pyedflib
>>> f = pyedflib.data.test_generator()
>>> ... | Returns the maximum digital value of signal edfsignal.
Parameters
----------
chn : int
channel number
Examples
--------
>>> import pyedflib
>>> f = pyedflib.data.test_generator()
>>> f.getDigitalMaximum(0)
32767
>>> f._close()... | Below is the the instruction that describes the task:
### Input:
Returns the maximum digital value of signal edfsignal.
Parameters
----------
chn : int
channel number
Examples
--------
>>> import pyedflib
>>> f = pyedflib.data.test_generator()
... |
def encode(self, obj):
"""
Take a Python object and return it as a tuple (value, value_type), a
blob and a one-char code for what type it is
"""
if self._is_valid_mysql_bigint(obj):
return obj, 'i'
value = pickle.dumps(obj, pickle.HIGHEST_PROTOCOL)
va... | Take a Python object and return it as a tuple (value, value_type), a
blob and a one-char code for what type it is | Below is the the instruction that describes the task:
### Input:
Take a Python object and return it as a tuple (value, value_type), a
blob and a one-char code for what type it is
### Response:
def encode(self, obj):
"""
Take a Python object and return it as a tuple (value, value_type), a
... |
def store(self, msg, stuff_to_store, *args, **kwargs):
""" Stores a particular item to disk.
The storage service always accepts these parameters:
:param trajectory_name: Name or current trajectory and name of top node in hdf5 file
:param filename: Name of the hdf5 file
:param... | Stores a particular item to disk.
The storage service always accepts these parameters:
:param trajectory_name: Name or current trajectory and name of top node in hdf5 file
:param filename: Name of the hdf5 file
:param file_title: If file needs to be created, assigns a title to the fi... | Below is the the instruction that describes the task:
### Input:
Stores a particular item to disk.
The storage service always accepts these parameters:
:param trajectory_name: Name or current trajectory and name of top node in hdf5 file
:param filename: Name of the hdf5 file
:par... |
def token(self):
""" obtains a token from the site """
if self._token is None or \
datetime.datetime.now() >= self._token_expires_on:
self._generateForOAuthSecurity(self._client_id,
self._secret_id,
... | obtains a token from the site | Below is the the instruction that describes the task:
### Input:
obtains a token from the site
### Response:
def token(self):
""" obtains a token from the site """
if self._token is None or \
datetime.datetime.now() >= self._token_expires_on:
self._generateForOAuthSecurity(se... |
def is_production(flag_name: str = 'PRODUCTION', strict: bool = False):
"""
Reads env ``PRODUCTION`` variable as a boolean.
:param flag_name: environment variable name
:param strict: raise a ``ValueError`` if variable does not look like a normal boolean
:return: ``True`` if has truthy ``PRODUCTION`... | Reads env ``PRODUCTION`` variable as a boolean.
:param flag_name: environment variable name
:param strict: raise a ``ValueError`` if variable does not look like a normal boolean
:return: ``True`` if has truthy ``PRODUCTION`` env, ``False`` otherwise | Below is the the instruction that describes the task:
### Input:
Reads env ``PRODUCTION`` variable as a boolean.
:param flag_name: environment variable name
:param strict: raise a ``ValueError`` if variable does not look like a normal boolean
:return: ``True`` if has truthy ``PRODUCTION`` env, ``False`... |
def rtruncated_normal(mu, tau, a=-np.inf, b=np.inf, size=None):
"""
Random truncated normal variates.
"""
sigma = 1. / np.sqrt(tau)
na = utils.normcdf((a - mu) / sigma)
nb = utils.normcdf((b - mu) / sigma)
# Use the inverse CDF generation method.
U = np.random.mtrand.uniform(size=size)... | Random truncated normal variates. | Below is the the instruction that describes the task:
### Input:
Random truncated normal variates.
### Response:
def rtruncated_normal(mu, tau, a=-np.inf, b=np.inf, size=None):
"""
Random truncated normal variates.
"""
sigma = 1. / np.sqrt(tau)
na = utils.normcdf((a - mu) / sigma)
nb = uti... |
def set_progress(self, scan_id, progress):
""" Sets scan_id scan's progress. """
if progress > 0 and progress <= 100:
self.scans_table[scan_id]['progress'] = progress
if progress == 100:
self.scans_table[scan_id]['end_time'] = int(time.time()) | Sets scan_id scan's progress. | Below is the the instruction that describes the task:
### Input:
Sets scan_id scan's progress.
### Response:
def set_progress(self, scan_id, progress):
""" Sets scan_id scan's progress. """
if progress > 0 and progress <= 100:
self.scans_table[scan_id]['progress'] = progress
if... |
def run_to_rel_pos(self, **kwargs):
"""
Run to a position relative to the current `position` value.
The new position will be current `position` + `position_sp`.
When the new position is reached, the motor will stop using
the action specified by `stop_action`.
"""
... | Run to a position relative to the current `position` value.
The new position will be current `position` + `position_sp`.
When the new position is reached, the motor will stop using
the action specified by `stop_action`. | Below is the the instruction that describes the task:
### Input:
Run to a position relative to the current `position` value.
The new position will be current `position` + `position_sp`.
When the new position is reached, the motor will stop using
the action specified by `stop_action`.
### Res... |
def as_report_request(self, rules, timer=datetime.utcnow):
"""Makes a `ServicecontrolServicesReportRequest` from this instance
Args:
rules (:class:`ReportingRules`): determines what labels, metrics and
logs to include in the report request.
timer: a function that determi... | Makes a `ServicecontrolServicesReportRequest` from this instance
Args:
rules (:class:`ReportingRules`): determines what labels, metrics and
logs to include in the report request.
timer: a function that determines the current time
Return:
a ``ServicecontrolServ... | Below is the the instruction that describes the task:
### Input:
Makes a `ServicecontrolServicesReportRequest` from this instance
Args:
rules (:class:`ReportingRules`): determines what labels, metrics and
logs to include in the report request.
timer: a function that determin... |
def is_dict_like(obj, attr=('keys', 'items')):
"""test if object is dict like"""
for a in attr:
if not hasattr(obj, a):
return False
return True | test if object is dict like | Below is the the instruction that describes the task:
### Input:
test if object is dict like
### Response:
def is_dict_like(obj, attr=('keys', 'items')):
"""test if object is dict like"""
for a in attr:
if not hasattr(obj, a):
return False
return True |
def cee_map_priority_group_table_pfc(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
cee_map = ET.SubElement(config, "cee-map", xmlns="urn:brocade.com:mgmt:brocade-cee-map")
name_key = ET.SubElement(cee_map, "name")
name_key.text = kwargs.pop('na... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def cee_map_priority_group_table_pfc(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
cee_map = ET.SubElement(config, "cee-map", xmlns="urn:brocade.com:mgmt:br... |
def clean_text(text):
"""Clean text before parsing."""
# Replace a few nasty unicode characters with their ASCII equivalent
maps = {u'×': u'x', u'–': u'-', u'−': '-'}
for element in maps:
text = text.replace(element, maps[element])
# Replace genitives
text = re.sub(r'(?<=\w)\'s\b|(?<=\w... | Clean text before parsing. | Below is the the instruction that describes the task:
### Input:
Clean text before parsing.
### Response:
def clean_text(text):
"""Clean text before parsing."""
# Replace a few nasty unicode characters with their ASCII equivalent
maps = {u'×': u'x', u'–': u'-', u'−': '-'}
for element in maps:
... |
def _content(note, content):
"""
content of the note
:param note: note object
:param content: content string to make the main body of the note
:return:
"""
note.content = EvernoteMgr.set_header()
note.content += sanitize(content)
return note | content of the note
:param note: note object
:param content: content string to make the main body of the note
:return: | Below is the the instruction that describes the task:
### Input:
content of the note
:param note: note object
:param content: content string to make the main body of the note
:return:
### Response:
def _content(note, content):
"""
content of the note
:param note: not... |
def DeserializeUnsigned(self, reader):
"""
Deserialize unsigned data only.
Args:
reader (neo.IO.BinaryReader):
"""
self.Version = reader.ReadUInt32()
self.PrevHash = reader.ReadUInt256()
self.MerkleRoot = reader.ReadUInt256()
self.Timestamp = ... | Deserialize unsigned data only.
Args:
reader (neo.IO.BinaryReader): | Below is the the instruction that describes the task:
### Input:
Deserialize unsigned data only.
Args:
reader (neo.IO.BinaryReader):
### Response:
def DeserializeUnsigned(self, reader):
"""
Deserialize unsigned data only.
Args:
reader (neo.IO.BinaryReader):... |
def distance(self, loc):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
"""
assert type(loc) == type(self)
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(radians, [
self.lon,
... | Calculate the great circle distance between two points
on the earth (specified in decimal degrees) | Below is the the instruction that describes the task:
### Input:
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
### Response:
def distance(self, loc):
"""
Calculate the great circle distance between two points
on the earth (specifi... |
def repository_create(name, body, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Create repository for storing snapshots. Note that shared repository paths have to be specified in path.repo Elasticsearch configuration option.
name
Repository name
body
Repository definiti... | .. versionadded:: 2017.7.0
Create repository for storing snapshots. Note that shared repository paths have to be specified in path.repo Elasticsearch configuration option.
name
Repository name
body
Repository definition as in https://www.elastic.co/guide/en/elasticsearch/reference/current/... | Below is the the instruction that describes the task:
### Input:
.. versionadded:: 2017.7.0
Create repository for storing snapshots. Note that shared repository paths have to be specified in path.repo Elasticsearch configuration option.
name
Repository name
body
Repository definition a... |
def mdr_mutual_information(X, Y, labels, base=2):
"""Calculates the MDR mutual information, I(XY;labels), in the given base
MDR mutual information is calculated by combining variables X and Y into a single MDR model then calculating
the mutual information between the resulting model's predictions and the l... | Calculates the MDR mutual information, I(XY;labels), in the given base
MDR mutual information is calculated by combining variables X and Y into a single MDR model then calculating
the mutual information between the resulting model's predictions and the labels.
Parameters
----------
X: array-like (... | Below is the the instruction that describes the task:
### Input:
Calculates the MDR mutual information, I(XY;labels), in the given base
MDR mutual information is calculated by combining variables X and Y into a single MDR model then calculating
the mutual information between the resulting model's predictio... |
def as_part(func):
"""
Converts a function to a :class:`Part <cqparts.Part>` instance.
So the conventionally defined *part*::
import cadquery
from cqparts import Part
from cqparts.params import Float
class Box(Part):
x = Float(1)
y = Float(2)
... | Converts a function to a :class:`Part <cqparts.Part>` instance.
So the conventionally defined *part*::
import cadquery
from cqparts import Part
from cqparts.params import Float
class Box(Part):
x = Float(1)
y = Float(2)
z = Float(4)
... | Below is the the instruction that describes the task:
### Input:
Converts a function to a :class:`Part <cqparts.Part>` instance.
So the conventionally defined *part*::
import cadquery
from cqparts import Part
from cqparts.params import Float
class Box(Part):
x = Fl... |
def check_with_uniform(uf, arg_shapes, dim=None, npuf=None, rmin=-10, type_list=[np.float32]):
"""check function consistency with uniform random numbers"""
if isinstance(arg_shapes, int):
assert dim
shape = tuple(np.random.randint(1, int(1000**(1.0/dim)), size=dim))
arg_shapes = [shape] ... | check function consistency with uniform random numbers | Below is the the instruction that describes the task:
### Input:
check function consistency with uniform random numbers
### Response:
def check_with_uniform(uf, arg_shapes, dim=None, npuf=None, rmin=-10, type_list=[np.float32]):
"""check function consistency with uniform random numbers"""
if isinstance(arg... |
def cut(self):
"""
Cuts the text from the serial to the clipboard.
"""
text = self.selectedText()
for editor in self.editors():
editor.cut()
QtGui.QApplication.clipboard().setText(text) | Cuts the text from the serial to the clipboard. | Below is the the instruction that describes the task:
### Input:
Cuts the text from the serial to the clipboard.
### Response:
def cut(self):
"""
Cuts the text from the serial to the clipboard.
"""
text = self.selectedText()
for editor in self.editors():
ed... |
async def getLiftRows(self, lops):
'''
Returns:
Iterable[Tuple[bytes, Dict[str, Any]]]: yield a stream of tuple (buid, propdict)
'''
for oper in lops:
func = self._lift_funcs.get(oper[0])
if func is None:
raise s_exc.NoSuchLift(name=o... | Returns:
Iterable[Tuple[bytes, Dict[str, Any]]]: yield a stream of tuple (buid, propdict) | Below is the the instruction that describes the task:
### Input:
Returns:
Iterable[Tuple[bytes, Dict[str, Any]]]: yield a stream of tuple (buid, propdict)
### Response:
async def getLiftRows(self, lops):
'''
Returns:
Iterable[Tuple[bytes, Dict[str, Any]]]: yield a stream o... |
def files_generator(path, recursive):
"""Yield files found in a given path.
Walk over a given path finding and yielding all
files found on it. This can be done only on the root
directory or recursively.
Args:
path: Path to the directory.
recursive: Whether to find files recursively... | Yield files found in a given path.
Walk over a given path finding and yielding all
files found on it. This can be done only on the root
directory or recursively.
Args:
path: Path to the directory.
recursive: Whether to find files recursively or not.
Yields:
A tuple for eac... | Below is the the instruction that describes the task:
### Input:
Yield files found in a given path.
Walk over a given path finding and yielding all
files found on it. This can be done only on the root
directory or recursively.
Args:
path: Path to the directory.
recursive: Whether t... |
def _get_underlying_data(self, instance):
"""Return data from raw data store, rather than overridden
__get__ methods. Should NOT be overwritten.
"""
self._touch(instance)
return self.data.get(instance, None) | Return data from raw data store, rather than overridden
__get__ methods. Should NOT be overwritten. | Below is the the instruction that describes the task:
### Input:
Return data from raw data store, rather than overridden
__get__ methods. Should NOT be overwritten.
### Response:
def _get_underlying_data(self, instance):
"""Return data from raw data store, rather than overridden
__get__ met... |
def locally_linear_embedding(self, num_dims=None):
'''Locally Linear Embedding (LLE).
Note: may need to call barycenter_edge_weights() before this!
'''
W = self.matrix()
# compute M = (I-W)'(I-W)
M = W.T.dot(W) - W.T - W
if issparse(M):
M = M.toarray()
M.flat[::M.shape[0] + 1] += 1... | Locally Linear Embedding (LLE).
Note: may need to call barycenter_edge_weights() before this! | Below is the the instruction that describes the task:
### Input:
Locally Linear Embedding (LLE).
Note: may need to call barycenter_edge_weights() before this!
### Response:
def locally_linear_embedding(self, num_dims=None):
'''Locally Linear Embedding (LLE).
Note: may need to call barycenter_edge_weigh... |
def cli(env, identifier):
"""Detail firewall."""
mgr = SoftLayer.FirewallManager(env.client)
firewall_type, firewall_id = firewall.parse_id(identifier)
if firewall_type == 'vlan':
rules = mgr.get_dedicated_fwl_rules(firewall_id)
else:
rules = mgr.get_standard_fwl_rules(firewall_id)... | Detail firewall. | Below is the the instruction that describes the task:
### Input:
Detail firewall.
### Response:
def cli(env, identifier):
"""Detail firewall."""
mgr = SoftLayer.FirewallManager(env.client)
firewall_type, firewall_id = firewall.parse_id(identifier)
if firewall_type == 'vlan':
rules = mgr.g... |
def prevparent(self, parent, depth):
'''
Subtract lines from our curline if the name of a node is prefixed with
the parent directory when traversing the grandparent object.
'''
pdir = os.path.dirname(self.name)
if depth > 1: # can't jump to parent of root node!
... | Subtract lines from our curline if the name of a node is prefixed with
the parent directory when traversing the grandparent object. | Below is the the instruction that describes the task:
### Input:
Subtract lines from our curline if the name of a node is prefixed with
the parent directory when traversing the grandparent object.
### Response:
def prevparent(self, parent, depth):
'''
Subtract lines from our curline if the ... |
def flag_change(self, flags, level, location=None, worksheet=None, message=''):
'''
Wraps the pushing of a change flag into the flags dictionary to handle
all edge cases/auto-filling.
'''
if not isinstance(level, basestring):
try:
level = self.FLAG_LEV... | Wraps the pushing of a change flag into the flags dictionary to handle
all edge cases/auto-filling. | Below is the the instruction that describes the task:
### Input:
Wraps the pushing of a change flag into the flags dictionary to handle
all edge cases/auto-filling.
### Response:
def flag_change(self, flags, level, location=None, worksheet=None, message=''):
'''
Wraps the pushing of a chang... |
def logline_timestamp_comparator(t1, t2):
"""Comparator for timestamps in logline format.
Args:
t1: Timestamp in logline format.
t2: Timestamp in logline format.
Returns:
-1 if t1 < t2; 1 if t1 > t2; 0 if t1 == t2.
"""
dt1 = _parse_logline_timestamp(t1)
dt2 = _parse_log... | Comparator for timestamps in logline format.
Args:
t1: Timestamp in logline format.
t2: Timestamp in logline format.
Returns:
-1 if t1 < t2; 1 if t1 > t2; 0 if t1 == t2. | Below is the the instruction that describes the task:
### Input:
Comparator for timestamps in logline format.
Args:
t1: Timestamp in logline format.
t2: Timestamp in logline format.
Returns:
-1 if t1 < t2; 1 if t1 > t2; 0 if t1 == t2.
### Response:
def logline_timestamp_comparator... |
def create_actor_tri(pts, tris, color, **kwargs):
""" Creates a VTK actor for rendering triangulated surface plots.
:param pts: points
:type pts: vtkFloatArray
:param tris: list of triangle indices
:type tris: ndarray
:param color: actor color
:type color: list
:return: a VTK actor
... | Creates a VTK actor for rendering triangulated surface plots.
:param pts: points
:type pts: vtkFloatArray
:param tris: list of triangle indices
:type tris: ndarray
:param color: actor color
:type color: list
:return: a VTK actor
:rtype: vtkActor | Below is the the instruction that describes the task:
### Input:
Creates a VTK actor for rendering triangulated surface plots.
:param pts: points
:type pts: vtkFloatArray
:param tris: list of triangle indices
:type tris: ndarray
:param color: actor color
:type color: list
:return: a VTK... |
def Produce_Predictions(FileName,train,test):
"""
Produces predictions for testing set, based off of training set.
:param FileName: This is the csv file name we wish to have our predictions exported to.
:param train: This is the file name of a csv file that will be the training set.
:param test... | Produces predictions for testing set, based off of training set.
:param FileName: This is the csv file name we wish to have our predictions exported to.
:param train: This is the file name of a csv file that will be the training set.
:param test: This is the file name of the testing set that prediction... | Below is the the instruction that describes the task:
### Input:
Produces predictions for testing set, based off of training set.
:param FileName: This is the csv file name we wish to have our predictions exported to.
:param train: This is the file name of a csv file that will be the training set.
... |
def auth(self, request):
"""
let's auth the user to the Service
:param request: request object
:return: callback url
:rtype: string that contains the url to redirect after auth
"""
callback_url = self.callback_url(request)
request_token = ... | let's auth the user to the Service
:param request: request object
:return: callback url
:rtype: string that contains the url to redirect after auth | Below is the the instruction that describes the task:
### Input:
let's auth the user to the Service
:param request: request object
:return: callback url
:rtype: string that contains the url to redirect after auth
### Response:
def auth(self, request):
"""
let... |
def _evaluate_tempyREPR(self, child, repr_cls):
"""Assign a score ito a TempyRepr class.
The scores depends on the current scope and position of the object in which the TempyREPR is found."""
score = 0
if repr_cls.__name__ == self.__class__.__name__:
# One point if the REPR h... | Assign a score ito a TempyRepr class.
The scores depends on the current scope and position of the object in which the TempyREPR is found. | Below is the the instruction that describes the task:
### Input:
Assign a score ito a TempyRepr class.
The scores depends on the current scope and position of the object in which the TempyREPR is found.
### Response:
def _evaluate_tempyREPR(self, child, repr_cls):
"""Assign a score ito a TempyRepr ... |
def batch(self, num):
"""
Iterator returning results in batches. When making more general queries
that might have larger results, specify a batch result that should be
returned with each iteration.
:param int num: number of results per iteration
:return: iterator... | Iterator returning results in batches. When making more general queries
that might have larger results, specify a batch result that should be
returned with each iteration.
:param int num: number of results per iteration
:return: iterator holding list of results | Below is the the instruction that describes the task:
### Input:
Iterator returning results in batches. When making more general queries
that might have larger results, specify a batch result that should be
returned with each iteration.
:param int num: number of results per iteratio... |
def _gen_input_mask(mask):
"""Generate input mask from bytemask"""
return input_mask(
shift=bool(mask & MOD_Shift),
lock=bool(mask & MOD_Lock),
control=bool(mask & MOD_Control),
mod1=bool(mask & MOD_Mod1),
mod2=bool(mask & MOD_Mod2),
mod3=bool(mask & MOD_Mod3),
... | Generate input mask from bytemask | Below is the the instruction that describes the task:
### Input:
Generate input mask from bytemask
### Response:
def _gen_input_mask(mask):
"""Generate input mask from bytemask"""
return input_mask(
shift=bool(mask & MOD_Shift),
lock=bool(mask & MOD_Lock),
control=bool(mask & MOD_Co... |
def _apply_record_length_checks(self, i, r, summarize=False, context=None):
"""Apply record length checks on the given record `r`."""
for code, message, modulus in self._record_length_checks:
if i % modulus == 0: # support sampling
if len(r) != len(self._field_names):
... | Apply record length checks on the given record `r`. | Below is the the instruction that describes the task:
### Input:
Apply record length checks on the given record `r`.
### Response:
def _apply_record_length_checks(self, i, r, summarize=False, context=None):
"""Apply record length checks on the given record `r`."""
for code, message, modulus in sel... |
def temp_dir(apply_chown=None, apply_chmod=None, remove_using_sudo=None, remove_force=False):
"""
Creates a temporary directory on the remote machine. The directory is removed when no longer needed. Failure to do
so will be ignored.
:param apply_chown: Optional; change the owner of the directory.
:... | Creates a temporary directory on the remote machine. The directory is removed when no longer needed. Failure to do
so will be ignored.
:param apply_chown: Optional; change the owner of the directory.
:type apply_chown: unicode
:param apply_chmod: Optional; change the permissions of the directory.
:... | Below is the the instruction that describes the task:
### Input:
Creates a temporary directory on the remote machine. The directory is removed when no longer needed. Failure to do
so will be ignored.
:param apply_chown: Optional; change the owner of the directory.
:type apply_chown: unicode
:param ... |
def interpret_script(shell_script):
"""Make it appear as if commands are typed into the terminal."""
with CaptureOutput() as capturer:
shell = subprocess.Popen(['bash', '-'], stdin=subprocess.PIPE)
with open(shell_script) as handle:
for line in handle:
sys.stdout.writ... | Make it appear as if commands are typed into the terminal. | Below is the the instruction that describes the task:
### Input:
Make it appear as if commands are typed into the terminal.
### Response:
def interpret_script(shell_script):
"""Make it appear as if commands are typed into the terminal."""
with CaptureOutput() as capturer:
shell = subprocess.Popen([... |
def define_sub_network_cycle_constraints( subnetwork, snapshots, passive_branch_p, attribute):
""" Constructs cycle_constraints for a particular subnetwork
"""
sub_network_cycle_constraints = {}
sub_network_cycle_index = []
matrix = subnetwork.C.tocsc()
branches = subnetwork.branches()
fo... | Constructs cycle_constraints for a particular subnetwork | Below is the the instruction that describes the task:
### Input:
Constructs cycle_constraints for a particular subnetwork
### Response:
def define_sub_network_cycle_constraints( subnetwork, snapshots, passive_branch_p, attribute):
""" Constructs cycle_constraints for a particular subnetwork
"""
sub_ne... |
def peer_store_and_set(relation_id=None, peer_relation_name='cluster',
peer_store_fatal=False, relation_settings=None,
delimiter='_', **kwargs):
"""Store passed-in arguments both in argument relation and in peer storage.
It functions like doing relation_set() and p... | Store passed-in arguments both in argument relation and in peer storage.
It functions like doing relation_set() and peer_store() at the same time,
with the same data.
@param relation_id: the id of the relation to store the data on. Defaults
to the current relation.
@param peer_... | Below is the the instruction that describes the task:
### Input:
Store passed-in arguments both in argument relation and in peer storage.
It functions like doing relation_set() and peer_store() at the same time,
with the same data.
@param relation_id: the id of the relation to store the data on. Defau... |
def group_samaccountnames(self, base_dn):
"""For the current ADUser instance, determine which
groups the user is a member of and convert the
group DistinguishedNames to sAMAccountNames.
The resulting list of groups may not be complete
if explicit_membership_only was set to
... | For the current ADUser instance, determine which
groups the user is a member of and convert the
group DistinguishedNames to sAMAccountNames.
The resulting list of groups may not be complete
if explicit_membership_only was set to
True when the object factory method (user() or user... | Below is the the instruction that describes the task:
### Input:
For the current ADUser instance, determine which
groups the user is a member of and convert the
group DistinguishedNames to sAMAccountNames.
The resulting list of groups may not be complete
if explicit_membership_only w... |
def add_library(self, library):
"""
Adds functions from a library module
:param library: the library module
:return:
"""
for fn in library.__dict__.copy().values():
# ignore imported methods and anything beginning __
if inspect.isfunction(fn) and i... | Adds functions from a library module
:param library: the library module
:return: | Below is the the instruction that describes the task:
### Input:
Adds functions from a library module
:param library: the library module
:return:
### Response:
def add_library(self, library):
"""
Adds functions from a library module
:param library: the library module
... |
def badge(self, *args, **kwargs):
"""
Latest Build Status Badge
Checks the status of the latest build of a given branch
and returns corresponding badge svg.
This method is ``experimental``
"""
return self._makeApiCall(self.funcinfo["badge"], *args, **kwargs) | Latest Build Status Badge
Checks the status of the latest build of a given branch
and returns corresponding badge svg.
This method is ``experimental`` | Below is the the instruction that describes the task:
### Input:
Latest Build Status Badge
Checks the status of the latest build of a given branch
and returns corresponding badge svg.
This method is ``experimental``
### Response:
def badge(self, *args, **kwargs):
"""
Lates... |
def two_phase_dP_dz_gravitational(angle, alpha, rhol, rhog, g=g):
r'''This function handles calculation of two-phase liquid-gas pressure drop
due to gravitation for flow inside channels. This is a differential
calculation for a segment with an infinitesimal difference in elevation for
use in performing... | r'''This function handles calculation of two-phase liquid-gas pressure drop
due to gravitation for flow inside channels. This is a differential
calculation for a segment with an infinitesimal difference in elevation for
use in performing integration over a pipe as shown in [1]_ and [2]_.
.. math::... | Below is the the instruction that describes the task:
### Input:
r'''This function handles calculation of two-phase liquid-gas pressure drop
due to gravitation for flow inside channels. This is a differential
calculation for a segment with an infinitesimal difference in elevation for
use in performing ... |
def unwrap(self):
"""Return a deep copy of myself as a list, and unwrap any wrapper objects in me."""
return [v.unwrap() if hasattr(v, 'unwrap') and not hasattr(v, 'no_unwrap') else v for v in self] | Return a deep copy of myself as a list, and unwrap any wrapper objects in me. | Below is the the instruction that describes the task:
### Input:
Return a deep copy of myself as a list, and unwrap any wrapper objects in me.
### Response:
def unwrap(self):
"""Return a deep copy of myself as a list, and unwrap any wrapper objects in me."""
return [v.unwrap() if hasattr(v, 'unwrap... |
def getMessage(self):
"""
Return the message for this LogRecord.
Return the message for this LogRecord after merging any user-supplied
arguments with the message.
"""
msg = self.msg
if self.args:
msg = msg.format(*self.args)
return maybe_encod... | Return the message for this LogRecord.
Return the message for this LogRecord after merging any user-supplied
arguments with the message. | Below is the the instruction that describes the task:
### Input:
Return the message for this LogRecord.
Return the message for this LogRecord after merging any user-supplied
arguments with the message.
### Response:
def getMessage(self):
"""
Return the message for this LogRecord.
... |
def Decrypt(self, encrypted_data):
"""Decrypts the encrypted data.
Args:
encrypted_data (bytes): encrypted data.
Returns:
tuple[bytes, bytes]: decrypted data and remaining encrypted data.
"""
index_split = -(len(encrypted_data) % AES.block_size)
if index_split:
remaining_encr... | Decrypts the encrypted data.
Args:
encrypted_data (bytes): encrypted data.
Returns:
tuple[bytes, bytes]: decrypted data and remaining encrypted data. | Below is the the instruction that describes the task:
### Input:
Decrypts the encrypted data.
Args:
encrypted_data (bytes): encrypted data.
Returns:
tuple[bytes, bytes]: decrypted data and remaining encrypted data.
### Response:
def Decrypt(self, encrypted_data):
"""Decrypts the encrypted... |
def getSiblings(self, textId, subreference):
""" Retrieve the siblings of a textual node
:param textId: CtsTextMetadata Identifier
:type textId: str
:param subreference: CapitainsCtsPassage Reference
:type subreference: str
:return: Tuple of references
:rtype: (s... | Retrieve the siblings of a textual node
:param textId: CtsTextMetadata Identifier
:type textId: str
:param subreference: CapitainsCtsPassage Reference
:type subreference: str
:return: Tuple of references
:rtype: (str, str) | Below is the the instruction that describes the task:
### Input:
Retrieve the siblings of a textual node
:param textId: CtsTextMetadata Identifier
:type textId: str
:param subreference: CapitainsCtsPassage Reference
:type subreference: str
:return: Tuple of references
... |
def namedb_get_record_states_at(cur, history_id, block_number):
"""
Get the state(s) that the given history record was in at a given block height.
Normally, this is one state (i.e. if a name was registered at block 8, then it is in a NAME_REGISTRATION state in block 10)
However, if the record changed a... | Get the state(s) that the given history record was in at a given block height.
Normally, this is one state (i.e. if a name was registered at block 8, then it is in a NAME_REGISTRATION state in block 10)
However, if the record changed at this block, then this method returns all states the record passed through.... | Below is the the instruction that describes the task:
### Input:
Get the state(s) that the given history record was in at a given block height.
Normally, this is one state (i.e. if a name was registered at block 8, then it is in a NAME_REGISTRATION state in block 10)
However, if the record changed at this ... |
def from_der_data(cls, data):
"""Decode DER-encoded certificate.
:Parameters:
- `data`: the encoded certificate
:Types:
- `data`: `bytes`
:Return: decoded certificate data
:Returntype: ASN1CertificateData
"""
# pylint: disable=W0212
... | Decode DER-encoded certificate.
:Parameters:
- `data`: the encoded certificate
:Types:
- `data`: `bytes`
:Return: decoded certificate data
:Returntype: ASN1CertificateData | Below is the the instruction that describes the task:
### Input:
Decode DER-encoded certificate.
:Parameters:
- `data`: the encoded certificate
:Types:
- `data`: `bytes`
:Return: decoded certificate data
:Returntype: ASN1CertificateData
### Response:
def fr... |
def ensure_v8_src():
""" Ensure that v8 src are presents and up-to-date
"""
path = local_path('v8')
if not os.path.isdir(path):
fetch_v8(path)
else:
update_v8(path)
checkout_v8_version(local_path("v8/v8"), V8_VERSION)
dependencies_sync(path) | Ensure that v8 src are presents and up-to-date | Below is the the instruction that describes the task:
### Input:
Ensure that v8 src are presents and up-to-date
### Response:
def ensure_v8_src():
""" Ensure that v8 src are presents and up-to-date
"""
path = local_path('v8')
if not os.path.isdir(path):
fetch_v8(path)
else:
upd... |
def list_privileges(name, **client_args):
'''
List privileges from a user.
name
Name of the user from whom privileges will be listed.
CLI Example:
.. code-block:: bash
salt '*' influxdb.list_privileges <name>
'''
client = _client(**client_args)
res = {}
for item ... | List privileges from a user.
name
Name of the user from whom privileges will be listed.
CLI Example:
.. code-block:: bash
salt '*' influxdb.list_privileges <name> | Below is the the instruction that describes the task:
### Input:
List privileges from a user.
name
Name of the user from whom privileges will be listed.
CLI Example:
.. code-block:: bash
salt '*' influxdb.list_privileges <name>
### Response:
def list_privileges(name, **client_args):... |
def has_concluded(self, bigchain, current_votes=[]):
"""Check if the election can be concluded or not.
* Elections can only be concluded if the validator set has not changed
since the election was initiated.
* Elections can be concluded only if the current votes form a supermajority.
... | Check if the election can be concluded or not.
* Elections can only be concluded if the validator set has not changed
since the election was initiated.
* Elections can be concluded only if the current votes form a supermajority.
Custom elections may override this function and introdu... | Below is the the instruction that describes the task:
### Input:
Check if the election can be concluded or not.
* Elections can only be concluded if the validator set has not changed
since the election was initiated.
* Elections can be concluded only if the current votes form a supermajor... |
def selectAssemblies(pth, manifest=None):
"""
Return a binary's dependent assemblies files that should be included.
Return a list of pairs (name, fullpath)
"""
rv = []
if not os.path.isfile(pth):
pth = check_extract_from_egg(pth)[0][0]
if manifest:
_depNames = set([dep.name ... | Return a binary's dependent assemblies files that should be included.
Return a list of pairs (name, fullpath) | Below is the the instruction that describes the task:
### Input:
Return a binary's dependent assemblies files that should be included.
Return a list of pairs (name, fullpath)
### Response:
def selectAssemblies(pth, manifest=None):
"""
Return a binary's dependent assemblies files that should be include... |
def invite(self, event):
"""A new user has been invited to enrol by an admin user"""
self.log('Inviting new user to enrol')
name = event.data['name']
email = event.data['email']
method = event.data['method']
self._invite(name, method, email, event.client.uuid, event) | A new user has been invited to enrol by an admin user | Below is the the instruction that describes the task:
### Input:
A new user has been invited to enrol by an admin user
### Response:
def invite(self, event):
"""A new user has been invited to enrol by an admin user"""
self.log('Inviting new user to enrol')
name = event.data['name']
... |
def Type_string(self, text, interval = 0, dl = 0):
"""键盘输入字符串,interval是字符间输入时间间隔,单位"秒"
"""
self.Delay(dl)
self.keyboard.type_string(text, interval) | 键盘输入字符串,interval是字符间输入时间间隔,单位"秒" | Below is the the instruction that describes the task:
### Input:
键盘输入字符串,interval是字符间输入时间间隔,单位"秒"
### Response:
def Type_string(self, text, interval = 0, dl = 0):
"""键盘输入字符串,interval是字符间输入时间间隔,单位"秒"
"""
self.Delay(dl)
self.keyboard.type_string(text, interval) |
def pegasus_node_placer_2d(G, scale=1., center=None, dim=2, crosses=False):
"""Generates a function that converts Pegasus indices to x, y
coordinates for a plot.
Parameters
----------
G : NetworkX graph
Should be a Pegasus graph or a subgraph of a Pegasus graph.
This should be the p... | Generates a function that converts Pegasus indices to x, y
coordinates for a plot.
Parameters
----------
G : NetworkX graph
Should be a Pegasus graph or a subgraph of a Pegasus graph.
This should be the product of dwave_networkx.pegasus_graph
scale : float (default 1.)
Scal... | Below is the the instruction that describes the task:
### Input:
Generates a function that converts Pegasus indices to x, y
coordinates for a plot.
Parameters
----------
G : NetworkX graph
Should be a Pegasus graph or a subgraph of a Pegasus graph.
This should be the product of dwav... |
def header_output(self):
'''只输出cookie的key-value字串.
比如: HISTORY=21341; PHPSESSION=3289012u39jsdijf28; token=233129
'''
result = []
for key in self.keys():
result.append(key + '=' + self.get(key).value)
return '; '.join(result) | 只输出cookie的key-value字串.
比如: HISTORY=21341; PHPSESSION=3289012u39jsdijf28; token=233129 | Below is the the instruction that describes the task:
### Input:
只输出cookie的key-value字串.
比如: HISTORY=21341; PHPSESSION=3289012u39jsdijf28; token=233129
### Response:
def header_output(self):
'''只输出cookie的key-value字串.
比如: HISTORY=21341; PHPSESSION=3289012u39jsdijf28; token=2... |
def cid(self):
"""The PubChem Compound Identifier (CID).
.. note::
When searching using a SMILES or InChI query that is not present in the PubChem Compound database, an
automatically generated record may be returned that contains properties that have been calculated on the
... | The PubChem Compound Identifier (CID).
.. note::
When searching using a SMILES or InChI query that is not present in the PubChem Compound database, an
automatically generated record may be returned that contains properties that have been calculated on the
fly. These records... | Below is the the instruction that describes the task:
### Input:
The PubChem Compound Identifier (CID).
.. note::
When searching using a SMILES or InChI query that is not present in the PubChem Compound database, an
automatically generated record may be returned that contains prope... |
def pcolormesh(self, *args, **kwargs):
"""Create a pseudocolor plot of a 2-D array.
If a 3D or higher Data object is passed, a lower dimensional
channel can be plotted, provided the ``squeeze`` of the channel
has ``ndim==2`` and the first two axes do not span dimensions
other th... | Create a pseudocolor plot of a 2-D array.
If a 3D or higher Data object is passed, a lower dimensional
channel can be plotted, provided the ``squeeze`` of the channel
has ``ndim==2`` and the first two axes do not span dimensions
other than those spanned by that channel.
Uses pc... | Below is the the instruction that describes the task:
### Input:
Create a pseudocolor plot of a 2-D array.
If a 3D or higher Data object is passed, a lower dimensional
channel can be plotted, provided the ``squeeze`` of the channel
has ``ndim==2`` and the first two axes do not span dimensio... |
def encode(self, word, max_length=4):
"""Return the Statistics Canada code for a word.
Parameters
----------
word : str
The word to transform
max_length : int
The maximum length (default 4) of the code to return
Returns
-------
st... | Return the Statistics Canada code for a word.
Parameters
----------
word : str
The word to transform
max_length : int
The maximum length (default 4) of the code to return
Returns
-------
str
The Statistics Canada name code val... | Below is the the instruction that describes the task:
### Input:
Return the Statistics Canada code for a word.
Parameters
----------
word : str
The word to transform
max_length : int
The maximum length (default 4) of the code to return
Returns
... |
def chdir(__path: str) -> ContextManager:
"""Context handler to temporarily switch directories.
Args:
__path: Directory to change to
Yields:
Execution context in ``path``
"""
old = os.getcwd()
try:
os.chdir(__path)
yield
finally:
os.chdir(old) | Context handler to temporarily switch directories.
Args:
__path: Directory to change to
Yields:
Execution context in ``path`` | Below is the the instruction that describes the task:
### Input:
Context handler to temporarily switch directories.
Args:
__path: Directory to change to
Yields:
Execution context in ``path``
### Response:
def chdir(__path: str) -> ContextManager:
"""Context handler to temporarily swit... |
def typing(self, *, channel: str):
"""Sends a typing indicator to the specified channel.
This indicates that this app is currently
writing a message to send to a channel.
Args:
channel (str): The channel id. e.g. 'C024BE91L'
Raises:
SlackClientNotConnec... | Sends a typing indicator to the specified channel.
This indicates that this app is currently
writing a message to send to a channel.
Args:
channel (str): The channel id. e.g. 'C024BE91L'
Raises:
SlackClientNotConnectedError: Websocket connection is closed. | Below is the the instruction that describes the task:
### Input:
Sends a typing indicator to the specified channel.
This indicates that this app is currently
writing a message to send to a channel.
Args:
channel (str): The channel id. e.g. 'C024BE91L'
Raises:
... |
def pre_save(self, model_instance, add):
"""Updates socket.gethostname() on each save."""
value = socket.gethostname()
setattr(model_instance, self.attname, value)
return value | Updates socket.gethostname() on each save. | Below is the the instruction that describes the task:
### Input:
Updates socket.gethostname() on each save.
### Response:
def pre_save(self, model_instance, add):
"""Updates socket.gethostname() on each save."""
value = socket.gethostname()
setattr(model_instance, self.attname, value)
... |
def exploit_single(self, ip, operating_system):
"""
Exploits a single ip, exploit is based on the given operating system.
"""
result = None
if "Windows Server 2008" in operating_system or "Windows 7" in operating_system:
result = subprocess.run(['python2', os.path... | Exploits a single ip, exploit is based on the given operating system. | Below is the the instruction that describes the task:
### Input:
Exploits a single ip, exploit is based on the given operating system.
### Response:
def exploit_single(self, ip, operating_system):
"""
Exploits a single ip, exploit is based on the given operating system.
"""
resu... |
def partial_predict(self, X, y=None):
"""Predict the closest cluster each sample in X belongs to.
In the vector quantization literature, `cluster_centers_` is called
the code book and each value returned by `predict` is the index of
the closest code in the code book.
Parameters... | Predict the closest cluster each sample in X belongs to.
In the vector quantization literature, `cluster_centers_` is called
the code book and each value returned by `predict` is the index of
the closest code in the code book.
Parameters
----------
X : array-like shape=... | Below is the the instruction that describes the task:
### Input:
Predict the closest cluster each sample in X belongs to.
In the vector quantization literature, `cluster_centers_` is called
the code book and each value returned by `predict` is the index of
the closest code in the code book.... |
def get_service_inspect(self, stack, service):
"""查看服务
查看指定名称服务的属性。
Args:
- stack: 服务所属的服务组名称
- service: 服务名
Returns:
返回一个tuple对象,其格式为(<result>, <ResponseInfo>)
- result 成功返回服务信息,失败返回{"error": "<errMsg string>"}
... | 查看服务
查看指定名称服务的属性。
Args:
- stack: 服务所属的服务组名称
- service: 服务名
Returns:
返回一个tuple对象,其格式为(<result>, <ResponseInfo>)
- result 成功返回服务信息,失败返回{"error": "<errMsg string>"}
- ResponseInfo 请求的Response信息 | Below is the the instruction that describes the task:
### Input:
查看服务
查看指定名称服务的属性。
Args:
- stack: 服务所属的服务组名称
- service: 服务名
Returns:
返回一个tuple对象,其格式为(<result>, <ResponseInfo>)
- result 成功返回服务信息,失败返回{"error": "<errMsg string>"}
... |
def grading_means_passed(self):
'''
Information if the given grading means passed.
Non-graded assignments are always passed.
'''
if self.assignment.is_graded():
if self.grading and self.grading.means_passed:
return True
else:
... | Information if the given grading means passed.
Non-graded assignments are always passed. | Below is the the instruction that describes the task:
### Input:
Information if the given grading means passed.
Non-graded assignments are always passed.
### Response:
def grading_means_passed(self):
'''
Information if the given grading means passed.
Non-graded assignments are alway... |
def rot_rads(self, rads):
""" Rotate vector by angle in radians."""
new_x = self.x * math.cos(rads) - self.y * math.sin(rads)
self.y = self.x * math.sin(rads) + self.y * math.cos(rads)
self.x = new_x | Rotate vector by angle in radians. | Below is the the instruction that describes the task:
### Input:
Rotate vector by angle in radians.
### Response:
def rot_rads(self, rads):
""" Rotate vector by angle in radians."""
new_x = self.x * math.cos(rads) - self.y * math.sin(rads)
self.y = self.x * math.sin(rads) + self.y * math.c... |
def tree_iterator(self, visited=None, path=None):
'''
Generator function that traverse the dr tree start from this node (self).
'''
if visited is None:
visited = set()
if self not in visited:
if path and isinstance(path, list):
path.append... | Generator function that traverse the dr tree start from this node (self). | Below is the the instruction that describes the task:
### Input:
Generator function that traverse the dr tree start from this node (self).
### Response:
def tree_iterator(self, visited=None, path=None):
'''
Generator function that traverse the dr tree start from this node (self).
'''
... |
def battery_voltage(self):
""" Returns voltage in mV """
msb = self.bus.read_byte_data(AXP209_ADDRESS, BATTERY_VOLTAGE_MSB_REG)
lsb = self.bus.read_byte_data(AXP209_ADDRESS, BATTERY_VOLTAGE_LSB_REG)
voltage_bin = msb << 4 | lsb & 0x0f
return voltage_bin * 1.1 | Returns voltage in mV | Below is the the instruction that describes the task:
### Input:
Returns voltage in mV
### Response:
def battery_voltage(self):
""" Returns voltage in mV """
msb = self.bus.read_byte_data(AXP209_ADDRESS, BATTERY_VOLTAGE_MSB_REG)
lsb = self.bus.read_byte_data(AXP209_ADDRESS, BATTERY_VOLTAGE_... |
def convert_to_mb(s):
"""Convert memory size from GB to MB."""
s = s.upper()
try:
if s.endswith('G'):
return float(s[:-1].strip()) * 1024
elif s.endswith('T'):
return float(s[:-1].strip()) * 1024 * 1024
else:
return float(s[:-1].strip())
except... | Convert memory size from GB to MB. | Below is the the instruction that describes the task:
### Input:
Convert memory size from GB to MB.
### Response:
def convert_to_mb(s):
"""Convert memory size from GB to MB."""
s = s.upper()
try:
if s.endswith('G'):
return float(s[:-1].strip()) * 1024
elif s.endswith('T'):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.