code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def shoebot_example(**shoebot_kwargs):
"""
Decorator to run some code in a bot instance.
"""
def decorator(f):
def run():
from shoebot import ShoebotInstallError # https://github.com/shoebot/shoebot/issues/206
print(" Shoebot - %s:" % f.__name__.replace("_", " "))
... | Decorator to run some code in a bot instance. | Below is the the instruction that describes the task:
### Input:
Decorator to run some code in a bot instance.
### Response:
def shoebot_example(**shoebot_kwargs):
"""
Decorator to run some code in a bot instance.
"""
def decorator(f):
def run():
from shoebot import ShoebotInst... |
def list_group_members(self, name, url_prefix, auth, session, send_opts):
"""Get the members of a group (does not include maintainers).
Args:
name (string): Name of group to query.
url_prefix (string): Protocol + host such as https://api.theboss.io
auth (string): Tok... | Get the members of a group (does not include maintainers).
Args:
name (string): Name of group to query.
url_prefix (string): Protocol + host such as https://api.theboss.io
auth (string): Token to send in the request header.
session (requests.Session): HTTP sessio... | Below is the the instruction that describes the task:
### Input:
Get the members of a group (does not include maintainers).
Args:
name (string): Name of group to query.
url_prefix (string): Protocol + host such as https://api.theboss.io
auth (string): Token to send in th... |
def _vpc_config(self):
"""Get VPC config."""
if self.vpc_enabled:
subnets = get_subnets(env=self.env, region=self.region, purpose='internal')['subnet_ids'][self.region]
security_groups = self._get_sg_ids()
vpc_config = {'SubnetIds': subnets, 'SecurityGroupIds': secur... | Get VPC config. | Below is the the instruction that describes the task:
### Input:
Get VPC config.
### Response:
def _vpc_config(self):
"""Get VPC config."""
if self.vpc_enabled:
subnets = get_subnets(env=self.env, region=self.region, purpose='internal')['subnet_ids'][self.region]
security_gr... |
def spheres_intersect(ar, aR, br, bR):
"""Return whether or not two spheres intersect each other.
Parameters
----------
ar, br: array-like, shape (n,) in n dimensions
Coordinates of the centres of the spheres `a` and `b`.
aR, bR: float
Radiuses of the spheres `a` and `b`.
Retur... | Return whether or not two spheres intersect each other.
Parameters
----------
ar, br: array-like, shape (n,) in n dimensions
Coordinates of the centres of the spheres `a` and `b`.
aR, bR: float
Radiuses of the spheres `a` and `b`.
Returns
-------
intersecting: boolean
... | Below is the the instruction that describes the task:
### Input:
Return whether or not two spheres intersect each other.
Parameters
----------
ar, br: array-like, shape (n,) in n dimensions
Coordinates of the centres of the spheres `a` and `b`.
aR, bR: float
Radiuses of the spheres ... |
def _dereference(cls, documents, references):
"""Dereference one or more documents"""
# Dereference each reference
for path, projection in references.items():
# Check there is a $ref in the projection, else skip it
if '$ref' not in projection:
continue
... | Dereference one or more documents | Below is the the instruction that describes the task:
### Input:
Dereference one or more documents
### Response:
def _dereference(cls, documents, references):
"""Dereference one or more documents"""
# Dereference each reference
for path, projection in references.items():
# Che... |
def service_start(name):
'''
Start a "service" on the ssh server
.. versionadded:: 2015.8.2
'''
cmd = 'start ' + name
# Send the command to execute
out, err = DETAILS['server'].sendline(cmd)
# "scrape" the output and return the right fields as a dict
return parse(out) | Start a "service" on the ssh server
.. versionadded:: 2015.8.2 | Below is the the instruction that describes the task:
### Input:
Start a "service" on the ssh server
.. versionadded:: 2015.8.2
### Response:
def service_start(name):
'''
Start a "service" on the ssh server
.. versionadded:: 2015.8.2
'''
cmd = 'start ' + name
# Send the command to ex... |
def SA_torispheroidal(D, fd, fk):
r'''Calculates surface area of a torispherical head according to [1]_.
Somewhat involved. Equations are adapted to be used for a full head.
.. math::
SA = S_1 + S_2
.. math::
S_1 = 2\pi D^2 f_d \alpha
.. math::
S_2 = 2\pi D^2 f_k\left(\alp... | r'''Calculates surface area of a torispherical head according to [1]_.
Somewhat involved. Equations are adapted to be used for a full head.
.. math::
SA = S_1 + S_2
.. math::
S_1 = 2\pi D^2 f_d \alpha
.. math::
S_2 = 2\pi D^2 f_k\left(\alpha - \alpha_1 + (0.5 - f_k)\left(\sin^... | Below is the the instruction that describes the task:
### Input:
r'''Calculates surface area of a torispherical head according to [1]_.
Somewhat involved. Equations are adapted to be used for a full head.
.. math::
SA = S_1 + S_2
.. math::
S_1 = 2\pi D^2 f_d \alpha
.. math::
... |
def dictfetchall(cursor: Cursor) -> List[Dict[str, Any]]:
"""
Return all rows from a cursor as a list of :class:`OrderedDict` objects.
Args:
cursor: the cursor
Returns:
a list (one item per row) of :class:`OrderedDict` objects whose key are
column names and whose values are the... | Return all rows from a cursor as a list of :class:`OrderedDict` objects.
Args:
cursor: the cursor
Returns:
a list (one item per row) of :class:`OrderedDict` objects whose key are
column names and whose values are the row values | Below is the the instruction that describes the task:
### Input:
Return all rows from a cursor as a list of :class:`OrderedDict` objects.
Args:
cursor: the cursor
Returns:
a list (one item per row) of :class:`OrderedDict` objects whose key are
column names and whose values are the ... |
def _get_word_end_cursor(self, position):
""" Find the end of the word to the right the given position. If a
sequence of non-word characters precedes the first word, skip over
them. (This emulates the behavior of bash, emacs, etc.)
"""
document = self._control.document()
... | Find the end of the word to the right the given position. If a
sequence of non-word characters precedes the first word, skip over
them. (This emulates the behavior of bash, emacs, etc.) | Below is the the instruction that describes the task:
### Input:
Find the end of the word to the right the given position. If a
sequence of non-word characters precedes the first word, skip over
them. (This emulates the behavior of bash, emacs, etc.)
### Response:
def _get_word_end_cursor(s... |
def init(opts):
'''
This function gets called when the proxy starts up. For
login
the protocol and port are cached.
'''
log.debug('Initting esxcluster proxy module in process %s', os.getpid())
log.debug('Validating esxcluster proxy input')
schema = EsxclusterProxySchema.serialize()
l... | This function gets called when the proxy starts up. For
login
the protocol and port are cached. | Below is the the instruction that describes the task:
### Input:
This function gets called when the proxy starts up. For
login
the protocol and port are cached.
### Response:
def init(opts):
'''
This function gets called when the proxy starts up. For
login
the protocol and port are cached.
... |
def fullname(self) -> str:
"""
Description of the process.
"""
fullname = "Process {}/{} ({})".format(self.procnum, self.nprocs,
self.details.name)
if self.running:
fullname += " (PID={})".format(self.process.pid)
... | Description of the process. | Below is the the instruction that describes the task:
### Input:
Description of the process.
### Response:
def fullname(self) -> str:
"""
Description of the process.
"""
fullname = "Process {}/{} ({})".format(self.procnum, self.nprocs,
... |
def confirmation(self, pdu):
"""Packets coming up the stack are APDU's."""
if _debug: StateMachineAccessPoint._debug("confirmation %r", pdu)
# check device communication control
if self.dccEnableDisable == 'enable':
if _debug: StateMachineAccessPoint._debug(" - communicat... | Packets coming up the stack are APDU's. | Below is the the instruction that describes the task:
### Input:
Packets coming up the stack are APDU's.
### Response:
def confirmation(self, pdu):
"""Packets coming up the stack are APDU's."""
if _debug: StateMachineAccessPoint._debug("confirmation %r", pdu)
# check device communication c... |
def seconds_to_hms_verbose(t):
"""
Converts seconds float to 'H hours 8 minutes, 30 seconds' format
"""
hours = int((t / 3600))
mins = int((t / 60) % 60)
secs = int(t % 60)
return ' '.join([
(hours + ' hour' + ('s' if hours > 1 else '')) if hours > 0 else '',
(mins + ' minute... | Converts seconds float to 'H hours 8 minutes, 30 seconds' format | Below is the the instruction that describes the task:
### Input:
Converts seconds float to 'H hours 8 minutes, 30 seconds' format
### Response:
def seconds_to_hms_verbose(t):
"""
Converts seconds float to 'H hours 8 minutes, 30 seconds' format
"""
hours = int((t / 3600))
mins = int((t / 60) % 6... |
def handle(self, sock, read_data, path, headers):
"Just waits, and checks for other actions to replace us"
for i in range(self.timeout // self.check_interval):
# Sleep first
eventlet.sleep(self.check_interval)
# Check for another action
action = self.balan... | Just waits, and checks for other actions to replace us | Below is the the instruction that describes the task:
### Input:
Just waits, and checks for other actions to replace us
### Response:
def handle(self, sock, read_data, path, headers):
"Just waits, and checks for other actions to replace us"
for i in range(self.timeout // self.check_interval):
... |
def nanvl(col1, col2):
"""Returns col1 if it is not NaN, or col2 if col1 is NaN.
Both inputs should be floating point columns (:class:`DoubleType` or :class:`FloatType`).
>>> df = spark.createDataFrame([(1.0, float('nan')), (float('nan'), 2.0)], ("a", "b"))
>>> df.select(nanvl("a", "b").alias("r1"), n... | Returns col1 if it is not NaN, or col2 if col1 is NaN.
Both inputs should be floating point columns (:class:`DoubleType` or :class:`FloatType`).
>>> df = spark.createDataFrame([(1.0, float('nan')), (float('nan'), 2.0)], ("a", "b"))
>>> df.select(nanvl("a", "b").alias("r1"), nanvl(df.a, df.b).alias("r2")).... | Below is the the instruction that describes the task:
### Input:
Returns col1 if it is not NaN, or col2 if col1 is NaN.
Both inputs should be floating point columns (:class:`DoubleType` or :class:`FloatType`).
>>> df = spark.createDataFrame([(1.0, float('nan')), (float('nan'), 2.0)], ("a", "b"))
>>> d... |
def get_info_by_tail_number(self, tail_number, page=1, limit=100):
"""Fetch the details of a particular aircraft by its tail number.
This method can be used to get the details of a particular aircraft by its tail number.
Details include the serial number, age etc along with links to the images ... | Fetch the details of a particular aircraft by its tail number.
This method can be used to get the details of a particular aircraft by its tail number.
Details include the serial number, age etc along with links to the images of the aircraft.
It checks the user authentication and returns the dat... | Below is the the instruction that describes the task:
### Input:
Fetch the details of a particular aircraft by its tail number.
This method can be used to get the details of a particular aircraft by its tail number.
Details include the serial number, age etc along with links to the images of the ai... |
def _expand_nbest_translation(translation: Translation) -> List[Translation]:
"""
Expand nbest translations in a single Translation object to one Translation
object per nbest translation.
:param translation: A Translation object.
:return: A list of Translation objects.
"""
nbest_list = ... | Expand nbest translations in a single Translation object to one Translation
object per nbest translation.
:param translation: A Translation object.
:return: A list of Translation objects. | Below is the the instruction that describes the task:
### Input:
Expand nbest translations in a single Translation object to one Translation
object per nbest translation.
:param translation: A Translation object.
:return: A list of Translation objects.
### Response:
def _expand_nbest_translation(t... |
def create_logger(name):
"""
Create a logger object with the given name.
If this is the first time that we call this method, then initialize the
formatter.
"""
base = logging.getLogger("cleverhans")
if len(base.handlers) == 0:
ch = logging.StreamHandler()
formatter = logging.Formatter('[%(levelna... | Create a logger object with the given name.
If this is the first time that we call this method, then initialize the
formatter. | Below is the the instruction that describes the task:
### Input:
Create a logger object with the given name.
If this is the first time that we call this method, then initialize the
formatter.
### Response:
def create_logger(name):
"""
Create a logger object with the given name.
If this is the first tim... |
def _folder_item_uncertainty(self, analysis_brain, item):
"""Fills the analysis' uncertainty to the item passed in.
:param analysis_brain: Brain that represents an analysis
:param item: analysis' dictionary counterpart that represents a row
"""
item["Uncertainty"] = ""
... | Fills the analysis' uncertainty to the item passed in.
:param analysis_brain: Brain that represents an analysis
:param item: analysis' dictionary counterpart that represents a row | Below is the the instruction that describes the task:
### Input:
Fills the analysis' uncertainty to the item passed in.
:param analysis_brain: Brain that represents an analysis
:param item: analysis' dictionary counterpart that represents a row
### Response:
def _folder_item_uncertainty(self, anal... |
def load(self, *args, **kwargs):
""" Imports metadata by the use of HTTP GET.
If the fingerprint is known the file will be checked for
compliance before it is imported.
"""
response = self.http.send(self.url)
if response.status_code == 200:
_txt = response.con... | Imports metadata by the use of HTTP GET.
If the fingerprint is known the file will be checked for
compliance before it is imported. | Below is the the instruction that describes the task:
### Input:
Imports metadata by the use of HTTP GET.
If the fingerprint is known the file will be checked for
compliance before it is imported.
### Response:
def load(self, *args, **kwargs):
""" Imports metadata by the use of HTTP GET.
... |
def string(self, writesize=None):
'''
Looks like a file handle
'''
if not self.finished:
self.finished = True
return self.content
return '' | Looks like a file handle | Below is the the instruction that describes the task:
### Input:
Looks like a file handle
### Response:
def string(self, writesize=None):
'''
Looks like a file handle
'''
if not self.finished:
self.finished = True
return self.content
return '' |
def are_equivalent(*args, **kwargs):
"""Indicate if arguments passed to this function are equivalent.
.. hint::
This checker operates recursively on the members contained within iterables
and :class:`dict <python:dict>` objects.
.. caution::
If you only pass one argument to this checke... | Indicate if arguments passed to this function are equivalent.
.. hint::
This checker operates recursively on the members contained within iterables
and :class:`dict <python:dict>` objects.
.. caution::
If you only pass one argument to this checker - even if it is an iterable -
the ch... | Below is the the instruction that describes the task:
### Input:
Indicate if arguments passed to this function are equivalent.
.. hint::
This checker operates recursively on the members contained within iterables
and :class:`dict <python:dict>` objects.
.. caution::
If you only pass on... |
def check_if_song_name(self,html):
'''
Returns true if user entered artist or movie name
'''
soup=BeautifulSoup(html)
a_list=soup.findAll('a','touch')
#print a_list
text=[str(x) for x in a_list]
text=''.join(text)
text=text.lower()
string1='download in 48 kbps'
string2='download in 128 kbps'
str... | Returns true if user entered artist or movie name | Below is the the instruction that describes the task:
### Input:
Returns true if user entered artist or movie name
### Response:
def check_if_song_name(self,html):
'''
Returns true if user entered artist or movie name
'''
soup=BeautifulSoup(html)
a_list=soup.findAll('a','touch')
#print a_list
text=[s... |
def get_enroll(self):
"""Returns new enroll seed"""
devices = [DeviceRegistration.wrap(device) for device in self.__get_u2f_devices()]
enroll = start_register(self.__appid, devices)
enroll['status'] = 'ok'
session['_u2f_enroll_'] = enroll.json
return enroll | Returns new enroll seed | Below is the the instruction that describes the task:
### Input:
Returns new enroll seed
### Response:
def get_enroll(self):
"""Returns new enroll seed"""
devices = [DeviceRegistration.wrap(device) for device in self.__get_u2f_devices()]
enroll = start_register(self.__appid, devices)
... |
def create_mysql_oursql(username, password, host, port, database, **kwargs): # pragma: no cover
"""
create an engine connected to a mysql database using oursql.
"""
return create_engine(
_create_mysql_oursql(username, password, host, port, database),
**kwargs
) | create an engine connected to a mysql database using oursql. | Below is the the instruction that describes the task:
### Input:
create an engine connected to a mysql database using oursql.
### Response:
def create_mysql_oursql(username, password, host, port, database, **kwargs): # pragma: no cover
"""
create an engine connected to a mysql database using oursql.
"... |
def field_schema(
field: Field,
*,
by_alias: bool = True,
model_name_map: Dict[Type['main.BaseModel'], str],
ref_prefix: Optional[str] = None,
) -> Tuple[Dict[str, Any], Dict[str, Any]]:
"""
Process a Pydantic field and return a tuple with a JSON Schema for it as the first item.
Also ret... | Process a Pydantic field and return a tuple with a JSON Schema for it as the first item.
Also return a dictionary of definitions with models as keys and their schemas as values. If the passed field
is a model and has sub-models, and those sub-models don't have overrides (as ``title``, ``default``, etc), they
... | Below is the the instruction that describes the task:
### Input:
Process a Pydantic field and return a tuple with a JSON Schema for it as the first item.
Also return a dictionary of definitions with models as keys and their schemas as values. If the passed field
is a model and has sub-models, and those sub-... |
def write_offsets_to_file(cls, json_file_name, consumer_offsets_data):
"""Save built consumer-offsets data to given json file."""
# Save consumer-offsets to file
with open(json_file_name, "w") as json_file:
try:
json.dump(consumer_offsets_data, json_file)
... | Save built consumer-offsets data to given json file. | Below is the the instruction that describes the task:
### Input:
Save built consumer-offsets data to given json file.
### Response:
def write_offsets_to_file(cls, json_file_name, consumer_offsets_data):
"""Save built consumer-offsets data to given json file."""
# Save consumer-offsets to file
... |
def run_periodfinding(simbasedir,
pfmethods=('gls','pdm','bls'),
pfkwargs=({},{},{'startp':1.0,'maxtransitduration':0.3}),
getblssnr=False,
sigclip=5.0,
nperiodworkers=10,
ncontrolworkers=... | This runs periodfinding using several period-finders on a collection of
fake LCs.
As a rough benchmark, 25000 fake LCs with 10000--50000 points per LC take
about 26 days in total to run on an invocation of this function using
GLS+PDM+BLS and 10 periodworkers and 4 controlworkers (so all 40 'cores') on
... | Below is the the instruction that describes the task:
### Input:
This runs periodfinding using several period-finders on a collection of
fake LCs.
As a rough benchmark, 25000 fake LCs with 10000--50000 points per LC take
about 26 days in total to run on an invocation of this function using
GLS+PDM+... |
def version(rest):
"Get the version of pmxbot or one of its plugins"
pkg = rest.strip() or 'pmxbot'
if pkg.lower() == 'python':
return sys.version.split()[0]
return importlib_metadata.version(pkg) | Get the version of pmxbot or one of its plugins | Below is the the instruction that describes the task:
### Input:
Get the version of pmxbot or one of its plugins
### Response:
def version(rest):
"Get the version of pmxbot or one of its plugins"
pkg = rest.strip() or 'pmxbot'
if pkg.lower() == 'python':
return sys.version.split()[0]
return importlib_metadat... |
def pos3(self):
''' Use pos-sc1-sc2 as POS '''
parts = [self.pos]
if self.sc1 and self.sc1 != '*':
parts.append(self.sc1)
if self.sc2 and self.sc2 != '*':
parts.append(self.sc2)
return '-'.join(parts) | Use pos-sc1-sc2 as POS | Below is the the instruction that describes the task:
### Input:
Use pos-sc1-sc2 as POS
### Response:
def pos3(self):
''' Use pos-sc1-sc2 as POS '''
parts = [self.pos]
if self.sc1 and self.sc1 != '*':
parts.append(self.sc1)
if self.sc2 and self.sc2 != '*':
... |
def start_search(self):
"""
Start the Gateway Search Request and return the address information
:rtype: (string,int)
:return: a tuple(string(IP),int(Port) when found or None when
timeout occurs
"""
self._asyncio_loop = asyncio.get_event_loop()
# Cre... | Start the Gateway Search Request and return the address information
:rtype: (string,int)
:return: a tuple(string(IP),int(Port) when found or None when
timeout occurs | Below is the the instruction that describes the task:
### Input:
Start the Gateway Search Request and return the address information
:rtype: (string,int)
:return: a tuple(string(IP),int(Port) when found or None when
timeout occurs
### Response:
def start_search(self):
"""
... |
def scale_points(df_points, scale=INKSCAPE_PPmm.magnitude, inplace=False):
'''
Translate points such that bounding box is anchored at (0, 0) and scale
``x`` and ``y`` columns of input frame by specified :data:`scale`.
Parameters
----------
df_points : pandas.DataFrame
Table of ``x``/``y... | Translate points such that bounding box is anchored at (0, 0) and scale
``x`` and ``y`` columns of input frame by specified :data:`scale`.
Parameters
----------
df_points : pandas.DataFrame
Table of ``x``/``y`` point positions.
Must have at least the following columns:
- ``x``... | Below is the the instruction that describes the task:
### Input:
Translate points such that bounding box is anchored at (0, 0) and scale
``x`` and ``y`` columns of input frame by specified :data:`scale`.
Parameters
----------
df_points : pandas.DataFrame
Table of ``x``/``y`` point positions... |
def evaluate_http_conditionals(dav_res, last_modified, entitytag, environ):
"""Handle 'If-...:' headers (but not 'If:' header).
If-Match
@see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.24
Only perform the action if the client supplied entity matches the
same entity on... | Handle 'If-...:' headers (but not 'If:' header).
If-Match
@see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.24
Only perform the action if the client supplied entity matches the
same entity on the server. This is mainly for methods like
PUT to only update a resource ... | Below is the the instruction that describes the task:
### Input:
Handle 'If-...:' headers (but not 'If:' header).
If-Match
@see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.24
Only perform the action if the client supplied entity matches the
same entity on the server. T... |
def check_for_git_repo(url):
"""Check if a url points to a git repository."""
u = parse.urlparse(url)
is_git = False
if os.path.splitext(u.path)[1] == '.git':
is_git = True
elif u.scheme in ('', 'file'):
from git import InvalidGitRepositoryError, Repo
try:
Repo(... | Check if a url points to a git repository. | Below is the the instruction that describes the task:
### Input:
Check if a url points to a git repository.
### Response:
def check_for_git_repo(url):
"""Check if a url points to a git repository."""
u = parse.urlparse(url)
is_git = False
if os.path.splitext(u.path)[1] == '.git':
is_git = ... |
def find_objects(self, ObjectClass, **kwargs):
""" Retrieve all objects of type ``ObjectClass``,
matching the filters specified in ``**kwargs`` -- case sensitive.
"""
print('dynamo.find_objects(%s, %s)' % (ObjectClass, str(kwargs)))
query = self.db.engine.query(ObjectClass)
... | Retrieve all objects of type ``ObjectClass``,
matching the filters specified in ``**kwargs`` -- case sensitive. | Below is the the instruction that describes the task:
### Input:
Retrieve all objects of type ``ObjectClass``,
matching the filters specified in ``**kwargs`` -- case sensitive.
### Response:
def find_objects(self, ObjectClass, **kwargs):
""" Retrieve all objects of type ``ObjectClass``,
mat... |
def uvw2enu(u: float, v: float, w: float,
lat0: float, lon0: float, deg: bool = True) -> Tuple[float, float, float]:
"""
Parameters
----------
u : float or numpy.ndarray of float
v : float or numpy.ndarray of float
w : float or numpy.ndarray of float
Results
-------
E... | Parameters
----------
u : float or numpy.ndarray of float
v : float or numpy.ndarray of float
w : float or numpy.ndarray of float
Results
-------
East : float or numpy.ndarray of float
target east ENU coordinate (meters)
North : float or numpy.ndarray of float
target ... | Below is the the instruction that describes the task:
### Input:
Parameters
----------
u : float or numpy.ndarray of float
v : float or numpy.ndarray of float
w : float or numpy.ndarray of float
Results
-------
East : float or numpy.ndarray of float
target east ENU coordinate... |
def check_table(
problems: List,
table: str,
df: DataFrame,
condition,
message: str,
type_: str = "error",
) -> List:
"""
Check the given GTFS table for the given problem condition.
Parameters
----------
problems : list
A four-tuple containing
1. A problem t... | Check the given GTFS table for the given problem condition.
Parameters
----------
problems : list
A four-tuple containing
1. A problem type (string) equal to ``'error'`` or ``'warning'``;
``'error'`` means the GTFS is violated;
``'warning'`` means there is a problem b... | Below is the the instruction that describes the task:
### Input:
Check the given GTFS table for the given problem condition.
Parameters
----------
problems : list
A four-tuple containing
1. A problem type (string) equal to ``'error'`` or ``'warning'``;
``'error'`` means the ... |
def reads(self, s, **_):
"""Read a notebook represented as text"""
if self.fmt.get('format_name') == 'pandoc':
return md_to_notebook(s)
lines = s.splitlines()
cells = []
metadata, jupyter_md, header_cell, pos = header_to_metadata_and_cell(lines,
... | Read a notebook represented as text | Below is the the instruction that describes the task:
### Input:
Read a notebook represented as text
### Response:
def reads(self, s, **_):
"""Read a notebook represented as text"""
if self.fmt.get('format_name') == 'pandoc':
return md_to_notebook(s)
lines = s.splitlines()
... |
def register_printer(self, printer_class):
"""
:param printer_class: Class inheriting from `AbstractPrinter`.
"""
self._check_common_things('printer', printer_class, AbstractPrinter, self._printers)
instance = printer_class(self, logger_printer)
self._printers.append(ins... | :param printer_class: Class inheriting from `AbstractPrinter`. | Below is the the instruction that describes the task:
### Input:
:param printer_class: Class inheriting from `AbstractPrinter`.
### Response:
def register_printer(self, printer_class):
"""
:param printer_class: Class inheriting from `AbstractPrinter`.
"""
self._check_common_things('... |
def load_scripts():
'''Import all of the modules named in REGISTERED_SCRIPTS'''
# Add scrypture package package to the path before importing
# so everything can import everything else regardless of package
scrypture_dir = os.path.realpath(
os.path.abspath(
... | Import all of the modules named in REGISTERED_SCRIPTS | Below is the the instruction that describes the task:
### Input:
Import all of the modules named in REGISTERED_SCRIPTS
### Response:
def load_scripts():
'''Import all of the modules named in REGISTERED_SCRIPTS'''
# Add scrypture package package to the path before importing
# so everything can import ev... |
def update(self, campaign_id, schedule, nick=None):
'''xxxxx.xxxxx.campaign.schedule.update
===================================
更新一个推广计划的分时折扣设置'''
request = TOPRequest('xxxxx.xxxxx.campaign.schedule.update')
request['campaign_id'] = campaign_id
request['schedule'] = sched... | xxxxx.xxxxx.campaign.schedule.update
===================================
更新一个推广计划的分时折扣设置 | Below is the the instruction that describes the task:
### Input:
xxxxx.xxxxx.campaign.schedule.update
===================================
更新一个推广计划的分时折扣设置
### Response:
def update(self, campaign_id, schedule, nick=None):
'''xxxxx.xxxxx.campaign.schedule.update
=======================... |
def from_sym_2_tri(symm):
"""convert a 2D symmetric matrix to an upper
triangular matrix in 1D format
Parameters
----------
symm : 2D array
Symmetric matrix
Returns
-------
tri: 1D array
Contains elements of upper triangular matrix
"""
inds = np.triu_... | convert a 2D symmetric matrix to an upper
triangular matrix in 1D format
Parameters
----------
symm : 2D array
Symmetric matrix
Returns
-------
tri: 1D array
Contains elements of upper triangular matrix | Below is the the instruction that describes the task:
### Input:
convert a 2D symmetric matrix to an upper
triangular matrix in 1D format
Parameters
----------
symm : 2D array
Symmetric matrix
Returns
-------
tri: 1D array
Contains elements of upper triangular... |
def allowed_info_messages(*info_messages):
"""
Decorator ignoring defined info messages at the end of test method. As
param use what
:py:meth:`~.WebdriverWrapperInfoMixin.get_info_messages`
returns.
.. versionadded:: 2.0
"""
def wrapper(func):
setattr(func, ALLOWED_INFO_MESSAGES... | Decorator ignoring defined info messages at the end of test method. As
param use what
:py:meth:`~.WebdriverWrapperInfoMixin.get_info_messages`
returns.
.. versionadded:: 2.0 | Below is the the instruction that describes the task:
### Input:
Decorator ignoring defined info messages at the end of test method. As
param use what
:py:meth:`~.WebdriverWrapperInfoMixin.get_info_messages`
returns.
.. versionadded:: 2.0
### Response:
def allowed_info_messages(*info_messages):
... |
def _set_route_target(self, v, load=False):
"""
Setter method for route_target, mapped from YANG variable /rbridge_id/vrf/address_family/ipv6/unicast/route_target (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_route_target is considered as a private
method. B... | Setter method for route_target, mapped from YANG variable /rbridge_id/vrf/address_family/ipv6/unicast/route_target (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_route_target is considered as a private
method. Backends looking to populate this variable should
do ... | Below is the the instruction that describes the task:
### Input:
Setter method for route_target, mapped from YANG variable /rbridge_id/vrf/address_family/ipv6/unicast/route_target (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_route_target is considered as a private
... |
def cmd_devop(self, args):
'''device operations'''
usage = "Usage: devop <read|write> <spi|i2c> name bus address"
if len(args) < 5:
print(usage)
return
if args[1] == 'spi':
bustype = mavutil.mavlink.DEVICE_OP_BUSTYPE_SPI
elif args[1] == 'i2c':... | device operations | Below is the the instruction that describes the task:
### Input:
device operations
### Response:
def cmd_devop(self, args):
'''device operations'''
usage = "Usage: devop <read|write> <spi|i2c> name bus address"
if len(args) < 5:
print(usage)
return
if args[1... |
def rename(self, arr, new_name=True):
"""
Rename an array to find a name that isn't already in the list
Parameters
----------
arr: InteractiveBase
A :class:`InteractiveArray` or :class:`InteractiveList` instance
whose name shall be checked
new_nam... | Rename an array to find a name that isn't already in the list
Parameters
----------
arr: InteractiveBase
A :class:`InteractiveArray` or :class:`InteractiveList` instance
whose name shall be checked
new_name: bool or str
If False, and the ``arr_name`` ... | Below is the the instruction that describes the task:
### Input:
Rename an array to find a name that isn't already in the list
Parameters
----------
arr: InteractiveBase
A :class:`InteractiveArray` or :class:`InteractiveList` instance
whose name shall be checked
... |
def handle_update(self, action, params):
"""Handle the specified action on this component."""
_LOGGER.debug('Keypad: "%s" Handling "%s" Action: %s Params: %s"' % (
self._keypad.name, self.name, action, params))
return False | Handle the specified action on this component. | Below is the the instruction that describes the task:
### Input:
Handle the specified action on this component.
### Response:
def handle_update(self, action, params):
"""Handle the specified action on this component."""
_LOGGER.debug('Keypad: "%s" Handling "%s" Action: %s Params: %s"' % (
... |
def set_label(self, label, lang=None):
"""Sets the `label` metadata property on your Thing/Point. Only one label is allowed per language, so any
other labels in this language are removed before adding this one
Raises `ValueError` containing an error message if the parameters fail validation
... | Sets the `label` metadata property on your Thing/Point. Only one label is allowed per language, so any
other labels in this language are removed before adding this one
Raises `ValueError` containing an error message if the parameters fail validation
`label` (mandatory) (string) the new text o... | Below is the the instruction that describes the task:
### Input:
Sets the `label` metadata property on your Thing/Point. Only one label is allowed per language, so any
other labels in this language are removed before adding this one
Raises `ValueError` containing an error message if the parameters... |
def resources_gc_prefix(options, policy_config, policy_collection):
"""Garbage collect old custodian policies based on prefix.
We attempt to introspect to find the event sources for a policy
but without the old configuration this is implicit.
"""
# Classify policies by region
policy_regions = ... | Garbage collect old custodian policies based on prefix.
We attempt to introspect to find the event sources for a policy
but without the old configuration this is implicit. | Below is the the instruction that describes the task:
### Input:
Garbage collect old custodian policies based on prefix.
We attempt to introspect to find the event sources for a policy
but without the old configuration this is implicit.
### Response:
def resources_gc_prefix(options, policy_config, policy_... |
def _merge_tops_same(self, tops):
'''
For each saltenv, only consider the top file from that saltenv. All
sections matching a given saltenv, which appear in a different
saltenv's top file, will be ignored.
'''
top = DefaultOrderedDict(OrderedDict)
for cenv, ctops ... | For each saltenv, only consider the top file from that saltenv. All
sections matching a given saltenv, which appear in a different
saltenv's top file, will be ignored. | Below is the the instruction that describes the task:
### Input:
For each saltenv, only consider the top file from that saltenv. All
sections matching a given saltenv, which appear in a different
saltenv's top file, will be ignored.
### Response:
def _merge_tops_same(self, tops):
'''
... |
def packtar(tarfile, files, srcdir):
""" Pack the given files into a tar, setting cwd = srcdir"""
nullfd = open(os.devnull, "w")
tarfile = cygpath(os.path.abspath(tarfile))
log.debug("pack tar %s from folder %s with files ", tarfile, srcdir)
log.debug(files)
try:
check_call([TAR, '-czf'... | Pack the given files into a tar, setting cwd = srcdir | Below is the the instruction that describes the task:
### Input:
Pack the given files into a tar, setting cwd = srcdir
### Response:
def packtar(tarfile, files, srcdir):
""" Pack the given files into a tar, setting cwd = srcdir"""
nullfd = open(os.devnull, "w")
tarfile = cygpath(os.path.abspath(tarfile... |
def estimate_library_complexity(df, algorithm="RNA-seq"):
"""
estimate library complexity from the number of reads vs.
number of unique start sites. returns "NA" if there are
not enough data points to fit the line
"""
DEFAULT_CUTOFFS = {"RNA-seq": (0.25, 0.40)}
cutoffs = DEFAULT_CUTOFFS[algo... | estimate library complexity from the number of reads vs.
number of unique start sites. returns "NA" if there are
not enough data points to fit the line | Below is the the instruction that describes the task:
### Input:
estimate library complexity from the number of reads vs.
number of unique start sites. returns "NA" if there are
not enough data points to fit the line
### Response:
def estimate_library_complexity(df, algorithm="RNA-seq"):
"""
estima... |
def _parselog(self, r):
"""
Parse bazaar log file format
Args:
r (str): bzr revision identifier
Yields:
dict: dict of (attr, value) pairs
::
$ bzr log -l1
------------------------------------------------------------
... | Parse bazaar log file format
Args:
r (str): bzr revision identifier
Yields:
dict: dict of (attr, value) pairs
::
$ bzr log -l1
------------------------------------------------------------
revno: 1
committer: ubuntu <ubun... | Below is the the instruction that describes the task:
### Input:
Parse bazaar log file format
Args:
r (str): bzr revision identifier
Yields:
dict: dict of (attr, value) pairs
::
$ bzr log -l1
------------------------------------------------... |
def add_after(self):
"""Returns a builder inserting a new block after the current block"""
idx = self._container.structure.index(self)
return BlockBuilder(self._container, idx+1) | Returns a builder inserting a new block after the current block | Below is the the instruction that describes the task:
### Input:
Returns a builder inserting a new block after the current block
### Response:
def add_after(self):
"""Returns a builder inserting a new block after the current block"""
idx = self._container.structure.index(self)
return BlockB... |
def plot_predict(self, h=5, past_values=20, intervals=True, oos_data=None, **kwargs):
""" Makes forecast with the estimated model
Parameters
----------
h : int (default : 5)
How many steps ahead would you like to forecast?
past_values : int (default : 20)
... | Makes forecast with the estimated model
Parameters
----------
h : int (default : 5)
How many steps ahead would you like to forecast?
past_values : int (default : 20)
How many past observations to show on the forecast graph?
intervals : Boolean
... | Below is the the instruction that describes the task:
### Input:
Makes forecast with the estimated model
Parameters
----------
h : int (default : 5)
How many steps ahead would you like to forecast?
past_values : int (default : 20)
How many past observations ... |
def setData(self, index, value, role=Qt.EditRole):
"""
Reimplements the :meth:`QAbstractItemModel.setData` method.
:param index: Index.
:type index: QModelIndex
:param value: Value.
:type value: QVariant
:param role: Role.
:type role: int
:return:... | Reimplements the :meth:`QAbstractItemModel.setData` method.
:param index: Index.
:type index: QModelIndex
:param value: Value.
:type value: QVariant
:param role: Role.
:type role: int
:return: Method success.
:rtype: bool | Below is the the instruction that describes the task:
### Input:
Reimplements the :meth:`QAbstractItemModel.setData` method.
:param index: Index.
:type index: QModelIndex
:param value: Value.
:type value: QVariant
:param role: Role.
:type role: int
:return: M... |
def correct_db_restart(self):
"""Ensure DB is consistent after unexpected restarts. """
LOG.info("Checking consistency of DB")
# Any Segments allocated that's not in Network or FW DB, release it
seg_netid_dict = self.service_segs.get_seg_netid_src(fw_const.FW_CONST)
vlan_netid_di... | Ensure DB is consistent after unexpected restarts. | Below is the the instruction that describes the task:
### Input:
Ensure DB is consistent after unexpected restarts.
### Response:
def correct_db_restart(self):
"""Ensure DB is consistent after unexpected restarts. """
LOG.info("Checking consistency of DB")
# Any Segments allocated that's no... |
def _get_encrypted_masterpassword(self):
""" Obtain the encrypted masterkey
.. note:: The encrypted masterkey is checksummed, so that we can
figure out that a provided password is correct or not. The
checksum is only 4 bytes long!
"""
if not self.unlo... | Obtain the encrypted masterkey
.. note:: The encrypted masterkey is checksummed, so that we can
figure out that a provided password is correct or not. The
checksum is only 4 bytes long! | Below is the the instruction that describes the task:
### Input:
Obtain the encrypted masterkey
.. note:: The encrypted masterkey is checksummed, so that we can
figure out that a provided password is correct or not. The
checksum is only 4 bytes long!
### Response:
def _... |
def refresh(self, index=None):
"""Refresh tabwidget"""
if index is None:
index = self.get_stack_index()
# Set current editor
if self.get_stack_count():
index = self.get_stack_index()
finfo = self.data[index]
editor = finfo.editor
... | Refresh tabwidget | Below is the the instruction that describes the task:
### Input:
Refresh tabwidget
### Response:
def refresh(self, index=None):
"""Refresh tabwidget"""
if index is None:
index = self.get_stack_index()
# Set current editor
if self.get_stack_count():
inde... |
def process_children(self, node, elem, module, path, omit=[]):
"""Proceed with all children of `node`."""
for ch in node.i_children:
if ch not in omit and (ch.i_config or self.doctype == "data"):
self.node_handler.get(ch.keyword, self.ignore)(
ch, elem, mo... | Proceed with all children of `node`. | Below is the the instruction that describes the task:
### Input:
Proceed with all children of `node`.
### Response:
def process_children(self, node, elem, module, path, omit=[]):
"""Proceed with all children of `node`."""
for ch in node.i_children:
if ch not in omit and (ch.i_config or ... |
def get(cls, *args, **kwargs):
"""Create and return a serializable Report object, retrieved from cache if possible"""
from indico_piwik.plugin import PiwikPlugin
if not PiwikPlugin.settings.get('cache_enabled'):
return cls(*args, **kwargs).to_serializable()
cache = Generic... | Create and return a serializable Report object, retrieved from cache if possible | Below is the the instruction that describes the task:
### Input:
Create and return a serializable Report object, retrieved from cache if possible
### Response:
def get(cls, *args, **kwargs):
"""Create and return a serializable Report object, retrieved from cache if possible"""
from indico_piwik.pl... |
def get_word_saliency(topic_word_distrib, doc_topic_distrib, doc_lengths):
"""
Calculate word saliency according to Chuang et al. 2012.
saliency(w) = p(w) * distinctiveness(w)
J. Chuang, C. Manning, J. Heer 2012: "Termite: Visualization Techniques for Assessing Textual Topic Models"
"""
p_t = g... | Calculate word saliency according to Chuang et al. 2012.
saliency(w) = p(w) * distinctiveness(w)
J. Chuang, C. Manning, J. Heer 2012: "Termite: Visualization Techniques for Assessing Textual Topic Models" | Below is the the instruction that describes the task:
### Input:
Calculate word saliency according to Chuang et al. 2012.
saliency(w) = p(w) * distinctiveness(w)
J. Chuang, C. Manning, J. Heer 2012: "Termite: Visualization Techniques for Assessing Textual Topic Models"
### Response:
def get_word_saliency(... |
def p44(msg):
"""Static pressure.
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
int: static pressure in hPa
"""
d = hex2bin(data(msg))
if d[34] == '0':
return None
p = bin2int(d[35:46]) # hPa
return p | Static pressure.
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
int: static pressure in hPa | Below is the the instruction that describes the task:
### Input:
Static pressure.
Args:
msg (String): 28 bytes hexadecimal message string
Returns:
int: static pressure in hPa
### Response:
def p44(msg):
"""Static pressure.
Args:
msg (String): 28 bytes hexadecimal message ... |
def outputStandard(self, extended=False):
"""
Standard, multi-line output display
"""
successfulResponses = len(
[
True for rsp in self.results if rsp['success']
]
)
sys.stdout.write(""" - RESULTS
I asked {num_servers} servers fo... | Standard, multi-line output display | Below is the the instruction that describes the task:
### Input:
Standard, multi-line output display
### Response:
def outputStandard(self, extended=False):
"""
Standard, multi-line output display
"""
successfulResponses = len(
[
True for rsp in self.res... |
def solve_sdr(prob, *args, **kwargs):
"""Solve the SDP relaxation.
"""
# lifted variables and semidefinite constraint
X = cvx.Semidef(prob.n + 1)
W = prob.f0.homogeneous_form()
rel_obj = cvx.Minimize(cvx.sum_entries(cvx.mul_elemwise(W, X)))
rel_constr = [X[-1, -1] == 1]
for f in prob.... | Solve the SDP relaxation. | Below is the the instruction that describes the task:
### Input:
Solve the SDP relaxation.
### Response:
def solve_sdr(prob, *args, **kwargs):
"""Solve the SDP relaxation.
"""
# lifted variables and semidefinite constraint
X = cvx.Semidef(prob.n + 1)
W = prob.f0.homogeneous_form()
rel_obj... |
def check_match(self, name):
"""
Check if a release version matches any of the specificed patterns.
Parameters
==========
name: str
Release name
Returns
=======
bool:
True if it matches, False otherwise.
"""
return... | Check if a release version matches any of the specificed patterns.
Parameters
==========
name: str
Release name
Returns
=======
bool:
True if it matches, False otherwise. | Below is the the instruction that describes the task:
### Input:
Check if a release version matches any of the specificed patterns.
Parameters
==========
name: str
Release name
Returns
=======
bool:
True if it matches, False otherwise.
### Re... |
def protected_resource_view(scopes=None):
"""
View decorator. The client accesses protected resources by presenting the
access token to the resource server.
https://tools.ietf.org/html/rfc6749#section-7
"""
if scopes is None:
scopes = []
def wrapper(view):
def view_wrapper(r... | View decorator. The client accesses protected resources by presenting the
access token to the resource server.
https://tools.ietf.org/html/rfc6749#section-7 | Below is the the instruction that describes the task:
### Input:
View decorator. The client accesses protected resources by presenting the
access token to the resource server.
https://tools.ietf.org/html/rfc6749#section-7
### Response:
def protected_resource_view(scopes=None):
"""
View decorator. T... |
def find_by_name(name):
"""
Find and return a format by name.
:param name: A string describing the name of the format.
"""
for format in FORMATS:
if name == format.name:
return format
raise UnknownFormat('No format found with name "%s"' % name) | Find and return a format by name.
:param name: A string describing the name of the format. | Below is the the instruction that describes the task:
### Input:
Find and return a format by name.
:param name: A string describing the name of the format.
### Response:
def find_by_name(name):
"""
Find and return a format by name.
:param name: A string describing the name of the format.
"""
... |
def image_meta_set(image_id=None,
name=None,
profile=None,
**kwargs): # pylint: disable=C0103
'''
Sets a key=value pair in the metadata for an image (nova image-meta set)
CLI Examples:
.. code-block:: bash
salt '*' nova.image_meta_set ... | Sets a key=value pair in the metadata for an image (nova image-meta set)
CLI Examples:
.. code-block:: bash
salt '*' nova.image_meta_set 6f52b2ff-0b31-4d84-8fd1-af45b84824f6 cheese=gruyere
salt '*' nova.image_meta_set name=myimage salad=pasta beans=baked | Below is the the instruction that describes the task:
### Input:
Sets a key=value pair in the metadata for an image (nova image-meta set)
CLI Examples:
.. code-block:: bash
salt '*' nova.image_meta_set 6f52b2ff-0b31-4d84-8fd1-af45b84824f6 cheese=gruyere
salt '*' nova.image_meta_set name=m... |
def validate_signature(self, signedtext, cert_file, cert_type, node_name, node_id, id_attr):
"""
Validate signature on XML document.
The parameters actually used in this CryptoBackend
implementation are :
:param signedtext: The signed XML data as string
:param cert_file... | Validate signature on XML document.
The parameters actually used in this CryptoBackend
implementation are :
:param signedtext: The signed XML data as string
:param cert_file: xmlsec key_spec string(), filename,
'pkcs11://' URI or PEM data
:param cert_type: string, m... | Below is the the instruction that describes the task:
### Input:
Validate signature on XML document.
The parameters actually used in this CryptoBackend
implementation are :
:param signedtext: The signed XML data as string
:param cert_file: xmlsec key_spec string(), filename,
... |
def _consume(self):
""" Consume commands from the queue.
The command is repeated according to the configured value.
Wait after each command is sent.
The bridge socket is a shared resource. It must only
be used by one thread at a time. Note that this can and
will delay c... | Consume commands from the queue.
The command is repeated according to the configured value.
Wait after each command is sent.
The bridge socket is a shared resource. It must only
be used by one thread at a time. Note that this can and
will delay commands if multiple groups are a... | Below is the the instruction that describes the task:
### Input:
Consume commands from the queue.
The command is repeated according to the configured value.
Wait after each command is sent.
The bridge socket is a shared resource. It must only
be used by one thread at a time. Note t... |
def isnumeric(obj):
'''
Return true if obj is a numeric value
'''
from decimal import Decimal
if type(obj) == Decimal:
return True
else:
try:
float(obj)
except:
return False
return True | Return true if obj is a numeric value | Below is the the instruction that describes the task:
### Input:
Return true if obj is a numeric value
### Response:
def isnumeric(obj):
'''
Return true if obj is a numeric value
'''
from decimal import Decimal
if type(obj) == Decimal:
return True
else:
try:
... |
def _combine_results(self, match_as_dict):
'''Combine results from different parsed parts:
we look for non-empty results in values like
'postal_code_b' or 'postal_code_c' and store
them as main value.
So 'postal_code_b':'123456'
becomes:
... | Combine results from different parsed parts:
we look for non-empty results in values like
'postal_code_b' or 'postal_code_c' and store
them as main value.
So 'postal_code_b':'123456'
becomes:
'postal_code' :'123456' | Below is the the instruction that describes the task:
### Input:
Combine results from different parsed parts:
we look for non-empty results in values like
'postal_code_b' or 'postal_code_c' and store
them as main value.
So 'postal_code_b':'123456'
bec... |
def generate_view_data(self):
"""Generate the views."""
self.view_data['version'] = '{} {}'.format('Glances', __version__)
self.view_data['psutil_version'] = ' with psutil {}'.format(psutil_version)
try:
self.view_data['configuration_file'] = 'Configuration file: {}'.format(... | Generate the views. | Below is the the instruction that describes the task:
### Input:
Generate the views.
### Response:
def generate_view_data(self):
"""Generate the views."""
self.view_data['version'] = '{} {}'.format('Glances', __version__)
self.view_data['psutil_version'] = ' with psutil {}'.format(psutil_ve... |
def import_file(
src,
file_name,
imported_format=ImportedFormat.BOTH,
progress_from=0.0,
progress_to=None,
):
"""Import file to working directory.
:param src: Source file path or URL
:param file_name: Source file name
:param imported_format: Import file format (extracted, compressed... | Import file to working directory.
:param src: Source file path or URL
:param file_name: Source file name
:param imported_format: Import file format (extracted, compressed or both)
:param progress_from: Initial progress value
:param progress_to: Final progress value
:return: Destination file pat... | Below is the the instruction that describes the task:
### Input:
Import file to working directory.
:param src: Source file path or URL
:param file_name: Source file name
:param imported_format: Import file format (extracted, compressed or both)
:param progress_from: Initial progress value
:para... |
def go_to_marker(self, row, col, table_type):
"""Move to point in time marked by the marker.
Parameters
----------
row : QtCore.int
column : QtCore.int
table_type : str
'dataset' table or 'annot' table, it works on either
"""
if table_type =... | Move to point in time marked by the marker.
Parameters
----------
row : QtCore.int
column : QtCore.int
table_type : str
'dataset' table or 'annot' table, it works on either | Below is the the instruction that describes the task:
### Input:
Move to point in time marked by the marker.
Parameters
----------
row : QtCore.int
column : QtCore.int
table_type : str
'dataset' table or 'annot' table, it works on either
### Response:
def go_t... |
def postinit(self, left=None, ops=None):
"""Do some setup after initialisation.
:param left: The value at the left being applied to a comparison
operator.
:type left: NodeNG or None
:param ops: The remainder of the operators
and their relevant right hand value.
... | Do some setup after initialisation.
:param left: The value at the left being applied to a comparison
operator.
:type left: NodeNG or None
:param ops: The remainder of the operators
and their relevant right hand value.
:type ops: list(tuple(str, NodeNG)) or None | Below is the the instruction that describes the task:
### Input:
Do some setup after initialisation.
:param left: The value at the left being applied to a comparison
operator.
:type left: NodeNG or None
:param ops: The remainder of the operators
and their relevant r... |
def accept_reject_or_neither(self, url, parent_page=None):
'''
Returns `True` (accepted), `False` (rejected), or `None` (no decision).
`None` usually means rejected, unless `max_hops_off` comes into play.
'''
if not isinstance(url, urlcanon.ParsedUrl):
url = urlcanon... | Returns `True` (accepted), `False` (rejected), or `None` (no decision).
`None` usually means rejected, unless `max_hops_off` comes into play. | Below is the the instruction that describes the task:
### Input:
Returns `True` (accepted), `False` (rejected), or `None` (no decision).
`None` usually means rejected, unless `max_hops_off` comes into play.
### Response:
def accept_reject_or_neither(self, url, parent_page=None):
'''
Return... |
def normalize_exception(self, space):
"""Normalize the OperationError. In other words, fix w_type and/or
w_value to make sure that the __class__ of w_value is exactly w_type.
"""
#
# This method covers all ways in which the Python statement
# "raise X, Y" can produce a v... | Normalize the OperationError. In other words, fix w_type and/or
w_value to make sure that the __class__ of w_value is exactly w_type. | Below is the the instruction that describes the task:
### Input:
Normalize the OperationError. In other words, fix w_type and/or
w_value to make sure that the __class__ of w_value is exactly w_type.
### Response:
def normalize_exception(self, space):
"""Normalize the OperationError. In other word... |
def cycle_canceling(self, display):
'''
API:
cycle_canceling(self, display)
Description:
Solves minimum cost feasible flow problem using cycle canceling
algorithm. Returns True when an optimal solution is found, returns
False otherwise. 'flow' attr... | API:
cycle_canceling(self, display)
Description:
Solves minimum cost feasible flow problem using cycle canceling
algorithm. Returns True when an optimal solution is found, returns
False otherwise. 'flow' attribute values of arcs should be
considered as... | Below is the the instruction that describes the task:
### Input:
API:
cycle_canceling(self, display)
Description:
Solves minimum cost feasible flow problem using cycle canceling
algorithm. Returns True when an optimal solution is found, returns
False otherwise... |
def unchunk(self):
"""
Convert a chunked array back into a full array with (key,value) pairs
where key is a tuple of indices, and value is an ndarray.
"""
plan, padding, vshape, split = self.plan, self.padding, self.vshape, self.split
nchunks = self.getnumber(plan, vshape... | Convert a chunked array back into a full array with (key,value) pairs
where key is a tuple of indices, and value is an ndarray. | Below is the the instruction that describes the task:
### Input:
Convert a chunked array back into a full array with (key,value) pairs
where key is a tuple of indices, and value is an ndarray.
### Response:
def unchunk(self):
"""
Convert a chunked array back into a full array with (key,valu... |
def moment_inertia(self):
"""
The analytic inertia tensor of the sphere primitive.
Returns
----------
tensor: (3,3) float, 3D inertia tensor
"""
tensor = inertia.sphere_inertia(mass=self.volume,
radius=self.primitive.radius... | The analytic inertia tensor of the sphere primitive.
Returns
----------
tensor: (3,3) float, 3D inertia tensor | Below is the the instruction that describes the task:
### Input:
The analytic inertia tensor of the sphere primitive.
Returns
----------
tensor: (3,3) float, 3D inertia tensor
### Response:
def moment_inertia(self):
"""
The analytic inertia tensor of the sphere primitive.
... |
def add_ignored(self, ignored):
"""Add ignored text to the node. This will add the length of the ignored text to the node's
consumed property.
"""
if ignored:
if self.ignored:
self.ignored = ignored + self.ignored
else:
self.ignored = ignored
self.consumed += len(ignored... | Add ignored text to the node. This will add the length of the ignored text to the node's
consumed property. | Below is the the instruction that describes the task:
### Input:
Add ignored text to the node. This will add the length of the ignored text to the node's
consumed property.
### Response:
def add_ignored(self, ignored):
"""Add ignored text to the node. This will add the length of the ignored text to the nod... |
def get_datetime_at_period_ix(self, ix):
"""
Get the datetime at a given period.
:param period: The index of the period.
:returns: The datetime.
"""
if self.timestep_period_duration == TimePeriod.millisecond:
return self.start_datetime + timedelta(milliseco... | Get the datetime at a given period.
:param period: The index of the period.
:returns: The datetime. | Below is the the instruction that describes the task:
### Input:
Get the datetime at a given period.
:param period: The index of the period.
:returns: The datetime.
### Response:
def get_datetime_at_period_ix(self, ix):
"""
Get the datetime at a given period.
:param perio... |
def visit_GeneratorExp(self, node: AST, dfltChaining: bool = True) -> str:
"""Return `node`s representation as generator expression."""
return f"({self.visit(node.elt)} " \
f"{' '.join(self.visit(gen) for gen in node.generators)})" | Return `node`s representation as generator expression. | Below is the the instruction that describes the task:
### Input:
Return `node`s representation as generator expression.
### Response:
def visit_GeneratorExp(self, node: AST, dfltChaining: bool = True) -> str:
"""Return `node`s representation as generator expression."""
return f"({self.visit(node.el... |
def zbar_function(fname, restype, *args):
"""Returns a foreign function exported by `zbar`.
Args:
fname (:obj:`str`): Name of the exported function as string.
restype (:obj:): Return type - one of the `ctypes` primitive C data
types.
*args: Arguments - a sequence of `ctypes` pri... | Returns a foreign function exported by `zbar`.
Args:
fname (:obj:`str`): Name of the exported function as string.
restype (:obj:): Return type - one of the `ctypes` primitive C data
types.
*args: Arguments - a sequence of `ctypes` primitive C data types.
Returns:
cddl.C... | Below is the the instruction that describes the task:
### Input:
Returns a foreign function exported by `zbar`.
Args:
fname (:obj:`str`): Name of the exported function as string.
restype (:obj:): Return type - one of the `ctypes` primitive C data
types.
*args: Arguments - a sequ... |
def deterministic_shuffle(list_, seed=0, rng=None):
r"""
Args:
list_ (list):
seed (int):
Returns:
list: list_
CommandLine:
python -m utool.util_numpy --test-deterministic_shuffle
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_numpy import * # NO... | r"""
Args:
list_ (list):
seed (int):
Returns:
list: list_
CommandLine:
python -m utool.util_numpy --test-deterministic_shuffle
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_numpy import * # NOQA
>>> list_ = [1, 2, 3, 4, 5, 6]
>>> se... | Below is the the instruction that describes the task:
### Input:
r"""
Args:
list_ (list):
seed (int):
Returns:
list: list_
CommandLine:
python -m utool.util_numpy --test-deterministic_shuffle
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_numpy i... |
def create_track_token(request):
"""Returns ``TrackToken``.
``TrackToken' contains request and user making changes.
It can be passed to ``TrackedModel.save`` instead of ``request``.
It is intended to be used when passing ``request`` is not possible
e.g. when ``TrackedModel.save`` will be called fro... | Returns ``TrackToken``.
``TrackToken' contains request and user making changes.
It can be passed to ``TrackedModel.save`` instead of ``request``.
It is intended to be used when passing ``request`` is not possible
e.g. when ``TrackedModel.save`` will be called from celery task. | Below is the the instruction that describes the task:
### Input:
Returns ``TrackToken``.
``TrackToken' contains request and user making changes.
It can be passed to ``TrackedModel.save`` instead of ``request``.
It is intended to be used when passing ``request`` is not possible
e.g. when ``TrackedMo... |
def quit(self, reason=''):
"""
Sends a QUIT message, closes the connection and -
ends Lurklib's main loop.
Optional arguments:
* reason='' - Reason for quitting.
"""
with self.lock:
self.keep_going = False
self._quit(reason)
... | Sends a QUIT message, closes the connection and -
ends Lurklib's main loop.
Optional arguments:
* reason='' - Reason for quitting. | Below is the the instruction that describes the task:
### Input:
Sends a QUIT message, closes the connection and -
ends Lurklib's main loop.
Optional arguments:
* reason='' - Reason for quitting.
### Response:
def quit(self, reason=''):
"""
Sends a QUIT message, closes t... |
def create_namespaced_resource_quota(self, namespace, body, **kwargs): # noqa: E501
"""create_namespaced_resource_quota # noqa: E501
create a ResourceQuota # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_re... | create_namespaced_resource_quota # noqa: E501
create a ResourceQuota # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_namespaced_resource_quota(namespace, body, async_req=True... | Below is the the instruction that describes the task:
### Input:
create_namespaced_resource_quota # noqa: E501
create a ResourceQuota # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread =... |
def get_query_builder(self, *args, **kwargs):
"""
Return the query builder class instance that should be used to
build the query which is passed to the search engine backend.
"""
query_builder = self.get_query_builder_class()
return query_builder(*args, **kwargs) | Return the query builder class instance that should be used to
build the query which is passed to the search engine backend. | Below is the the instruction that describes the task:
### Input:
Return the query builder class instance that should be used to
build the query which is passed to the search engine backend.
### Response:
def get_query_builder(self, *args, **kwargs):
"""
Return the query builder class instan... |
def _send_splunk(event, index_override=None, sourcetype_override=None):
'''
Send the results to Splunk.
Requires the Splunk HTTP Event Collector running on port 8088.
This is available on Splunk Enterprise version 6.3 or higher.
'''
# Get Splunk Options
opts = _get_options()
log.info(st... | Send the results to Splunk.
Requires the Splunk HTTP Event Collector running on port 8088.
This is available on Splunk Enterprise version 6.3 or higher. | Below is the the instruction that describes the task:
### Input:
Send the results to Splunk.
Requires the Splunk HTTP Event Collector running on port 8088.
This is available on Splunk Enterprise version 6.3 or higher.
### Response:
def _send_splunk(event, index_override=None, sourcetype_override=None):
... |
def get_actions(self, params):
"""Send a HTTP request to the satellite (GET /_checks)
Get actions from the scheduler.
Un-serialize data received.
:param params: the request parameters
:type params: str
:return: Actions list on success, [] on failure
:rtype: list
... | Send a HTTP request to the satellite (GET /_checks)
Get actions from the scheduler.
Un-serialize data received.
:param params: the request parameters
:type params: str
:return: Actions list on success, [] on failure
:rtype: list | Below is the the instruction that describes the task:
### Input:
Send a HTTP request to the satellite (GET /_checks)
Get actions from the scheduler.
Un-serialize data received.
:param params: the request parameters
:type params: str
:return: Actions list on success, [] on fa... |
def get_rsc_list_2(self, rsc_clz_list=None):
"""get the list of resource list to collect based on clz list
:param rsc_clz_list: the list of classes to collect
:return: filtered list of resource list,
like [VNXLunList(), VNXDiskList()]
"""
rsc_list_2 = self._defa... | get the list of resource list to collect based on clz list
:param rsc_clz_list: the list of classes to collect
:return: filtered list of resource list,
like [VNXLunList(), VNXDiskList()] | Below is the the instruction that describes the task:
### Input:
get the list of resource list to collect based on clz list
:param rsc_clz_list: the list of classes to collect
:return: filtered list of resource list,
like [VNXLunList(), VNXDiskList()]
### Response:
def get_rsc_lis... |
def hash(self, raw: Any) -> str:
"""
Returns the hex digest of a HMAC-encoded version of the input.
"""
with MultiTimerContext(timer, TIMING_HASH):
raw_bytes = str(raw).encode('utf-8')
hmac_obj = hmac.new(key=self.key_bytes, msg=raw_bytes,
... | Returns the hex digest of a HMAC-encoded version of the input. | Below is the the instruction that describes the task:
### Input:
Returns the hex digest of a HMAC-encoded version of the input.
### Response:
def hash(self, raw: Any) -> str:
"""
Returns the hex digest of a HMAC-encoded version of the input.
"""
with MultiTimerContext(timer, TIMING_... |
def verify_report(self, device_id, root, data, signature, **kwargs):
"""Verify a buffer of report data on behalf of a device.
Args:
device_id (int): The id of the device that we should encrypt for
root (int): The root key type that should be used to generate the report
... | Verify a buffer of report data on behalf of a device.
Args:
device_id (int): The id of the device that we should encrypt for
root (int): The root key type that should be used to generate the report
data (bytearray): The data that we should verify
signature (bytea... | Below is the the instruction that describes the task:
### Input:
Verify a buffer of report data on behalf of a device.
Args:
device_id (int): The id of the device that we should encrypt for
root (int): The root key type that should be used to generate the report
data (by... |
def _create_add_petabencana_layer_action(self):
"""Create action for import OSM Dialog."""
icon = resources_path('img', 'icons', 'add-petabencana-layer.svg')
self.action_add_petabencana_layer = QAction(
QIcon(icon),
self.tr('Add PetaBencana Flood Layer'),
self... | Create action for import OSM Dialog. | Below is the the instruction that describes the task:
### Input:
Create action for import OSM Dialog.
### Response:
def _create_add_petabencana_layer_action(self):
"""Create action for import OSM Dialog."""
icon = resources_path('img', 'icons', 'add-petabencana-layer.svg')
self.action_add_p... |
def iteritems(self):
"""Iterator across all the non-duplicate keys and their values.
Only yields the first key of duplicates.
"""
keys_yielded = set()
for k, v in self._pairs:
if k not in keys_yielded:
keys_yielded.add(k)
... | Iterator across all the non-duplicate keys and their values.
Only yields the first key of duplicates. | Below is the the instruction that describes the task:
### Input:
Iterator across all the non-duplicate keys and their values.
Only yields the first key of duplicates.
### Response:
def iteritems(self):
"""Iterator across all the non-duplicate keys and their values.
Only yi... |
def cmd_shodan(ip, no_cache, verbose, output):
"""Simple shodan API client.
Prints the JSON result of a shodan query.
Example:
\b
$ habu.shodan 8.8.8.8
{
"hostnames": [
"google-public-dns-a.google.com"
],
"country_code": "US",
"org": "Google",
... | Simple shodan API client.
Prints the JSON result of a shodan query.
Example:
\b
$ habu.shodan 8.8.8.8
{
"hostnames": [
"google-public-dns-a.google.com"
],
"country_code": "US",
"org": "Google",
"data": [
{
"isp": "Goo... | Below is the the instruction that describes the task:
### Input:
Simple shodan API client.
Prints the JSON result of a shodan query.
Example:
\b
$ habu.shodan 8.8.8.8
{
"hostnames": [
"google-public-dns-a.google.com"
],
"country_code": "US",
"org": ... |
def all(self):
"""
Returns all the values joined together.
:return <int>
"""
out = 0
for key, value in self.items():
out |= value
return out | Returns all the values joined together.
:return <int> | Below is the the instruction that describes the task:
### Input:
Returns all the values joined together.
:return <int>
### Response:
def all(self):
"""
Returns all the values joined together.
:return <int>
"""
out = 0
for key, value ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.