code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def gen_send_version_url(ip, port):
'''Generate send error url'''
return '{0}:{1}{2}{3}/{4}/{5}'.format(BASE_URL.format(ip), port, API_ROOT_URL, VERSION_API, NNI_EXP_ID, NNI_TRIAL_JOB_ID) | Generate send error url | Below is the the instruction that describes the task:
### Input:
Generate send error url
### Response:
def gen_send_version_url(ip, port):
'''Generate send error url'''
return '{0}:{1}{2}{3}/{4}/{5}'.format(BASE_URL.format(ip), port, API_ROOT_URL, VERSION_API, NNI_EXP_ID, NNI_TRIAL_JOB_ID) |
def pivot(self, pivot_col, values=None):
"""
Pivots a column of the current :class:`DataFrame` and perform the specified aggregation.
There are two versions of pivot function: one that requires the caller to specify the list
of distinct values to pivot on, and one that does not. The latt... | Pivots a column of the current :class:`DataFrame` and perform the specified aggregation.
There are two versions of pivot function: one that requires the caller to specify the list
of distinct values to pivot on, and one that does not. The latter is more concise but less
efficient, because Spark ... | Below is the the instruction that describes the task:
### Input:
Pivots a column of the current :class:`DataFrame` and perform the specified aggregation.
There are two versions of pivot function: one that requires the caller to specify the list
of distinct values to pivot on, and one that does not. ... |
def calibrate_signal(signal, resp, fs, frange):
"""Given original signal and recording, spits out a calibrated signal"""
# remove dc offset from recorded response (synthesized orignal shouldn't have one)
dc = np.mean(resp)
resp = resp - dc
npts = len(signal)
f0 = np.ceil(frange[0] / (float(fs) ... | Given original signal and recording, spits out a calibrated signal | Below is the the instruction that describes the task:
### Input:
Given original signal and recording, spits out a calibrated signal
### Response:
def calibrate_signal(signal, resp, fs, frange):
"""Given original signal and recording, spits out a calibrated signal"""
# remove dc offset from recorded respons... |
def calc_track_errors(model_tracks, obs_tracks, track_pairings):
"""
Calculates spatial and temporal translation errors between matched
forecast and observed tracks.
Args:
model_tracks: List of model track STObjects
obs_tracks: List of observed track STObjects
... | Calculates spatial and temporal translation errors between matched
forecast and observed tracks.
Args:
model_tracks: List of model track STObjects
obs_tracks: List of observed track STObjects
track_pairings: List of tuples pairing forecast and observed tracks.
... | Below is the the instruction that describes the task:
### Input:
Calculates spatial and temporal translation errors between matched
forecast and observed tracks.
Args:
model_tracks: List of model track STObjects
obs_tracks: List of observed track STObjects
track_... |
def setup_cmd_parser(cls):
"""Returns the Gerrit argument parser."""
parser = BackendCommandArgumentParser(cls.BACKEND.CATEGORIES,
from_date=True,
archive=True)
# Gerrit options
group = parser.p... | Returns the Gerrit argument parser. | Below is the the instruction that describes the task:
### Input:
Returns the Gerrit argument parser.
### Response:
def setup_cmd_parser(cls):
"""Returns the Gerrit argument parser."""
parser = BackendCommandArgumentParser(cls.BACKEND.CATEGORIES,
from_d... |
def add_watcher(self, issue, watcher):
"""Add a user to an issue's watchers list.
:param issue: ID or key of the issue affected
:param watcher: username of the user to add to the watchers list
"""
url = self._get_url('issue/' + str(issue) + '/watchers')
self._session.pos... | Add a user to an issue's watchers list.
:param issue: ID or key of the issue affected
:param watcher: username of the user to add to the watchers list | Below is the the instruction that describes the task:
### Input:
Add a user to an issue's watchers list.
:param issue: ID or key of the issue affected
:param watcher: username of the user to add to the watchers list
### Response:
def add_watcher(self, issue, watcher):
"""Add a user to an i... |
def get_all_connected_devices(self):
"""
Get all info about devices connected to the box
:return: a list with each device info
:rtype: list
"""
self.bbox_auth.set_access(BboxConstant.AUTHENTICATION_LEVEL_PUBLIC, BboxConstant.AUTHENTICATION_LEVEL_PRIVATE)
self.bbox... | Get all info about devices connected to the box
:return: a list with each device info
:rtype: list | Below is the the instruction that describes the task:
### Input:
Get all info about devices connected to the box
:return: a list with each device info
:rtype: list
### Response:
def get_all_connected_devices(self):
"""
Get all info about devices connected to the box
:return:... |
def fetch_entities(self):
"""Fetch entities for which we have data."""
query = text(
"""
SELECT entity_id
FROM states
GROUP BY entity_id
"""
)
response = self.perform_query(query)
# Parse the domains from the entities.
... | Fetch entities for which we have data. | Below is the the instruction that describes the task:
### Input:
Fetch entities for which we have data.
### Response:
def fetch_entities(self):
"""Fetch entities for which we have data."""
query = text(
"""
SELECT entity_id
FROM states
GROUP BY entity... |
def monday_of_week(year, week):
"""
Returns a datetime for the monday of the given week of the given year.
"""
str_time = time.strptime('{0} {1} 1'.format(year, week), '%Y %W %w')
date = timezone.datetime(year=str_time.tm_year, month=str_time.tm_mon,
day=str_time.tm_mda... | Returns a datetime for the monday of the given week of the given year. | Below is the the instruction that describes the task:
### Input:
Returns a datetime for the monday of the given week of the given year.
### Response:
def monday_of_week(year, week):
"""
Returns a datetime for the monday of the given week of the given year.
"""
str_time = time.strptime('{0} {1} 1'.... |
def get_command_instance(name, parent=None, checkexists=True):
"""Try to guess and create the appropriate command instance
Given a command name (encountered by the parser), construct the
associated class name and, if known, return a new instance.
If the command is not known or has not been loaded usin... | Try to guess and create the appropriate command instance
Given a command name (encountered by the parser), construct the
associated class name and, if known, return a new instance.
If the command is not known or has not been loaded using require,
an UnknownCommand exception is raised.
:param name... | Below is the the instruction that describes the task:
### Input:
Try to guess and create the appropriate command instance
Given a command name (encountered by the parser), construct the
associated class name and, if known, return a new instance.
If the command is not known or has not been loaded using... |
def search(self, buf):
"""Search the provided buffer for a match to any sub-searchers.
Search the provided buffer for a match to any of this collection's
sub-searchers. If a single matching sub-searcher is found, returns that
sub-searcher's *match* object. If multiple matches are found,... | Search the provided buffer for a match to any sub-searchers.
Search the provided buffer for a match to any of this collection's
sub-searchers. If a single matching sub-searcher is found, returns that
sub-searcher's *match* object. If multiple matches are found, the match
with the smalle... | Below is the the instruction that describes the task:
### Input:
Search the provided buffer for a match to any sub-searchers.
Search the provided buffer for a match to any of this collection's
sub-searchers. If a single matching sub-searcher is found, returns that
sub-searcher's *match* obj... |
def translate_text(estimator, subtokenizer, txt):
"""Translate a single string."""
encoded_txt = _encode_and_add_eos(txt, subtokenizer)
def input_fn():
ds = tf.data.Dataset.from_tensors(encoded_txt)
ds = ds.batch(_DECODE_BATCH_SIZE)
return ds
predictions = estimator.predict(input_fn)
translation... | Translate a single string. | Below is the the instruction that describes the task:
### Input:
Translate a single string.
### Response:
def translate_text(estimator, subtokenizer, txt):
"""Translate a single string."""
encoded_txt = _encode_and_add_eos(txt, subtokenizer)
def input_fn():
ds = tf.data.Dataset.from_tensors(encoded_txt)... |
def get(cls, key):
"""
str, int or Enum => Enum
"""
if isinstance(key, Enum) and not isinstance(key, cls):
raise TypeError("Cannot type cast between enums")
if isinstance(key, int):
if not int(key) in cls._values:
raise KeyError("There is n... | str, int or Enum => Enum | Below is the the instruction that describes the task:
### Input:
str, int or Enum => Enum
### Response:
def get(cls, key):
"""
str, int or Enum => Enum
"""
if isinstance(key, Enum) and not isinstance(key, cls):
raise TypeError("Cannot type cast between enums")
if... |
def fit_error_ellipse(tsmap, xy=None, dpix=3, zmin=None):
"""Fit a positional uncertainty ellipse from a TS map. The fit
will be performed over pixels in the vicinity of the peak pixel
with D < dpix OR z > zmin where D is the distance from the peak
pixel in pixel coordinates and z is the difference in ... | Fit a positional uncertainty ellipse from a TS map. The fit
will be performed over pixels in the vicinity of the peak pixel
with D < dpix OR z > zmin where D is the distance from the peak
pixel in pixel coordinates and z is the difference in amplitude
from the peak pixel.
Parameters
----------... | Below is the the instruction that describes the task:
### Input:
Fit a positional uncertainty ellipse from a TS map. The fit
will be performed over pixels in the vicinity of the peak pixel
with D < dpix OR z > zmin where D is the distance from the peak
pixel in pixel coordinates and z is the difference... |
def remove_usage_rights_courses(self, file_ids, course_id, folder_ids=None):
"""
Remove usage rights.
Removes copyright and license information associated with one or more files
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
... | Remove usage rights.
Removes copyright and license information associated with one or more files | Below is the the instruction that describes the task:
### Input:
Remove usage rights.
Removes copyright and license information associated with one or more files
### Response:
def remove_usage_rights_courses(self, file_ids, course_id, folder_ids=None):
"""
Remove usage rights.
... |
def _indexOfEndTag(istack):
"""
Go through `istack` and search endtag. Element at first index is considered
as opening tag.
Args:
istack (list): List of :class:`.HTMLElement` objects.
Returns:
int: Index of end tag or 0 if not found.
"""
if len(istack) <= 0:
return ... | Go through `istack` and search endtag. Element at first index is considered
as opening tag.
Args:
istack (list): List of :class:`.HTMLElement` objects.
Returns:
int: Index of end tag or 0 if not found. | Below is the the instruction that describes the task:
### Input:
Go through `istack` and search endtag. Element at first index is considered
as opening tag.
Args:
istack (list): List of :class:`.HTMLElement` objects.
Returns:
int: Index of end tag or 0 if not found.
### Response:
def ... |
def _validate_virtualbox(self):
'''
a method to validate that virtualbox is running on Win 7/8 machines
:return: boolean indicating whether virtualbox is running
'''
# validate operating system
if self.localhost.os.sysname != 'Windows':
return Fal... | a method to validate that virtualbox is running on Win 7/8 machines
:return: boolean indicating whether virtualbox is running | Below is the the instruction that describes the task:
### Input:
a method to validate that virtualbox is running on Win 7/8 machines
:return: boolean indicating whether virtualbox is running
### Response:
def _validate_virtualbox(self):
'''
a method to validate that virtualbox is... |
def set_relative_path(self, common_prefix, base_dir):
"""
generate output representation of rows
"""
self.short_filename = self.filename.replace(common_prefix, '', 1) | generate output representation of rows | Below is the the instruction that describes the task:
### Input:
generate output representation of rows
### Response:
def set_relative_path(self, common_prefix, base_dir):
"""
generate output representation of rows
"""
self.short_filename = self.filename.replace(common_prefix, '', 1... |
def random_hex(length):
"""
Return a random hex string.
:param int length: The length of string to return
:returns: A random string
:rtype: str
"""
charset = ''.join(set(string.hexdigits.lower()))
return random_string(length, charset) | Return a random hex string.
:param int length: The length of string to return
:returns: A random string
:rtype: str | Below is the the instruction that describes the task:
### Input:
Return a random hex string.
:param int length: The length of string to return
:returns: A random string
:rtype: str
### Response:
def random_hex(length):
"""
Return a random hex string.
:param int length: The length of strin... |
def fetch_logs(self, lambda_name, filter_pattern='', limit=10000, start_time=0):
"""
Fetch the CloudWatch logs for a given Lambda name.
"""
log_name = '/aws/lambda/' + lambda_name
streams = self.logs_client.describe_log_streams(
logGroupName=log_name,
desc... | Fetch the CloudWatch logs for a given Lambda name. | Below is the the instruction that describes the task:
### Input:
Fetch the CloudWatch logs for a given Lambda name.
### Response:
def fetch_logs(self, lambda_name, filter_pattern='', limit=10000, start_time=0):
"""
Fetch the CloudWatch logs for a given Lambda name.
"""
log_name = '/... |
def find_and_replace(self, node):
"""Parses URIs containing .md and replaces them with their HTML page.
Args:
node(node): docutils node.
Returns:
node: docutils node.
"""
if isinstance(node, nodes.reference) and 'refuri' in node:
reference_uri = node['refuri']
if referenc... | Parses URIs containing .md and replaces them with their HTML page.
Args:
node(node): docutils node.
Returns:
node: docutils node. | Below is the the instruction that describes the task:
### Input:
Parses URIs containing .md and replaces them with their HTML page.
Args:
node(node): docutils node.
Returns:
node: docutils node.
### Response:
def find_and_replace(self, node):
"""Parses URIs containing .md and replaces t... |
def iter_markers(self):
"""
Generate a (marker_code, segment_offset) 2-tuple for each marker in
the JPEG *stream*, in the order they occur in the stream.
"""
marker_finder = _MarkerFinder.from_stream(self._stream)
start = 0
marker_code = None
while marker_... | Generate a (marker_code, segment_offset) 2-tuple for each marker in
the JPEG *stream*, in the order they occur in the stream. | Below is the the instruction that describes the task:
### Input:
Generate a (marker_code, segment_offset) 2-tuple for each marker in
the JPEG *stream*, in the order they occur in the stream.
### Response:
def iter_markers(self):
"""
Generate a (marker_code, segment_offset) 2-tuple for each ... |
def save(self, chunk_size=DEFAULT_DATA_CHUNK_SIZE, named=False):
"""
Get a tarball of an image. Similar to the ``docker save`` command.
Args:
chunk_size (int): The generator will return up to that much data
per iteration, but may return less. If ``None``, data will b... | Get a tarball of an image. Similar to the ``docker save`` command.
Args:
chunk_size (int): The generator will return up to that much data
per iteration, but may return less. If ``None``, data will be
streamed as it is received. Default: 2 MB
named (str or... | Below is the the instruction that describes the task:
### Input:
Get a tarball of an image. Similar to the ``docker save`` command.
Args:
chunk_size (int): The generator will return up to that much data
per iteration, but may return less. If ``None``, data will be
... |
def arg_types(parsed: Parsed, errors: Errors) -> Tuple[Parsed, Errors]:
"""Add argument types to parsed function data structure
Args:
parsed: function and arg locations in BEL string
errors: error messages
Returns:
(parsed, errors): parsed, arguments with arg types plus error messa... | Add argument types to parsed function data structure
Args:
parsed: function and arg locations in BEL string
errors: error messages
Returns:
(parsed, errors): parsed, arguments with arg types plus error messages | Below is the the instruction that describes the task:
### Input:
Add argument types to parsed function data structure
Args:
parsed: function and arg locations in BEL string
errors: error messages
Returns:
(parsed, errors): parsed, arguments with arg types plus error messages
### Re... |
def set_doc_comment(self, doc, comment):
"""Sets document comment, Raises CardinalityError if
comment already set.
"""
if not self.doc_comment_set:
self.doc_comment_set = True
doc.comment = comment
else:
raise CardinalityError('Document::Commen... | Sets document comment, Raises CardinalityError if
comment already set. | Below is the the instruction that describes the task:
### Input:
Sets document comment, Raises CardinalityError if
comment already set.
### Response:
def set_doc_comment(self, doc, comment):
"""Sets document comment, Raises CardinalityError if
comment already set.
"""
if not... |
def _create_epoch_data(self, streams: Optional[Iterable[str]]=None) -> EpochData:
"""Create empty epoch data double dict."""
if streams is None:
streams = [self._train_stream_name] + self._extra_streams
return OrderedDict([(stream_name, OrderedDict()) for stream_name in streams]) | Create empty epoch data double dict. | Below is the the instruction that describes the task:
### Input:
Create empty epoch data double dict.
### Response:
def _create_epoch_data(self, streams: Optional[Iterable[str]]=None) -> EpochData:
"""Create empty epoch data double dict."""
if streams is None:
streams = [self._train_str... |
def register_on_event_source_changed(self, callback):
"""Set the callback function to consume on event source changed
events. This occurs when a listener is added or removed.
Callback receives a IEventStateChangedEvent object.
Returns the callback_id
"""
event_type = l... | Set the callback function to consume on event source changed
events. This occurs when a listener is added or removed.
Callback receives a IEventStateChangedEvent object.
Returns the callback_id | Below is the the instruction that describes the task:
### Input:
Set the callback function to consume on event source changed
events. This occurs when a listener is added or removed.
Callback receives a IEventStateChangedEvent object.
Returns the callback_id
### Response:
def register_on... |
def add_service(self, zeroconf, srv_type, srv_name):
"""Method called when a new Zeroconf client is detected.
Return True if the zeroconf client is a Glances server
Note: the return code will never be used
"""
if srv_type != zeroconf_type:
return False
logger... | Method called when a new Zeroconf client is detected.
Return True if the zeroconf client is a Glances server
Note: the return code will never be used | Below is the the instruction that describes the task:
### Input:
Method called when a new Zeroconf client is detected.
Return True if the zeroconf client is a Glances server
Note: the return code will never be used
### Response:
def add_service(self, zeroconf, srv_type, srv_name):
"""Metho... |
def probe(self, ipaddr=None):
""" Probe given address for bulb. """
if ipaddr is None:
# no address so use broadcast
ipaddr = self._broadcast_addr
cmd = {"payloadtype": PayloadType.GET,
"target": ipaddr}
self._send_command(cmd) | Probe given address for bulb. | Below is the the instruction that describes the task:
### Input:
Probe given address for bulb.
### Response:
def probe(self, ipaddr=None):
""" Probe given address for bulb. """
if ipaddr is None:
# no address so use broadcast
ipaddr = self._broadcast_addr
cmd = {"pa... |
def _cmp_by_asn(local_asn, path1, path2):
"""Select the path based on source (iBGP/eBGP) peer.
eBGP path is preferred over iBGP. If both paths are from same kind of
peers, return None.
"""
def get_path_source_asn(path):
asn = None
if path.source is None:
asn = local_asn
... | Select the path based on source (iBGP/eBGP) peer.
eBGP path is preferred over iBGP. If both paths are from same kind of
peers, return None. | Below is the the instruction that describes the task:
### Input:
Select the path based on source (iBGP/eBGP) peer.
eBGP path is preferred over iBGP. If both paths are from same kind of
peers, return None.
### Response:
def _cmp_by_asn(local_asn, path1, path2):
"""Select the path based on source (iBGP/... |
def get_pypi_package_data(package_name, version=None):
"""
Get package data from pypi by the package name
https://wiki.python.org/moin/PyPIJSON
:param package_name: string
:param version: string
:return: dict
"""
pypi_url = 'https://pypi.org/pypi'
if version:
package_url =... | Get package data from pypi by the package name
https://wiki.python.org/moin/PyPIJSON
:param package_name: string
:param version: string
:return: dict | Below is the the instruction that describes the task:
### Input:
Get package data from pypi by the package name
https://wiki.python.org/moin/PyPIJSON
:param package_name: string
:param version: string
:return: dict
### Response:
def get_pypi_package_data(package_name, version=None):
"""
G... |
def new_cast_status(self, status):
""" Called when a new status received from the Chromecast. """
self.status = status
if status:
self.status_event.set() | Called when a new status received from the Chromecast. | Below is the the instruction that describes the task:
### Input:
Called when a new status received from the Chromecast.
### Response:
def new_cast_status(self, status):
""" Called when a new status received from the Chromecast. """
self.status = status
if status:
self.status_eve... |
def init(len,default_element=None):
'''
from elist.elist import *
init(5)
init(5,"x")
'''
rslt = []
for i in range(0,len):
rslt.append(copy.deepcopy(default_element))
return(rslt) | from elist.elist import *
init(5)
init(5,"x") | Below is the the instruction that describes the task:
### Input:
from elist.elist import *
init(5)
init(5,"x")
### Response:
def init(len,default_element=None):
'''
from elist.elist import *
init(5)
init(5,"x")
'''
rslt = []
for i in range(0,len):
rsl... |
def connected_socket(address, timeout=3):
""" yields a connected socket """
sock = socket.create_connection(address, timeout)
yield sock
sock.close() | yields a connected socket | Below is the the instruction that describes the task:
### Input:
yields a connected socket
### Response:
def connected_socket(address, timeout=3):
""" yields a connected socket """
sock = socket.create_connection(address, timeout)
yield sock
sock.close() |
def on_files_dropped_on_group(self, files, group_id: int):
"""
:param group_id:
:type files: list of QtCore.QUrl
"""
self.__add_urls_to_group(files, group_id=group_id) | :param group_id:
:type files: list of QtCore.QUrl | Below is the the instruction that describes the task:
### Input:
:param group_id:
:type files: list of QtCore.QUrl
### Response:
def on_files_dropped_on_group(self, files, group_id: int):
"""
:param group_id:
:type files: list of QtCore.QUrl
"""
self.__add_urls_to_gr... |
def nvalues(self):
"""Returns the number of values recorded on this single line. If the
number is variable, it returns -1."""
if self._nvalues is None:
self._nvalues = 0
for val in self.values:
if type(val) == type(int):
self._nvalues +... | Returns the number of values recorded on this single line. If the
number is variable, it returns -1. | Below is the the instruction that describes the task:
### Input:
Returns the number of values recorded on this single line. If the
number is variable, it returns -1.
### Response:
def nvalues(self):
"""Returns the number of values recorded on this single line. If the
number is variable, it ... |
def description(pokemon):
"""Return a description of the given Pokemon."""
r = requests.get('http://pokeapi.co/' + (pokemon.descriptions.values()[0]))
desc = eval(r.text)['description'].replace('Pokmon', 'Pokémon')
return desc | Return a description of the given Pokemon. | Below is the the instruction that describes the task:
### Input:
Return a description of the given Pokemon.
### Response:
def description(pokemon):
"""Return a description of the given Pokemon."""
r = requests.get('http://pokeapi.co/' + (pokemon.descriptions.values()[0]))
desc = eval(r.text)['descripti... |
def execute(self, task, script, **kwargs):
"""
Execute the script, within the context of the specified task
"""
locals().update(kwargs)
exec(script) | Execute the script, within the context of the specified task | Below is the the instruction that describes the task:
### Input:
Execute the script, within the context of the specified task
### Response:
def execute(self, task, script, **kwargs):
"""
Execute the script, within the context of the specified task
"""
locals().update(kwargs)
... |
def project(dest, app_bundle, force, dev,
admin, api, celery, graphene, mail, oauth,
security, session, sqlalchemy, webpack):
"""
Create a new Flask Unchained project.
"""
if os.path.exists(dest) and os.listdir(dest) and not force:
if not click.confirm(f'WARNING: Project ... | Create a new Flask Unchained project. | Below is the the instruction that describes the task:
### Input:
Create a new Flask Unchained project.
### Response:
def project(dest, app_bundle, force, dev,
admin, api, celery, graphene, mail, oauth,
security, session, sqlalchemy, webpack):
"""
Create a new Flask Unchained project... |
def unserialize(wd: WordDictionary, text: Dict):
"""
Transforms back a serialized value of `serialize()`
"""
if not isinstance(text, Mapping):
raise ValueError('Text has not the right format')
try:
t = text['type']
if t == 'string':
return text['value']
... | Transforms back a serialized value of `serialize()` | Below is the the instruction that describes the task:
### Input:
Transforms back a serialized value of `serialize()`
### Response:
def unserialize(wd: WordDictionary, text: Dict):
"""
Transforms back a serialized value of `serialize()`
"""
if not isinstance(text, Mapping):
raise ValueError... |
def _indexable_roles_and_users(self):
"""Return a string made for indexing roles having :any:`READ`
permission on this object."""
from abilian.services.indexing import indexable_role
from abilian.services.security import READ, Admin, Anonymous, Creator, Owner
from abilian.service... | Return a string made for indexing roles having :any:`READ`
permission on this object. | Below is the the instruction that describes the task:
### Input:
Return a string made for indexing roles having :any:`READ`
permission on this object.
### Response:
def _indexable_roles_and_users(self):
"""Return a string made for indexing roles having :any:`READ`
permission on this object.... |
def bool_value(self):
"""Infer the truth value for an Instance
The truth value of an instance is determined by these conditions:
* if it implements __bool__ on Python 3 or __nonzero__
on Python 2, then its bool value will be determined by
calling this special metho... | Infer the truth value for an Instance
The truth value of an instance is determined by these conditions:
* if it implements __bool__ on Python 3 or __nonzero__
on Python 2, then its bool value will be determined by
calling this special method and checking its result.
... | Below is the the instruction that describes the task:
### Input:
Infer the truth value for an Instance
The truth value of an instance is determined by these conditions:
* if it implements __bool__ on Python 3 or __nonzero__
on Python 2, then its bool value will be determined by
... |
def raster_collection_vrt(fc, relative_to_vrt=True, nodata=None, mask_band=None):
"""Make a VRT XML document from a feature collection of GeoRaster2 objects.
Parameters
----------
rasters : FeatureCollection
The FeatureCollection of GeoRasters.
relative_to_vrt : bool, optional
If Tru... | Make a VRT XML document from a feature collection of GeoRaster2 objects.
Parameters
----------
rasters : FeatureCollection
The FeatureCollection of GeoRasters.
relative_to_vrt : bool, optional
If True the bands simple source url will be related to the VRT file
nodata : int, optional
... | Below is the the instruction that describes the task:
### Input:
Make a VRT XML document from a feature collection of GeoRaster2 objects.
Parameters
----------
rasters : FeatureCollection
The FeatureCollection of GeoRasters.
relative_to_vrt : bool, optional
If True the bands simple s... |
def ellipticity2phi_q(e1, e2):
"""
:param e1:
:param e2:
:return:
"""
phi = np.arctan2(e2, e1)/2
c = np.sqrt(e1**2+e2**2)
if c > 0.999:
c = 0.999
q = (1-c)/(1+c)
return phi, q | :param e1:
:param e2:
:return: | Below is the the instruction that describes the task:
### Input:
:param e1:
:param e2:
:return:
### Response:
def ellipticity2phi_q(e1, e2):
"""
:param e1:
:param e2:
:return:
"""
phi = np.arctan2(e2, e1)/2
c = np.sqrt(e1**2+e2**2)
if c > 0.999:
c = 0.999
q = (1-... |
def body(self):
"""The body of the packet."""
view = ffi.buffer(self.packet.m_body, self.packet.m_nBodySize)
return view[:] | The body of the packet. | Below is the the instruction that describes the task:
### Input:
The body of the packet.
### Response:
def body(self):
"""The body of the packet."""
view = ffi.buffer(self.packet.m_body, self.packet.m_nBodySize)
return view[:] |
def list_rulesets(debug):
"""
List available rulesets.
"""
try:
rulesets = get_rulesets()
max_len = max([len(r[0]) for r in rulesets])
for r in rulesets:
click.echo('{0: <{1}} ({2})'.format(r[0], max_len, r[1]))
except Exception as ex:
logger.error("An err... | List available rulesets. | Below is the the instruction that describes the task:
### Input:
List available rulesets.
### Response:
def list_rulesets(debug):
"""
List available rulesets.
"""
try:
rulesets = get_rulesets()
max_len = max([len(r[0]) for r in rulesets])
for r in rulesets:
click... |
def clean(self, is_table=False):
"""
Remove reserved keywords from the header.
These are keywords that the fits writer must write in order
to maintain consistency between header and data.
keywords
--------
is_table: bool, optional
Set True if this is... | Remove reserved keywords from the header.
These are keywords that the fits writer must write in order
to maintain consistency between header and data.
keywords
--------
is_table: bool, optional
Set True if this is a table, so extra keywords will be cleaned | Below is the the instruction that describes the task:
### Input:
Remove reserved keywords from the header.
These are keywords that the fits writer must write in order
to maintain consistency between header and data.
keywords
--------
is_table: bool, optional
Set... |
async def servo_config(self, pin, min_pulse=544, max_pulse=2400):
"""
Configure a pin as a servo pin. Set pulse min, max in ms.
Use this method (not set_pin_mode) to configure a pin for servo
operation.
:param pin: Servo Pin.
:param min_pulse: Min pulse width in ms.
... | Configure a pin as a servo pin. Set pulse min, max in ms.
Use this method (not set_pin_mode) to configure a pin for servo
operation.
:param pin: Servo Pin.
:param min_pulse: Min pulse width in ms.
:param max_pulse: Max pulse width in ms.
:returns: No return value | Below is the the instruction that describes the task:
### Input:
Configure a pin as a servo pin. Set pulse min, max in ms.
Use this method (not set_pin_mode) to configure a pin for servo
operation.
:param pin: Servo Pin.
:param min_pulse: Min pulse width in ms.
:param max_... |
def getPlatformInfo():
"""Identify platform."""
if "linux" in sys.platform:
platform = "linux"
elif "darwin" in sys.platform:
platform = "darwin"
# win32
elif sys.platform.startswith("win"):
platform = "windows"
else:
raise Exception("Platform '%s' is unsupported!" % sys.platform)
return p... | Identify platform. | Below is the the instruction that describes the task:
### Input:
Identify platform.
### Response:
def getPlatformInfo():
"""Identify platform."""
if "linux" in sys.platform:
platform = "linux"
elif "darwin" in sys.platform:
platform = "darwin"
# win32
elif sys.platform.startswith("win"):
plat... |
def DeregisterAnalyzer(cls, analyzer_class):
"""Deregisters a analyzer class.
The analyzer classes are identified based on their lower case name.
Args:
analyzer_class (type): class object of the analyzer.
Raises:
KeyError: if analyzer class is not set for the corresponding name.
"""
... | Deregisters a analyzer class.
The analyzer classes are identified based on their lower case name.
Args:
analyzer_class (type): class object of the analyzer.
Raises:
KeyError: if analyzer class is not set for the corresponding name. | Below is the the instruction that describes the task:
### Input:
Deregisters a analyzer class.
The analyzer classes are identified based on their lower case name.
Args:
analyzer_class (type): class object of the analyzer.
Raises:
KeyError: if analyzer class is not set for the correspondin... |
def _expand_inputs(step, steps=None):
"""
Returns the set of this step and all steps passed to the constructor (recursively).
"""
if steps is None:
steps = set()
for arg in step._kwargs.values():
if isinstance(arg, Step):
_expand_inputs(arg, steps=steps)
elif uti... | Returns the set of this step and all steps passed to the constructor (recursively). | Below is the the instruction that describes the task:
### Input:
Returns the set of this step and all steps passed to the constructor (recursively).
### Response:
def _expand_inputs(step, steps=None):
"""
Returns the set of this step and all steps passed to the constructor (recursively).
"""
if ste... |
def assemble(self):
"""Assemble a QasmQobjInstruction"""
instruction = QasmQobjInstruction(name=self.name)
# Evaluate parameters
if self.params:
params = [
x.evalf() if hasattr(x, 'evalf') else x for x in self.params
]
params = [
... | Assemble a QasmQobjInstruction | Below is the the instruction that describes the task:
### Input:
Assemble a QasmQobjInstruction
### Response:
def assemble(self):
"""Assemble a QasmQobjInstruction"""
instruction = QasmQobjInstruction(name=self.name)
# Evaluate parameters
if self.params:
params = [
... |
def find_prop_overlap(rdf, prop1, prop2):
"""Generate (subject,object) pairs connected by two properties."""
for s, o in sorted(rdf.subject_objects(prop1)):
if (s, prop2, o) in rdf:
yield (s, o) | Generate (subject,object) pairs connected by two properties. | Below is the the instruction that describes the task:
### Input:
Generate (subject,object) pairs connected by two properties.
### Response:
def find_prop_overlap(rdf, prop1, prop2):
"""Generate (subject,object) pairs connected by two properties."""
for s, o in sorted(rdf.subject_objects(prop1)):
if... |
def publish(self, path):
"""Publish file or folder and return public url"""
def parseContent(content):
root = ET.fromstring(content)
prop = root.find(".//d:prop", namespaces=self.namespaces)
return prop.find("{urn:yandex:disk:meta}public_url").text.strip()
... | Publish file or folder and return public url | Below is the the instruction that describes the task:
### Input:
Publish file or folder and return public url
### Response:
def publish(self, path):
"""Publish file or folder and return public url"""
def parseContent(content):
root = ET.fromstring(content)
prop = ro... |
def add_eval(self, agent, e, fr=None):
"""Add or change agent's evaluation of the artifact with given framing
information.
:param agent: Name of the agent which did the evaluation.
:param float e: Evaluation for the artifact.
:param object fr: Framing information for the evaluat... | Add or change agent's evaluation of the artifact with given framing
information.
:param agent: Name of the agent which did the evaluation.
:param float e: Evaluation for the artifact.
:param object fr: Framing information for the evaluation. | Below is the the instruction that describes the task:
### Input:
Add or change agent's evaluation of the artifact with given framing
information.
:param agent: Name of the agent which did the evaluation.
:param float e: Evaluation for the artifact.
:param object fr: Framing informat... |
def command(self, name, handler_name, **kwargs):
""" Register a command into the command table
:param name: The name of the command
:type name: str
:param handler_name: The name of the handler that will be applied to the operations template
:type handler_name: str
:param... | Register a command into the command table
:param name: The name of the command
:type name: str
:param handler_name: The name of the handler that will be applied to the operations template
:type handler_name: str
:param kwargs: Kwargs to apply to the command.
... | Below is the the instruction that describes the task:
### Input:
Register a command into the command table
:param name: The name of the command
:type name: str
:param handler_name: The name of the handler that will be applied to the operations template
:type handler_name: str
... |
def setup_singlecolor(self):
""" initial setup of single color options and variables"""
self.singlecolorframe = tk.Frame(self.tab_configure, bg=self.single_color_theme)
channel_choices = sorted(list(self.data.keys()))
self.singlecolorlabel = tk.Label(self.singlecolorframe, text="single",... | initial setup of single color options and variables | Below is the the instruction that describes the task:
### Input:
initial setup of single color options and variables
### Response:
def setup_singlecolor(self):
""" initial setup of single color options and variables"""
self.singlecolorframe = tk.Frame(self.tab_configure, bg=self.single_color_theme)... |
def execute(self):
"""
self.params = {
"ActionScriptType" : "None",
"ExecutableEntityId" : "01pd0000001yXtYAAU",
"IsDumpingHeap" : True,
"Iteration" : 1,
"Line" : 3,
... | self.params = {
"ActionScriptType" : "None",
"ExecutableEntityId" : "01pd0000001yXtYAAU",
"IsDumpingHeap" : True,
"Iteration" : 1,
"Line" : 3,
"ScopeId" : "005d00000... | Below is the the instruction that describes the task:
### Input:
self.params = {
"ActionScriptType" : "None",
"ExecutableEntityId" : "01pd0000001yXtYAAU",
"IsDumpingHeap" : True,
"Iteration" : 1,
"Line" ... |
async def _poll(self):
"""Poll status of operation so long as operation is incomplete and
we have an endpoint to query.
:param callable update_cmd: The function to call to retrieve the
latest status of the long running operation.
:raises: OperationFailed if operation status 'Fa... | Poll status of operation so long as operation is incomplete and
we have an endpoint to query.
:param callable update_cmd: The function to call to retrieve the
latest status of the long running operation.
:raises: OperationFailed if operation status 'Failed' or 'Cancelled'.
:rai... | Below is the the instruction that describes the task:
### Input:
Poll status of operation so long as operation is incomplete and
we have an endpoint to query.
:param callable update_cmd: The function to call to retrieve the
latest status of the long running operation.
:raises: Oper... |
def get_dump_names(self, names, dumps=None):
"""
Find and return all dump names required (by dependancies) for a given
dump names list
Beware, the returned name list does not respect order, you should only
use it when walking throught the "original" dict builded by OrderedDict
... | Find and return all dump names required (by dependancies) for a given
dump names list
Beware, the returned name list does not respect order, you should only
use it when walking throught the "original" dict builded by OrderedDict | Below is the the instruction that describes the task:
### Input:
Find and return all dump names required (by dependancies) for a given
dump names list
Beware, the returned name list does not respect order, you should only
use it when walking throught the "original" dict builded by OrderedDi... |
def focus(self, height, width, center_i=None, center_j=None):
"""Zero out all of the image outside of a crop box.
Parameters
----------
height : int
The height of the desired crop box.
width : int
The width of the desired crop box.
center_i : in... | Zero out all of the image outside of a crop box.
Parameters
----------
height : int
The height of the desired crop box.
width : int
The width of the desired crop box.
center_i : int
The center height point of the crop box. If not specified, ... | Below is the the instruction that describes the task:
### Input:
Zero out all of the image outside of a crop box.
Parameters
----------
height : int
The height of the desired crop box.
width : int
The width of the desired crop box.
center_i : int
... |
def pow(x, y, context=None):
"""
Return ``x`` raised to the power ``y``.
Special values are handled as described in the ISO C99 and IEEE 754-2008
standards for the pow function.
* pow(±0, y) returns plus or minus infinity for y a negative odd integer.
* pow(±0, y) returns plus infinity fo... | Return ``x`` raised to the power ``y``.
Special values are handled as described in the ISO C99 and IEEE 754-2008
standards for the pow function.
* pow(±0, y) returns plus or minus infinity for y a negative odd integer.
* pow(±0, y) returns plus infinity for y negative and not an odd integer.
... | Below is the the instruction that describes the task:
### Input:
Return ``x`` raised to the power ``y``.
Special values are handled as described in the ISO C99 and IEEE 754-2008
standards for the pow function.
* pow(±0, y) returns plus or minus infinity for y a negative odd integer.
* pow(±0,... |
def configure(self, **_options):
'''
Sets language-specific configuration.
Raises TTSError on error.
'''
language, voice, voiceinfo, options = self._configure(**_options)
self.languages_options[language] = (voice, options) | Sets language-specific configuration.
Raises TTSError on error. | Below is the the instruction that describes the task:
### Input:
Sets language-specific configuration.
Raises TTSError on error.
### Response:
def configure(self, **_options):
'''
Sets language-specific configuration.
Raises TTSError on error.
'''
language, voice, ... |
def _unpack_episode_title(element: ET.Element):
"""Unpack EpisodeTitle from title XML element."""
return EpisodeTitle(title=element.text,
lang=element.get(f'{XML}lang')) | Unpack EpisodeTitle from title XML element. | Below is the the instruction that describes the task:
### Input:
Unpack EpisodeTitle from title XML element.
### Response:
def _unpack_episode_title(element: ET.Element):
"""Unpack EpisodeTitle from title XML element."""
return EpisodeTitle(title=element.text,
lang=element.get(f'{XM... |
def roots(self):
"""
Utilises Boyd's O(n^2) recursive subdivision algorithm. The chebfun
is recursively subsampled until it is successfully represented to
machine precision by a sequence of piecewise interpolants of degree
100 or less. A colleague matrix eigenvalue solve is then ... | Utilises Boyd's O(n^2) recursive subdivision algorithm. The chebfun
is recursively subsampled until it is successfully represented to
machine precision by a sequence of piecewise interpolants of degree
100 or less. A colleague matrix eigenvalue solve is then applied to
each of these piec... | Below is the the instruction that describes the task:
### Input:
Utilises Boyd's O(n^2) recursive subdivision algorithm. The chebfun
is recursively subsampled until it is successfully represented to
machine precision by a sequence of piecewise interpolants of degree
100 or less. A colleague ... |
def get_files_changed(repository, review_id):
"""
Get a list of files changed compared to the given review.
Compares against current directory.
:param repository: Git repository. Used to get remote.
- By default uses first remote in list.
:param review_id: Gerrit review ID.
:return: List ... | Get a list of files changed compared to the given review.
Compares against current directory.
:param repository: Git repository. Used to get remote.
- By default uses first remote in list.
:param review_id: Gerrit review ID.
:return: List of file paths relative to current directory. | Below is the the instruction that describes the task:
### Input:
Get a list of files changed compared to the given review.
Compares against current directory.
:param repository: Git repository. Used to get remote.
- By default uses first remote in list.
:param review_id: Gerrit review ID.
:re... |
def add_template(self, template_short_id, keyword_id_list):
"""
组合模板,并将其添加至账号下的模板列表里
详情请参考
https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&id=open1500465446_j4CgR
:param template_short_id: 模板标题ID
:param keyword_id_list: 按照顺序排列的模板关键词列表,最多10个
:type ... | 组合模板,并将其添加至账号下的模板列表里
详情请参考
https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&id=open1500465446_j4CgR
:param template_short_id: 模板标题ID
:param keyword_id_list: 按照顺序排列的模板关键词列表,最多10个
:type keyword_id_list: list[int]
:return: 模板ID | Below is the the instruction that describes the task:
### Input:
组合模板,并将其添加至账号下的模板列表里
详情请参考
https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&id=open1500465446_j4CgR
:param template_short_id: 模板标题ID
:param keyword_id_list: 按照顺序排列的模板关键词列表,最多10个
:type keyword_id_... |
def round(self, value_array):
"""
Rounds a discrete variable by selecting the closest point in the domain
Assumes an 1d array with a single element as an input.
"""
value = value_array[0]
rounded_value = self.domain[0]
for domain_value in self.domain:
... | Rounds a discrete variable by selecting the closest point in the domain
Assumes an 1d array with a single element as an input. | Below is the the instruction that describes the task:
### Input:
Rounds a discrete variable by selecting the closest point in the domain
Assumes an 1d array with a single element as an input.
### Response:
def round(self, value_array):
"""
Rounds a discrete variable by selecting the closest... |
def _extract_links(self, selector, response_url, response_encoding, base_url):
'''
Pretty much the same function, just added 'ignore' to to_native_str()
'''
links = []
# hacky way to get the underlying lxml parsed document
for el, attr, attr_val in self._iter_links(select... | Pretty much the same function, just added 'ignore' to to_native_str() | Below is the the instruction that describes the task:
### Input:
Pretty much the same function, just added 'ignore' to to_native_str()
### Response:
def _extract_links(self, selector, response_url, response_encoding, base_url):
'''
Pretty much the same function, just added 'ignore' to to_native_str... |
def copy(self):
"""Create a copy.
Examples:
This example copies constraint :math:`a \\ne b` and tests a solution
on the copied constraint.
>>> import dwavebinarycsp
>>> import operator
>>> const = dwavebinarycsp.Constraint.from_func(operator.... | Create a copy.
Examples:
This example copies constraint :math:`a \\ne b` and tests a solution
on the copied constraint.
>>> import dwavebinarycsp
>>> import operator
>>> const = dwavebinarycsp.Constraint.from_func(operator.ne,
... ... | Below is the the instruction that describes the task:
### Input:
Create a copy.
Examples:
This example copies constraint :math:`a \\ne b` and tests a solution
on the copied constraint.
>>> import dwavebinarycsp
>>> import operator
>>> const = dwa... |
def _instant_search(self):
"""Determine possible keys after a push or pop
"""
_keys = []
for k,v in self.searchables.iteritems():
if self.string in v:
_keys.append(k)
self.candidates.append(_keys) | Determine possible keys after a push or pop | Below is the the instruction that describes the task:
### Input:
Determine possible keys after a push or pop
### Response:
def _instant_search(self):
"""Determine possible keys after a push or pop
"""
_keys = []
for k,v in self.searchables.iteritems():
if self.string in ... |
def _osx_memdata():
'''
Return the memory information for BSD-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
sysctl = salt.utils.path.which('sysctl')
if sysctl:
mem = __salt__['cmd.run']('{0} -n hw.memsize'.format(sysctl))
swap_total = __salt__['cmd.run']('{0} -n vm... | Return the memory information for BSD-like systems | Below is the the instruction that describes the task:
### Input:
Return the memory information for BSD-like systems
### Response:
def _osx_memdata():
'''
Return the memory information for BSD-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
sysctl = salt.utils.path.which('sysctl')
... |
def get_random_telephonenumber():
"""Get a random 10 digit phone number that complies with most of the requirements.
Returns:
str: The random telephone number.
"""
phone = [
RandomInputHelper.get_random_value(3, "123456789"),
RandomInputHelper.get_r... | Get a random 10 digit phone number that complies with most of the requirements.
Returns:
str: The random telephone number. | Below is the the instruction that describes the task:
### Input:
Get a random 10 digit phone number that complies with most of the requirements.
Returns:
str: The random telephone number.
### Response:
def get_random_telephonenumber():
"""Get a random 10 digit phone number that complie... |
def for_user(cls, user):
"""
Returns an authorization token for the given user that will be provided
after authenticating the user's credentials.
"""
user_id = getattr(user, api_settings.USER_ID_FIELD)
if not isinstance(user_id, int):
user_id = str(user_id)
... | Returns an authorization token for the given user that will be provided
after authenticating the user's credentials. | Below is the the instruction that describes the task:
### Input:
Returns an authorization token for the given user that will be provided
after authenticating the user's credentials.
### Response:
def for_user(cls, user):
"""
Returns an authorization token for the given user that will be pro... |
def load_b26_file(file_name):
"""
loads a .b26 file into a dictionary
Args:
file_name:
Returns: dictionary with keys instrument, scripts, probes
"""
# file_name = "Z:\Lab\Cantilever\Measurements\\tmp_\\a"
assert os.path.exists(file_name)
with open(file_name, 'r') as infile:
... | loads a .b26 file into a dictionary
Args:
file_name:
Returns: dictionary with keys instrument, scripts, probes | Below is the the instruction that describes the task:
### Input:
loads a .b26 file into a dictionary
Args:
file_name:
Returns: dictionary with keys instrument, scripts, probes
### Response:
def load_b26_file(file_name):
"""
loads a .b26 file into a dictionary
Args:
file_name:... |
def poly_energies(samples_like, poly):
"""Calculates energy of samples from a higher order polynomial.
Args:
sample (samples_like):
A collection of raw samples. `samples_like` is an extension of
NumPy's array_like structure. See :func:`.as_samples`.
poly (dict):
... | Calculates energy of samples from a higher order polynomial.
Args:
sample (samples_like):
A collection of raw samples. `samples_like` is an extension of
NumPy's array_like structure. See :func:`.as_samples`.
poly (dict):
Polynomial as a dict of form {term: bias,... | Below is the the instruction that describes the task:
### Input:
Calculates energy of samples from a higher order polynomial.
Args:
sample (samples_like):
A collection of raw samples. `samples_like` is an extension of
NumPy's array_like structure. See :func:`.as_samples`.
... |
def is_mirrable(d):
'''
d = {1:'a',2:'a',3:'b'}
'''
vl = list(d.values())
lngth1 = vl.__len__()
uvl = elel.uniqualize(vl)
lngth2 = uvl.__len__()
cond = (lngth1 == lngth2)
return(cond) | d = {1:'a',2:'a',3:'b'} | Below is the the instruction that describes the task:
### Input:
d = {1:'a',2:'a',3:'b'}
### Response:
def is_mirrable(d):
'''
d = {1:'a',2:'a',3:'b'}
'''
vl = list(d.values())
lngth1 = vl.__len__()
uvl = elel.uniqualize(vl)
lngth2 = uvl.__len__()
cond = (lngth1 == lngth2)
r... |
def validate_usage(self, key_usage, extended_key_usage=None, extended_optional=False):
"""
Validates the certificate path and that the certificate is valid for
the key usage and extended key usage purposes specified.
:param key_usage:
A set of unicode strings of the required... | Validates the certificate path and that the certificate is valid for
the key usage and extended key usage purposes specified.
:param key_usage:
A set of unicode strings of the required key usage purposes. Valid
values include:
- "digital_signature"
- "... | Below is the the instruction that describes the task:
### Input:
Validates the certificate path and that the certificate is valid for
the key usage and extended key usage purposes specified.
:param key_usage:
A set of unicode strings of the required key usage purposes. Valid
... |
def write_xml(xml, output_file=None):
"""Outputs the XML content into a file."""
gen_filename = "requirements-{:%Y%m%d%H%M%S}.xml".format(datetime.datetime.now())
utils.write_xml(xml, output_loc=output_file, filename=gen_filename) | Outputs the XML content into a file. | Below is the the instruction that describes the task:
### Input:
Outputs the XML content into a file.
### Response:
def write_xml(xml, output_file=None):
"""Outputs the XML content into a file."""
gen_filename = "requirements-{:%Y%m%d%H%M%S}.xml".format(datetime.datetime.now())
utils.write_... |
def get_article_by_search(text):
"""从搜索文章获得的文本 提取章列表信息
Parameters
----------
text : str or unicode
搜索文章获得的文本
Returns
-------
list[dict]
{
'article': {
'title': '', # 文章标题
'url': '',... | 从搜索文章获得的文本 提取章列表信息
Parameters
----------
text : str or unicode
搜索文章获得的文本
Returns
-------
list[dict]
{
'article': {
'title': '', # 文章标题
'url': '', # 文章链接
'imgs': '', # ... | Below is the the instruction that describes the task:
### Input:
从搜索文章获得的文本 提取章列表信息
Parameters
----------
text : str or unicode
搜索文章获得的文本
Returns
-------
list[dict]
{
'article': {
'title': '', # 文章标题
... |
def warm(self, jittering_ratio=0.2):
"""Progressively load the previous snapshot during the day.
Loading all the snapshots at once can takes a substantial amount of time. This method, if called
periodically during the day will progressively load those snapshots one by one. Because many workers ... | Progressively load the previous snapshot during the day.
Loading all the snapshots at once can takes a substantial amount of time. This method, if called
periodically during the day will progressively load those snapshots one by one. Because many workers are
going to use this method at the same... | Below is the the instruction that describes the task:
### Input:
Progressively load the previous snapshot during the day.
Loading all the snapshots at once can takes a substantial amount of time. This method, if called
periodically during the day will progressively load those snapshots one by one. ... |
def PUT(self, rest_path_list, **kwargs):
"""Send a PUT request with optional streaming multipart encoding. See
requests.sessions.request for optional parameters. See post() for parameters.
:returns: Response object
"""
fields = kwargs.pop("fields", None)
if fields is no... | Send a PUT request with optional streaming multipart encoding. See
requests.sessions.request for optional parameters. See post() for parameters.
:returns: Response object | Below is the the instruction that describes the task:
### Input:
Send a PUT request with optional streaming multipart encoding. See
requests.sessions.request for optional parameters. See post() for parameters.
:returns: Response object
### Response:
def PUT(self, rest_path_list, **kwargs):
... |
def get_cantera_mass_fraction(self, species_conversion=None):
"""Get the mass fractions in a string format suitable for input to Cantera.
Arguments:
species_conversion (`dict`, optional): Mapping of species identifier to a
species name. This argument should be supplied when ... | Get the mass fractions in a string format suitable for input to Cantera.
Arguments:
species_conversion (`dict`, optional): Mapping of species identifier to a
species name. This argument should be supplied when the name of the
species in the ChemKED YAML file does not... | Below is the the instruction that describes the task:
### Input:
Get the mass fractions in a string format suitable for input to Cantera.
Arguments:
species_conversion (`dict`, optional): Mapping of species identifier to a
species name. This argument should be supplied when the ... |
def do_photometry(self):
"""
Does photometry and estimates uncertainties by calculating the scatter around a linear fit to the data
in each orientation. This function is called by other functions and generally the user will not need
to interact with it directly.
"""
... | Does photometry and estimates uncertainties by calculating the scatter around a linear fit to the data
in each orientation. This function is called by other functions and generally the user will not need
to interact with it directly. | Below is the the instruction that describes the task:
### Input:
Does photometry and estimates uncertainties by calculating the scatter around a linear fit to the data
in each orientation. This function is called by other functions and generally the user will not need
to interact with it directly.
#... |
def gen_non_ca_cert(filename, dirname, days, ip_list, dns_list,
ca_crt, ca_key, silent=False):
"""
generate a non CA key and certificate key pair signed by the private
CA key and crt.
:param filename: prefix for the key and cert file
:param dirname: name of the directory
:par... | generate a non CA key and certificate key pair signed by the private
CA key and crt.
:param filename: prefix for the key and cert file
:param dirname: name of the directory
:param days: days of the certificate being valid
:ip_list: a list of ip address to be included in the certificate
:dns_list... | Below is the the instruction that describes the task:
### Input:
generate a non CA key and certificate key pair signed by the private
CA key and crt.
:param filename: prefix for the key and cert file
:param dirname: name of the directory
:param days: days of the certificate being valid
:ip_list:... |
def glob_config(pattern, *search_dirs):
"""Return glob results for all possible configuration locations.
Note: This method does not check the configuration "base" directory if the pattern includes a subdirectory.
This is done for performance since this is usually used to find *all* configs for a cert... | Return glob results for all possible configuration locations.
Note: This method does not check the configuration "base" directory if the pattern includes a subdirectory.
This is done for performance since this is usually used to find *all* configs for a certain component. | Below is the the instruction that describes the task:
### Input:
Return glob results for all possible configuration locations.
Note: This method does not check the configuration "base" directory if the pattern includes a subdirectory.
This is done for performance since this is usually used to find *a... |
def velocity(data, vkey='velocity', mode=None, fit_offset=False, fit_offset2=False, filter_genes=False,
groups=None, groupby=None, groups_for_fit=None, use_raw=False, perc=[5, 95], copy=False):
"""Estimates velocities in a gene-specific manner
Arguments
---------
data: :class:`~anndata.Ann... | Estimates velocities in a gene-specific manner
Arguments
---------
data: :class:`~anndata.AnnData`
Annotated data matrix.
vkey: `str` (default: `'velocity'`)
Name under which to refer to the computed velocities for `velocity_graph` and `velocity_embedding`.
mode: `'deterministic'`, ... | Below is the the instruction that describes the task:
### Input:
Estimates velocities in a gene-specific manner
Arguments
---------
data: :class:`~anndata.AnnData`
Annotated data matrix.
vkey: `str` (default: `'velocity'`)
Name under which to refer to the computed velocities for `ve... |
def get_variables(run_name):
"""
Returns a dict of variables in the selected run table.
:param run_name: str, required run table name
:return: dict -> {<int_keys>: <variable_name>}
"""
conn, c = open_data_base_connection()
try:
# Get latest project
c.execute("""SELECT variabl... | Returns a dict of variables in the selected run table.
:param run_name: str, required run table name
:return: dict -> {<int_keys>: <variable_name>} | Below is the the instruction that describes the task:
### Input:
Returns a dict of variables in the selected run table.
:param run_name: str, required run table name
:return: dict -> {<int_keys>: <variable_name>}
### Response:
def get_variables(run_name):
"""
Returns a dict of variables in the sele... |
def get_gaf_gene_ontology_file(path):
"""Extract the gene ontology file associated with a GO annotation file.
Parameters
----------
path: str
The path name of the GO annotation file.
Returns
-------
str
The URL of the associated gene ontology file.
"""
assert isinst... | Extract the gene ontology file associated with a GO annotation file.
Parameters
----------
path: str
The path name of the GO annotation file.
Returns
-------
str
The URL of the associated gene ontology file. | Below is the the instruction that describes the task:
### Input:
Extract the gene ontology file associated with a GO annotation file.
Parameters
----------
path: str
The path name of the GO annotation file.
Returns
-------
str
The URL of the associated gene ontology file.
#... |
def set_current_limit(self, channel, value, unit='A'):
'''Setting current limit
Note: same limit for all channels.
'''
# TODO: add units / calibration
if unit == 'raw':
value = value
elif unit == 'A':
value = int(value * 1000 * self.CURRENT_LIMIT_... | Setting current limit
Note: same limit for all channels. | Below is the the instruction that describes the task:
### Input:
Setting current limit
Note: same limit for all channels.
### Response:
def set_current_limit(self, channel, value, unit='A'):
'''Setting current limit
Note: same limit for all channels.
'''
# TODO: add units ... |
async def join(self, ctx):
"""Sends you the bot invite link."""
perms = discord.Permissions.none()
perms.read_messages = True
perms.send_messages = True
perms.manage_messages = True
perms.embed_links = True
perms.read_message_history = True
perms.attach_fi... | Sends you the bot invite link. | Below is the the instruction that describes the task:
### Input:
Sends you the bot invite link.
### Response:
async def join(self, ctx):
"""Sends you the bot invite link."""
perms = discord.Permissions.none()
perms.read_messages = True
perms.send_messages = True
perms.manage... |
def update(self, uid):
'''
in infor.
'''
postinfo = MPost.get_by_uid(uid)
if postinfo.kind == self.kind:
pass
else:
return False
post_data, ext_dic = self.fetch_post_data()
if 'gcat0' in post_data:
pass
else:
... | in infor. | Below is the the instruction that describes the task:
### Input:
in infor.
### Response:
def update(self, uid):
'''
in infor.
'''
postinfo = MPost.get_by_uid(uid)
if postinfo.kind == self.kind:
pass
else:
return False
post_data, ext_... |
def n_leaves(neurites, neurite_type=NeuriteType.all):
'''number of leaves points in a collection of neurites'''
return n_sections(neurites, neurite_type=neurite_type, iterator_type=Tree.ileaf) | number of leaves points in a collection of neurites | Below is the the instruction that describes the task:
### Input:
number of leaves points in a collection of neurites
### Response:
def n_leaves(neurites, neurite_type=NeuriteType.all):
'''number of leaves points in a collection of neurites'''
return n_sections(neurites, neurite_type=neurite_type, iterator_... |
def add_mismatch(self, entity, *traits):
"""
Add a mismatching entity to the index.
We do this by simply adding the mismatch to the index.
:param collections.Hashable entity: an object to be mismatching the values of `traits_indexed_by`
:param list traits: a list of hashable tr... | Add a mismatching entity to the index.
We do this by simply adding the mismatch to the index.
:param collections.Hashable entity: an object to be mismatching the values of `traits_indexed_by`
:param list traits: a list of hashable traits to index the entity with | Below is the the instruction that describes the task:
### Input:
Add a mismatching entity to the index.
We do this by simply adding the mismatch to the index.
:param collections.Hashable entity: an object to be mismatching the values of `traits_indexed_by`
:param list traits: a list of has... |
def get_serializer(
self,
action_kwargs: Dict=None,
*args, **kwargs) -> Serializer:
"""
Return the serializer instance that should be used for validating and
deserializing input, and for serializing output.
"""
serializer_class = self.get_seria... | Return the serializer instance that should be used for validating and
deserializing input, and for serializing output. | Below is the the instruction that describes the task:
### Input:
Return the serializer instance that should be used for validating and
deserializing input, and for serializing output.
### Response:
def get_serializer(
self,
action_kwargs: Dict=None,
*args, **kwargs) -> S... |
def _register_name(self, name):
"""Get register name.
"""
if name not in self._var_name_mappers:
self._var_name_mappers[name] = VariableNamer(name) | Get register name. | Below is the the instruction that describes the task:
### Input:
Get register name.
### Response:
def _register_name(self, name):
"""Get register name.
"""
if name not in self._var_name_mappers:
self._var_name_mappers[name] = VariableNamer(name) |
def publish(self, service, routing_id, method, args=None, kwargs=None,
broadcast=False, udp=False):
'''Send a 1-way message
:param service: the service name (the routing top level)
:type service: anything hash-able
:param int routing_id:
the id used for routing w... | Send a 1-way message
:param service: the service name (the routing top level)
:type service: anything hash-able
:param int routing_id:
the id used for routing within the registered handlers of the
service
:param string method: the method name to call
:par... | Below is the the instruction that describes the task:
### Input:
Send a 1-way message
:param service: the service name (the routing top level)
:type service: anything hash-able
:param int routing_id:
the id used for routing within the registered handlers of the
servi... |
def stopService(self):
"""
Stop the writer thread, wait for it to finish.
"""
Service.stopService(self)
removeDestination(self)
self._reactor.callFromThread(self._reactor.stop)
return deferToThreadPool(
self._mainReactor,
self._mainReactor.... | Stop the writer thread, wait for it to finish. | Below is the the instruction that describes the task:
### Input:
Stop the writer thread, wait for it to finish.
### Response:
def stopService(self):
"""
Stop the writer thread, wait for it to finish.
"""
Service.stopService(self)
removeDestination(self)
self._reactor... |
def GetSubNodeByLocation(self, location):
"""Retrieves a sub scan node based on the location.
Args:
location (str): location that should match the location of the path
specification of a sub scan node.
Returns:
SourceScanNode: sub scan node or None if not available.
"""
for s... | Retrieves a sub scan node based on the location.
Args:
location (str): location that should match the location of the path
specification of a sub scan node.
Returns:
SourceScanNode: sub scan node or None if not available. | Below is the the instruction that describes the task:
### Input:
Retrieves a sub scan node based on the location.
Args:
location (str): location that should match the location of the path
specification of a sub scan node.
Returns:
SourceScanNode: sub scan node or None if not availabl... |
def _convert_camera(camera):
"""
Convert a trimesh camera to a GLTF camera.
Parameters
------------
camera : trimesh.scene.cameras.Camera
Trimesh camera object
Returns
-------------
gltf_camera : dict
Camera represented as a GLTF dict
"""
result = {
"name": ... | Convert a trimesh camera to a GLTF camera.
Parameters
------------
camera : trimesh.scene.cameras.Camera
Trimesh camera object
Returns
-------------
gltf_camera : dict
Camera represented as a GLTF dict | Below is the the instruction that describes the task:
### Input:
Convert a trimesh camera to a GLTF camera.
Parameters
------------
camera : trimesh.scene.cameras.Camera
Trimesh camera object
Returns
-------------
gltf_camera : dict
Camera represented as a GLTF dict
### Respons... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.