code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def casefold_parts(self, parts):
"""Return the lower-case version of parts for a Windows filesystem."""
if self.filesystem.is_windows_fs:
return [p.lower() for p in parts]
return parts | Return the lower-case version of parts for a Windows filesystem. | Below is the the instruction that describes the task:
### Input:
Return the lower-case version of parts for a Windows filesystem.
### Response:
def casefold_parts(self, parts):
"""Return the lower-case version of parts for a Windows filesystem."""
if self.filesystem.is_windows_fs:
retur... |
def get(self, key):
"""
Returns the value for the specified key, or ``None`` if this map does not contain this key.
**Warning:
This method returns a clone of original value, modifying the returned value does not change the actual value in
the map. One should put modified value b... | Returns the value for the specified key, or ``None`` if this map does not contain this key.
**Warning:
This method returns a clone of original value, modifying the returned value does not change the actual value in
the map. One should put modified value back to make changes visible to all nodes... | Below is the the instruction that describes the task:
### Input:
Returns the value for the specified key, or ``None`` if this map does not contain this key.
**Warning:
This method returns a clone of original value, modifying the returned value does not change the actual value in
the map. On... |
def append(self, node):
"""To append a new child."""
if node.parent == self.key and not self.elapsed_time:
self.children.append(node)
else:
# Recursive call
for child in self.children:
if not child.elapsed_time:
child.append... | To append a new child. | Below is the the instruction that describes the task:
### Input:
To append a new child.
### Response:
def append(self, node):
"""To append a new child."""
if node.parent == self.key and not self.elapsed_time:
self.children.append(node)
else:
# Recursive call
... |
def _populate_worksheet(self, workbook, worksheet):
"""
Write chart data contents to *worksheet* in the bubble chart layout.
Write the data for each series to a separate three-column table with
X values in column A, Y values in column B, and bubble sizes in
column C. Place the se... | Write chart data contents to *worksheet* in the bubble chart layout.
Write the data for each series to a separate three-column table with
X values in column A, Y values in column B, and bubble sizes in
column C. Place the series label in the first (heading) cell of the
values column. | Below is the the instruction that describes the task:
### Input:
Write chart data contents to *worksheet* in the bubble chart layout.
Write the data for each series to a separate three-column table with
X values in column A, Y values in column B, and bubble sizes in
column C. Place the serie... |
def get_container_id(self, container_id=None):
''' a helper function shared between functions that will return a
container_id. First preference goes to a container_id provided by
the user at runtime. Second preference goes to the container_id
instantiated with the client.
... | a helper function shared between functions that will return a
container_id. First preference goes to a container_id provided by
the user at runtime. Second preference goes to the container_id
instantiated with the client.
Parameters
==========
co... | Below is the the instruction that describes the task:
### Input:
a helper function shared between functions that will return a
container_id. First preference goes to a container_id provided by
the user at runtime. Second preference goes to the container_id
instantiated with the ... |
def replace(self, expression: Expression, max_count: int=math.inf) -> Union[Expression, Sequence[Expression]]:
"""Replace all occurrences of the patterns according to the replacement rules.
Args:
expression:
The expression to which the replacement rules are applied.
... | Replace all occurrences of the patterns according to the replacement rules.
Args:
expression:
The expression to which the replacement rules are applied.
max_count:
If given, at most *max_count* applications of the rules are performed. Otherwise, the rules... | Below is the the instruction that describes the task:
### Input:
Replace all occurrences of the patterns according to the replacement rules.
Args:
expression:
The expression to which the replacement rules are applied.
max_count:
If given, at most *max... |
def average_duration(total_duration, visits):
""" Method to calculate and format an average duration safely """
if not visits:
seconds = 0
else:
seconds = int(round(total_duration / Decimal(visits)))
duration = timedelta(seconds=seconds)
return str(duration) | Method to calculate and format an average duration safely | Below is the the instruction that describes the task:
### Input:
Method to calculate and format an average duration safely
### Response:
def average_duration(total_duration, visits):
""" Method to calculate and format an average duration safely """
if not visits:
seconds = 0
else:
secon... |
def key_from_protobuf(pb):
"""Factory method for creating a key based on a protobuf.
The protobuf should be one returned from the Cloud Datastore
Protobuf API.
:type pb: :class:`.entity_pb2.Key`
:param pb: The Protobuf representing the key.
:rtype: :class:`google.cloud.datastore.key.Key`
... | Factory method for creating a key based on a protobuf.
The protobuf should be one returned from the Cloud Datastore
Protobuf API.
:type pb: :class:`.entity_pb2.Key`
:param pb: The Protobuf representing the key.
:rtype: :class:`google.cloud.datastore.key.Key`
:returns: a new `Key` instance | Below is the the instruction that describes the task:
### Input:
Factory method for creating a key based on a protobuf.
The protobuf should be one returned from the Cloud Datastore
Protobuf API.
:type pb: :class:`.entity_pb2.Key`
:param pb: The Protobuf representing the key.
:rtype: :class:`g... |
def _recursive_split(self, bbox, zoom_level, column, row):
"""Method that recursively creates bounding boxes of OSM grid that intersect the area.
:param bbox: Bounding box
:type bbox: BBox
:param zoom_level: OSM zoom level
:type zoom_level: int
:param column: Column in t... | Method that recursively creates bounding boxes of OSM grid that intersect the area.
:param bbox: Bounding box
:type bbox: BBox
:param zoom_level: OSM zoom level
:type zoom_level: int
:param column: Column in the OSM grid
:type column: int
:param row: Row in the O... | Below is the the instruction that describes the task:
### Input:
Method that recursively creates bounding boxes of OSM grid that intersect the area.
:param bbox: Bounding box
:type bbox: BBox
:param zoom_level: OSM zoom level
:type zoom_level: int
:param column: Column in th... |
def download_docs(client, output_filename=None, expanded=False):
"""
Given a LuminosoClient pointing to a project and a filename to write to,
retrieve all its documents in batches, and write them to a JSON lines
(.jsons) file with one document per line.
"""
if output_filename is None:
# ... | Given a LuminosoClient pointing to a project and a filename to write to,
retrieve all its documents in batches, and write them to a JSON lines
(.jsons) file with one document per line. | Below is the the instruction that describes the task:
### Input:
Given a LuminosoClient pointing to a project and a filename to write to,
retrieve all its documents in batches, and write them to a JSON lines
(.jsons) file with one document per line.
### Response:
def download_docs(client, output_filename=N... |
def get_default_configfile_path():
"""Return the default configuration-file path.
Typically returns a user-local configuration file; e.g:
``~/.config/dwave/dwave.conf``.
Returns:
str:
Configuration file path.
Examples:
This example displays the default configuration fi... | Return the default configuration-file path.
Typically returns a user-local configuration file; e.g:
``~/.config/dwave/dwave.conf``.
Returns:
str:
Configuration file path.
Examples:
This example displays the default configuration file on an Ubuntu Unix system
runnin... | Below is the the instruction that describes the task:
### Input:
Return the default configuration-file path.
Typically returns a user-local configuration file; e.g:
``~/.config/dwave/dwave.conf``.
Returns:
str:
Configuration file path.
Examples:
This example displays t... |
def run(cmd):
"""Prepare and run a subprocess cmd, returning a CompletedProcess."""
print("Preparing the following cmd:")
cmd = prepare_subprocess_cmd(cmd)
print("Running the following cmd:")
print('\n'.join(cmd))
return subprocess.run(cmd, stdout=sys.stdout, stderr=sys.stderr) | Prepare and run a subprocess cmd, returning a CompletedProcess. | Below is the the instruction that describes the task:
### Input:
Prepare and run a subprocess cmd, returning a CompletedProcess.
### Response:
def run(cmd):
"""Prepare and run a subprocess cmd, returning a CompletedProcess."""
print("Preparing the following cmd:")
cmd = prepare_subprocess_cmd(cmd)
... |
def update_ride(api_client, ride_status, ride_id):
"""Use an UberRidesClient to update ride status and print the results.
Parameters
api_client (UberRidesClient)
An authorized UberRidesClient with 'request' scope.
ride_status (str)
New ride status to update to.
r... | Use an UberRidesClient to update ride status and print the results.
Parameters
api_client (UberRidesClient)
An authorized UberRidesClient with 'request' scope.
ride_status (str)
New ride status to update to.
ride_id (str)
Unique identifier for ride to upd... | Below is the the instruction that describes the task:
### Input:
Use an UberRidesClient to update ride status and print the results.
Parameters
api_client (UberRidesClient)
An authorized UberRidesClient with 'request' scope.
ride_status (str)
New ride status to update to... |
def set(self, folder: str, subscribed: bool) -> None:
"""Set the subscribed status of a folder."""
if subscribed:
self.add(folder)
else:
self.remove(folder) | Set the subscribed status of a folder. | Below is the the instruction that describes the task:
### Input:
Set the subscribed status of a folder.
### Response:
def set(self, folder: str, subscribed: bool) -> None:
"""Set the subscribed status of a folder."""
if subscribed:
self.add(folder)
else:
self.remove(... |
def _assert_all_loadable_terms_specialized_to(self, domain):
"""Make sure that we've specialized all loadable terms in the graph.
"""
for term in self.graph.node:
if isinstance(term, LoadableTerm):
assert term.domain is domain | Make sure that we've specialized all loadable terms in the graph. | Below is the the instruction that describes the task:
### Input:
Make sure that we've specialized all loadable terms in the graph.
### Response:
def _assert_all_loadable_terms_specialized_to(self, domain):
"""Make sure that we've specialized all loadable terms in the graph.
"""
for term in ... |
def variance(data, data_mean=None):
"""Return variance of a sequence of numbers.
:param data_mean: Precomputed mean of the sequence.
"""
data_mean = data_mean or mean(data)
return sum((x - data_mean) ** 2 for x in data) / len(data) | Return variance of a sequence of numbers.
:param data_mean: Precomputed mean of the sequence. | Below is the the instruction that describes the task:
### Input:
Return variance of a sequence of numbers.
:param data_mean: Precomputed mean of the sequence.
### Response:
def variance(data, data_mean=None):
"""Return variance of a sequence of numbers.
:param data_mean: Precomputed mean of the sequenc... |
def get_item(self):
"""Returns the item to send back into the workflow generator."""
if self.was_list:
result = ResultList()
for item in self:
if isinstance(item, WorkflowItem):
if item.done and not item.error:
result.ap... | Returns the item to send back into the workflow generator. | Below is the the instruction that describes the task:
### Input:
Returns the item to send back into the workflow generator.
### Response:
def get_item(self):
"""Returns the item to send back into the workflow generator."""
if self.was_list:
result = ResultList()
for item in ... |
def add_all_at(self, index, items):
"""
Adds all of the elements in the specified collection into this list at the specified position. Elements in this
positions and following elements are shifted to the right, if any. The order of new elements is determined by the
specified collection's... | Adds all of the elements in the specified collection into this list at the specified position. Elements in this
positions and following elements are shifted to the right, if any. The order of new elements is determined by the
specified collection's iterator.
:param index: (int), the specified i... | Below is the the instruction that describes the task:
### Input:
Adds all of the elements in the specified collection into this list at the specified position. Elements in this
positions and following elements are shifted to the right, if any. The order of new elements is determined by the
specified... |
def color_stream_st(istream=sys.stdin, save_palette=False, **kwargs):
"""
Read filenames from the input stream and detect their palette.
"""
for line in istream:
filename = line.strip()
try:
palette = extract_colors(filename, **kwargs)
except Exception as e:
... | Read filenames from the input stream and detect their palette. | Below is the the instruction that describes the task:
### Input:
Read filenames from the input stream and detect their palette.
### Response:
def color_stream_st(istream=sys.stdin, save_palette=False, **kwargs):
"""
Read filenames from the input stream and detect their palette.
"""
for line in istr... |
def load_resource(resource_url: str, forceupdate: bool = False):
"""Load BEL Resource file
Forceupdate will create a new index in Elasticsearch regardless of whether
an index with the resource version already exists.
Args:
resource_url: URL from which to download the resource to load into the ... | Load BEL Resource file
Forceupdate will create a new index in Elasticsearch regardless of whether
an index with the resource version already exists.
Args:
resource_url: URL from which to download the resource to load into the BEL API
forceupdate: force full update - e.g. don't leave Elasti... | Below is the the instruction that describes the task:
### Input:
Load BEL Resource file
Forceupdate will create a new index in Elasticsearch regardless of whether
an index with the resource version already exists.
Args:
resource_url: URL from which to download the resource to load into the BEL... |
def format_table(self, width=None,
min_label_width=10, min_progress_width=10):
"""Format the entire table of progress bars.
The function first computes the widths of the fields so they can be
aligned across lines and then returns formatted lines as a list of
strings... | Format the entire table of progress bars.
The function first computes the widths of the fields so they can be
aligned across lines and then returns formatted lines as a list of
strings. | Below is the the instruction that describes the task:
### Input:
Format the entire table of progress bars.
The function first computes the widths of the fields so they can be
aligned across lines and then returns formatted lines as a list of
strings.
### Response:
def format_table(self, wi... |
def delete_collection_namespaced_config_map(self, namespace, **kwargs): # noqa: E501
"""delete_collection_namespaced_config_map # noqa: E501
delete collection of ConfigMap # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, plea... | delete_collection_namespaced_config_map # noqa: E501
delete collection of ConfigMap # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_collection_namespaced_config_map(namespace... | Below is the the instruction that describes the task:
### Input:
delete_collection_namespaced_config_map # noqa: E501
delete collection of ConfigMap # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
... |
def get_queues(self):
"""Return a list of current active Celery queues."""
res = self.celery.control.inspect().active_queues() or dict()
return [result.get('name') for host in res.values() for result in host] | Return a list of current active Celery queues. | Below is the the instruction that describes the task:
### Input:
Return a list of current active Celery queues.
### Response:
def get_queues(self):
"""Return a list of current active Celery queues."""
res = self.celery.control.inspect().active_queues() or dict()
return [result.get('name') f... |
def cmd(*args, **kwargs):
"""Decorate a callable to replace it with a manufactured command
class.
Extends the interface of ``CommandDecorator``, allowing the same
``cmd`` to be used as a decorator or as a decorator factory::
@cmd(root=True)
def build():
...
@build.... | Decorate a callable to replace it with a manufactured command
class.
Extends the interface of ``CommandDecorator``, allowing the same
``cmd`` to be used as a decorator or as a decorator factory::
@cmd(root=True)
def build():
...
@build.register
@cmd
def... | Below is the the instruction that describes the task:
### Input:
Decorate a callable to replace it with a manufactured command
class.
Extends the interface of ``CommandDecorator``, allowing the same
``cmd`` to be used as a decorator or as a decorator factory::
@cmd(root=True)
def build... |
def visit_Output(self, node, frame):
"""Same as :meth:`CodeGenerator.visit_Output`, but do not call
``to_string`` on output nodes in generated code.
"""
if self.has_known_extends and frame.require_output_check:
return
finalize = self.environment.finalize
fina... | Same as :meth:`CodeGenerator.visit_Output`, but do not call
``to_string`` on output nodes in generated code. | Below is the the instruction that describes the task:
### Input:
Same as :meth:`CodeGenerator.visit_Output`, but do not call
``to_string`` on output nodes in generated code.
### Response:
def visit_Output(self, node, frame):
"""Same as :meth:`CodeGenerator.visit_Output`, but do not call
``t... |
def _send_outgoing_route_refresh_msg(self, rr_msg):
"""Sends given message `rr_msg` to peer.
Parameters:
- rr_msg: (RouteRefresh) route refresh message to send to peer.
Update appropriate counters and set appropriate timers.
"""
assert rr_msg.type == BGP_MSG_ROUTE_R... | Sends given message `rr_msg` to peer.
Parameters:
- rr_msg: (RouteRefresh) route refresh message to send to peer.
Update appropriate counters and set appropriate timers. | Below is the the instruction that describes the task:
### Input:
Sends given message `rr_msg` to peer.
Parameters:
- rr_msg: (RouteRefresh) route refresh message to send to peer.
Update appropriate counters and set appropriate timers.
### Response:
def _send_outgoing_route_refresh_msg... |
def switch(self, val=None):
"""
Set the state of the switch. If the armed state is set to False,
the function does nothing.
:param val: Boolean. The value to set the switch state to. When None,
the switch will be set to the opposite of its current state.
:return: Boo... | Set the state of the switch. If the armed state is set to False,
the function does nothing.
:param val: Boolean. The value to set the switch state to. When None,
the switch will be set to the opposite of its current state.
:return: Boolean. Returns True if operation was successful (... | Below is the the instruction that describes the task:
### Input:
Set the state of the switch. If the armed state is set to False,
the function does nothing.
:param val: Boolean. The value to set the switch state to. When None,
the switch will be set to the opposite of its current state.... |
def element_tree_collection_to_records(tree):
"""Take an ElementTree and converts the nodes into BibRecord records.
This function is for a tree root of collection as such:
<collection>
<record>
<!-- MARCXML -->
</record>
<record> ... </record>
</collection>
"""
... | Take an ElementTree and converts the nodes into BibRecord records.
This function is for a tree root of collection as such:
<collection>
<record>
<!-- MARCXML -->
</record>
<record> ... </record>
</collection> | Below is the the instruction that describes the task:
### Input:
Take an ElementTree and converts the nodes into BibRecord records.
This function is for a tree root of collection as such:
<collection>
<record>
<!-- MARCXML -->
</record>
<record> ... </record>
</colle... |
def get_urls(self):
"""
Add a calendar URL.
"""
from django.conf.urls import patterns, url
urls = super(EventAdmin, self).get_urls()
my_urls = patterns(
'',
url(
r'^calendar/$',
self.admin_site.admin_view(self.calend... | Add a calendar URL. | Below is the the instruction that describes the task:
### Input:
Add a calendar URL.
### Response:
def get_urls(self):
"""
Add a calendar URL.
"""
from django.conf.urls import patterns, url
urls = super(EventAdmin, self).get_urls()
my_urls = patterns(
'',... |
def _slugify_foreign_key(schema):
"""Slugify foreign key
"""
for foreign_key in schema.get('foreignKeys', []):
foreign_key['reference']['resource'] = _slugify_resource_name(
foreign_key['reference'].get('resource', ''))
return schema | Slugify foreign key | Below is the the instruction that describes the task:
### Input:
Slugify foreign key
### Response:
def _slugify_foreign_key(schema):
"""Slugify foreign key
"""
for foreign_key in schema.get('foreignKeys', []):
foreign_key['reference']['resource'] = _slugify_resource_name(
foreign_ke... |
def check_for_usable_restore_env(self):
"""Check if the current env can be used to restore files."""
self.check_for_usable_environment()
if not os.path.isdir(self.mackup_folder):
utils.error("Unable to find the Mackup folder: {}\n"
"You might want to back up ... | Check if the current env can be used to restore files. | Below is the the instruction that describes the task:
### Input:
Check if the current env can be used to restore files.
### Response:
def check_for_usable_restore_env(self):
"""Check if the current env can be used to restore files."""
self.check_for_usable_environment()
if not os.path.isdi... |
def deploy_media():
"""
Deploy MEDIA_ROOT unversioned on host
"""
if not env.MEDIA_URL or not env.MEDIA_ROOT or 'http://' in env.MEDIA_URL: return
local_dir = env.MEDIA_ROOT
remote_dir = '/'.join([deployment_root(),'public'])
media_url = env.MEDIA_URL[1:]
if media_url:
remo... | Deploy MEDIA_ROOT unversioned on host | Below is the the instruction that describes the task:
### Input:
Deploy MEDIA_ROOT unversioned on host
### Response:
def deploy_media():
"""
Deploy MEDIA_ROOT unversioned on host
"""
if not env.MEDIA_URL or not env.MEDIA_ROOT or 'http://' in env.MEDIA_URL: return
local_dir = env.MEDIA_ROOT
... |
def _do_code_exchange(self, request, # type: Dict[str, str]
extra_id_token_claims=None
# type: Optional[Union[Mapping[str, Union[str, List[str]]], Callable[[str, str], Mapping[str, Union[str, List[str]]]]]
):
# type: (...) -> oic.mes... | Handles a token request for exchanging an authorization code for an access token
(grant_type=authorization_code).
:param request: parsed http request parameters
:param extra_id_token_claims: any extra parameters to include in the signed ID Token, either as a dict-like
object or as a ... | Below is the the instruction that describes the task:
### Input:
Handles a token request for exchanging an authorization code for an access token
(grant_type=authorization_code).
:param request: parsed http request parameters
:param extra_id_token_claims: any extra parameters to include in t... |
def get_authorizations_for_resource_and_function(self, resource_id, function_id):
"""Gets a list of ``Authorizations`` associated with a given resource.
Authorizations related to the given resource, including those
related through an ``Agent,`` are returned. In plenary mode, the
returne... | Gets a list of ``Authorizations`` associated with a given resource.
Authorizations related to the given resource, including those
related through an ``Agent,`` are returned. In plenary mode, the
returned list contains all known authorizations or an error
results. Otherwise, the returned... | Below is the the instruction that describes the task:
### Input:
Gets a list of ``Authorizations`` associated with a given resource.
Authorizations related to the given resource, including those
related through an ``Agent,`` are returned. In plenary mode, the
returned list contains all know... |
def sum_filter(input, size=None, footprint=None, output=None, mode="reflect", cval=0.0, origin=0):
r"""
Calculates a multi-dimensional sum filter.
Parameters
----------
input : array-like
input array to filter
size : scalar or tuple, optional
See footprint, below
footprint :... | r"""
Calculates a multi-dimensional sum filter.
Parameters
----------
input : array-like
input array to filter
size : scalar or tuple, optional
See footprint, below
footprint : array, optional
Either `size` or `footprint` must be defined. `size` gives
the shape t... | Below is the the instruction that describes the task:
### Input:
r"""
Calculates a multi-dimensional sum filter.
Parameters
----------
input : array-like
input array to filter
size : scalar or tuple, optional
See footprint, below
footprint : array, optional
Either `s... |
def get_css_classes(document, style):
"""Returns CSS classes for this style.
This function will check all the styles specified style is based on and return their CSS classes.
:Args:
- document (:class:`ooxml.doc.Document`): Document object
- style (:class:`ooxml.doc.Style`): Style object
... | Returns CSS classes for this style.
This function will check all the styles specified style is based on and return their CSS classes.
:Args:
- document (:class:`ooxml.doc.Document`): Document object
- style (:class:`ooxml.doc.Style`): Style object
:Returns:
String representing all the C... | Below is the the instruction that describes the task:
### Input:
Returns CSS classes for this style.
This function will check all the styles specified style is based on and return their CSS classes.
:Args:
- document (:class:`ooxml.doc.Document`): Document object
- style (:class:`ooxml.doc.Sty... |
def store(self, image, file):
"""Stores the actual data ``file`` of the given ``image``.
::
with open(imagefile, 'rb') as f:
store.store(image, f)
:param image: the image to store its actual data file
:type image: :class:`sqlalchemy_imageattach.entity.Image`... | Stores the actual data ``file`` of the given ``image``.
::
with open(imagefile, 'rb') as f:
store.store(image, f)
:param image: the image to store its actual data file
:type image: :class:`sqlalchemy_imageattach.entity.Image`
:param file: the image file to p... | Below is the the instruction that describes the task:
### Input:
Stores the actual data ``file`` of the given ``image``.
::
with open(imagefile, 'rb') as f:
store.store(image, f)
:param image: the image to store its actual data file
:type image: :class:`sqlalche... |
def do_authentication(environ, start_response, authn_context, key,
redirect_uri):
"""
Display the login form
"""
logger.debug("Do authentication")
auth_info = AUTHN_BROKER.pick(authn_context)
if len(auth_info):
method, reference = auth_info[0]
logger.debug(... | Display the login form | Below is the the instruction that describes the task:
### Input:
Display the login form
### Response:
def do_authentication(environ, start_response, authn_context, key,
redirect_uri):
"""
Display the login form
"""
logger.debug("Do authentication")
auth_info = AUTHN_BROKER... |
def livehtml(context):
"Launch webserver on http://localhost:8000 with rendered documentation"
builder = 'html'
outputdir = os.path.join(DOCS_BUILDDIR, builder)
cmdline = 'sphinx-autobuild -b {} {} {}'.format(builder, DOCS_SRCDIR, outputdir)
context.run(cmdline, pty=True) | Launch webserver on http://localhost:8000 with rendered documentation | Below is the the instruction that describes the task:
### Input:
Launch webserver on http://localhost:8000 with rendered documentation
### Response:
def livehtml(context):
"Launch webserver on http://localhost:8000 with rendered documentation"
builder = 'html'
outputdir = os.path.join(DOCS_BUILDDIR, bu... |
def load_csv_data(fname, tag):
"""Load data from a comma separated SuperMAG file
Parameters
------------
fname : (str)
CSV SuperMAG file name
tag : (str)
Denotes type of file to load. Accepted types are 'indices', 'all',
'stations', and '' (for just magnetometer measurement... | Load data from a comma separated SuperMAG file
Parameters
------------
fname : (str)
CSV SuperMAG file name
tag : (str)
Denotes type of file to load. Accepted types are 'indices', 'all',
'stations', and '' (for just magnetometer measurements).
Returns
--------
data... | Below is the the instruction that describes the task:
### Input:
Load data from a comma separated SuperMAG file
Parameters
------------
fname : (str)
CSV SuperMAG file name
tag : (str)
Denotes type of file to load. Accepted types are 'indices', 'all',
'stations', and '' (fo... |
def status(name, location='\\'):
r'''
Determine the status of a task. Is it Running, Queued, Ready, etc.
:param str name: The name of the task for which to return the status
:param str location: A string value representing the location of the task.
Default is '\\' which is the root for the tas... | r'''
Determine the status of a task. Is it Running, Queued, Ready, etc.
:param str name: The name of the task for which to return the status
:param str location: A string value representing the location of the task.
Default is '\\' which is the root for the task scheduler
(C:\Windows\Syste... | Below is the the instruction that describes the task:
### Input:
r'''
Determine the status of a task. Is it Running, Queued, Ready, etc.
:param str name: The name of the task for which to return the status
:param str location: A string value representing the location of the task.
Default is '\... |
def has_button(self, button):
"""Check if this device has a given button.
Args:
button (int): Button to check for, see ``input.h`` for button
definitions.
Returns:
bool: :obj:`True` if the device has this button, :obj:`False` if
it does not.
Raises:
AssertionError
"""
rc = self._libinput.l... | Check if this device has a given button.
Args:
button (int): Button to check for, see ``input.h`` for button
definitions.
Returns:
bool: :obj:`True` if the device has this button, :obj:`False` if
it does not.
Raises:
AssertionError | Below is the the instruction that describes the task:
### Input:
Check if this device has a given button.
Args:
button (int): Button to check for, see ``input.h`` for button
definitions.
Returns:
bool: :obj:`True` if the device has this button, :obj:`False` if
it does not.
Raises:
AssertionEr... |
def save(self):
"""
Saves changes made to the locally cached DesignDocument object's data
structures to the remote database. If the design document does not
exist remotely then it is created in the remote database. If the object
does exist remotely then the design document is u... | Saves changes made to the locally cached DesignDocument object's data
structures to the remote database. If the design document does not
exist remotely then it is created in the remote database. If the object
does exist remotely then the design document is updated remotely. In
either ... | Below is the the instruction that describes the task:
### Input:
Saves changes made to the locally cached DesignDocument object's data
structures to the remote database. If the design document does not
exist remotely then it is created in the remote database. If the object
does exist remot... |
def format(self, record):
"""
Modified from logging/__init__.py in python 2.7 lib
Format the specified record as text.
The record's attribute dictionary is used as the operand to a
string formatting operation which yields the returned string.
Before formatting the dicti... | Modified from logging/__init__.py in python 2.7 lib
Format the specified record as text.
The record's attribute dictionary is used as the operand to a
string formatting operation which yields the returned string.
Before formatting the dictionary, a couple of preparatory steps
a... | Below is the the instruction that describes the task:
### Input:
Modified from logging/__init__.py in python 2.7 lib
Format the specified record as text.
The record's attribute dictionary is used as the operand to a
string formatting operation which yields the returned string.
Befo... |
def query(self, queryString):
'''
Executes a query against the specified object and returns data that matches
the specified criteria.
'''
self._setHeaders('query')
return self._sforce.service.query(queryString) | Executes a query against the specified object and returns data that matches
the specified criteria. | Below is the the instruction that describes the task:
### Input:
Executes a query against the specified object and returns data that matches
the specified criteria.
### Response:
def query(self, queryString):
'''
Executes a query against the specified object and returns data that matches
the specif... |
def _read_para_unassigned(self, code, cbit, clen, *, desc, length, version):
"""Read HIP unassigned parameters.
Structure of HIP unassigned parameters [RFC 5201][RFC 7401]:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 ... | Read HIP unassigned parameters.
Structure of HIP unassigned parameters [RFC 5201][RFC 7401]:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-... | Below is the the instruction that describes the task:
### Input:
Read HIP unassigned parameters.
Structure of HIP unassigned parameters [RFC 5201][RFC 7401]:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0... |
def _mergeGoSymbols(self, jsons = []):
"""
Exported symbols for a given package does not have any prefix.
So I can drop all import paths that are file specific and merge
all symbols.
Assuming all files in the given package has mutual exclusive symbols.
"""
# <siXy> imports are per file, exports are per pa... | Exported symbols for a given package does not have any prefix.
So I can drop all import paths that are file specific and merge
all symbols.
Assuming all files in the given package has mutual exclusive symbols. | Below is the the instruction that describes the task:
### Input:
Exported symbols for a given package does not have any prefix.
So I can drop all import paths that are file specific and merge
all symbols.
Assuming all files in the given package has mutual exclusive symbols.
### Response:
def _mergeGoSymbols(... |
def _format_num(self, value):
"""Return the number value for value, given this field's `num_type`."""
# (value is True or value is False) is ~5x faster than isinstance(value, bool)
if value is True or value is False:
raise TypeError('value must be a Number, not a boolean.')
r... | Return the number value for value, given this field's `num_type`. | Below is the the instruction that describes the task:
### Input:
Return the number value for value, given this field's `num_type`.
### Response:
def _format_num(self, value):
"""Return the number value for value, given this field's `num_type`."""
# (value is True or value is False) is ~5x faster th... |
def records(self):
"""Return a list of records for this sentence."""
compounds = ModelList()
seen_labels = set()
# Ensure no control characters are sent to a parser (need to be XML compatible)
tagged_tokens = [(CONTROL_RE.sub('', token), tag) for token, tag in self.tagged_tokens]... | Return a list of records for this sentence. | Below is the the instruction that describes the task:
### Input:
Return a list of records for this sentence.
### Response:
def records(self):
"""Return a list of records for this sentence."""
compounds = ModelList()
seen_labels = set()
# Ensure no control characters are sent to a pa... |
def get_instances(feature_name):
"""Return all all instances that compute `feature_name`"""
feats = []
for ft in AncillaryFeature.features:
if ft.feature_name == feature_name:
feats.append(ft)
return feats | Return all all instances that compute `feature_name` | Below is the the instruction that describes the task:
### Input:
Return all all instances that compute `feature_name`
### Response:
def get_instances(feature_name):
"""Return all all instances that compute `feature_name`"""
feats = []
for ft in AncillaryFeature.features:
if ft.f... |
def get_image(self, filename: str=None) -> None:
"""Download the photo associated with a Savings Goal."""
if filename is None:
filename = "{0}.png".format(self.name)
endpoint = "/account/{0}/savings-goals/{1}/photo".format(
self._account_uid,
self.uid
... | Download the photo associated with a Savings Goal. | Below is the the instruction that describes the task:
### Input:
Download the photo associated with a Savings Goal.
### Response:
def get_image(self, filename: str=None) -> None:
"""Download the photo associated with a Savings Goal."""
if filename is None:
filename = "{0}.png".format(se... |
def _get_arg_tokens(cli):
"""
Tokens for the arg-prompt.
"""
arg = cli.input_processor.arg
return [
(Token.Prompt.Arg, '(arg: '),
(Token.Prompt.Arg.Text, str(arg)),
(Token.Prompt.Arg, ') '),
] | Tokens for the arg-prompt. | Below is the the instruction that describes the task:
### Input:
Tokens for the arg-prompt.
### Response:
def _get_arg_tokens(cli):
"""
Tokens for the arg-prompt.
"""
arg = cli.input_processor.arg
return [
(Token.Prompt.Arg, '(arg: '),
(Token.Prompt.Arg.Text, str(arg)),
... |
def _spawn(self):
""" Initialize the queue and the threads. """
self.queue = Queue(maxsize=self.num_threads * 10)
for i in range(self.num_threads):
t = Thread(target=self._consume)
t.daemon = True
t.start() | Initialize the queue and the threads. | Below is the the instruction that describes the task:
### Input:
Initialize the queue and the threads.
### Response:
def _spawn(self):
""" Initialize the queue and the threads. """
self.queue = Queue(maxsize=self.num_threads * 10)
for i in range(self.num_threads):
t = Thread(tar... |
def process_configs(file_lookup, app_config_format, pipeline_config):
"""Processes the configs from lookup sources.
Args:
file_lookup (FileLookup): Source to look for file/config
app_config_format (str): The format for application config files.
pipeline_config (str): Name/path of the pi... | Processes the configs from lookup sources.
Args:
file_lookup (FileLookup): Source to look for file/config
app_config_format (str): The format for application config files.
pipeline_config (str): Name/path of the pipeline config
Returns:
dict: Retreived application config | Below is the the instruction that describes the task:
### Input:
Processes the configs from lookup sources.
Args:
file_lookup (FileLookup): Source to look for file/config
app_config_format (str): The format for application config files.
pipeline_config (str): Name/path of the pipeline c... |
def set_widgets(self):
"""Set widgets on the Field tab."""
self.clear_further_steps()
purpose = self.parent.step_kw_purpose.selected_purpose()
subcategory = self.parent.step_kw_subcategory.selected_subcategory()
unit = self.parent.step_kw_unit.selected_unit()
layer_mode =... | Set widgets on the Field tab. | Below is the the instruction that describes the task:
### Input:
Set widgets on the Field tab.
### Response:
def set_widgets(self):
"""Set widgets on the Field tab."""
self.clear_further_steps()
purpose = self.parent.step_kw_purpose.selected_purpose()
subcategory = self.parent.step_... |
def get_addon_name(addonxml):
'''Parses an addon name from the given addon.xml filename.'''
xml = parse(addonxml)
addon_node = xml.getElementsByTagName('addon')[0]
return addon_node.getAttribute('name') | Parses an addon name from the given addon.xml filename. | Below is the the instruction that describes the task:
### Input:
Parses an addon name from the given addon.xml filename.
### Response:
def get_addon_name(addonxml):
'''Parses an addon name from the given addon.xml filename.'''
xml = parse(addonxml)
addon_node = xml.getElementsByTagName('addon')[0]
... |
def get_data(self, minion):
'''
Return the configured ip
'''
ret = copy.deepcopy(__opts__.get('roster_defaults', {}))
if isinstance(self.raw[minion], six.string_types):
ret.update({'host': self.raw[minion]})
return ret
elif isinstance(self.raw[mini... | Return the configured ip | Below is the the instruction that describes the task:
### Input:
Return the configured ip
### Response:
def get_data(self, minion):
'''
Return the configured ip
'''
ret = copy.deepcopy(__opts__.get('roster_defaults', {}))
if isinstance(self.raw[minion], six.string_types):
... |
def _hide_column(self, column):
'''Hides a column by prefixing the name with \'__\''''
column = _ensure_string_from_expression(column)
new_name = self._find_valid_name('__' + column)
self._rename(column, new_name) | Hides a column by prefixing the name with \'__\ | Below is the the instruction that describes the task:
### Input:
Hides a column by prefixing the name with \'__\
### Response:
def _hide_column(self, column):
'''Hides a column by prefixing the name with \'__\''''
column = _ensure_string_from_expression(column)
new_name = self._find_valid_n... |
def get_version_string(check_name):
"""
Get the version string for the given check.
"""
version = VERSION.search(read_version_file(check_name))
if version:
return version.group(1) | Get the version string for the given check. | Below is the the instruction that describes the task:
### Input:
Get the version string for the given check.
### Response:
def get_version_string(check_name):
"""
Get the version string for the given check.
"""
version = VERSION.search(read_version_file(check_name))
if version:
return v... |
def add(self, num_particles, D):
"""Add particles with diffusion coefficient `D` at random positions.
"""
self._plist += self._generate(num_particles, D, box=self.box,
rs=self.rs) | Add particles with diffusion coefficient `D` at random positions. | Below is the the instruction that describes the task:
### Input:
Add particles with diffusion coefficient `D` at random positions.
### Response:
def add(self, num_particles, D):
"""Add particles with diffusion coefficient `D` at random positions.
"""
self._plist += self._generate(num_partic... |
def unique_list_dicts(dlist, key):
"""Return a list of dictionaries which are sorted for only unique entries.
:param dlist:
:param key:
:return list:
"""
return list(dict((val[key], val) for val in dlist).values()) | Return a list of dictionaries which are sorted for only unique entries.
:param dlist:
:param key:
:return list: | Below is the the instruction that describes the task:
### Input:
Return a list of dictionaries which are sorted for only unique entries.
:param dlist:
:param key:
:return list:
### Response:
def unique_list_dicts(dlist, key):
"""Return a list of dictionaries which are sorted for only unique entrie... |
def wait_any(futures, timeout=None):
'''Wait for the completion of any (the first) one of multiple futures
:param list futures: A list of :class:`Future`\s
:param timeout:
The maximum time to wait. With ``None``, will block indefinitely.
:type timeout: float or None
:returns:
One o... | Wait for the completion of any (the first) one of multiple futures
:param list futures: A list of :class:`Future`\s
:param timeout:
The maximum time to wait. With ``None``, will block indefinitely.
:type timeout: float or None
:returns:
One of the futures from the provided list -- the ... | Below is the the instruction that describes the task:
### Input:
Wait for the completion of any (the first) one of multiple futures
:param list futures: A list of :class:`Future`\s
:param timeout:
The maximum time to wait. With ``None``, will block indefinitely.
:type timeout: float or None
... |
def _insert_pairs(self, ids_and_pairs):
"""Insert some new pairs, and keep the _key_ids updated.
Params:
ids_and_pairs -- A list of (index, (key, value)) tuples.
"""
ids_to_insert = [x[0] for x in ids_and_pairs]
# We use the bisect to tell u... | Insert some new pairs, and keep the _key_ids updated.
Params:
ids_and_pairs -- A list of (index, (key, value)) tuples. | Below is the the instruction that describes the task:
### Input:
Insert some new pairs, and keep the _key_ids updated.
Params:
ids_and_pairs -- A list of (index, (key, value)) tuples.
### Response:
def _insert_pairs(self, ids_and_pairs):
"""Insert some new pairs, and keep the _... |
def _simplify_blocks(self, stack_pointer_tracker=None):
"""
Simplify all blocks in self._blocks.
:param stack_pointer_tracker: The RegisterDeltaTracker analysis instance.
:return: None
"""
# First of all, let's simplify blocks one by one
... | Simplify all blocks in self._blocks.
:param stack_pointer_tracker: The RegisterDeltaTracker analysis instance.
:return: None | Below is the the instruction that describes the task:
### Input:
Simplify all blocks in self._blocks.
:param stack_pointer_tracker: The RegisterDeltaTracker analysis instance.
:return: None
### Response:
def _simplify_blocks(self, stack_pointer_tracker=None):
"""
... |
def articles(self):
''' Tries to scrape the correct articles for singular and plural from vandale.nl. '''
result = [None, None]
element = self._first('NN')
if element:
if re.search('(de|het/?de|het);', element, re.U):
result[0] = re.findall('(de|het/?de|het);', element, re.U)[0].split('/')
if re.sear... | Tries to scrape the correct articles for singular and plural from vandale.nl. | Below is the the instruction that describes the task:
### Input:
Tries to scrape the correct articles for singular and plural from vandale.nl.
### Response:
def articles(self):
''' Tries to scrape the correct articles for singular and plural from vandale.nl. '''
result = [None, None]
element = self._first('... |
def pullPath_copy(self, d_msg, **kwargs):
"""
Handle the "copy" pull operation
"""
# Parse "header" information
d_meta = d_msg['meta']
d_local = d_meta['local']
str_localPath = d_local['path']
d_remote = d_meta['r... | Handle the "copy" pull operation | Below is the the instruction that describes the task:
### Input:
Handle the "copy" pull operation
### Response:
def pullPath_copy(self, d_msg, **kwargs):
"""
Handle the "copy" pull operation
"""
# Parse "header" information
d_meta = d_msg['meta']
d_loca... |
def to_dict(self):
"""
Create a JSON-serializable representation of the device Specs.
The dictionary representation is of the form::
{
'1Q': {
"0": {
"f1QRB": 0.99,
"T1": 20e-6,
... | Create a JSON-serializable representation of the device Specs.
The dictionary representation is of the form::
{
'1Q': {
"0": {
"f1QRB": 0.99,
"T1": 20e-6,
...
},
... | Below is the the instruction that describes the task:
### Input:
Create a JSON-serializable representation of the device Specs.
The dictionary representation is of the form::
{
'1Q': {
"0": {
"f1QRB": 0.99,
"T1... |
def attr_to_path(node):
""" Compute path and final object for an attribute node """
def get_intrinsic_path(modules, attr):
""" Get function path and intrinsic from an ast.Attribute. """
if isinstance(attr, ast.Name):
return modules[demangle(attr.id)], (demangle(attr.id),)
e... | Compute path and final object for an attribute node | Below is the the instruction that describes the task:
### Input:
Compute path and final object for an attribute node
### Response:
def attr_to_path(node):
""" Compute path and final object for an attribute node """
def get_intrinsic_path(modules, attr):
""" Get function path and intrinsic from an ... |
def add_answer(self, vote, rationale):
"""
Add an answer
Args:
vote (int): the option that student voted for
rationale (str): the reason why the student vote for the option
"""
self.raw_answers.append({
VOTE_KEY: vote,
RATIONALE_KE... | Add an answer
Args:
vote (int): the option that student voted for
rationale (str): the reason why the student vote for the option | Below is the the instruction that describes the task:
### Input:
Add an answer
Args:
vote (int): the option that student voted for
rationale (str): the reason why the student vote for the option
### Response:
def add_answer(self, vote, rationale):
"""
Add an answer
... |
def _parse_arg(self, var, arg, scope):
""" Parse a single argument to mixin.
args:
var (Variable object): variable
arg (mixed): argument
scope (Scope object): current scope
returns:
Variable object or None
"""
if isinstance(var, Var... | Parse a single argument to mixin.
args:
var (Variable object): variable
arg (mixed): argument
scope (Scope object): current scope
returns:
Variable object or None | Below is the the instruction that describes the task:
### Input:
Parse a single argument to mixin.
args:
var (Variable object): variable
arg (mixed): argument
scope (Scope object): current scope
returns:
Variable object or None
### Response:
def _pars... |
def get_by_email(cls, email):
"""
Return a User by email address
"""
return cls.query().filter(cls.email == email).first() | Return a User by email address | Below is the the instruction that describes the task:
### Input:
Return a User by email address
### Response:
def get_by_email(cls, email):
"""
Return a User by email address
"""
return cls.query().filter(cls.email == email).first() |
def steem_instance(self):
''' Returns the steem instance if it already exists
otherwise uses the goodnode method to fetch a node
and instantiate the Steem class.
'''
if self.s:
return self.s
for num_of_retries in range(default.max_retry):
node = se... | Returns the steem instance if it already exists
otherwise uses the goodnode method to fetch a node
and instantiate the Steem class. | Below is the the instruction that describes the task:
### Input:
Returns the steem instance if it already exists
otherwise uses the goodnode method to fetch a node
and instantiate the Steem class.
### Response:
def steem_instance(self):
''' Returns the steem instance if it already exists
... |
def _collect_external_resources(self, resource_attr):
""" Collect external resources set on resource_attr attribute of all models."""
external_resources = []
for _, cls in sorted(Model.model_class_reverse_map.items(), key=lambda arg: arg[0]):
external = getattr(cls, resource_attr, ... | Collect external resources set on resource_attr attribute of all models. | Below is the the instruction that describes the task:
### Input:
Collect external resources set on resource_attr attribute of all models.
### Response:
def _collect_external_resources(self, resource_attr):
""" Collect external resources set on resource_attr attribute of all models."""
external_res... |
def mouseMoveEvent(self, event):
"""
Drags the selection view for this widget.
:param event | <QMouseMoveEvent>
"""
w = event.pos().x() - self._region.x()
h = event.pos().y() - self._region.y()
self._region.setWidth(w)
self... | Drags the selection view for this widget.
:param event | <QMouseMoveEvent> | Below is the the instruction that describes the task:
### Input:
Drags the selection view for this widget.
:param event | <QMouseMoveEvent>
### Response:
def mouseMoveEvent(self, event):
"""
Drags the selection view for this widget.
:param event | <... |
def _get_module_folders(self, temp_repo):
"""Get a list of module paths contained in a temp directory.
:param string temp_repo: the folder containing the modules.
"""
paths = (
os.path.join(temp_repo, path) for path in os.listdir(temp_repo)
if self._is_module_inc... | Get a list of module paths contained in a temp directory.
:param string temp_repo: the folder containing the modules. | Below is the the instruction that describes the task:
### Input:
Get a list of module paths contained in a temp directory.
:param string temp_repo: the folder containing the modules.
### Response:
def _get_module_folders(self, temp_repo):
"""Get a list of module paths contained in a temp directory... |
def get_line(s, bold=False, underline=False, blinking=False, color=None,
bgcolor=None, update_line=False):
"""
Returns a string with the given formatting.
"""
parts = []
if update_line:
parts.append(_UPDATE_LINE)
for val in [color, bgcolor]:
if val:
pa... | Returns a string with the given formatting. | Below is the the instruction that describes the task:
### Input:
Returns a string with the given formatting.
### Response:
def get_line(s, bold=False, underline=False, blinking=False, color=None,
bgcolor=None, update_line=False):
"""
Returns a string with the given formatting.
"""
par... |
def vcf_to_df_worker(arg):
""" Convert CANVAS vcf to a dict, single thread
"""
canvasvcf, exonbed, i = arg
logging.debug("Working on job {}: {}".format(i, canvasvcf))
samplekey = op.basename(canvasvcf).split(".")[0].rsplit('_', 1)[0]
d = {'SampleKey': samplekey}
exons = BedTool(exonbed)
... | Convert CANVAS vcf to a dict, single thread | Below is the the instruction that describes the task:
### Input:
Convert CANVAS vcf to a dict, single thread
### Response:
def vcf_to_df_worker(arg):
""" Convert CANVAS vcf to a dict, single thread
"""
canvasvcf, exonbed, i = arg
logging.debug("Working on job {}: {}".format(i, canvasvcf))
sampl... |
def _getFeedContent(self, url, excludeRead=False, continuation=None, loadLimit=20, since=None, until=None):
"""
A list of items (from a feed, a category or from URLs made with SPECIAL_ITEMS_URL)
Returns a dict with
:param id: (str, feed's id)
:param continuation: (str, to be u... | A list of items (from a feed, a category or from URLs made with SPECIAL_ITEMS_URL)
Returns a dict with
:param id: (str, feed's id)
:param continuation: (str, to be used to fetch more items)
:param items: array of dits with :
- update (update timestamp)
- auth... | Below is the the instruction that describes the task:
### Input:
A list of items (from a feed, a category or from URLs made with SPECIAL_ITEMS_URL)
Returns a dict with
:param id: (str, feed's id)
:param continuation: (str, to be used to fetch more items)
:param items: array of d... |
def read_plain_text(fname, encoding="utf-8"):
"""Reads a file as a list of strings."""
with io.open(fname, encoding=encoding) as f:
result = list(f)
if result:
if result[-1][-1:] == "\n":
result.append("\n")
else:
result[-1] += "\n"
return [line[:-1] f... | Reads a file as a list of strings. | Below is the the instruction that describes the task:
### Input:
Reads a file as a list of strings.
### Response:
def read_plain_text(fname, encoding="utf-8"):
"""Reads a file as a list of strings."""
with io.open(fname, encoding=encoding) as f:
result = list(f)
if result:
if result[-1]... |
def set_mode_loiter(self):
'''enter LOITER mode'''
if self.mavlink10():
self.mav.command_long_send(self.target_system, self.target_component,
mavlink.MAV_CMD_NAV_LOITER_UNLIM, 0, 0, 0, 0, 0, 0, 0, 0)
else:
MAV_ACTION_LOITER = 27
... | enter LOITER mode | Below is the the instruction that describes the task:
### Input:
enter LOITER mode
### Response:
def set_mode_loiter(self):
'''enter LOITER mode'''
if self.mavlink10():
self.mav.command_long_send(self.target_system, self.target_component,
mavlink.M... |
def define_format(self, plotStyle, plotSize):
#Default sizes for computer
sizing_dict = {}
sizing_dict['figure.figsize'] = (14, 8)
sizing_dict['legend.fontsize'] = 15
sizing_dict['axes.labelsize'] = 20
sizing_dict['axes.titlesize'] = 24
sizing_dict['xtick.labelsi... | Seaborn color blind
#0072B2 dark blue
#009E73 green
#D55E00 orangish
#CC79A7 pink
#F0E442 yellow
#56B4E9 cyan
#bcbd22 olive #adicional
#7f7f7f grey
#FFB5B8 skin | Below is the the instruction that describes the task:
### Input:
Seaborn color blind
#0072B2 dark blue
#009E73 green
#D55E00 orangish
#CC79A7 pink
#F0E442 yellow
#56B4E9 cyan
#bcbd22 olive #adicional
#7f7f7f grey
#FFB5B8 skin
### Response:
de... |
def evidence(ns_run, logw=None, simulate=False):
r"""Bayesian evidence :math:`\log \mathcal{Z}`.
Parameters
----------
ns_run: dict
Nested sampling run dict (see the data_processing module
docstring for more details).
logw: None or 1d numpy array, optional
Log weights of sam... | r"""Bayesian evidence :math:`\log \mathcal{Z}`.
Parameters
----------
ns_run: dict
Nested sampling run dict (see the data_processing module
docstring for more details).
logw: None or 1d numpy array, optional
Log weights of samples.
simulate: bool, optional
Passed to ... | Below is the the instruction that describes the task:
### Input:
r"""Bayesian evidence :math:`\log \mathcal{Z}`.
Parameters
----------
ns_run: dict
Nested sampling run dict (see the data_processing module
docstring for more details).
logw: None or 1d numpy array, optional
Lo... |
def load_plugins(self, raise_error=False):
"""
Load the plotters and defaultParams from the plugins
This method loads the `plotters` attribute and `defaultParams`
attribute from the plugins that use the entry point specified by
`group`. Entry points must be objects (or modules) ... | Load the plotters and defaultParams from the plugins
This method loads the `plotters` attribute and `defaultParams`
attribute from the plugins that use the entry point specified by
`group`. Entry points must be objects (or modules) that have a
`defaultParams` and a `plotters` attribute.... | Below is the the instruction that describes the task:
### Input:
Load the plotters and defaultParams from the plugins
This method loads the `plotters` attribute and `defaultParams`
attribute from the plugins that use the entry point specified by
`group`. Entry points must be objects (or mod... |
def App(apptype, data_flow_kernel=None, walltime=60, cache=False, executors='all'):
"""The App decorator function.
Args:
- apptype (string) : Apptype can be bash|python
Kwargs:
- data_flow_kernel (DataFlowKernel): The :class:`~parsl.dataflow.dflow.DataFlowKernel` responsible for
... | The App decorator function.
Args:
- apptype (string) : Apptype can be bash|python
Kwargs:
- data_flow_kernel (DataFlowKernel): The :class:`~parsl.dataflow.dflow.DataFlowKernel` responsible for
managing this app. This can be omitted only
after calling :meth:`parsl.dataflow.d... | Below is the the instruction that describes the task:
### Input:
The App decorator function.
Args:
- apptype (string) : Apptype can be bash|python
Kwargs:
- data_flow_kernel (DataFlowKernel): The :class:`~parsl.dataflow.dflow.DataFlowKernel` responsible for
managing this app. Thi... |
def support_autoupload_enable(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
support = ET.SubElement(config, "support", xmlns="urn:brocade.com:mgmt:brocade-ras")
autoupload = ET.SubElement(support, "autoupload")
enable = ET.SubElement(autoupload... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def support_autoupload_enable(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
support = ET.SubElement(config, "support", xmlns="urn:brocade.com:mgmt:brocade-r... |
def system_find_apps(input_params={}, always_retry=True, **kwargs):
"""
Invokes the /system/findApps API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Search#API-method%3A-%2Fsystem%2FfindApps
"""
return DXHTTPRequest('/system/findApps', input_params, always_retry=a... | Invokes the /system/findApps API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Search#API-method%3A-%2Fsystem%2FfindApps | Below is the the instruction that describes the task:
### Input:
Invokes the /system/findApps API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Search#API-method%3A-%2Fsystem%2FfindApps
### Response:
def system_find_apps(input_params={}, always_retry=True, **kwargs):
"""
... |
def items(self):
"""
return list of pair of name and value of all declared columns.
"""
return [
(c.name, getattr(self, c.name, None))
for c in self.__table__._columns
] | return list of pair of name and value of all declared columns. | Below is the the instruction that describes the task:
### Input:
return list of pair of name and value of all declared columns.
### Response:
def items(self):
"""
return list of pair of name and value of all declared columns.
"""
return [
(c.name, getattr(self, c.name, N... |
def stop(self, id):
""" stop the tracker. """
path = partial(_path, self.adapter)
path = path(id)
return self._delete(path) | stop the tracker. | Below is the the instruction that describes the task:
### Input:
stop the tracker.
### Response:
def stop(self, id):
""" stop the tracker. """
path = partial(_path, self.adapter)
path = path(id)
return self._delete(path) |
def create_subject(self,
authc_token=None,
account_id=None,
existing_subject=None,
subject_context=None):
"""
Creates a ``Subject`` instance for the user represented by the given method
arguments.
... | Creates a ``Subject`` instance for the user represented by the given method
arguments.
It is an overloaded method, due to porting java to python, and is
consequently highly likely to be refactored.
It gets called in one of two ways:
1) when creating an anonymous subject, passin... | Below is the the instruction that describes the task:
### Input:
Creates a ``Subject`` instance for the user represented by the given method
arguments.
It is an overloaded method, due to porting java to python, and is
consequently highly likely to be refactored.
It gets called in o... |
def file(self):
""" Method returns formated photo path - derived from format.id and source Photo filename """
if photos_settings.FORMATED_PHOTO_FILENAME is not None:
return photos_settings.FORMATED_PHOTO_FILENAME(self)
source_file = path.split(self.photo.image.name)
return pa... | Method returns formated photo path - derived from format.id and source Photo filename | Below is the the instruction that describes the task:
### Input:
Method returns formated photo path - derived from format.id and source Photo filename
### Response:
def file(self):
""" Method returns formated photo path - derived from format.id and source Photo filename """
if photos_settings.FORMA... |
def form_valid(self, post_form, attachment_formset, poll_option_formset, **kwargs):
""" Processes valid forms. """
save_poll_option_formset = poll_option_formset is not None \
and not self.preview
valid = super().form_valid(
post_form, attachment_formset, poll_option_for... | Processes valid forms. | Below is the the instruction that describes the task:
### Input:
Processes valid forms.
### Response:
def form_valid(self, post_form, attachment_formset, poll_option_formset, **kwargs):
""" Processes valid forms. """
save_poll_option_formset = poll_option_formset is not None \
and not s... |
def map_with_obj_deep(f, dct):
"""
Implementation of map that recurses. This tests the same keys at every level of dict and in lists
:param f: 2-ary function expecting a key and value and returns a modified value
:param dct: Dict for deep processing
:return: Modified dct with matching props mapped
... | Implementation of map that recurses. This tests the same keys at every level of dict and in lists
:param f: 2-ary function expecting a key and value and returns a modified value
:param dct: Dict for deep processing
:return: Modified dct with matching props mapped | Below is the the instruction that describes the task:
### Input:
Implementation of map that recurses. This tests the same keys at every level of dict and in lists
:param f: 2-ary function expecting a key and value and returns a modified value
:param dct: Dict for deep processing
:return: Modified dct wi... |
def create_execution_state(self, topologyName, executionState):
""" create execution state """
if not executionState or not executionState.IsInitialized():
raise_(StateException("Execution State protobuf not init properly",
StateException.EX_TYPE_PROTOBUF_ERROR), sys.exc_info()... | create execution state | Below is the the instruction that describes the task:
### Input:
create execution state
### Response:
def create_execution_state(self, topologyName, executionState):
""" create execution state """
if not executionState or not executionState.IsInitialized():
raise_(StateException("Execution State prot... |
def count(cls, user_id):
""" Count sessions with user_id """
return cls.query.with_entities(
cls.user_id).filter_by(user_id=user_id).count() | Count sessions with user_id | Below is the the instruction that describes the task:
### Input:
Count sessions with user_id
### Response:
def count(cls, user_id):
""" Count sessions with user_id """
return cls.query.with_entities(
cls.user_id).filter_by(user_id=user_id).count() |
def badges(request):
''' Either displays a form containing a list of users with badges to
render, or returns a .zip file containing their badges. '''
category = request.GET.getlist("category", [])
product = request.GET.getlist("product", [])
status = request.GET.get("status")
form = forms.Invo... | Either displays a form containing a list of users with badges to
render, or returns a .zip file containing their badges. | Below is the the instruction that describes the task:
### Input:
Either displays a form containing a list of users with badges to
render, or returns a .zip file containing their badges.
### Response:
def badges(request):
''' Either displays a form containing a list of users with badges to
render, or re... |
def save(self, *args, **kwargs):
"""Serializer save that address prefetch issues."""
update = getattr(self, 'instance', None) is not None
instance = super(
WithDynamicSerializerMixin,
self
).save(
*args,
**kwargs
)
view = se... | Serializer save that address prefetch issues. | Below is the the instruction that describes the task:
### Input:
Serializer save that address prefetch issues.
### Response:
def save(self, *args, **kwargs):
"""Serializer save that address prefetch issues."""
update = getattr(self, 'instance', None) is not None
instance = super(
... |
def to_dict(self, drop_null=True, camel=False):
"""Serialize self as dict.
Args:
drop_null: bool, default True. Remove 'empty' attributes.
camel: bool, default True. Convert keys to camelCase.
Return:
dict: object params.
"""
#return _to_dict... | Serialize self as dict.
Args:
drop_null: bool, default True. Remove 'empty' attributes.
camel: bool, default True. Convert keys to camelCase.
Return:
dict: object params. | Below is the the instruction that describes the task:
### Input:
Serialize self as dict.
Args:
drop_null: bool, default True. Remove 'empty' attributes.
camel: bool, default True. Convert keys to camelCase.
Return:
dict: object params.
### Response:
def to_dict... |
def cell_array_generator(self, key):
"""Generator traversing cells specified in key
Parameters
----------
key: Iterable of Integer or slice
\tThe key specifies the cell keys of the generator
"""
for i, key_ele in enumerate(key):
# Get first element... | Generator traversing cells specified in key
Parameters
----------
key: Iterable of Integer or slice
\tThe key specifies the cell keys of the generator | Below is the the instruction that describes the task:
### Input:
Generator traversing cells specified in key
Parameters
----------
key: Iterable of Integer or slice
\tThe key specifies the cell keys of the generator
### Response:
def cell_array_generator(self, key):
"""Gene... |
def RegisterAnyElement(cls):
'''If find registered TypeCode instance, add Wrapper class
to TypeCode class serialmap and Re-RegisterType. Provides
Any serialzation of any instances of the Wrapper.
'''
for k,v in cls.types_dict.items():
what = Any.serialmap.get(k)
... | If find registered TypeCode instance, add Wrapper class
to TypeCode class serialmap and Re-RegisterType. Provides
Any serialzation of any instances of the Wrapper. | Below is the the instruction that describes the task:
### Input:
If find registered TypeCode instance, add Wrapper class
to TypeCode class serialmap and Re-RegisterType. Provides
Any serialzation of any instances of the Wrapper.
### Response:
def RegisterAnyElement(cls):
'''If find regist... |
async def stepper_step(self, command):
"""
This method activates a stepper motor motion.
This is a FirmataPlus feature.
:param command: {"method": "stepper_step", "params": [SPEED, NUMBER_OF_STEPS]}
:returns:No message returned.
"""
speed = int(command[0])
... | This method activates a stepper motor motion.
This is a FirmataPlus feature.
:param command: {"method": "stepper_step", "params": [SPEED, NUMBER_OF_STEPS]}
:returns:No message returned. | Below is the the instruction that describes the task:
### Input:
This method activates a stepper motor motion.
This is a FirmataPlus feature.
:param command: {"method": "stepper_step", "params": [SPEED, NUMBER_OF_STEPS]}
:returns:No message returned.
### Response:
async def stepper_step(sel... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.