code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def gen_batches(data, batch_size):
"""Divide input data into batches.
:param data: input data
:param batch_size: size of each batch
:return: data divided into batches
"""
data = np.array(data)
for i in range(0, data.shape[0], batch_size):
yield data[i:i + batch_size] | Divide input data into batches.
:param data: input data
:param batch_size: size of each batch
:return: data divided into batches | Below is the the instruction that describes the task:
### Input:
Divide input data into batches.
:param data: input data
:param batch_size: size of each batch
:return: data divided into batches
### Response:
def gen_batches(data, batch_size):
"""Divide input data into batches.
:param data: in... |
def set_figure(self, figure, handle=None):
"""Call this with the Bokeh figure object."""
self.figure = figure
self.bkimage = None
self._push_handle = handle
wd = figure.plot_width
ht = figure.plot_height
self.configure_window(wd, ht)
doc = curdoc()
... | Call this with the Bokeh figure object. | Below is the the instruction that describes the task:
### Input:
Call this with the Bokeh figure object.
### Response:
def set_figure(self, figure, handle=None):
"""Call this with the Bokeh figure object."""
self.figure = figure
self.bkimage = None
self._push_handle = handle
... |
def _data_from_df(df):
''' Create a ``dict`` of columns from a Pandas ``DataFrame``,
suitable for creating a ColumnDataSource.
Args:
df (DataFrame) : data to convert
Returns:
dict[str, np.array]
'''
_df = df.copy()
# Flatten columns
... | Create a ``dict`` of columns from a Pandas ``DataFrame``,
suitable for creating a ColumnDataSource.
Args:
df (DataFrame) : data to convert
Returns:
dict[str, np.array] | Below is the the instruction that describes the task:
### Input:
Create a ``dict`` of columns from a Pandas ``DataFrame``,
suitable for creating a ColumnDataSource.
Args:
df (DataFrame) : data to convert
Returns:
dict[str, np.array]
### Response:
def _data_from_df(... |
def _prepare_requirements(requirements, requires_filters):
"""
Overrides the filters specified in the decorator with the given ones
:param requirements: Dictionary of requirements (field → Requirement)
:param requires_filters: Content of the 'requires.filter' component
... | Overrides the filters specified in the decorator with the given ones
:param requirements: Dictionary of requirements (field → Requirement)
:param requires_filters: Content of the 'requires.filter' component
property (field → string)
:return: The new requirements | Below is the the instruction that describes the task:
### Input:
Overrides the filters specified in the decorator with the given ones
:param requirements: Dictionary of requirements (field → Requirement)
:param requires_filters: Content of the 'requires.filter' component
... |
def setEditable(self, state):
"""
Sets whether or not this combo box is editable.
:param state | <bool>
"""
self._editable = state
self._hourCombo.setEditable(state)
self._minuteCombo.setEditable(state)
self._secondCombo.setEditable(state)
... | Sets whether or not this combo box is editable.
:param state | <bool> | Below is the the instruction that describes the task:
### Input:
Sets whether or not this combo box is editable.
:param state | <bool>
### Response:
def setEditable(self, state):
"""
Sets whether or not this combo box is editable.
:param state | <bool>
"""... |
def generate_docstr(element, indent='', wrap=None):
"""
Generate a Python docstr for a given element in the AMQP
XML spec file. The element could be a class or method
The 'wrap' parameter is an optional chunk of text that's
added to the beginning and end of the resulting docstring.
"""
re... | Generate a Python docstr for a given element in the AMQP
XML spec file. The element could be a class or method
The 'wrap' parameter is an optional chunk of text that's
added to the beginning and end of the resulting docstring. | Below is the the instruction that describes the task:
### Input:
Generate a Python docstr for a given element in the AMQP
XML spec file. The element could be a class or method
The 'wrap' parameter is an optional chunk of text that's
added to the beginning and end of the resulting docstring.
### Respon... |
def _ParseKeysFromFindSpecs(self, parser_mediator, win_registry, find_specs):
"""Parses the Registry keys from FindSpecs.
Args:
parser_mediator (ParserMediator): parser mediator.
win_registry (dfwinreg.WinRegistryKey): root Windows Registry key.
find_specs (dfwinreg.FindSpecs): Keys to search... | Parses the Registry keys from FindSpecs.
Args:
parser_mediator (ParserMediator): parser mediator.
win_registry (dfwinreg.WinRegistryKey): root Windows Registry key.
find_specs (dfwinreg.FindSpecs): Keys to search for. | Below is the the instruction that describes the task:
### Input:
Parses the Registry keys from FindSpecs.
Args:
parser_mediator (ParserMediator): parser mediator.
win_registry (dfwinreg.WinRegistryKey): root Windows Registry key.
find_specs (dfwinreg.FindSpecs): Keys to search for.
### Respon... |
def wrap_node(self, node, options):
'''
we have the option to construct nodes here, so we can use different
queues for nodes without having to have different queue objects.
'''
job_kwargs = {
'queue': options.get('queue', 'default'),
'connection': options.... | we have the option to construct nodes here, so we can use different
queues for nodes without having to have different queue objects. | Below is the the instruction that describes the task:
### Input:
we have the option to construct nodes here, so we can use different
queues for nodes without having to have different queue objects.
### Response:
def wrap_node(self, node, options):
'''
we have the option to construct nodes h... |
def empty_mets():
"""
Create an empty METS file from bundled template.
"""
tpl = METS_XML_EMPTY.decode('utf-8')
tpl = tpl.replace('{{ VERSION }}', VERSION)
tpl = tpl.replace('{{ NOW }}', '%s' % datetime.now())
return OcrdMets(content=tpl.encode('utf-8')) | Create an empty METS file from bundled template. | Below is the the instruction that describes the task:
### Input:
Create an empty METS file from bundled template.
### Response:
def empty_mets():
"""
Create an empty METS file from bundled template.
"""
tpl = METS_XML_EMPTY.decode('utf-8')
tpl = tpl.replace('{{ VERSION }}', ... |
def _get_initial_residual(self, x0):
'''Return the projected initial residual.
Returns :math:`MPM_l(b-Ax_0)`.
'''
if x0 is None:
Mlr = self.linear_system.Mlb
else:
r = self.linear_system.b - self.linear_system.A*x0
Mlr = self.linear_system.Ml*... | Return the projected initial residual.
Returns :math:`MPM_l(b-Ax_0)`. | Below is the the instruction that describes the task:
### Input:
Return the projected initial residual.
Returns :math:`MPM_l(b-Ax_0)`.
### Response:
def _get_initial_residual(self, x0):
'''Return the projected initial residual.
Returns :math:`MPM_l(b-Ax_0)`.
'''
if x0 is N... |
def from_web(self, url):
"""
Reverse-engineer a kojiweb URL into an equivalent API response.
Only a few kojiweb URL endpoints work here.
See also connect_from_web().
:param url: ``str``, for example
"http://cbs.centos.org/koji/buildinfo?buildID=21155"
... | Reverse-engineer a kojiweb URL into an equivalent API response.
Only a few kojiweb URL endpoints work here.
See also connect_from_web().
:param url: ``str``, for example
"http://cbs.centos.org/koji/buildinfo?buildID=21155"
:returns: deferred that when fired returns... | Below is the the instruction that describes the task:
### Input:
Reverse-engineer a kojiweb URL into an equivalent API response.
Only a few kojiweb URL endpoints work here.
See also connect_from_web().
:param url: ``str``, for example
"http://cbs.centos.org/koji/buildi... |
def copy(self):
"""
Create an inactive copy of the client object, suitable for passing
to a separate thread.
Note that the copied connections are not initialized, so reinit() must
be called on the returned copy.
"""
c = copy.deepcopy(self)
for key in c.co... | Create an inactive copy of the client object, suitable for passing
to a separate thread.
Note that the copied connections are not initialized, so reinit() must
be called on the returned copy. | Below is the the instruction that describes the task:
### Input:
Create an inactive copy of the client object, suitable for passing
to a separate thread.
Note that the copied connections are not initialized, so reinit() must
be called on the returned copy.
### Response:
def copy(self):
... |
def get_jsonparsed_data(url):
"""Receive the content of ``url``, parse it as JSON and return the
object.
"""
response = urlopen(url)
data = response.read().decode('utf-8')
return json.loads(data) | Receive the content of ``url``, parse it as JSON and return the
object. | Below is the the instruction that describes the task:
### Input:
Receive the content of ``url``, parse it as JSON and return the
object.
### Response:
def get_jsonparsed_data(url):
"""Receive the content of ``url``, parse it as JSON and return the
object.
"""
response = urlopen(url)
d... |
def delete(self):
""" Delete
Deletes directory and drops the file name from dictionary. File on
file system removed on disk.
"""
directory = self._directory()
assert isinstance(directory, Directory)
realPath = self.realPath
assert (os.path.exists(realP... | Delete
Deletes directory and drops the file name from dictionary. File on
file system removed on disk. | Below is the the instruction that describes the task:
### Input:
Delete
Deletes directory and drops the file name from dictionary. File on
file system removed on disk.
### Response:
def delete(self):
""" Delete
Deletes directory and drops the file name from dictionary. File on
... |
def main(sample_id, fastq_pair, clear):
"""Main executor of the skesa template.
Parameters
----------
sample_id : str
Sample Identification string.
fastq_pair : list
Two element list containing the paired FastQ files.
clear : str
Can be either 'true' or 'false'. If 'true... | Main executor of the skesa template.
Parameters
----------
sample_id : str
Sample Identification string.
fastq_pair : list
Two element list containing the paired FastQ files.
clear : str
Can be either 'true' or 'false'. If 'true', the input fastq files will
be remove... | Below is the the instruction that describes the task:
### Input:
Main executor of the skesa template.
Parameters
----------
sample_id : str
Sample Identification string.
fastq_pair : list
Two element list containing the paired FastQ files.
clear : str
Can be either 'true... |
def set_scenario_role_names(self):
"""Populates the list of scenario role names in this deployment and
populates the scenario_master with the master role
Gets a list of deployment properties containing "isMaster" because
there is exactly one per scenario host, containing the role name
... | Populates the list of scenario role names in this deployment and
populates the scenario_master with the master role
Gets a list of deployment properties containing "isMaster" because
there is exactly one per scenario host, containing the role name
:return: | Below is the the instruction that describes the task:
### Input:
Populates the list of scenario role names in this deployment and
populates the scenario_master with the master role
Gets a list of deployment properties containing "isMaster" because
there is exactly one per scenario host, con... |
def get_policies_by_id(profile_manager, policy_ids):
'''
Returns a list of policies with the specified ids.
profile_manager
Reference to the profile manager.
policy_ids
List of policy ids to retrieve.
'''
try:
return profile_manager.RetrieveContent(policy_ids)
excep... | Returns a list of policies with the specified ids.
profile_manager
Reference to the profile manager.
policy_ids
List of policy ids to retrieve. | Below is the the instruction that describes the task:
### Input:
Returns a list of policies with the specified ids.
profile_manager
Reference to the profile manager.
policy_ids
List of policy ids to retrieve.
### Response:
def get_policies_by_id(profile_manager, policy_ids):
'''
R... |
def _GetStat(self):
"""Retrieves information about the file entry.
Returns:
VFSStat: a stat object.
"""
stat_object = vfs_stat.VFSStat()
# Date and time stat information.
access_time = self.access_time
if access_time:
stat_time, stat_time_nano = access_time.CopyToStatTimeTuple(... | Retrieves information about the file entry.
Returns:
VFSStat: a stat object. | Below is the the instruction that describes the task:
### Input:
Retrieves information about the file entry.
Returns:
VFSStat: a stat object.
### Response:
def _GetStat(self):
"""Retrieves information about the file entry.
Returns:
VFSStat: a stat object.
"""
stat_object = vfs_sta... |
async def _cleanup_subprocess(self, process):
"""
Kill the given process and properly closes any pipes connected to it.
"""
if process.returncode is None:
try:
process.kill()
return await asyncio.wait_for(process.wait(), 1)
except c... | Kill the given process and properly closes any pipes connected to it. | Below is the the instruction that describes the task:
### Input:
Kill the given process and properly closes any pipes connected to it.
### Response:
async def _cleanup_subprocess(self, process):
"""
Kill the given process and properly closes any pipes connected to it.
"""
if process... |
def _climlab_to_rrtm(field):
'''Prepare field with proper dimension order.
RRTM code expects arrays with (ncol, nlay)
and with pressure decreasing from surface at element 0
climlab grid dimensions are any of:
- (num_lev,) --> (1, num_lev)
- (num_lat, num_lev) --> (num_lat, num_lev)
... | Prepare field with proper dimension order.
RRTM code expects arrays with (ncol, nlay)
and with pressure decreasing from surface at element 0
climlab grid dimensions are any of:
- (num_lev,) --> (1, num_lev)
- (num_lat, num_lev) --> (num_lat, num_lev)
- (num_lat, num_lon, num_lev) ... | Below is the the instruction that describes the task:
### Input:
Prepare field with proper dimension order.
RRTM code expects arrays with (ncol, nlay)
and with pressure decreasing from surface at element 0
climlab grid dimensions are any of:
- (num_lev,) --> (1, num_lev)
- (num_lat, num... |
def msg_curse(self, args=None, max_width=None):
"""Return the string to display in the curse interface."""
# Init the return message
ret = []
# Build the string message
# 23 is the padding for the process list
msg = '{:23}'.format(self.stats)
ret.append(self.curs... | Return the string to display in the curse interface. | Below is the the instruction that describes the task:
### Input:
Return the string to display in the curse interface.
### Response:
def msg_curse(self, args=None, max_width=None):
"""Return the string to display in the curse interface."""
# Init the return message
ret = []
# Build ... |
def d3logpdf_dlink3(self, link_f, y, Y_metadata=None):
"""
Third order derivative log-likelihood function at y given link(f) w.r.t link(f)
.. math::
\\frac{d^{3} \\ln p(y_{i}|\lambda(f_{i}))}{d^{3}\\lambda(f)} = -\\beta^{3}\\frac{d^{2}\\Psi(\\alpha_{i})}{d\\alpha_{i}}\\\\
... | Third order derivative log-likelihood function at y given link(f) w.r.t link(f)
.. math::
\\frac{d^{3} \\ln p(y_{i}|\lambda(f_{i}))}{d^{3}\\lambda(f)} = -\\beta^{3}\\frac{d^{2}\\Psi(\\alpha_{i})}{d\\alpha_{i}}\\\\
\\alpha_{i} = \\beta y_{i}
:param link_f: latent variables link(... | Below is the the instruction that describes the task:
### Input:
Third order derivative log-likelihood function at y given link(f) w.r.t link(f)
.. math::
\\frac{d^{3} \\ln p(y_{i}|\lambda(f_{i}))}{d^{3}\\lambda(f)} = -\\beta^{3}\\frac{d^{2}\\Psi(\\alpha_{i})}{d\\alpha_{i}}\\\\
\\al... |
def keyPressEvent(self, event):
"""
Qt override.
"""
if event.key() in [Qt.Key_Enter, Qt.Key_Return]:
self._parent.process_text()
if self._parent.is_valid():
self._parent.keyPressEvent(event)
else:
QLineEdit.keyPressEve... | Qt override. | Below is the the instruction that describes the task:
### Input:
Qt override.
### Response:
def keyPressEvent(self, event):
"""
Qt override.
"""
if event.key() in [Qt.Key_Enter, Qt.Key_Return]:
self._parent.process_text()
if self._parent.is_valid():
... |
def set_port_profile_created(self, vlan_id, profile_name, device_id):
"""Sets created_on_ucs flag to True."""
with self.session.begin(subtransactions=True):
port_profile = self.session.query(
ucsm_model.PortProfile).filter_by(
vlan_id=vlan_id, profile_id=p... | Sets created_on_ucs flag to True. | Below is the the instruction that describes the task:
### Input:
Sets created_on_ucs flag to True.
### Response:
def set_port_profile_created(self, vlan_id, profile_name, device_id):
"""Sets created_on_ucs flag to True."""
with self.session.begin(subtransactions=True):
port_profile = se... |
def add_handlers(web_app, config):
"""Add the appropriate handlers to the web app.
"""
base_url = web_app.settings['base_url']
url = ujoin(base_url, config.page_url)
assets_dir = config.assets_dir
package_file = os.path.join(assets_dir, 'package.json')
with open(package_file) as fid:
... | Add the appropriate handlers to the web app. | Below is the the instruction that describes the task:
### Input:
Add the appropriate handlers to the web app.
### Response:
def add_handlers(web_app, config):
"""Add the appropriate handlers to the web app.
"""
base_url = web_app.settings['base_url']
url = ujoin(base_url, config.page_url)
asset... |
def get_scheduler_location(self, topologyName, callback=None):
""" get scheduler location """
isWatching = False
# Temp dict used to return result
# if callback is not provided.
ret = {
"result": None
}
if callback:
isWatching = True
else:
def callback(data):
... | get scheduler location | Below is the the instruction that describes the task:
### Input:
get scheduler location
### Response:
def get_scheduler_location(self, topologyName, callback=None):
""" get scheduler location """
isWatching = False
# Temp dict used to return result
# if callback is not provided.
ret = {
... |
def getInternSig(self):
"""
return signal inside unit which has this port
"""
d = self.direction
if d == DIRECTION.IN:
return self.dst
elif d == DIRECTION.OUT:
return self.src
else:
raise NotImplementedError(d) | return signal inside unit which has this port | Below is the the instruction that describes the task:
### Input:
return signal inside unit which has this port
### Response:
def getInternSig(self):
"""
return signal inside unit which has this port
"""
d = self.direction
if d == DIRECTION.IN:
return self.dst
... |
def TerminateStuckRunIfNeeded(self, job):
"""Cleans up job state if the last run is stuck."""
if job.current_run_id and job.last_run_time and job.lifetime:
now = rdfvalue.RDFDatetime.Now()
# We add additional 10 minutes to give the job run a chance to kill itself
# during one of the HeartBeat ... | Cleans up job state if the last run is stuck. | Below is the the instruction that describes the task:
### Input:
Cleans up job state if the last run is stuck.
### Response:
def TerminateStuckRunIfNeeded(self, job):
"""Cleans up job state if the last run is stuck."""
if job.current_run_id and job.last_run_time and job.lifetime:
now = rdfvalue.RDFDa... |
def _check_condition(self, name, condition):
"""Verify that the condition is valid.
Args:
name (string): used for error reporting
condition (tuple or None): a condition tuple (ClassicalRegister,int)
Raises:
DAGCircuitError: if conditioning on an invalid regi... | Verify that the condition is valid.
Args:
name (string): used for error reporting
condition (tuple or None): a condition tuple (ClassicalRegister,int)
Raises:
DAGCircuitError: if conditioning on an invalid register | Below is the the instruction that describes the task:
### Input:
Verify that the condition is valid.
Args:
name (string): used for error reporting
condition (tuple or None): a condition tuple (ClassicalRegister,int)
Raises:
DAGCircuitError: if conditioning on an... |
def health_state(consul_url=None, token=None, state=None, **kwargs):
'''
Returns the checks in the state provided on the path.
:param consul_url: The Consul server URL.
:param state: The state to show checks for. The supported states
are any, unknown, passing, warning, or critical.
... | Returns the checks in the state provided on the path.
:param consul_url: The Consul server URL.
:param state: The state to show checks for. The supported states
are any, unknown, passing, warning, or critical.
The any state is a wildcard that can be used to
... | Below is the the instruction that describes the task:
### Input:
Returns the checks in the state provided on the path.
:param consul_url: The Consul server URL.
:param state: The state to show checks for. The supported states
are any, unknown, passing, warning, or critical.
... |
def preprocess_script_string(str):
"""
Process python script represented as string `str` in preparation
for conversion to a notebook. This processing includes removal of
the header comment, modification of the plotting configuration,
and replacement of certain sphinx cross-references with
appro... | Process python script represented as string `str` in preparation
for conversion to a notebook. This processing includes removal of
the header comment, modification of the plotting configuration,
and replacement of certain sphinx cross-references with
appropriate links to online docs. | Below is the the instruction that describes the task:
### Input:
Process python script represented as string `str` in preparation
for conversion to a notebook. This processing includes removal of
the header comment, modification of the plotting configuration,
and replacement of certain sphinx cross-ref... |
def main(filename):
""" Given an input file containing nothing but styles, print out an
unrolled list of declarations in cascade order.
"""
input = open(filename, 'r').read()
declarations = cascadenik.stylesheet_declarations(input, is_merc=True)
for dec in declarations:
print de... | Given an input file containing nothing but styles, print out an
unrolled list of declarations in cascade order. | Below is the the instruction that describes the task:
### Input:
Given an input file containing nothing but styles, print out an
unrolled list of declarations in cascade order.
### Response:
def main(filename):
""" Given an input file containing nothing but styles, print out an
unrolled list of... |
def update(self):
"""Updates parameters according to installed optimizer and the gradient computed
in the previous forward-backward cycle.
When KVStore is used to update parameters for multi-device or multi-machine training,
a copy of the parameters are stored in KVStore. Note that for ... | Updates parameters according to installed optimizer and the gradient computed
in the previous forward-backward cycle.
When KVStore is used to update parameters for multi-device or multi-machine training,
a copy of the parameters are stored in KVStore. Note that for `row_sparse` parameters,
... | Below is the the instruction that describes the task:
### Input:
Updates parameters according to installed optimizer and the gradient computed
in the previous forward-backward cycle.
When KVStore is used to update parameters for multi-device or multi-machine training,
a copy of the paramete... |
def _ParseKey(self, knowledge_base, registry_key, value_name):
"""Parses a Windows Registry key for a preprocessing attribute.
Args:
knowledge_base (KnowledgeBase): to fill with preprocessing information.
registry_key (dfwinreg.WinRegistryKey): Windows Registry key.
value_name (str): name of ... | Parses a Windows Registry key for a preprocessing attribute.
Args:
knowledge_base (KnowledgeBase): to fill with preprocessing information.
registry_key (dfwinreg.WinRegistryKey): Windows Registry key.
value_name (str): name of the Windows Registry value.
Raises:
errors.PreProcessFail: ... | Below is the the instruction that describes the task:
### Input:
Parses a Windows Registry key for a preprocessing attribute.
Args:
knowledge_base (KnowledgeBase): to fill with preprocessing information.
registry_key (dfwinreg.WinRegistryKey): Windows Registry key.
value_name (str): name of t... |
def stop(self):
"""
Stop the daemon
"""
# Get the pid from the pidfile
try:
pf = file(self.pidfile,'r')
pid = int(pf.read().strip())
pf.close()
except IOError:
pid = None
if not pid:
message = "pidfile %... | Stop the daemon | Below is the the instruction that describes the task:
### Input:
Stop the daemon
### Response:
def stop(self):
"""
Stop the daemon
"""
# Get the pid from the pidfile
try:
pf = file(self.pidfile,'r')
pid = int(pf.read().strip())
pf.close()
... |
def auth(
cls, consumer_key, redirect_uri='http://example.com/', state=None,
):
'''
This is a test method for verifying if oauth worked
http://getpocket.com/developer/docs/authentication
'''
code = cls.get_request_token(consumer_key, redirect_uri, state)
aut... | This is a test method for verifying if oauth worked
http://getpocket.com/developer/docs/authentication | Below is the the instruction that describes the task:
### Input:
This is a test method for verifying if oauth worked
http://getpocket.com/developer/docs/authentication
### Response:
def auth(
cls, consumer_key, redirect_uri='http://example.com/', state=None,
):
'''
This is a tes... |
def _default_to_pandas(self, op, *args, **kwargs):
"""Helper method to use default pandas function"""
empty_self_str = "" if not self.empty else " for empty DataFrame"
ErrorMessage.default_to_pandas(
"`{}.{}`{}".format(
self.__name__,
op if isins... | Helper method to use default pandas function | Below is the the instruction that describes the task:
### Input:
Helper method to use default pandas function
### Response:
def _default_to_pandas(self, op, *args, **kwargs):
"""Helper method to use default pandas function"""
empty_self_str = "" if not self.empty else " for empty DataFrame"
... |
def report_import(self, name, filename):
"""report_import Report_Name, filename
Uploads a report template to the current user's reports
UN-DOCUMENTED CALL: This function is not considered stable.
"""
data = self._upload(filename)
return self.raw_query('report', 'import',... | report_import Report_Name, filename
Uploads a report template to the current user's reports
UN-DOCUMENTED CALL: This function is not considered stable. | Below is the the instruction that describes the task:
### Input:
report_import Report_Name, filename
Uploads a report template to the current user's reports
UN-DOCUMENTED CALL: This function is not considered stable.
### Response:
def report_import(self, name, filename):
"""report_import R... |
def update(fields, path='', profile=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Sets a dictionary of values in one call. Useful for large updates
in syndic environments. The dictionary can contain a mix of formats
such as:
.. code-block:: python
{
'/some/example/key': ... | .. versionadded:: 2016.3.0
Sets a dictionary of values in one call. Useful for large updates
in syndic environments. The dictionary can contain a mix of formats
such as:
.. code-block:: python
{
'/some/example/key': 'bar',
'/another/example/key': 'baz'
}
Or ... | Below is the the instruction that describes the task:
### Input:
.. versionadded:: 2016.3.0
Sets a dictionary of values in one call. Useful for large updates
in syndic environments. The dictionary can contain a mix of formats
such as:
.. code-block:: python
{
'/some/example/ke... |
def filter(self, entries):
"""Filter a set of declarations: keep only those related to this object.
This will keep:
- Declarations that 'override' the current ones
- Declarations that are parameters to current ones
"""
return [
entry for entry in entries
... | Filter a set of declarations: keep only those related to this object.
This will keep:
- Declarations that 'override' the current ones
- Declarations that are parameters to current ones | Below is the the instruction that describes the task:
### Input:
Filter a set of declarations: keep only those related to this object.
This will keep:
- Declarations that 'override' the current ones
- Declarations that are parameters to current ones
### Response:
def filter(self, entries):... |
def _guess_content_type(url):
'''
Guess content type by url.
>>> _guess_content_type('http://test/A.HTML')
'text/html'
>>> _guess_content_type('http://test/a.jpg')
'image/jpeg'
>>> _guess_content_type('/path.txt/aaa')
'application/octet-stream'
'''
OCTET_STREAM = 'application/oc... | Guess content type by url.
>>> _guess_content_type('http://test/A.HTML')
'text/html'
>>> _guess_content_type('http://test/a.jpg')
'image/jpeg'
>>> _guess_content_type('/path.txt/aaa')
'application/octet-stream' | Below is the the instruction that describes the task:
### Input:
Guess content type by url.
>>> _guess_content_type('http://test/A.HTML')
'text/html'
>>> _guess_content_type('http://test/a.jpg')
'image/jpeg'
>>> _guess_content_type('/path.txt/aaa')
'application/octet-stream'
### Response:
... |
def random_eulerien_graph(n):
"""Generates some random eulerian graph
:param int n: number of vertices
:returns: undirected graph in listlist representation
:complexity: linear
"""
graphe = [[] for _ in range(n)]
for v in range(n - 1):
noeuds = random.sample(range(v + 1, n)... | Generates some random eulerian graph
:param int n: number of vertices
:returns: undirected graph in listlist representation
:complexity: linear | Below is the the instruction that describes the task:
### Input:
Generates some random eulerian graph
:param int n: number of vertices
:returns: undirected graph in listlist representation
:complexity: linear
### Response:
def random_eulerien_graph(n):
"""Generates some random eulerian gr... |
def to_bytes(s, encoding=None, errors='strict'):
"""Returns a bytestring version of 's',
encoded as specified in 'encoding'."""
encoding = encoding or 'utf-8'
if isinstance(s, bytes):
if encoding != 'utf-8':
return s.decode('utf-8', errors).encode(encoding, errors)
else:
... | Returns a bytestring version of 's',
encoded as specified in 'encoding'. | Below is the the instruction that describes the task:
### Input:
Returns a bytestring version of 's',
encoded as specified in 'encoding'.
### Response:
def to_bytes(s, encoding=None, errors='strict'):
"""Returns a bytestring version of 's',
encoded as specified in 'encoding'."""
encoding = encoding or ... |
def get_objective_requisite_session(self, proxy):
"""Gets the session for examining objective requisites.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.learning.ObjectiveRequisiteSession) - an
``ObjectiveRequisiteSession``
raise: NullArgument - ``proxy`` is ``... | Gets the session for examining objective requisites.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.learning.ObjectiveRequisiteSession) - an
``ObjectiveRequisiteSession``
raise: NullArgument - ``proxy`` is ``null``
raise: OperationFailed - unable to complete r... | Below is the the instruction that describes the task:
### Input:
Gets the session for examining objective requisites.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.learning.ObjectiveRequisiteSession) - an
``ObjectiveRequisiteSession``
raise: NullArgument - ``proxy... |
def _process_version_lines(self):
"""Process version line rules."""
if len(self._lines_seen["version"]) > 1:
self._add_error(_("Multiple version lines appeared."))
elif self._lines_seen["version"][0] != 1:
self._add_error(_("The version must be on the first line.")) | Process version line rules. | Below is the the instruction that describes the task:
### Input:
Process version line rules.
### Response:
def _process_version_lines(self):
"""Process version line rules."""
if len(self._lines_seen["version"]) > 1:
self._add_error(_("Multiple version lines appeared."))
elif sel... |
def arduino_path():
"""expanded root path, ARDUINO_HOME env var or arduino_default_path()"""
x = _ARDUINO_PATH
if not x:
x = os.environ.get('ARDUINO_HOME')
if not x:
x = arduino_default_path()
assert x, str(x)
x = path(x).expand().abspath()
assert x.exists(), 'arduino pa... | expanded root path, ARDUINO_HOME env var or arduino_default_path() | Below is the the instruction that describes the task:
### Input:
expanded root path, ARDUINO_HOME env var or arduino_default_path()
### Response:
def arduino_path():
"""expanded root path, ARDUINO_HOME env var or arduino_default_path()"""
x = _ARDUINO_PATH
if not x:
x = os.environ.get('ARDUINO... |
def generate_requirements_files(self, base_dir='.'):
""" Generate set of requirements files for config """
print("Creating requirements files\n")
# TODO How to deal with requirements that are not simple, e.g. a github url
shared = self._get_shared_section()
requirements_dir =... | Generate set of requirements files for config | Below is the the instruction that describes the task:
### Input:
Generate set of requirements files for config
### Response:
def generate_requirements_files(self, base_dir='.'):
""" Generate set of requirements files for config """
print("Creating requirements files\n")
# TODO How to deal... |
def header_without_lines(header, remove):
"""Return :py:class:`Header` without lines given in ``remove``
``remove`` is an iterable of pairs ``key``/``ID`` with the VCF header key
and ``ID`` of entry to remove. In the case that a line does not have
a ``mapping`` entry, you can give the full value to re... | Return :py:class:`Header` without lines given in ``remove``
``remove`` is an iterable of pairs ``key``/``ID`` with the VCF header key
and ``ID`` of entry to remove. In the case that a line does not have
a ``mapping`` entry, you can give the full value to remove.
.. code-block:: python
# head... | Below is the the instruction that describes the task:
### Input:
Return :py:class:`Header` without lines given in ``remove``
``remove`` is an iterable of pairs ``key``/``ID`` with the VCF header key
and ``ID`` of entry to remove. In the case that a line does not have
a ``mapping`` entry, you can give ... |
def createBamHeader(self, baseHeader):
"""
Creates a new bam header based on the specified header from the
parent BAM file.
"""
header = dict(baseHeader)
newSequences = []
for index, referenceInfo in enumerate(header['SQ']):
if index < self.numChromoso... | Creates a new bam header based on the specified header from the
parent BAM file. | Below is the the instruction that describes the task:
### Input:
Creates a new bam header based on the specified header from the
parent BAM file.
### Response:
def createBamHeader(self, baseHeader):
"""
Creates a new bam header based on the specified header from the
parent BAM file.... |
def CheckBlobsExist(self, blob_ids):
"""Checks if given blobs exit."""
result = {}
for blob_id in blob_ids:
result[blob_id] = blob_id in self.blobs
return result | Checks if given blobs exit. | Below is the the instruction that describes the task:
### Input:
Checks if given blobs exit.
### Response:
def CheckBlobsExist(self, blob_ids):
"""Checks if given blobs exit."""
result = {}
for blob_id in blob_ids:
result[blob_id] = blob_id in self.blobs
return result |
def is_expired_token(self, client):
"""
For a given client will test whether or not the token
has expired.
This is for testing a client object and does not look up
from client_id. You can use _get_client_from_cache() to
lookup a client from client_id.
"""
... | For a given client will test whether or not the token
has expired.
This is for testing a client object and does not look up
from client_id. You can use _get_client_from_cache() to
lookup a client from client_id. | Below is the the instruction that describes the task:
### Input:
For a given client will test whether or not the token
has expired.
This is for testing a client object and does not look up
from client_id. You can use _get_client_from_cache() to
lookup a client from client_id.
### R... |
def set_config_item(self, key, value):
"""
Set a config key to a provided value.
The value can be a list for the keys supporting multiple values.
"""
try:
old_value = self.get_config_item(key)
except KeyError:
old_value = None
# Ge... | Set a config key to a provided value.
The value can be a list for the keys supporting multiple values. | Below is the the instruction that describes the task:
### Input:
Set a config key to a provided value.
The value can be a list for the keys supporting multiple values.
### Response:
def set_config_item(self, key, value):
"""
Set a config key to a provided value.
The valu... |
def get_item(self, path, project=None, file_name=None, download=None, scope_path=None, recursion_level=None, version_descriptor=None, include_content=None):
"""GetItem.
Get Item Metadata and/or Content for a single item. The download parameter is to indicate whether the content should be available as a ... | GetItem.
Get Item Metadata and/or Content for a single item. The download parameter is to indicate whether the content should be available as a download or just sent as a stream in the response. Doesn't apply to zipped content which is always returned as a download.
:param str path: Version control path... | Below is the the instruction that describes the task:
### Input:
GetItem.
Get Item Metadata and/or Content for a single item. The download parameter is to indicate whether the content should be available as a download or just sent as a stream in the response. Doesn't apply to zipped content which is always ... |
def extract_diacritic(*diacritics):
"""
Given a collection of Unicode diacritics, return a function that takes a
Unicode character and returns the member of the collection the character
has (or None).
"""
def _(ch):
decomposed_form = unicodedata.normalize("NFD", ch)
for diacritic... | Given a collection of Unicode diacritics, return a function that takes a
Unicode character and returns the member of the collection the character
has (or None). | Below is the the instruction that describes the task:
### Input:
Given a collection of Unicode diacritics, return a function that takes a
Unicode character and returns the member of the collection the character
has (or None).
### Response:
def extract_diacritic(*diacritics):
"""
Given a collection ... |
def read_file(path):
"""Read a UTF-8 file from the package. Takes a list of strings to join to
make the path"""
file_path = os.path.join(here, *path)
with open(file_path, encoding="utf-8") as f:
return f.read() | Read a UTF-8 file from the package. Takes a list of strings to join to
make the path | Below is the the instruction that describes the task:
### Input:
Read a UTF-8 file from the package. Takes a list of strings to join to
make the path
### Response:
def read_file(path):
"""Read a UTF-8 file from the package. Takes a list of strings to join to
make the path"""
file_path = os.path.joi... |
def get_environments():
"""
Return defined environments from config file for default
environment values.
"""
config = ConfigParser.SafeConfigParser()
config = _config_file()
juicer.utils.Log.log_debug("Reading environment sections:")
environments = config.sections()
juicer.utils.L... | Return defined environments from config file for default
environment values. | Below is the the instruction that describes the task:
### Input:
Return defined environments from config file for default
environment values.
### Response:
def get_environments():
"""
Return defined environments from config file for default
environment values.
"""
config = ConfigParser.Safe... |
def create(self, data):
"""
Add a new store to your MailChimp account.
Error checking on the currency code verifies that it is in the correct
three-letter, all-caps format as specified by ISO 4217 but does not
check that it is a valid code as the list of valid codes changes over... | Add a new store to your MailChimp account.
Error checking on the currency code verifies that it is in the correct
three-letter, all-caps format as specified by ISO 4217 but does not
check that it is a valid code as the list of valid codes changes over
time.
:param data: The req... | Below is the the instruction that describes the task:
### Input:
Add a new store to your MailChimp account.
Error checking on the currency code verifies that it is in the correct
three-letter, all-caps format as specified by ISO 4217 but does not
check that it is a valid code as the list of... |
def _augment_text_w_syntactic_info( self, text, text_layer ):
''' Augments given Text object with the syntactic information
from the *text_layer*. More specifically, adds information
about SYNTAX_LABEL, SYNTAX_HEAD and DEPREL to each token
in the Text object;
... | Augments given Text object with the syntactic information
from the *text_layer*. More specifically, adds information
about SYNTAX_LABEL, SYNTAX_HEAD and DEPREL to each token
in the Text object;
(!) Note: this method is added to provide some initial
... | Below is the the instruction that describes the task:
### Input:
Augments given Text object with the syntactic information
from the *text_layer*. More specifically, adds information
about SYNTAX_LABEL, SYNTAX_HEAD and DEPREL to each token
in the Text object;
... |
def formatted_completion_sig(completion):
"""Regenerate signature for methods. Return just the name otherwise"""
f_result = completion["name"]
if is_basic_type(completion):
# It's a raw type
return f_result
elif len(completion["typeInfo"]["paramSections"]) == 0:
return f_result
... | Regenerate signature for methods. Return just the name otherwise | Below is the the instruction that describes the task:
### Input:
Regenerate signature for methods. Return just the name otherwise
### Response:
def formatted_completion_sig(completion):
"""Regenerate signature for methods. Return just the name otherwise"""
f_result = completion["name"]
if is_basic_type... |
def disable():
"""
Disable all benchmarking.
"""
Benchmark.enable = False
ComparisonBenchmark.enable = False
BenchmarkedFunction.enable = False
BenchmarkedClass.enable = False | Disable all benchmarking. | Below is the the instruction that describes the task:
### Input:
Disable all benchmarking.
### Response:
def disable():
"""
Disable all benchmarking.
"""
Benchmark.enable = False
ComparisonBenchmark.enable = False
BenchmarkedFunction.enable = False
BenchmarkedClass.enable = False |
def _on_report(_loop, adapter, conn_id, report):
"""Callback when a report is received."""
conn_string = None
if conn_id is not None:
conn_string = adapter._get_property(conn_id, 'connection_string')
if isinstance(report, BroadcastReport):
adapter.notify_event_nowait(conn_string, 'broa... | Callback when a report is received. | Below is the the instruction that describes the task:
### Input:
Callback when a report is received.
### Response:
def _on_report(_loop, adapter, conn_id, report):
"""Callback when a report is received."""
conn_string = None
if conn_id is not None:
conn_string = adapter._get_property(conn_id, ... |
def probabilities(self, choosers, alternatives):
"""
Returns alternative probabilties for each chooser segment as
a dictionary keyed by segment name.
Parameters
----------
choosers : pandas.DataFrame
Table describing the agents making choices, e.g. households... | Returns alternative probabilties for each chooser segment as
a dictionary keyed by segment name.
Parameters
----------
choosers : pandas.DataFrame
Table describing the agents making choices, e.g. households.
Must have a column matching the .segmentation_col attri... | Below is the the instruction that describes the task:
### Input:
Returns alternative probabilties for each chooser segment as
a dictionary keyed by segment name.
Parameters
----------
choosers : pandas.DataFrame
Table describing the agents making choices, e.g. households... |
def point_line_distance(point, start, end):
""" Distance from a point to a line, formed by two points
Args:
point (:obj:`Point`)
start (:obj:`Point`): line point
end (:obj:`Point`): line point
Returns:
float: distance to line, in degrees
"""
if start == end:
... | Distance from a point to a line, formed by two points
Args:
point (:obj:`Point`)
start (:obj:`Point`): line point
end (:obj:`Point`): line point
Returns:
float: distance to line, in degrees | Below is the the instruction that describes the task:
### Input:
Distance from a point to a line, formed by two points
Args:
point (:obj:`Point`)
start (:obj:`Point`): line point
end (:obj:`Point`): line point
Returns:
float: distance to line, in degrees
### Response:
def p... |
def check_rights_and_access(request, meta, project=None):
"""Check if the user can access the page"""
# User must be logged ?
if ('only_logged_user' in meta and meta['only_logged_user']):
if not request.user.is_authenticated():
return gen403(request, baseURI, 'only_logged_user', project)... | Check if the user can access the page | Below is the the instruction that describes the task:
### Input:
Check if the user can access the page
### Response:
def check_rights_and_access(request, meta, project=None):
"""Check if the user can access the page"""
# User must be logged ?
if ('only_logged_user' in meta and meta['only_logged_user'])... |
def get_doc(self, item_id, id_field="_id", **kwargs):
""" returns a single item data record/document based on specified
criteria
args:
item_id: the id value of the desired item. Can be used in
combination with the id_field for a paired lookup.
... | returns a single item data record/document based on specified
criteria
args:
item_id: the id value of the desired item. Can be used in
combination with the id_field for a paired lookup.
id_field: the field that is related to the item_id; default = '_id... | Below is the the instruction that describes the task:
### Input:
returns a single item data record/document based on specified
criteria
args:
item_id: the id value of the desired item. Can be used in
combination with the id_field for a paired lookup.
... |
def apply_tile_groups(self, tile_groups):
"""Increase mana, xp, money, anvils and scrolls based on tile groups."""
self_increase_types = ('r', 'g', 'b', 'y', 'x', 'm', 'h', 'c')
attack_types = ('s', '*')
total_attack = 0
for tile_group in tile_groups:
group_type = Non... | Increase mana, xp, money, anvils and scrolls based on tile groups. | Below is the the instruction that describes the task:
### Input:
Increase mana, xp, money, anvils and scrolls based on tile groups.
### Response:
def apply_tile_groups(self, tile_groups):
"""Increase mana, xp, money, anvils and scrolls based on tile groups."""
self_increase_types = ('r', 'g', 'b', ... |
def get_queryset_by_group_and_key(self, group, key=None):
"""get queryset"""
if key is None:
return self.filter_by(group=group)
else:
return self.filter_by(group=group, key=key) | get queryset | Below is the the instruction that describes the task:
### Input:
get queryset
### Response:
def get_queryset_by_group_and_key(self, group, key=None):
"""get queryset"""
if key is None:
return self.filter_by(group=group)
else:
return self.filter_by(group=group, key=k... |
def som_get_size(som_pointer):
"""!
@brief Returns size of self-organized map (number of neurons).
@param[in] som_pointer (c_pointer): pointer to object of self-organized map.
"""
ccore = ccore_library.get()
ccore.som_get_size.restype = c_size_t
return ccore.som_get_... | !
@brief Returns size of self-organized map (number of neurons).
@param[in] som_pointer (c_pointer): pointer to object of self-organized map. | Below is the the instruction that describes the task:
### Input:
!
@brief Returns size of self-organized map (number of neurons).
@param[in] som_pointer (c_pointer): pointer to object of self-organized map.
### Response:
def som_get_size(som_pointer):
"""!
@brief Returns size of self-orga... |
def isoformat(dt):
"""Return an ISO-8601 formatted string from the provided datetime object"""
if not isinstance(dt, datetime.datetime):
raise TypeError("Must provide datetime.datetime object to isoformat")
if dt.tzinfo is None:
raise ValueError("naive datetime objects are not allowed beyon... | Return an ISO-8601 formatted string from the provided datetime object | Below is the the instruction that describes the task:
### Input:
Return an ISO-8601 formatted string from the provided datetime object
### Response:
def isoformat(dt):
"""Return an ISO-8601 formatted string from the provided datetime object"""
if not isinstance(dt, datetime.datetime):
raise TypeErr... |
def rollback(self, revision):
"""
Rollsback the currently deploy lambda code to a previous revision.
"""
print("Rolling back..")
self.zappa.rollback_lambda_function_version(
self.lambda_name, versions_back=revision)
print("Done!") | Rollsback the currently deploy lambda code to a previous revision. | Below is the the instruction that describes the task:
### Input:
Rollsback the currently deploy lambda code to a previous revision.
### Response:
def rollback(self, revision):
"""
Rollsback the currently deploy lambda code to a previous revision.
"""
print("Rolling back..")
... |
def order(self):
"""
Finds the polynomial order.
Examples
--------
>>> (x + 4).order
1
>>> (x + 4 - x ** 18).order
18
>>> (x - x).order
0
>>> (x ** -3 + 4).order
Traceback (most recent call last):
...
AttributeError: Power needs to be positive integers
"""... | Finds the polynomial order.
Examples
--------
>>> (x + 4).order
1
>>> (x + 4 - x ** 18).order
18
>>> (x - x).order
0
>>> (x ** -3 + 4).order
Traceback (most recent call last):
...
AttributeError: Power needs to be positive integers | Below is the the instruction that describes the task:
### Input:
Finds the polynomial order.
Examples
--------
>>> (x + 4).order
1
>>> (x + 4 - x ** 18).order
18
>>> (x - x).order
0
>>> (x ** -3 + 4).order
Traceback (most recent call last):
...
AttributeError: Powe... |
def _remove_qs(self, url):
'''
Removes a query string from a URL before signing.
:param url: The URL to strip.
:type url: str
'''
scheme, netloc, path, query, fragment = urlsplit(url)
return urlunsplit((scheme, netloc, path, '', fragment)) | Removes a query string from a URL before signing.
:param url: The URL to strip.
:type url: str | Below is the the instruction that describes the task:
### Input:
Removes a query string from a URL before signing.
:param url: The URL to strip.
:type url: str
### Response:
def _remove_qs(self, url):
'''
Removes a query string from a URL before signing.
:param url: The UR... |
def download_folder(self, folder='', target_folder=''):
""" Downloads a whole folder from the server.
FtpHandler.download_folder() will download all the files
from the server in the working directory.
:param folder: the absolute path for the folder on the server.
:type folder: ... | Downloads a whole folder from the server.
FtpHandler.download_folder() will download all the files
from the server in the working directory.
:param folder: the absolute path for the folder on the server.
:type folder: string
:param target_folder: absolute or relative path for t... | Below is the the instruction that describes the task:
### Input:
Downloads a whole folder from the server.
FtpHandler.download_folder() will download all the files
from the server in the working directory.
:param folder: the absolute path for the folder on the server.
:type folder:... |
def numeric_columns(self, include_bool=True):
"""Returns the numeric columns of the Manager.
Returns:
List of index names.
"""
columns = []
for col, dtype in zip(self.columns, self.dtypes):
if is_numeric_dtype(dtype) and (
include_bool or ... | Returns the numeric columns of the Manager.
Returns:
List of index names. | Below is the the instruction that describes the task:
### Input:
Returns the numeric columns of the Manager.
Returns:
List of index names.
### Response:
def numeric_columns(self, include_bool=True):
"""Returns the numeric columns of the Manager.
Returns:
List of in... |
def attach_service(cls, service):
""" Allows you to attach one TCP and one HTTP service
deprecated:: 2.1.73 use http and tcp specific methods
:param service: A vyked TCP or HTTP service that needs to be hosted
"""
invalid_service = True
_service_classes = {'_tcp_service'... | Allows you to attach one TCP and one HTTP service
deprecated:: 2.1.73 use http and tcp specific methods
:param service: A vyked TCP or HTTP service that needs to be hosted | Below is the the instruction that describes the task:
### Input:
Allows you to attach one TCP and one HTTP service
deprecated:: 2.1.73 use http and tcp specific methods
:param service: A vyked TCP or HTTP service that needs to be hosted
### Response:
def attach_service(cls, service):
""" A... |
def check_positive(**params):
"""Check that parameters are positive as expected
Raises
------
ValueError : unacceptable choice of parameters
"""
for p in params:
if not isinstance(params[p], numbers.Number) or params[p] <= 0:
raise ValueError(
"Expected {} > ... | Check that parameters are positive as expected
Raises
------
ValueError : unacceptable choice of parameters | Below is the the instruction that describes the task:
### Input:
Check that parameters are positive as expected
Raises
------
ValueError : unacceptable choice of parameters
### Response:
def check_positive(**params):
"""Check that parameters are positive as expected
Raises
------
Valu... |
def upload(self, file_obj):
"""
Replace the content of this object.
:param file file_obj: The file (or file-like object) to upload.
"""
return self._client.upload_object(
self._instance, self._bucket, self.name, file_obj) | Replace the content of this object.
:param file file_obj: The file (or file-like object) to upload. | Below is the the instruction that describes the task:
### Input:
Replace the content of this object.
:param file file_obj: The file (or file-like object) to upload.
### Response:
def upload(self, file_obj):
"""
Replace the content of this object.
:param file file_obj: The file (or... |
def detrend(self, detrend='constant'):
"""Remove the trend from this `TimeSeries`
This method just wraps :func:`scipy.signal.detrend` to return
an object of the same type as the input.
Parameters
----------
detrend : `str`, optional
the type of detrending.
... | Remove the trend from this `TimeSeries`
This method just wraps :func:`scipy.signal.detrend` to return
an object of the same type as the input.
Parameters
----------
detrend : `str`, optional
the type of detrending.
Returns
-------
detrended ... | Below is the the instruction that describes the task:
### Input:
Remove the trend from this `TimeSeries`
This method just wraps :func:`scipy.signal.detrend` to return
an object of the same type as the input.
Parameters
----------
detrend : `str`, optional
the ty... |
def _process_pub_dbxref(self, limit):
"""
Xrefs for publications (ie FBrf = PMID)
:param limit:
:return:
"""
if self.test_mode:
graph = self.testgraph
else:
graph = self.graph
model = Model(graph)
raw = '/'.join((self.rawd... | Xrefs for publications (ie FBrf = PMID)
:param limit:
:return: | Below is the the instruction that describes the task:
### Input:
Xrefs for publications (ie FBrf = PMID)
:param limit:
:return:
### Response:
def _process_pub_dbxref(self, limit):
"""
Xrefs for publications (ie FBrf = PMID)
:param limit:
:return:
"""
... |
def _parse_response(resp):
""" Get xmlrpc response from scgi response
"""
# Assume they care for standards and send us CRLF (not just LF)
try:
headers, payload = resp.split("\r\n\r\n", 1)
except (TypeError, ValueError) as exc:
raise SCGIException("No header delimiter in SCGI response... | Get xmlrpc response from scgi response | Below is the the instruction that describes the task:
### Input:
Get xmlrpc response from scgi response
### Response:
def _parse_response(resp):
""" Get xmlrpc response from scgi response
"""
# Assume they care for standards and send us CRLF (not just LF)
try:
headers, payload = resp.split(... |
def SETE(cpu, dest):
"""
Sets byte if equal.
:param cpu: current CPU.
:param dest: destination operand.
"""
dest.write(Operators.ITEBV(dest.size, cpu.ZF, 1, 0)) | Sets byte if equal.
:param cpu: current CPU.
:param dest: destination operand. | Below is the the instruction that describes the task:
### Input:
Sets byte if equal.
:param cpu: current CPU.
:param dest: destination operand.
### Response:
def SETE(cpu, dest):
"""
Sets byte if equal.
:param cpu: current CPU.
:param dest: destination operand.
... |
def release():
"""
Release new package version to pypi
:return:
"""
from secrets import pypi_auth
# Check that all changes are committed before creating a new version
git_check()
# Test package
test()
# Increment version
inc_version()
# Commit new version, create tag... | Release new package version to pypi
:return: | Below is the the instruction that describes the task:
### Input:
Release new package version to pypi
:return:
### Response:
def release():
"""
Release new package version to pypi
:return:
"""
from secrets import pypi_auth
# Check that all changes are committed before creating a new ve... |
def unpack_directory(filename, extract_dir, progress_filter=default_filter):
""""Unpack" a directory, using the same interface as for archives
Raises ``UnrecognizedFormat`` if `filename` is not a directory
"""
if not os.path.isdir(filename):
raise UnrecognizedFormat("%s is not a directory" % (f... | Unpack" a directory, using the same interface as for archives
Raises ``UnrecognizedFormat`` if `filename` is not a directory | Below is the the instruction that describes the task:
### Input:
Unpack" a directory, using the same interface as for archives
Raises ``UnrecognizedFormat`` if `filename` is not a directory
### Response:
def unpack_directory(filename, extract_dir, progress_filter=default_filter):
""""Unpack" a directory, ... |
def ec2_route_table_tagged_route_table_id(self, lookup, default=None):
"""
Args:
lookup: the tagged route table name, should be unique
default: the optional value to return if lookup failed; returns None if not set
Returns:
the ID of the route table, or default if no match/multiple matches... | Args:
lookup: the tagged route table name, should be unique
default: the optional value to return if lookup failed; returns None if not set
Returns:
the ID of the route table, or default if no match/multiple matches found | Below is the the instruction that describes the task:
### Input:
Args:
lookup: the tagged route table name, should be unique
default: the optional value to return if lookup failed; returns None if not set
Returns:
the ID of the route table, or default if no match/multiple matches found
### Res... |
def get(self, id=None, **kwargs):
"""Retrieve a single object.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Returns:
object: The generated RESTObject
Raises:
GitlabAuthenticationError: If authentication is not correct
... | Retrieve a single object.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Returns:
object: The generated RESTObject
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabGetError: If the server cannot perform ... | Below is the the instruction that describes the task:
### Input:
Retrieve a single object.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Returns:
object: The generated RESTObject
Raises:
GitlabAuthenticationError: If authentication is ... |
def add(self, key, val, minutes):
"""
Store an item in the cache if it does not exist.
:param key: The cache key
:type key: str
:param val: The cache value
:type val: mixed
:param minutes: The lifetime in minutes of the cached value
:type minutes: int
... | Store an item in the cache if it does not exist.
:param key: The cache key
:type key: str
:param val: The cache value
:type val: mixed
:param minutes: The lifetime in minutes of the cached value
:type minutes: int
:rtype: bool | Below is the the instruction that describes the task:
### Input:
Store an item in the cache if it does not exist.
:param key: The cache key
:type key: str
:param val: The cache value
:type val: mixed
:param minutes: The lifetime in minutes of the cached value
:type... |
def register_lookup_handler(lookup_type, handler_or_path):
"""Register a lookup handler.
Args:
lookup_type (str): Name to register the handler under
handler_or_path (OneOf[func, str]): a function or a path to a handler
"""
handler = handler_or_path
if isinstance(handler_or_path, ba... | Register a lookup handler.
Args:
lookup_type (str): Name to register the handler under
handler_or_path (OneOf[func, str]): a function or a path to a handler | Below is the the instruction that describes the task:
### Input:
Register a lookup handler.
Args:
lookup_type (str): Name to register the handler under
handler_or_path (OneOf[func, str]): a function or a path to a handler
### Response:
def register_lookup_handler(lookup_type, handler_or_path):... |
def span(self, name='child_span'):
"""Create a child span for the current span and append it to the child
spans list.
:type name: str
:param name: (Optional) The name of the child span.
:rtype: :class: `~opencensus.trace.blankspan.BlankSpan`
:returns: A child Span to be... | Create a child span for the current span and append it to the child
spans list.
:type name: str
:param name: (Optional) The name of the child span.
:rtype: :class: `~opencensus.trace.blankspan.BlankSpan`
:returns: A child Span to be added to the current span. | Below is the the instruction that describes the task:
### Input:
Create a child span for the current span and append it to the child
spans list.
:type name: str
:param name: (Optional) The name of the child span.
:rtype: :class: `~opencensus.trace.blankspan.BlankSpan`
:retu... |
def skimage_radon_back_projector(sinogram, geometry, range, out=None):
"""Calculate forward projection using skimage.
Parameters
----------
sinogram : `DiscreteLpElement`
Sinogram (projections) to backproject.
geometry : `Geometry`
The projection geometry to use.
range : `Discre... | Calculate forward projection using skimage.
Parameters
----------
sinogram : `DiscreteLpElement`
Sinogram (projections) to backproject.
geometry : `Geometry`
The projection geometry to use.
range : `DiscreteLp`
range of this projection (volume space).
out : ``range`` ele... | Below is the the instruction that describes the task:
### Input:
Calculate forward projection using skimage.
Parameters
----------
sinogram : `DiscreteLpElement`
Sinogram (projections) to backproject.
geometry : `Geometry`
The projection geometry to use.
range : `DiscreteLp`
... |
def bounding_box(self):
"""
Generate a bounding box based on the full complexity part.
:return: bounding box of part
:rtype: cadquery.BoundBox
"""
if self.world_coords:
return self.world_obj.findSolid().BoundingBox()
return self.local_obj.findSolid().... | Generate a bounding box based on the full complexity part.
:return: bounding box of part
:rtype: cadquery.BoundBox | Below is the the instruction that describes the task:
### Input:
Generate a bounding box based on the full complexity part.
:return: bounding box of part
:rtype: cadquery.BoundBox
### Response:
def bounding_box(self):
"""
Generate a bounding box based on the full complexity part.
... |
def to_unicode(s):
""" Convert to unicode, raise exception with instructive error
message if s is not unicode, ascii, or utf-8. """
if not isinstance(s, TEXT):
if not isinstance(s, bytes):
raise TypeError('You are required to pass either unicode or '
'bytes he... | Convert to unicode, raise exception with instructive error
message if s is not unicode, ascii, or utf-8. | Below is the the instruction that describes the task:
### Input:
Convert to unicode, raise exception with instructive error
message if s is not unicode, ascii, or utf-8.
### Response:
def to_unicode(s):
""" Convert to unicode, raise exception with instructive error
message if s is not unicode, ascii, o... |
def names(self):
"""Return a list of the names referenced by this binding."""
names = []
if isinstance(self.source, ast.List):
for node in self.source.elts:
if isinstance(node, ast.Str):
names.append(node.s)
return names | Return a list of the names referenced by this binding. | Below is the the instruction that describes the task:
### Input:
Return a list of the names referenced by this binding.
### Response:
def names(self):
"""Return a list of the names referenced by this binding."""
names = []
if isinstance(self.source, ast.List):
for node in self.s... |
def rerender(self):
'''
Rerender all derived images from the original.
If optmization settings or expected sizes changed,
they will be used for the new rendering.
'''
with self.fs.open(self.original, 'rb') as f_img:
img = io.BytesIO(f_img.read()) # Store the ... | Rerender all derived images from the original.
If optmization settings or expected sizes changed,
they will be used for the new rendering. | Below is the the instruction that describes the task:
### Input:
Rerender all derived images from the original.
If optmization settings or expected sizes changed,
they will be used for the new rendering.
### Response:
def rerender(self):
'''
Rerender all derived images from the orig... |
async def dump_message_field(obj, msg, field, field_archiver=None):
"""
Dumps a message field to the object. Field is defined by the message field specification.
:param obj:
:param msg:
:param field:
:param field_archiver:
:return:
"""
fname, ftype, params = field[0], field[1], fiel... | Dumps a message field to the object. Field is defined by the message field specification.
:param obj:
:param msg:
:param field:
:param field_archiver:
:return: | Below is the the instruction that describes the task:
### Input:
Dumps a message field to the object. Field is defined by the message field specification.
:param obj:
:param msg:
:param field:
:param field_archiver:
:return:
### Response:
async def dump_message_field(obj, msg, field, field_arc... |
def find_apps(name=None, name_mode='exact', category=None,
all_versions=None, published=None,
billed_to=None, created_by=None, developer=None,
created_after=None, created_before=None,
modified_after=None, modified_before=None,
describe=False, limit=N... | This method is identical to :meth:`find_global_executables()` with the API method
used: :meth:`system_find_apps()`. | Below is the the instruction that describes the task:
### Input:
This method is identical to :meth:`find_global_executables()` with the API method
used: :meth:`system_find_apps()`.
### Response:
def find_apps(name=None, name_mode='exact', category=None,
all_versions=None, published=None,
... |
def additions_version():
'''
Check VirtualBox Guest Additions version.
CLI Example:
.. code-block:: bash
salt '*' vbox_guest.additions_version
:return: version of VirtualBox Guest Additions or False if they are not installed
'''
try:
d = _additions_dir()
except Enviro... | Check VirtualBox Guest Additions version.
CLI Example:
.. code-block:: bash
salt '*' vbox_guest.additions_version
:return: version of VirtualBox Guest Additions or False if they are not installed | Below is the the instruction that describes the task:
### Input:
Check VirtualBox Guest Additions version.
CLI Example:
.. code-block:: bash
salt '*' vbox_guest.additions_version
:return: version of VirtualBox Guest Additions or False if they are not installed
### Response:
def additions_ve... |
def _sendResult(self, result):
""" Send parseable json result of command. """
# logger.debug("Result: %s", result)
try:
result = json.dumps(result)
except Exception as error:
result = json.dumps(self._errorInfo(command, error))
sys.stdout.write(result)
... | Send parseable json result of command. | Below is the the instruction that describes the task:
### Input:
Send parseable json result of command.
### Response:
def _sendResult(self, result):
""" Send parseable json result of command. """
# logger.debug("Result: %s", result)
try:
result = json.dumps(result)
exce... |
def nopen(f, mode="r"):
r"""
open a file that's gzipped or return stdin for '-'
if f is a number, the result of nopen(sys.argv[f]) is returned.
>>> nopen('-') == sys.stdin, nopen('-', 'w') == sys.stdout
(True, True)
>>> nopen(sys.argv[0])
<...file...>
# expands user and vars ($HOME)
... | r"""
open a file that's gzipped or return stdin for '-'
if f is a number, the result of nopen(sys.argv[f]) is returned.
>>> nopen('-') == sys.stdin, nopen('-', 'w') == sys.stdout
(True, True)
>>> nopen(sys.argv[0])
<...file...>
# expands user and vars ($HOME)
>>> nopen("~/.bashrc").name ... | Below is the the instruction that describes the task:
### Input:
r"""
open a file that's gzipped or return stdin for '-'
if f is a number, the result of nopen(sys.argv[f]) is returned.
>>> nopen('-') == sys.stdin, nopen('-', 'w') == sys.stdout
(True, True)
>>> nopen(sys.argv[0])
<...file...>... |
def register(cls):
"""
Register a given model in the registry
"""
registry_entry = RegistryEntry(category = cls.category, namespace = cls.namespace, name = cls.name, cls=cls)
if registry_entry not in registry and not exists_in_registry(cls.category, cls.namespace, cls.name):
registry.append(... | Register a given model in the registry | Below is the the instruction that describes the task:
### Input:
Register a given model in the registry
### Response:
def register(cls):
"""
Register a given model in the registry
"""
registry_entry = RegistryEntry(category = cls.category, namespace = cls.namespace, name = cls.name, cls=cls)
if... |
def validate_is_document_type(option, value):
"""Validate the type of method arguments that expect a MongoDB document."""
if not isinstance(value, (collections.MutableMapping, RawBSONDocument)):
raise TypeError("%s must be an instance of dict, bson.son.SON, "
"bson.raw_bson.RawBS... | Validate the type of method arguments that expect a MongoDB document. | Below is the the instruction that describes the task:
### Input:
Validate the type of method arguments that expect a MongoDB document.
### Response:
def validate_is_document_type(option, value):
"""Validate the type of method arguments that expect a MongoDB document."""
if not isinstance(value, (collection... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.