code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def json_schema(self, schema_id=None, is_main_schema=True):
"""Generate a draft-07 JSON schema dict representing the Schema.
This method can only be called when the Schema's value is a dict.
This method must be called with a schema_id. Calling it without one
is used in a recursive contex... | Generate a draft-07 JSON schema dict representing the Schema.
This method can only be called when the Schema's value is a dict.
This method must be called with a schema_id. Calling it without one
is used in a recursive context for sub schemas. | Below is the the instruction that describes the task:
### Input:
Generate a draft-07 JSON schema dict representing the Schema.
This method can only be called when the Schema's value is a dict.
This method must be called with a schema_id. Calling it without one
is used in a recursive context ... |
def getOr(subject, predicate, *args, **kwargs):
""" Retrieve a metadata node or generate a new one
:param subject: Subject to which the metadata node should be connected
:param predicate: Predicate by which the metadata node should be connected
:return: Metadata for given node
:... | Retrieve a metadata node or generate a new one
:param subject: Subject to which the metadata node should be connected
:param predicate: Predicate by which the metadata node should be connected
:return: Metadata for given node
:rtype: Metadata | Below is the the instruction that describes the task:
### Input:
Retrieve a metadata node or generate a new one
:param subject: Subject to which the metadata node should be connected
:param predicate: Predicate by which the metadata node should be connected
:return: Metadata for given node
... |
def pop(self, *args):
"""remove and return item at index (default last)."""
value = list.pop(self, *args)
index = self._dict.pop(value.id)
# If the pop occured from a location other than the end of the list,
# we will need to subtract 1 from every entry afterwards
if len(... | remove and return item at index (default last). | Below is the the instruction that describes the task:
### Input:
remove and return item at index (default last).
### Response:
def pop(self, *args):
"""remove and return item at index (default last)."""
value = list.pop(self, *args)
index = self._dict.pop(value.id)
# If the pop occu... |
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True... | .. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True | Below is the the instruction that describes the task:
### Input:
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd... |
def slices(self):
"""
The bounding box as a tuple of `slice` objects.
The slice tuple is in numpy axis order (i.e. ``(y, x)``) and
therefore can be used to slice numpy arrays.
"""
return (slice(self.iymin, self.iymax), slice(self.ixmin, self.ixmax)) | The bounding box as a tuple of `slice` objects.
The slice tuple is in numpy axis order (i.e. ``(y, x)``) and
therefore can be used to slice numpy arrays. | Below is the the instruction that describes the task:
### Input:
The bounding box as a tuple of `slice` objects.
The slice tuple is in numpy axis order (i.e. ``(y, x)``) and
therefore can be used to slice numpy arrays.
### Response:
def slices(self):
"""
The bounding box as a tuple... |
def get_installed_classes(cls):
"""
Iterates over installed plugins associated with the `entry_point` and
returns a dictionary of viable ones keyed off of their names.
A viable installed plugin is one that is both loadable *and* a subclass
of the Pluggable subclass in question.
... | Iterates over installed plugins associated with the `entry_point` and
returns a dictionary of viable ones keyed off of their names.
A viable installed plugin is one that is both loadable *and* a subclass
of the Pluggable subclass in question. | Below is the the instruction that describes the task:
### Input:
Iterates over installed plugins associated with the `entry_point` and
returns a dictionary of viable ones keyed off of their names.
A viable installed plugin is one that is both loadable *and* a subclass
of the Pluggable subcl... |
def configKeyButtons( self, enableButtons = [], bounceTime = DEF_BOUNCE_TIME_NORMAL, pullUpDown = GPIO.PUD_UP, event = GPIO.BOTH ):
"""!
\~english
Config multi key buttons IO and event on same time
@param enableButtons: an array of key button configs. eg. <br>
[{ "id":BU... | !
\~english
Config multi key buttons IO and event on same time
@param enableButtons: an array of key button configs. eg. <br>
[{ "id":BUTTON_ACT_A, "callback": aCallbackFun }, ... ]
@param bounceTime: Default set to DEF_BOUNCE_TIME_NORMAL
@param pullUpDown: Defau... | Below is the the instruction that describes the task:
### Input:
!
\~english
Config multi key buttons IO and event on same time
@param enableButtons: an array of key button configs. eg. <br>
[{ "id":BUTTON_ACT_A, "callback": aCallbackFun }, ... ]
@param bounceTime: D... |
def remove_all_listeners(self, event=None):
"""Remove all functions for all events, or one event if one is specifed.
:param event: Optional event you wish to remove all functions from
"""
if event is not None:
self._registered_events[event] = OrderedDict()
else:
... | Remove all functions for all events, or one event if one is specifed.
:param event: Optional event you wish to remove all functions from | Below is the the instruction that describes the task:
### Input:
Remove all functions for all events, or one event if one is specifed.
:param event: Optional event you wish to remove all functions from
### Response:
def remove_all_listeners(self, event=None):
"""Remove all functions for all events... |
def proc_polyline(self, tokens):
""" Returns the components of a polyline. """
pts = [(p["x"], p["y"]) for p in tokens["points"]]
component = Polyline(pen=self.pen, points=pts)
return component | Returns the components of a polyline. | Below is the the instruction that describes the task:
### Input:
Returns the components of a polyline.
### Response:
def proc_polyline(self, tokens):
""" Returns the components of a polyline. """
pts = [(p["x"], p["y"]) for p in tokens["points"]]
component = Polyline(pen=self.pen, points=p... |
def set_wallpaper(image):
'''Set the desktop wallpaper.
Sets the desktop wallpaper to an image.
Args:
image (str): The path to the image to be set as wallpaper.
'''
desktop_env = system.get_name()
if desktop_env in ['gnome', 'unity', 'cinnamon', 'pantheon', 'mate']:
uri = 'file://%s' % image
SCHEMA = ... | Set the desktop wallpaper.
Sets the desktop wallpaper to an image.
Args:
image (str): The path to the image to be set as wallpaper. | Below is the the instruction that describes the task:
### Input:
Set the desktop wallpaper.
Sets the desktop wallpaper to an image.
Args:
image (str): The path to the image to be set as wallpaper.
### Response:
def set_wallpaper(image):
'''Set the desktop wallpaper.
Sets the desktop wallpaper to an image... |
def list_vnets(access_token, subscription_id):
'''List the VNETs in a subscription .
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
Returns:
HTTP response. JSON body of VNets list with properties.
'''
endpoint = '... | List the VNETs in a subscription .
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
Returns:
HTTP response. JSON body of VNets list with properties. | Below is the the instruction that describes the task:
### Input:
List the VNETs in a subscription .
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
Returns:
HTTP response. JSON body of VNets list with properties.
### Respo... |
def get_resource_area_by_host(self, area_id, host_id):
"""GetResourceAreaByHost.
[Preview API]
:param str area_id:
:param str host_id:
:rtype: :class:`<ResourceAreaInfo> <azure.devops.v5_0.location.models.ResourceAreaInfo>`
"""
route_values = {}
if area_id... | GetResourceAreaByHost.
[Preview API]
:param str area_id:
:param str host_id:
:rtype: :class:`<ResourceAreaInfo> <azure.devops.v5_0.location.models.ResourceAreaInfo>` | Below is the the instruction that describes the task:
### Input:
GetResourceAreaByHost.
[Preview API]
:param str area_id:
:param str host_id:
:rtype: :class:`<ResourceAreaInfo> <azure.devops.v5_0.location.models.ResourceAreaInfo>`
### Response:
def get_resource_area_by_host(self, ar... |
def do_quit(self, _: argparse.Namespace) -> bool:
"""Exit this application"""
self._should_quit = True
return self._STOP_AND_EXIT | Exit this application | Below is the the instruction that describes the task:
### Input:
Exit this application
### Response:
def do_quit(self, _: argparse.Namespace) -> bool:
"""Exit this application"""
self._should_quit = True
return self._STOP_AND_EXIT |
def cached(cls, timeout=60, cache_none=False):
""" Cache queries
:param timeout: cache timeout
:param cache_none: cache None result
Usage::
>>> Model.cached(60).query({...})
"""
return CachedModel(cls=cls, timeout=timeout, cache_none=cache_none) | Cache queries
:param timeout: cache timeout
:param cache_none: cache None result
Usage::
>>> Model.cached(60).query({...}) | Below is the the instruction that describes the task:
### Input:
Cache queries
:param timeout: cache timeout
:param cache_none: cache None result
Usage::
>>> Model.cached(60).query({...})
### Response:
def cached(cls, timeout=60, cache_none=False):
""" Cache queries
... |
def setCamera(self, camera_name, bit_depth=16):
'''
Args:
camera_name (str): Name of the camera
bit_depth (int): depth (bit) of the camera sensor
'''
self.coeffs['name'] = camera_name
self.coeffs['depth'] = bit_depth | Args:
camera_name (str): Name of the camera
bit_depth (int): depth (bit) of the camera sensor | Below is the the instruction that describes the task:
### Input:
Args:
camera_name (str): Name of the camera
bit_depth (int): depth (bit) of the camera sensor
### Response:
def setCamera(self, camera_name, bit_depth=16):
'''
Args:
camera_name (str): Name of ... |
def _cache_lookup(word, data_dir, native=False):
"""Checks if word is in cache.
Parameters
----------
word : str
Word to check in cache.
data_dir : pathlib.Path
Cache directory location.
Returns
-------
translation : str or None
Translation of given word.
""... | Checks if word is in cache.
Parameters
----------
word : str
Word to check in cache.
data_dir : pathlib.Path
Cache directory location.
Returns
-------
translation : str or None
Translation of given word. | Below is the the instruction that describes the task:
### Input:
Checks if word is in cache.
Parameters
----------
word : str
Word to check in cache.
data_dir : pathlib.Path
Cache directory location.
Returns
-------
translation : str or None
Translation of given... |
def less_than_obs_constraints(self):
"""get the names of the observations that
are listed as less than inequality constraints. Zero-
weighted obs are skipped
Returns
-------
pandas.Series : obsnme of obseravtions that are non-zero weighted
less t... | get the names of the observations that
are listed as less than inequality constraints. Zero-
weighted obs are skipped
Returns
-------
pandas.Series : obsnme of obseravtions that are non-zero weighted
less than constraints | Below is the the instruction that describes the task:
### Input:
get the names of the observations that
are listed as less than inequality constraints. Zero-
weighted obs are skipped
Returns
-------
pandas.Series : obsnme of obseravtions that are non-zero weighted
... |
def get_review_id(self, id_):
""" Get a particular review id, independent from the user_id and
startup_id
"""
return _get_request(_REVIEW_ID.format(c_api=_C_API_BEGINNING,
api=_API_VERSION,
... | Get a particular review id, independent from the user_id and
startup_id | Below is the the instruction that describes the task:
### Input:
Get a particular review id, independent from the user_id and
startup_id
### Response:
def get_review_id(self, id_):
""" Get a particular review id, independent from the user_id and
startup_id
"""
return _get_request(_REVIEW_ID.for... |
def find(self, obj, filter_to_class=Ingredient, constructor=None):
"""
Find an Ingredient, optionally using the shelf.
:param obj: A string or Ingredient
:param filter_to_class: The Ingredient subclass that obj must be an
instance of
:param constructor: An optional call... | Find an Ingredient, optionally using the shelf.
:param obj: A string or Ingredient
:param filter_to_class: The Ingredient subclass that obj must be an
instance of
:param constructor: An optional callable for building Ingredients
from obj
:return: An Ingredient of subcl... | Below is the the instruction that describes the task:
### Input:
Find an Ingredient, optionally using the shelf.
:param obj: A string or Ingredient
:param filter_to_class: The Ingredient subclass that obj must be an
instance of
:param constructor: An optional callable for building ... |
def subdevicenames(self) -> Tuple[str, ...]:
"""A |tuple| containing the device names."""
self: NetCDFVariableBase
return tuple(self.sequences.keys()) | A |tuple| containing the device names. | Below is the the instruction that describes the task:
### Input:
A |tuple| containing the device names.
### Response:
def subdevicenames(self) -> Tuple[str, ...]:
"""A |tuple| containing the device names."""
self: NetCDFVariableBase
return tuple(self.sequences.keys()) |
def query_source(self, source):
"""
Query by source
"""
return self._get_repo_filter(Layer.objects).filter(url=source) | Query by source | Below is the the instruction that describes the task:
### Input:
Query by source
### Response:
def query_source(self, source):
"""
Query by source
"""
return self._get_repo_filter(Layer.objects).filter(url=source) |
def migrate(move_data=True, update_alias=True):
"""
Upgrade function that creates a new index for the data. Optionally it also can
(and by default will) reindex previous copy of the data into the new index
(specify ``move_data=False`` to skip this step) and update the alias to
point to the latest in... | Upgrade function that creates a new index for the data. Optionally it also can
(and by default will) reindex previous copy of the data into the new index
(specify ``move_data=False`` to skip this step) and update the alias to
point to the latest index (set ``update_alias=False`` to skip).
Note that whi... | Below is the the instruction that describes the task:
### Input:
Upgrade function that creates a new index for the data. Optionally it also can
(and by default will) reindex previous copy of the data into the new index
(specify ``move_data=False`` to skip this step) and update the alias to
point to the ... |
def platform_information(_linux_distribution=None):
""" detect platform information from remote host """
linux_distribution = _linux_distribution or platform.linux_distribution
distro, release, codename = linux_distribution()
if not distro:
distro, release, codename = parse_os_release()
if n... | detect platform information from remote host | Below is the the instruction that describes the task:
### Input:
detect platform information from remote host
### Response:
def platform_information(_linux_distribution=None):
""" detect platform information from remote host """
linux_distribution = _linux_distribution or platform.linux_distribution
di... |
def update_remote_archive(self, save_uri, timeout=-1):
"""
Saves a backup of the appliance to a previously-configured remote location.
Args:
save_uri (dict): The URI for saving the backup to a previously configured location.
timeout:
Timeout in seconds. W... | Saves a backup of the appliance to a previously-configured remote location.
Args:
save_uri (dict): The URI for saving the backup to a previously configured location.
timeout:
Timeout in seconds. Wait for task completion by default. The timeout does not abort the operatio... | Below is the the instruction that describes the task:
### Input:
Saves a backup of the appliance to a previously-configured remote location.
Args:
save_uri (dict): The URI for saving the backup to a previously configured location.
timeout:
Timeout in seconds. Wait fo... |
def write_frames(filename, frames, compression=257, compression_level=6):
"""Write a list of frame objects to a file
**Requires:** |LDAStools.frameCPP|_
Parameters
----------
filename : `str`
path to write into
frames : `list` of `LDAStools.frameCPP.FrameH`
list of frames to w... | Write a list of frame objects to a file
**Requires:** |LDAStools.frameCPP|_
Parameters
----------
filename : `str`
path to write into
frames : `list` of `LDAStools.frameCPP.FrameH`
list of frames to write into file
compression : `int`, optional
enum value for compress... | Below is the the instruction that describes the task:
### Input:
Write a list of frame objects to a file
**Requires:** |LDAStools.frameCPP|_
Parameters
----------
filename : `str`
path to write into
frames : `list` of `LDAStools.frameCPP.FrameH`
list of frames to write into fi... |
def spell(self, word: str) -> List[str]:
"""
Return a list of possible words, according to edit distance of 1 and 2,
sorted by frequency of word occurrance in the spelling dictionary
:param str word: A word to check its spelling
"""
if not word:
return ""
... | Return a list of possible words, according to edit distance of 1 and 2,
sorted by frequency of word occurrance in the spelling dictionary
:param str word: A word to check its spelling | Below is the the instruction that describes the task:
### Input:
Return a list of possible words, according to edit distance of 1 and 2,
sorted by frequency of word occurrance in the spelling dictionary
:param str word: A word to check its spelling
### Response:
def spell(self, word: str) -> List[... |
def getPlainText(self, identify=None):
"""
Convenience function for templates which want access
to the raw text, without XML tags.
"""
frags = getattr(self, 'frags', None)
if frags:
plains = []
for frag in frags:
if hasattr(frag, '... | Convenience function for templates which want access
to the raw text, without XML tags. | Below is the the instruction that describes the task:
### Input:
Convenience function for templates which want access
to the raw text, without XML tags.
### Response:
def getPlainText(self, identify=None):
"""
Convenience function for templates which want access
to the raw text, wit... |
def get_subtree(self, name): # noqa: D302
r"""
Get all node names in a sub-tree.
:param name: Sub-tree root node name
:type name: :ref:`NodeName`
:rtype: list of :ref:`NodeName`
:raises:
* RuntimeError (Argument \`name\` is not valid)
* RuntimeErro... | r"""
Get all node names in a sub-tree.
:param name: Sub-tree root node name
:type name: :ref:`NodeName`
:rtype: list of :ref:`NodeName`
:raises:
* RuntimeError (Argument \`name\` is not valid)
* RuntimeError (Node *[name]* not in tree)
Using the sa... | Below is the the instruction that describes the task:
### Input:
r"""
Get all node names in a sub-tree.
:param name: Sub-tree root node name
:type name: :ref:`NodeName`
:rtype: list of :ref:`NodeName`
:raises:
* RuntimeError (Argument \`name\` is not valid)
... |
def filename(self):
"""
Returns the provided data as a file location.
"""
if self._filename:
return self._filename
else:
with tempfile.NamedTemporaryFile(delete=False) as f:
f.write(self._bytes)
return f.name | Returns the provided data as a file location. | Below is the the instruction that describes the task:
### Input:
Returns the provided data as a file location.
### Response:
def filename(self):
"""
Returns the provided data as a file location.
"""
if self._filename:
return self._filename
else:
with ... |
def apply_to_segmentlist(self, seglist):
"""
Apply our low and high windows to the segments in a
segmentlist.
"""
for i, seg in enumerate(seglist):
seglist[i] = seg.__class__(seg[0] - self.low_window, seg[1] + self.high_window) | Apply our low and high windows to the segments in a
segmentlist. | Below is the the instruction that describes the task:
### Input:
Apply our low and high windows to the segments in a
segmentlist.
### Response:
def apply_to_segmentlist(self, seglist):
"""
Apply our low and high windows to the segments in a
segmentlist.
"""
for i, seg in enumerate(seglist):
seglist[... |
def element_focus_should_be_set(self, locator):
"""Verifies the element identified by `locator` has focus.
| *Argument* | *Description* | *Example* |
| locator | Selenium 2 element locator | id=my_id |"""
self._info("Verifying element '%s' focus is set" % locator)
self._check_element_focus(True, locator) | Verifies the element identified by `locator` has focus.
| *Argument* | *Description* | *Example* |
| locator | Selenium 2 element locator | id=my_id | | Below is the the instruction that describes the task:
### Input:
Verifies the element identified by `locator` has focus.
| *Argument* | *Description* | *Example* |
| locator | Selenium 2 element locator | id=my_id |
### Response:
def element_focus_should_be_set(self, locator):
"""Verifies the element identi... |
def _generate_version(base_version):
"""Generate a version with information about the git repository"""
pkg_dir = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
if not _is_git_repo(pkg_dir) or not _have_git():
return base_version
if _is_release(pkg_dir, base_version) and not _is_d... | Generate a version with information about the git repository | Below is the the instruction that describes the task:
### Input:
Generate a version with information about the git repository
### Response:
def _generate_version(base_version):
"""Generate a version with information about the git repository"""
pkg_dir = os.path.abspath(os.path.dirname(os.path.dirname(__fil... |
def merge(
self, reservation_order_id, sources=None, custom_headers=None, raw=False, polling=True, **operation_config):
"""Merges two `Reservation`s.
Merge the specified `Reservation`s into a new `Reservation`. The two
`Reservation`s being merged must have same properties.
... | Merges two `Reservation`s.
Merge the specified `Reservation`s into a new `Reservation`. The two
`Reservation`s being merged must have same properties.
:param reservation_order_id: Order Id of the reservation
:type reservation_order_id: str
:param sources: Format of the resource... | Below is the the instruction that describes the task:
### Input:
Merges two `Reservation`s.
Merge the specified `Reservation`s into a new `Reservation`. The two
`Reservation`s being merged must have same properties.
:param reservation_order_id: Order Id of the reservation
:type res... |
def mutate_unsampled_call_args(self, module, method, wrapped, instance, args, kwargs, transaction):
"""
Method called for unsampled wrapped calls. This can e.g. be used to add traceparent headers to the
underlying http call for HTTP instrumentations.
:param module:
:param method... | Method called for unsampled wrapped calls. This can e.g. be used to add traceparent headers to the
underlying http call for HTTP instrumentations.
:param module:
:param method:
:param wrapped:
:param instance:
:param args:
:param kwargs:
:param transactio... | Below is the the instruction that describes the task:
### Input:
Method called for unsampled wrapped calls. This can e.g. be used to add traceparent headers to the
underlying http call for HTTP instrumentations.
:param module:
:param method:
:param wrapped:
:param instance:
... |
def get_start_and_end_time(self, ref=None):
"""Specific function to get start time and end time for MonthDayDaterange
:param ref: time in seconds
:type ref: int
:return: tuple with start and end time
:rtype: tuple (int, int)
"""
now = time.localtime(ref)
... | Specific function to get start time and end time for MonthDayDaterange
:param ref: time in seconds
:type ref: int
:return: tuple with start and end time
:rtype: tuple (int, int) | Below is the the instruction that describes the task:
### Input:
Specific function to get start time and end time for MonthDayDaterange
:param ref: time in seconds
:type ref: int
:return: tuple with start and end time
:rtype: tuple (int, int)
### Response:
def get_start_and_end_tim... |
def get_previous_request(rid):
"""Return the last ceph broker request sent on a given relation
@param rid: Relation id to query for request
"""
request = None
broker_req = relation_get(attribute='broker_req', rid=rid,
unit=local_unit())
if broker_req:
reque... | Return the last ceph broker request sent on a given relation
@param rid: Relation id to query for request | Below is the the instruction that describes the task:
### Input:
Return the last ceph broker request sent on a given relation
@param rid: Relation id to query for request
### Response:
def get_previous_request(rid):
"""Return the last ceph broker request sent on a given relation
@param rid: Relation ... |
def _validateurl(self, url):
"""assembles the server url"""
parsed = urlparse(url)
path = parsed.path.strip("/")
if path:
parts = path.split("/")
url_types = ("admin", "manager", "rest")
if any(i in parts for i in url_types):
while part... | assembles the server url | Below is the the instruction that describes the task:
### Input:
assembles the server url
### Response:
def _validateurl(self, url):
"""assembles the server url"""
parsed = urlparse(url)
path = parsed.path.strip("/")
if path:
parts = path.split("/")
url_types... |
def indicator(self, data):
"""Update the request URI to include the Indicator for specific indicator retrieval.
Args:
data (string): The indicator value
"""
# handle hashes in form md5 : sha1 : sha256
data = self.get_first_hash(data)
super(File, self).indicat... | Update the request URI to include the Indicator for specific indicator retrieval.
Args:
data (string): The indicator value | Below is the the instruction that describes the task:
### Input:
Update the request URI to include the Indicator for specific indicator retrieval.
Args:
data (string): The indicator value
### Response:
def indicator(self, data):
"""Update the request URI to include the Indicator for sp... |
def verify_rank_integrity(self, tax_id, rank, parent_id, children):
"""Confirm that for each node the parent ranks and children ranks are
coherent
"""
def _lower(n1, n2):
return self.ranks.index(n1) < self.ranks.index(n2)
if rank not in self.ranks:
raise... | Confirm that for each node the parent ranks and children ranks are
coherent | Below is the the instruction that describes the task:
### Input:
Confirm that for each node the parent ranks and children ranks are
coherent
### Response:
def verify_rank_integrity(self, tax_id, rank, parent_id, children):
"""Confirm that for each node the parent ranks and children ranks are
... |
def warn(self, message, *args, **kwargs):
"""alias to message at warning level"""
self.log("warn", message, *args, **kwargs) | alias to message at warning level | Below is the the instruction that describes the task:
### Input:
alias to message at warning level
### Response:
def warn(self, message, *args, **kwargs):
"""alias to message at warning level"""
self.log("warn", message, *args, **kwargs) |
def to_iso(dt):
'''
Format a date or datetime into an ISO-8601 string
Support dates before 1900.
'''
if isinstance(dt, datetime):
return to_iso_datetime(dt)
elif isinstance(dt, date):
return to_iso_date(dt) | Format a date or datetime into an ISO-8601 string
Support dates before 1900. | Below is the the instruction that describes the task:
### Input:
Format a date or datetime into an ISO-8601 string
Support dates before 1900.
### Response:
def to_iso(dt):
'''
Format a date or datetime into an ISO-8601 string
Support dates before 1900.
'''
if isinstance(dt, datetime):
... |
def count_by_key_impl(sequence):
"""
Implementation for count_by_key_t
:param sequence: sequence of (key, value) pairs
:return: counts by key
"""
counter = collections.Counter()
for key, _ in sequence:
counter[key] += 1
return six.viewitems(counter) | Implementation for count_by_key_t
:param sequence: sequence of (key, value) pairs
:return: counts by key | Below is the the instruction that describes the task:
### Input:
Implementation for count_by_key_t
:param sequence: sequence of (key, value) pairs
:return: counts by key
### Response:
def count_by_key_impl(sequence):
"""
Implementation for count_by_key_t
:param sequence: sequence of (key, value... |
def autogender(self, api_token=None, genderize_all=False):
"""Autocomplete gender information of unique identities.
Autocomplete unique identities gender using genderize.io
API. Only those unique identities without an assigned
gender will be updated unless `genderize_all` option is give... | Autocomplete gender information of unique identities.
Autocomplete unique identities gender using genderize.io
API. Only those unique identities without an assigned
gender will be updated unless `genderize_all` option is given. | Below is the the instruction that describes the task:
### Input:
Autocomplete gender information of unique identities.
Autocomplete unique identities gender using genderize.io
API. Only those unique identities without an assigned
gender will be updated unless `genderize_all` option is given... |
def reverse_deployments(deployments=None):
"""Reverse deployments and the modules/regions in them."""
if deployments is None:
deployments = []
reversed_deployments = []
for i in deployments[::-1]:
deployment = copy.deepcopy(i)
for config in ['modules'... | Reverse deployments and the modules/regions in them. | Below is the the instruction that describes the task:
### Input:
Reverse deployments and the modules/regions in them.
### Response:
def reverse_deployments(deployments=None):
"""Reverse deployments and the modules/regions in them."""
if deployments is None:
deployments = []
rev... |
def apply(self, **kwexpr):
"""
Specify one or more projection expressions to add to each result
### Parameters
- **kwexpr**: One or more key-value pairs for a projection. The key is
the alias for the projection, and the value is the projection
expression itself,... | Specify one or more projection expressions to add to each result
### Parameters
- **kwexpr**: One or more key-value pairs for a projection. The key is
the alias for the projection, and the value is the projection
expression itself, for example `apply(square_root="sqrt(@foo)")` | Below is the the instruction that describes the task:
### Input:
Specify one or more projection expressions to add to each result
### Parameters
- **kwexpr**: One or more key-value pairs for a projection. The key is
the alias for the projection, and the value is the projection
... |
def save(self, msg=None):
"""
Modify item data and commit to repo.
Git objects are immutable, to save means adding a new item
:param msg: Commit message.
"""
if msg is None:
msg = 'Saving %s' % self.name
log.debug(msg)
self.repo.addItem(self,... | Modify item data and commit to repo.
Git objects are immutable, to save means adding a new item
:param msg: Commit message. | Below is the the instruction that describes the task:
### Input:
Modify item data and commit to repo.
Git objects are immutable, to save means adding a new item
:param msg: Commit message.
### Response:
def save(self, msg=None):
"""
Modify item data and commit to repo.
Gi... |
def matrix(
m, n, lst,
m_text: list=None,
n_text: list=None):
"""
m: row
n: column
lst: items
>>> print(_matrix(2, 3, [(1, 1), (2, 3)]))
|x| | |
| | |x|
"""
fmt = ""
if n_text:
fmt += " {}\n".format(" ".join(n_text))
for ... | m: row
n: column
lst: items
>>> print(_matrix(2, 3, [(1, 1), (2, 3)]))
|x| | |
| | |x| | Below is the the instruction that describes the task:
### Input:
m: row
n: column
lst: items
>>> print(_matrix(2, 3, [(1, 1), (2, 3)]))
|x| | |
| | |x|
### Response:
def matrix(
m, n, lst,
m_text: list=None,
n_text: list=None):
"""
m: row
n: colu... |
def get_queryset(self):
"""
Check that the queryset is defined and call it.
"""
if self.queryset is None:
raise ImproperlyConfigured(
"'%s' must define 'queryset'" % self.__class__.__name__)
return self.queryset() | Check that the queryset is defined and call it. | Below is the the instruction that describes the task:
### Input:
Check that the queryset is defined and call it.
### Response:
def get_queryset(self):
"""
Check that the queryset is defined and call it.
"""
if self.queryset is None:
raise ImproperlyConfigured(
... |
def check_domain(self, service_id, version_number, name):
"""Checks the status of a domain's DNS record. Returns an array of 3 items. The first is the details for the domain. The second is the current CNAME of the domain. The third is a boolean indicating whether or not it has been properly setup to use Fastly."""
... | Checks the status of a domain's DNS record. Returns an array of 3 items. The first is the details for the domain. The second is the current CNAME of the domain. The third is a boolean indicating whether or not it has been properly setup to use Fastly. | Below is the the instruction that describes the task:
### Input:
Checks the status of a domain's DNS record. Returns an array of 3 items. The first is the details for the domain. The second is the current CNAME of the domain. The third is a boolean indicating whether or not it has been properly setup to use Fastly.... |
async def get_pinstate_report(self, command):
"""
This method retrieves a Firmata pin_state report for a pin..
See: http://firmata.org/wiki/Protocol#Pin_State_Query
:param command: {"method": "get_pin_state", "params": [PIN]}
:returns: {"method": "get_pin_state_reply", "params"... | This method retrieves a Firmata pin_state report for a pin..
See: http://firmata.org/wiki/Protocol#Pin_State_Query
:param command: {"method": "get_pin_state", "params": [PIN]}
:returns: {"method": "get_pin_state_reply", "params": [PIN_NUMBER, PIN_MODE, PIN_STATE]} | Below is the the instruction that describes the task:
### Input:
This method retrieves a Firmata pin_state report for a pin..
See: http://firmata.org/wiki/Protocol#Pin_State_Query
:param command: {"method": "get_pin_state", "params": [PIN]}
:returns: {"method": "get_pin_state_reply", "para... |
def get_notebook_tab_title(notebook, page_num):
"""Helper function that gets a notebook's tab title given its page number
:param notebook: The GTK notebook
:param page_num: The page number of the tab, for which the title is required
:return: The title of the tab
"""
child = notebook.get_nth_pag... | Helper function that gets a notebook's tab title given its page number
:param notebook: The GTK notebook
:param page_num: The page number of the tab, for which the title is required
:return: The title of the tab | Below is the the instruction that describes the task:
### Input:
Helper function that gets a notebook's tab title given its page number
:param notebook: The GTK notebook
:param page_num: The page number of the tab, for which the title is required
:return: The title of the tab
### Response:
def get_not... |
def selecttabindex(self, window_name, object_name, tab_index):
"""
Select tab based on index.
@param window_name: Window name to type in, either full name,
LDTP's name convention, or a Unix glob.
@type window_name: string
@param object_name: Object name to type i... | Select tab based on index.
@param window_name: Window name to type in, either full name,
LDTP's name convention, or a Unix glob.
@type window_name: string
@param object_name: Object name to type in, either full name,
LDTP's name convention, or a Unix glob.
@type... | Below is the the instruction that describes the task:
### Input:
Select tab based on index.
@param window_name: Window name to type in, either full name,
LDTP's name convention, or a Unix glob.
@type window_name: string
@param object_name: Object name to type in, either full... |
def make_name(self, reserved=[]):
"""
Autogenerates a :attr:`name` from the :attr:`title`. If the auto-generated name is already
in use in this model, :meth:`make_name` tries again by suffixing numbers starting with 2
until an available name is found.
:param reserved: List or se... | Autogenerates a :attr:`name` from the :attr:`title`. If the auto-generated name is already
in use in this model, :meth:`make_name` tries again by suffixing numbers starting with 2
until an available name is found.
:param reserved: List or set of reserved names unavailable for use | Below is the the instruction that describes the task:
### Input:
Autogenerates a :attr:`name` from the :attr:`title`. If the auto-generated name is already
in use in this model, :meth:`make_name` tries again by suffixing numbers starting with 2
until an available name is found.
:param reser... |
def accel_move_tab_left(self, *args):
# TODO KEYBINDINGS ONLY
""" Callback to move a tab to the left """
pos = self.get_notebook().get_current_page()
if pos != 0:
self.move_tab(pos, pos - 1)
return True | Callback to move a tab to the left | Below is the the instruction that describes the task:
### Input:
Callback to move a tab to the left
### Response:
def accel_move_tab_left(self, *args):
# TODO KEYBINDINGS ONLY
""" Callback to move a tab to the left """
pos = self.get_notebook().get_current_page()
if pos != 0:
... |
def infos(self, type=None, failed=False):
"""Get all infos created by the participants nodes.
Return a list of infos produced by nodes associated with the
participant. If specified, ``type`` filters by class. By default, failed
infos are excluded, to include only failed nodes use ``fail... | Get all infos created by the participants nodes.
Return a list of infos produced by nodes associated with the
participant. If specified, ``type`` filters by class. By default, failed
infos are excluded, to include only failed nodes use ``failed=True``,
for all nodes use ``failed=all``. ... | Below is the the instruction that describes the task:
### Input:
Get all infos created by the participants nodes.
Return a list of infos produced by nodes associated with the
participant. If specified, ``type`` filters by class. By default, failed
infos are excluded, to include only failed ... |
def _find_usage_cloudtrail(self):
"""Calculate current usage for CloudTrail related metrics"""
trail_list = self.conn.describe_trails()['trailList']
trail_count = len(trail_list) if trail_list else 0
for trail in trail_list:
data_resource_count = 0
if self.conn.... | Calculate current usage for CloudTrail related metrics | Below is the the instruction that describes the task:
### Input:
Calculate current usage for CloudTrail related metrics
### Response:
def _find_usage_cloudtrail(self):
"""Calculate current usage for CloudTrail related metrics"""
trail_list = self.conn.describe_trails()['trailList']
trail_c... |
def postprocess_result(morphresult, trim_phonetic, trim_compound):
"""Postprocess vabamorf wrapper output."""
word, analysis = morphresult
return {
'text': deconvert(word),
'analysis': [postprocess_analysis(a, trim_phonetic, trim_compound) for a in analysis]
} | Postprocess vabamorf wrapper output. | Below is the the instruction that describes the task:
### Input:
Postprocess vabamorf wrapper output.
### Response:
def postprocess_result(morphresult, trim_phonetic, trim_compound):
"""Postprocess vabamorf wrapper output."""
word, analysis = morphresult
return {
'text': deconvert(word),
... |
def handle_split(self, asset, ratio):
"""
Update the position by the split ratio, and return the resulting
fractional share that will be converted into cash.
Returns the unused cash.
"""
if self.asset != asset:
raise Exception("updating split with the wrong a... | Update the position by the split ratio, and return the resulting
fractional share that will be converted into cash.
Returns the unused cash. | Below is the the instruction that describes the task:
### Input:
Update the position by the split ratio, and return the resulting
fractional share that will be converted into cash.
Returns the unused cash.
### Response:
def handle_split(self, asset, ratio):
"""
Update the position ... |
def flatten2d(d, key_as_tuple=True, delim='.',
list_of_dicts=None):
""" get nested dict as {key:dict,...},
where key is tuple/string of all-1 nested keys
NB: is same as flattennd(d,1,key_as_tuple,delim)
Parameters
----------
d : dict
key_as_tuple : bool
whether keys a... | get nested dict as {key:dict,...},
where key is tuple/string of all-1 nested keys
NB: is same as flattennd(d,1,key_as_tuple,delim)
Parameters
----------
d : dict
key_as_tuple : bool
whether keys are list of nested keys or delimited string of nested keys
delim : str
if key_a... | Below is the the instruction that describes the task:
### Input:
get nested dict as {key:dict,...},
where key is tuple/string of all-1 nested keys
NB: is same as flattennd(d,1,key_as_tuple,delim)
Parameters
----------
d : dict
key_as_tuple : bool
whether keys are list of nested key... |
def save_point(self) -> str:
"""
Indexes the measured data with the current point as a key and saves the
current position once the 'Enter' key is pressed to the 'actual points'
vector.
"""
if self._current_mount is left:
msg = self.save_mount_offset()
... | Indexes the measured data with the current point as a key and saves the
current position once the 'Enter' key is pressed to the 'actual points'
vector. | Below is the the instruction that describes the task:
### Input:
Indexes the measured data with the current point as a key and saves the
current position once the 'Enter' key is pressed to the 'actual points'
vector.
### Response:
def save_point(self) -> str:
"""
Indexes the measure... |
def create_storage_policy(policy_name, policy_dict, service_instance=None):
'''
Creates a storage policy.
Supported capability types: scalar, set, range.
policy_name
Name of the policy to create.
The value of the argument will override any existing name in
``policy_dict``.
... | Creates a storage policy.
Supported capability types: scalar, set, range.
policy_name
Name of the policy to create.
The value of the argument will override any existing name in
``policy_dict``.
policy_dict
Dictionary containing the changes to apply to the policy.
(... | Below is the the instruction that describes the task:
### Input:
Creates a storage policy.
Supported capability types: scalar, set, range.
policy_name
Name of the policy to create.
The value of the argument will override any existing name in
``policy_dict``.
policy_dict
... |
def extract_solvent_accessibility_dssp(in_dssp, path=True):
"""Uses DSSP to extract solvent accessibilty information on every residue.
Notes
-----
For more information on the solvent accessibility metrics used in dssp, see:
http://swift.cmbi.ru.nl/gv/dssp/HTML/descrip.html#ACC
In the dssp files... | Uses DSSP to extract solvent accessibilty information on every residue.
Notes
-----
For more information on the solvent accessibility metrics used in dssp, see:
http://swift.cmbi.ru.nl/gv/dssp/HTML/descrip.html#ACC
In the dssp files value is labeled 'ACC'.
Parameters
----------
in_dssp... | Below is the the instruction that describes the task:
### Input:
Uses DSSP to extract solvent accessibilty information on every residue.
Notes
-----
For more information on the solvent accessibility metrics used in dssp, see:
http://swift.cmbi.ru.nl/gv/dssp/HTML/descrip.html#ACC
In the dssp fil... |
def allow(self, comment, content_object, request):
"""Moderates comments."""
POST = urlencode({
"blog": settings.AKISMET_BLOG.encode("utf-8"),
"user_ip": comment.ip_address,
"user_agent": request.META.get('HTTP_USER_AGENT', "").
... | Moderates comments. | Below is the the instruction that describes the task:
### Input:
Moderates comments.
### Response:
def allow(self, comment, content_object, request):
"""Moderates comments."""
POST = urlencode({
"blog": settings.AKISMET_BLOG.encode("utf-8"),
"user_ip": comme... |
def sigmoid_accuracy_one_hot(logits, labels, weights_fn=None):
"""Calculate accuracy for a set, given one-hot labels and logits.
Args:
logits: Tensor of size [batch-size, o=1, p=1, num-classes]
labels: Tensor of size [batch-size, o=1, p=1, num-classes]
weights_fn: Function that takes in labels and weig... | Calculate accuracy for a set, given one-hot labels and logits.
Args:
logits: Tensor of size [batch-size, o=1, p=1, num-classes]
labels: Tensor of size [batch-size, o=1, p=1, num-classes]
weights_fn: Function that takes in labels and weighs examples (unused)
Returns:
accuracy (scalar), weights | Below is the the instruction that describes the task:
### Input:
Calculate accuracy for a set, given one-hot labels and logits.
Args:
logits: Tensor of size [batch-size, o=1, p=1, num-classes]
labels: Tensor of size [batch-size, o=1, p=1, num-classes]
weights_fn: Function that takes in labels and wei... |
def patch_for_specialized_compiler():
"""
Patch functions in distutils.msvc9compiler to use the standalone compiler
build for Python (Windows only). Fall back to original behavior when the
standalone compiler is not available.
"""
if 'distutils' not in globals():
# The module isn't avail... | Patch functions in distutils.msvc9compiler to use the standalone compiler
build for Python (Windows only). Fall back to original behavior when the
standalone compiler is not available. | Below is the the instruction that describes the task:
### Input:
Patch functions in distutils.msvc9compiler to use the standalone compiler
build for Python (Windows only). Fall back to original behavior when the
standalone compiler is not available.
### Response:
def patch_for_specialized_compiler():
"... |
def close_tab(self):
"""
Close active tab.
"""
if len(self.tab_pages) > 1: # Cannot close last tab.
del self.tab_pages[self.active_tab_index]
self.active_tab_index = max(0, self.active_tab_index - 1)
# Clean up buffers.
self._auto_close_new_empty... | Close active tab. | Below is the the instruction that describes the task:
### Input:
Close active tab.
### Response:
def close_tab(self):
"""
Close active tab.
"""
if len(self.tab_pages) > 1: # Cannot close last tab.
del self.tab_pages[self.active_tab_index]
self.active_tab_ind... |
def s_l(l, alpha):
"""
get sigma as a function of degree l from Constable and Parker (1988)
"""
a2 = alpha**2
c_a = 0.547
s_l = np.sqrt(old_div(((c_a**(2. * l)) * a2), ((l + 1.) * (2. * l + 1.))))
return s_l | get sigma as a function of degree l from Constable and Parker (1988) | Below is the the instruction that describes the task:
### Input:
get sigma as a function of degree l from Constable and Parker (1988)
### Response:
def s_l(l, alpha):
"""
get sigma as a function of degree l from Constable and Parker (1988)
"""
a2 = alpha**2
c_a = 0.547
s_l = np.sqrt(old_div... |
def interfaces(self):
"""Collect the available wlan interfaces."""
self._ifaces = []
wifi_ctrl = wifiutil.WifiUtil()
for interface in wifi_ctrl.interfaces():
iface = Interface(interface)
self._ifaces.append(iface)
self._logger.info("Get interface: %s... | Collect the available wlan interfaces. | Below is the the instruction that describes the task:
### Input:
Collect the available wlan interfaces.
### Response:
def interfaces(self):
"""Collect the available wlan interfaces."""
self._ifaces = []
wifi_ctrl = wifiutil.WifiUtil()
for interface in wifi_ctrl.interfaces():
... |
def get_hosts_by_explosion(self, hostgroups):
# pylint: disable=access-member-before-definition
"""
Get hosts of this group
:param hostgroups: Hostgroup object
:type hostgroups: alignak.objects.hostgroup.Hostgroups
:return: list of hosts of this group
:rtype: lis... | Get hosts of this group
:param hostgroups: Hostgroup object
:type hostgroups: alignak.objects.hostgroup.Hostgroups
:return: list of hosts of this group
:rtype: list | Below is the the instruction that describes the task:
### Input:
Get hosts of this group
:param hostgroups: Hostgroup object
:type hostgroups: alignak.objects.hostgroup.Hostgroups
:return: list of hosts of this group
:rtype: list
### Response:
def get_hosts_by_explosion(self, hostg... |
def user_has_group(user, group, superuser_skip=True):
"""
Check if a user is in a certaing group.
By default, the check is skipped for superusers.
"""
if user.is_superuser and superuser_skip:
return True
return user.groups.filter(name=group).exists() | Check if a user is in a certaing group.
By default, the check is skipped for superusers. | Below is the the instruction that describes the task:
### Input:
Check if a user is in a certaing group.
By default, the check is skipped for superusers.
### Response:
def user_has_group(user, group, superuser_skip=True):
"""
Check if a user is in a certaing group.
By default, the check is skipped ... |
def attach(self, screen):
"""Adds a given screen to the listener queue.
:param pyte.screens.Screen screen: a screen to attach to.
"""
if self.listener is not None:
warnings.warn("As of version 0.6.0 the listener queue is "
"restricted to a single el... | Adds a given screen to the listener queue.
:param pyte.screens.Screen screen: a screen to attach to. | Below is the the instruction that describes the task:
### Input:
Adds a given screen to the listener queue.
:param pyte.screens.Screen screen: a screen to attach to.
### Response:
def attach(self, screen):
"""Adds a given screen to the listener queue.
:param pyte.screens.Screen screen: a ... |
def from_json(self, fname):
'''
Read contents of a CSV containing a list of servers.
'''
with open(fname, 'rt') as fp:
for row in json.load(fp):
nn = ServerInfo.from_dict(row)
self[str(nn)] = nn | Read contents of a CSV containing a list of servers. | Below is the the instruction that describes the task:
### Input:
Read contents of a CSV containing a list of servers.
### Response:
def from_json(self, fname):
'''
Read contents of a CSV containing a list of servers.
'''
with open(fname, 'rt') as fp:
for row in json.... |
def bar_chart_mf(data, path_name):
"""Make a bar chart for data on MF quantities."""
N = len(data)
ind = np.arange(N) # the x locations for the groups
width = 0.8 # the width of the bars
fig, ax = pyplot.subplots()
rects1 = ax.bar(ind, data, width, color='g')
# add some t... | Make a bar chart for data on MF quantities. | Below is the the instruction that describes the task:
### Input:
Make a bar chart for data on MF quantities.
### Response:
def bar_chart_mf(data, path_name):
"""Make a bar chart for data on MF quantities."""
N = len(data)
ind = np.arange(N) # the x locations for the groups
width = 0.8 ... |
def add_state_editor(self, state_m):
"""Triggered whenever a state is selected.
:param state_m: The selected state model.
"""
state_identifier = self.get_state_identifier(state_m)
if state_identifier in self.closed_tabs:
state_editor_ctrl = self.closed_tabs[state_id... | Triggered whenever a state is selected.
:param state_m: The selected state model. | Below is the the instruction that describes the task:
### Input:
Triggered whenever a state is selected.
:param state_m: The selected state model.
### Response:
def add_state_editor(self, state_m):
"""Triggered whenever a state is selected.
:param state_m: The selected state model.
... |
def Verify(self, public_key):
"""Verifies the certificate using the given key.
Args:
public_key: The public key to use.
Returns:
True: Everything went well.
Raises:
VerificationError: The certificate did not verify.
"""
# TODO(amoser): We have to do this manually for now sin... | Verifies the certificate using the given key.
Args:
public_key: The public key to use.
Returns:
True: Everything went well.
Raises:
VerificationError: The certificate did not verify. | Below is the the instruction that describes the task:
### Input:
Verifies the certificate using the given key.
Args:
public_key: The public key to use.
Returns:
True: Everything went well.
Raises:
VerificationError: The certificate did not verify.
### Response:
def Verify(self, pub... |
def _context(self):
"""
Return the context to pass to the template.
The context is a dict of the form:
{
'css_url': CSS_URL,
'report_name': REPORT_NAME,
'diff_name': DIFF_NAME,
'src_stats': {SRC_PATH: {
'percen... | Return the context to pass to the template.
The context is a dict of the form:
{
'css_url': CSS_URL,
'report_name': REPORT_NAME,
'diff_name': DIFF_NAME,
'src_stats': {SRC_PATH: {
'percent_covered': PERCENT_COVERED,
... | Below is the the instruction that describes the task:
### Input:
Return the context to pass to the template.
The context is a dict of the form:
{
'css_url': CSS_URL,
'report_name': REPORT_NAME,
'diff_name': DIFF_NAME,
'src_stats': {SRC_PATH: {
... |
def get_edge_annotations(self, u, v, key: str) -> Optional[AnnotationsDict]:
"""Get the annotations for a given edge."""
return self._get_edge_attr(u, v, key, ANNOTATIONS) | Get the annotations for a given edge. | Below is the the instruction that describes the task:
### Input:
Get the annotations for a given edge.
### Response:
def get_edge_annotations(self, u, v, key: str) -> Optional[AnnotationsDict]:
"""Get the annotations for a given edge."""
return self._get_edge_attr(u, v, key, ANNOTATIONS) |
def write_c_string( self, value ):
"""
Read a zero terminated (C style) string
"""
self.file.write( value )
self.file.write( b'\0' ) | Read a zero terminated (C style) string | Below is the the instruction that describes the task:
### Input:
Read a zero terminated (C style) string
### Response:
def write_c_string( self, value ):
"""
Read a zero terminated (C style) string
"""
self.file.write( value )
self.file.write( b'\0' ) |
def read_namespace_status(self, name, **kwargs): # noqa: E501
"""read_namespace_status # noqa: E501
read status of the specified Namespace # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>... | read_namespace_status # noqa: E501
read status of the specified Namespace # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespace_status(name, async_req=True)
>>> res... | Below is the the instruction that describes the task:
### Input:
read_namespace_status # noqa: E501
read status of the specified Namespace # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thr... |
def from_ISO_8601(cls, date_string, time_string, tz_string):
"""Sufficiently general ISO 8601 parser.
Inputs must be in "basic" format, i.e. no '-' or ':' separators.
See https://en.wikipedia.org/wiki/ISO_8601
"""
# parse tz_string
if tz_string:
tz_offset = ... | Sufficiently general ISO 8601 parser.
Inputs must be in "basic" format, i.e. no '-' or ':' separators.
See https://en.wikipedia.org/wiki/ISO_8601 | Below is the the instruction that describes the task:
### Input:
Sufficiently general ISO 8601 parser.
Inputs must be in "basic" format, i.e. no '-' or ':' separators.
See https://en.wikipedia.org/wiki/ISO_8601
### Response:
def from_ISO_8601(cls, date_string, time_string, tz_string):
"""S... |
def parameters(self, params):
"""
Sets the list of search parameters to use.
:param params: list of AbstractSearchParameter objects
:type params: list
"""
array = JavaArray(jobject=JavaArray.new_instance("weka.core.setupgenerator.AbstractParameter", len(params)))
... | Sets the list of search parameters to use.
:param params: list of AbstractSearchParameter objects
:type params: list | Below is the the instruction that describes the task:
### Input:
Sets the list of search parameters to use.
:param params: list of AbstractSearchParameter objects
:type params: list
### Response:
def parameters(self, params):
"""
Sets the list of search parameters to use.
... |
def O(self):
"""
Pairwise strandedness matrix. Each cell contains whether i-th and j-th
contig are the same orientation +1, or opposite orientation -1.
"""
N = self.N
tig_to_idx = self.tig_to_idx
O = np.zeros((N, N), dtype=int)
for (at, bt), (strandedness,... | Pairwise strandedness matrix. Each cell contains whether i-th and j-th
contig are the same orientation +1, or opposite orientation -1. | Below is the the instruction that describes the task:
### Input:
Pairwise strandedness matrix. Each cell contains whether i-th and j-th
contig are the same orientation +1, or opposite orientation -1.
### Response:
def O(self):
"""
Pairwise strandedness matrix. Each cell contains whether i-t... |
def add(self, rulefactory):
"""Add a new rule or factory to the map and bind it. Requires that the
rule is not bound to another map.
:param rulefactory: a :class:`Rule` or :class:`RuleFactory`
"""
for rule in rulefactory.get_rules(self):
rule.bind(self)
... | Add a new rule or factory to the map and bind it. Requires that the
rule is not bound to another map.
:param rulefactory: a :class:`Rule` or :class:`RuleFactory` | Below is the the instruction that describes the task:
### Input:
Add a new rule or factory to the map and bind it. Requires that the
rule is not bound to another map.
:param rulefactory: a :class:`Rule` or :class:`RuleFactory`
### Response:
def add(self, rulefactory):
"""Add a new rule or... |
def comparison(self):
"""
comparison: expr (('==' | '!=' | '<=' | '>=' | '<' | '>') expr)*
"""
node = self.expr()
while self.token.nature in (
Nature.EQ,
Nature.NE,
Nature.LE,
Nature.GE,
Nature.LT,
Nature.GT... | comparison: expr (('==' | '!=' | '<=' | '>=' | '<' | '>') expr)* | Below is the the instruction that describes the task:
### Input:
comparison: expr (('==' | '!=' | '<=' | '>=' | '<' | '>') expr)*
### Response:
def comparison(self):
"""
comparison: expr (('==' | '!=' | '<=' | '>=' | '<' | '>') expr)*
"""
node = self.expr()
while self.token... |
def create_quiz_report(self, quiz_id, course_id, quiz_report_report_type, include=None, quiz_report_includes_all_versions=None):
"""
Create a quiz report.
Create and return a new report for this quiz. If a previously
generated report matches the arguments and is still current (i.e.... | Create a quiz report.
Create and return a new report for this quiz. If a previously
generated report matches the arguments and is still current (i.e.
there have been no new submissions), it will be returned.
*Responses*
* <code>400 Bad Request</code> if... | Below is the the instruction that describes the task:
### Input:
Create a quiz report.
Create and return a new report for this quiz. If a previously
generated report matches the arguments and is still current (i.e.
there have been no new submissions), it will be returned.
... |
def getinfo(self):
"""
Backwards-compatibility for 0.14 and later
"""
try:
old_getinfo = AuthServiceProxy(self.__service_url, 'getinfo', self.__timeout, self.__conn, True)
res = old_getinfo()
if 'error' not in res:
# 0.13 and earlier
... | Backwards-compatibility for 0.14 and later | Below is the the instruction that describes the task:
### Input:
Backwards-compatibility for 0.14 and later
### Response:
def getinfo(self):
"""
Backwards-compatibility for 0.14 and later
"""
try:
old_getinfo = AuthServiceProxy(self.__service_url, 'getinfo', self.__timeo... |
def _get_randomized_range(val,
provided_range,
default_range):
"""
Helper to initialize by either value or a range
Returns a range to randomize from
"""
if val is None:
if provided_range is None:
return default_range
... | Helper to initialize by either value or a range
Returns a range to randomize from | Below is the the instruction that describes the task:
### Input:
Helper to initialize by either value or a range
Returns a range to randomize from
### Response:
def _get_randomized_range(val,
provided_range,
default_range):
"""
Helper to initi... |
def find_newline(self, size=-1):
"""Search for newline char in buffer starting from current offset.
Args:
size: number of bytes to search. -1 means all.
Returns:
offset of newline char in buffer. -1 if doesn't exist.
"""
if size < 0:
return self._buffer.find('\n', self._offset)
... | Search for newline char in buffer starting from current offset.
Args:
size: number of bytes to search. -1 means all.
Returns:
offset of newline char in buffer. -1 if doesn't exist. | Below is the the instruction that describes the task:
### Input:
Search for newline char in buffer starting from current offset.
Args:
size: number of bytes to search. -1 means all.
Returns:
offset of newline char in buffer. -1 if doesn't exist.
### Response:
def find_newline(self, size=-1):
... |
def get_rate(self, zipcode, city=None, state=None, multiple_rates=False):
"""
Finds sales tax for given info.
Returns Decimal of the tax rate, e.g. 8.750.
"""
data = self.make_request_data(zipcode, city, state)
r = requests.get(self.url, params=data)
resp = r.jso... | Finds sales tax for given info.
Returns Decimal of the tax rate, e.g. 8.750. | Below is the the instruction that describes the task:
### Input:
Finds sales tax for given info.
Returns Decimal of the tax rate, e.g. 8.750.
### Response:
def get_rate(self, zipcode, city=None, state=None, multiple_rates=False):
"""
Finds sales tax for given info.
Returns Decimal o... |
def load_data_old(self):
"""
Loads time series of 2D data grids from each opened file. The code
handles loading a full time series from one file or individual time steps
from multiple files. Missing files are supported.
"""
units = ""
if len(self.file_objects) ==... | Loads time series of 2D data grids from each opened file. The code
handles loading a full time series from one file or individual time steps
from multiple files. Missing files are supported. | Below is the the instruction that describes the task:
### Input:
Loads time series of 2D data grids from each opened file. The code
handles loading a full time series from one file or individual time steps
from multiple files. Missing files are supported.
### Response:
def load_data_old(self):
... |
def to_range(obj, score=None, id=None, strand=None):
"""
Given a gffutils object, convert it to a range object
"""
from jcvi.utils.range import Range
if score or id:
_score = score if score else obj.score
_id = id if id else obj.id
return Range(seqid=obj.seqid, start=obj.sta... | Given a gffutils object, convert it to a range object | Below is the the instruction that describes the task:
### Input:
Given a gffutils object, convert it to a range object
### Response:
def to_range(obj, score=None, id=None, strand=None):
"""
Given a gffutils object, convert it to a range object
"""
from jcvi.utils.range import Range
if score or... |
def parse(inp, format=None, encoding='utf-8', force_types=True):
"""Parse input from file-like object, unicode string or byte string.
Args:
inp: file-like object, unicode string or byte string with the markup
format: explicitly override the guessed `inp` markup format
encoding: `inp` en... | Parse input from file-like object, unicode string or byte string.
Args:
inp: file-like object, unicode string or byte string with the markup
format: explicitly override the guessed `inp` markup format
encoding: `inp` encoding, defaults to utf-8
force_types:
if `True`, in... | Below is the the instruction that describes the task:
### Input:
Parse input from file-like object, unicode string or byte string.
Args:
inp: file-like object, unicode string or byte string with the markup
format: explicitly override the guessed `inp` markup format
encoding: `inp` encod... |
def list(self, size=1000, tree_depth=1):
""" Creates a random #list
@size: #int number of random values to include in each @tree_depth
@tree_depth: #int dict tree dimensions size, i.e.
1=|[value1, value2]|
2=|[[value1, value2], [value1, value2]]|
... | Creates a random #list
@size: #int number of random values to include in each @tree_depth
@tree_depth: #int dict tree dimensions size, i.e.
1=|[value1, value2]|
2=|[[value1, value2], [value1, value2]]|
-> random #list | Below is the the instruction that describes the task:
### Input:
Creates a random #list
@size: #int number of random values to include in each @tree_depth
@tree_depth: #int dict tree dimensions size, i.e.
1=|[value1, value2]|
2=|[[value1, value2], [value1, va... |
def printArray(self, node, printState: PrintState):
""" Prints out the array declaration in a format of Array class
object declaration. 'arrayName = Array(Type, [bounds])'
"""
if (
self.nameMapper[node["name"]] not in printState.definedVars
and self.nameMapper... | Prints out the array declaration in a format of Array class
object declaration. 'arrayName = Array(Type, [bounds])' | Below is the the instruction that describes the task:
### Input:
Prints out the array declaration in a format of Array class
object declaration. 'arrayName = Array(Type, [bounds])'
### Response:
def printArray(self, node, printState: PrintState):
""" Prints out the array declaration in a format... |
def zeros_like(array, dtype=None, keepmeta=True):
"""Create an array of zeros with the same shape and type as the input array.
Args:
array (xarray.DataArray): The shape and data-type of it define
these same attributes of the output array.
dtype (data-type, optional): If specified, t... | Create an array of zeros with the same shape and type as the input array.
Args:
array (xarray.DataArray): The shape and data-type of it define
these same attributes of the output array.
dtype (data-type, optional): If specified, this function overrides
the data-type of the o... | Below is the the instruction that describes the task:
### Input:
Create an array of zeros with the same shape and type as the input array.
Args:
array (xarray.DataArray): The shape and data-type of it define
these same attributes of the output array.
dtype (data-type, optional): If ... |
def to_representation(self, instance):
"""
Return the updated course data dictionary.
Arguments:
instance (dict): The course data.
Returns:
dict: The updated course data.
"""
updated_course = copy.deepcopy(instance)
enterprise_customer_ca... | Return the updated course data dictionary.
Arguments:
instance (dict): The course data.
Returns:
dict: The updated course data. | Below is the the instruction that describes the task:
### Input:
Return the updated course data dictionary.
Arguments:
instance (dict): The course data.
Returns:
dict: The updated course data.
### Response:
def to_representation(self, instance):
"""
Return ... |
def change_cloud_password(
self,
current_password: str,
new_password: str,
new_hint: str = ""
) -> bool:
"""Use this method to change your Two-Step Verification password (Cloud Password) with a new one.
Args:
current_password (``str``):
Yo... | Use this method to change your Two-Step Verification password (Cloud Password) with a new one.
Args:
current_password (``str``):
Your current password.
new_password (``str``):
Your new password.
new_hint (``str``, *optional*):
... | Below is the the instruction that describes the task:
### Input:
Use this method to change your Two-Step Verification password (Cloud Password) with a new one.
Args:
current_password (``str``):
Your current password.
new_password (``str``):
Your new ... |
def sludge(self, column=None, value=None, **kwargs):
"""
Sludge information describes the volumn of sludge produced at a
facility, identification information on a sludge handler, and
classification/permitting information on a facility that handles
sludge, such as a pretreatment P... | Sludge information describes the volumn of sludge produced at a
facility, identification information on a sludge handler, and
classification/permitting information on a facility that handles
sludge, such as a pretreatment POTW.
>>> PCS().sludge('county_name', 'San Francisco') | Below is the the instruction that describes the task:
### Input:
Sludge information describes the volumn of sludge produced at a
facility, identification information on a sludge handler, and
classification/permitting information on a facility that handles
sludge, such as a pretreatment POTW.... |
def __split_file(self):
'''
Splits combined SAR output file (in ASCII format) in order to
extract info we need for it, in the format we want.
:return: ``List``-style of SAR file sections separated by
the type of info they contain (SAR file sections) without
... | Splits combined SAR output file (in ASCII format) in order to
extract info we need for it, in the format we want.
:return: ``List``-style of SAR file sections separated by
the type of info they contain (SAR file sections) without
parsing what is exactly what at this p... | Below is the the instruction that describes the task:
### Input:
Splits combined SAR output file (in ASCII format) in order to
extract info we need for it, in the format we want.
:return: ``List``-style of SAR file sections separated by
the type of info they contain (SAR file sec... |
def __validate_datetime_string(self):
"""
This will require validating version string (such as "3.3.5").
A version string could be converted to a datetime value if this
validation is not executed.
"""
try:
try:
StrictVersion(self._value)
... | This will require validating version string (such as "3.3.5").
A version string could be converted to a datetime value if this
validation is not executed. | Below is the the instruction that describes the task:
### Input:
This will require validating version string (such as "3.3.5").
A version string could be converted to a datetime value if this
validation is not executed.
### Response:
def __validate_datetime_string(self):
"""
This wi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.