code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def context_id(self):
"""Return this Async's Context Id if it exists."""
if not self._context_id:
self._context_id = self._get_context_id()
self.update_options(context_id=self._context_id)
return self._context_id | Return this Async's Context Id if it exists. | Below is the the instruction that describes the task:
### Input:
Return this Async's Context Id if it exists.
### Response:
def context_id(self):
"""Return this Async's Context Id if it exists."""
if not self._context_id:
self._context_id = self._get_context_id()
self.update... |
def losses_by_period(losses, return_periods, num_events=None, eff_time=None):
"""
:param losses: array of simulated losses
:param return_periods: return periods of interest
:param num_events: the number of events (>= to the number of losses)
:param eff_time: investigation_time * ses_per_logic_tree_p... | :param losses: array of simulated losses
:param return_periods: return periods of interest
:param num_events: the number of events (>= to the number of losses)
:param eff_time: investigation_time * ses_per_logic_tree_path
:returns: interpolated losses for the return periods, possibly with NaN
NB: t... | Below is the the instruction that describes the task:
### Input:
:param losses: array of simulated losses
:param return_periods: return periods of interest
:param num_events: the number of events (>= to the number of losses)
:param eff_time: investigation_time * ses_per_logic_tree_path
:returns: int... |
def make_figure(plots):
"""
:param plots: list of pairs (task_name, memory array)
"""
# NB: matplotlib is imported inside since it is a costly import
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.grid(True)
ax.set_xlabel('tasks')
ax.set_ylabel('GB')
start = 0
f... | :param plots: list of pairs (task_name, memory array) | Below is the the instruction that describes the task:
### Input:
:param plots: list of pairs (task_name, memory array)
### Response:
def make_figure(plots):
"""
:param plots: list of pairs (task_name, memory array)
"""
# NB: matplotlib is imported inside since it is a costly import
import matpl... |
def get_catalogs_by_query(self, catalog_query):
"""Gets a list of ``Catalogs`` matching the given catalog query.
arg: catalog_query (osid.cataloging.CatalogQuery): the
catalog query
return: (osid.cataloging.CatalogList) - the returned
``CatalogList``
r... | Gets a list of ``Catalogs`` matching the given catalog query.
arg: catalog_query (osid.cataloging.CatalogQuery): the
catalog query
return: (osid.cataloging.CatalogList) - the returned
``CatalogList``
raise: NullArgument - ``catalog_query`` is ``null``
... | Below is the the instruction that describes the task:
### Input:
Gets a list of ``Catalogs`` matching the given catalog query.
arg: catalog_query (osid.cataloging.CatalogQuery): the
catalog query
return: (osid.cataloging.CatalogList) - the returned
``CatalogList``... |
def refresh(self) -> None:
"""Prepare the actual |anntools.SeasonalANN| object for calculations.
Dispite all automated refreshings explained in the general
documentation on class |anntools.SeasonalANN|, it is still possible
to destroy the inner consistency of a |anntools.SeasonalANN| in... | Prepare the actual |anntools.SeasonalANN| object for calculations.
Dispite all automated refreshings explained in the general
documentation on class |anntools.SeasonalANN|, it is still possible
to destroy the inner consistency of a |anntools.SeasonalANN| instance,
as it stores its |annt... | Below is the the instruction that describes the task:
### Input:
Prepare the actual |anntools.SeasonalANN| object for calculations.
Dispite all automated refreshings explained in the general
documentation on class |anntools.SeasonalANN|, it is still possible
to destroy the inner consistency... |
def update_resources(self, dstpath, names=None, languages=None):
""" Update or add manifest resource in dll/exe file dstpath """
UpdateManifestResourcesFromXML(dstpath, self.toprettyxml(), names,
languages) | Update or add manifest resource in dll/exe file dstpath | Below is the the instruction that describes the task:
### Input:
Update or add manifest resource in dll/exe file dstpath
### Response:
def update_resources(self, dstpath, names=None, languages=None):
""" Update or add manifest resource in dll/exe file dstpath """
UpdateManifestResourcesFromXML(dstp... |
def get_sonos_playlist_by_attr(self, attr_name, match):
"""Return the first Sonos Playlist DidlPlaylistContainer that
matches the attribute specified.
Args:
attr_name (str): DidlPlaylistContainer attribute to compare. The
most useful being: 'title' and 'item_id'.
... | Return the first Sonos Playlist DidlPlaylistContainer that
matches the attribute specified.
Args:
attr_name (str): DidlPlaylistContainer attribute to compare. The
most useful being: 'title' and 'item_id'.
match (str): Value to match.
Returns:
... | Below is the the instruction that describes the task:
### Input:
Return the first Sonos Playlist DidlPlaylistContainer that
matches the attribute specified.
Args:
attr_name (str): DidlPlaylistContainer attribute to compare. The
most useful being: 'title' and 'item_id'.
... |
def check_datasource_perms(self, datasource_type=None, datasource_id=None):
"""
Check if user can access a cached response from explore_json.
This function takes `self` since it must have the same signature as the
the decorated method.
"""
form_data = get_form_data()[0]
datasource_id, data... | Check if user can access a cached response from explore_json.
This function takes `self` since it must have the same signature as the
the decorated method. | Below is the the instruction that describes the task:
### Input:
Check if user can access a cached response from explore_json.
This function takes `self` since it must have the same signature as the
the decorated method.
### Response:
def check_datasource_perms(self, datasource_type=None, datasource_id=No... |
def check_overlap(a, b):
"""Check for wavelength overlap between two spectra.
.. note::
Generalized from
:meth:`pysynphot.spectrum.SpectralElement.check_overlap`.
Parameters
----------
a, b : `~pysynphot.spectrum.SourceSpectrum` or `~pysynphot.spectrum.SpectralElement`
Typi... | Check for wavelength overlap between two spectra.
.. note::
Generalized from
:meth:`pysynphot.spectrum.SpectralElement.check_overlap`.
Parameters
----------
a, b : `~pysynphot.spectrum.SourceSpectrum` or `~pysynphot.spectrum.SpectralElement`
Typically a source spectrum, spectra... | Below is the the instruction that describes the task:
### Input:
Check for wavelength overlap between two spectra.
.. note::
Generalized from
:meth:`pysynphot.spectrum.SpectralElement.check_overlap`.
Parameters
----------
a, b : `~pysynphot.spectrum.SourceSpectrum` or `~pysynphot.... |
def with_port(self, port):
"""Return a new URL with port replaced.
Clear port to default if None is passed.
"""
# N.B. doesn't cleanup query/fragment
if port is not None and not isinstance(port, int):
raise TypeError("port should be int or None, got {}".format(type(... | Return a new URL with port replaced.
Clear port to default if None is passed. | Below is the the instruction that describes the task:
### Input:
Return a new URL with port replaced.
Clear port to default if None is passed.
### Response:
def with_port(self, port):
"""Return a new URL with port replaced.
Clear port to default if None is passed.
"""
# N... |
def getElementDeclaration(cls, namespaceURI, name, isref=False, lazy=False):
'''Grab an element declaration, returns a typecode instance
representation or a typecode class definition. An element
reference has its own facets, and is local so it will not be
cached.
Parameters:
... | Grab an element declaration, returns a typecode instance
representation or a typecode class definition. An element
reference has its own facets, and is local so it will not be
cached.
Parameters:
namespaceURI --
name --
isref -- if element referen... | Below is the the instruction that describes the task:
### Input:
Grab an element declaration, returns a typecode instance
representation or a typecode class definition. An element
reference has its own facets, and is local so it will not be
cached.
Parameters:
namespac... |
def get_layer_output(self, name):
'''Get symbolic output of a layer.'''
if not name in self._f_layer_outputs:
layer = self.net.get_layer(name)
self._f_layer_outputs[name] = layer.output
return self._f_layer_outputs[name] | Get symbolic output of a layer. | Below is the the instruction that describes the task:
### Input:
Get symbolic output of a layer.
### Response:
def get_layer_output(self, name):
'''Get symbolic output of a layer.'''
if not name in self._f_layer_outputs:
layer = self.net.get_layer(name)
self._f_layer_outputs... |
def run_healthchecks(self):
"""
Runs all registered healthchecks and returns a list of
HealthcheckResponse.
"""
if not self._registry_loaded:
self.load_healthchecks()
def get_healthcheck_name(hc):
if hasattr(hc, 'name'):
return hc.... | Runs all registered healthchecks and returns a list of
HealthcheckResponse. | Below is the the instruction that describes the task:
### Input:
Runs all registered healthchecks and returns a list of
HealthcheckResponse.
### Response:
def run_healthchecks(self):
"""
Runs all registered healthchecks and returns a list of
HealthcheckResponse.
"""
... |
def mean_harmonic(self):
'返回DataStruct.price的调和平均数'
res = self.price.groupby(level=1
).apply(lambda x: statistics.harmonic_mean(x))
res.name = 'mean_harmonic'
return res | 返回DataStruct.price的调和平均数 | Below is the the instruction that describes the task:
### Input:
返回DataStruct.price的调和平均数
### Response:
def mean_harmonic(self):
'返回DataStruct.price的调和平均数'
res = self.price.groupby(level=1
).apply(lambda x: statistics.harmonic_mean(x))
res.name = 'mean_harmon... |
def create_api_key(self):
"""Create API Key for API access."""
apikeys = self.client.get_api_keys()
for key in apikeys['items']:
if key['name'] == self.app_name:
self.log.info("Key %s already exists", self.app_name)
break
else:
self... | Create API Key for API access. | Below is the the instruction that describes the task:
### Input:
Create API Key for API access.
### Response:
def create_api_key(self):
"""Create API Key for API access."""
apikeys = self.client.get_api_keys()
for key in apikeys['items']:
if key['name'] == self.app_name:
... |
def atq(tag=None):
'''
List all queued and running jobs or only those with
an optional 'tag'.
CLI Example:
.. code-block:: bash
salt '*' at.atq
salt '*' at.atq [tag]
salt '*' at.atq [job number]
'''
jobs = []
# Shim to produce output similar to what __virtual_... | List all queued and running jobs or only those with
an optional 'tag'.
CLI Example:
.. code-block:: bash
salt '*' at.atq
salt '*' at.atq [tag]
salt '*' at.atq [job number] | Below is the the instruction that describes the task:
### Input:
List all queued and running jobs or only those with
an optional 'tag'.
CLI Example:
.. code-block:: bash
salt '*' at.atq
salt '*' at.atq [tag]
salt '*' at.atq [job number]
### Response:
def atq(tag=None):
''... |
def get_current_selection(self, i=None):
"""Get the :class:`TaskFileInfo` for the file selected in the active tab
:param i: If None, returns selection of active tab. If 0, assetselection. If 1, shotselection
:type i:
:returns: The taskfile info in the currently active tab
:rtype... | Get the :class:`TaskFileInfo` for the file selected in the active tab
:param i: If None, returns selection of active tab. If 0, assetselection. If 1, shotselection
:type i:
:returns: The taskfile info in the currently active tab
:rtype: :class:`TaskFileInfo` | None
:raises: None | Below is the the instruction that describes the task:
### Input:
Get the :class:`TaskFileInfo` for the file selected in the active tab
:param i: If None, returns selection of active tab. If 0, assetselection. If 1, shotselection
:type i:
:returns: The taskfile info in the currently active t... |
def make_plot(self):
"""Make the horizon plot.
"""
self.get_contour_values()
# sets levels of main contour plot
colors1 = ['blue', 'green', 'red', 'purple', 'orange',
'gold', 'magenta']
# set contour value. Default is SNR_CUT.
self.snr_contou... | Make the horizon plot. | Below is the the instruction that describes the task:
### Input:
Make the horizon plot.
### Response:
def make_plot(self):
"""Make the horizon plot.
"""
self.get_contour_values()
# sets levels of main contour plot
colors1 = ['blue', 'green', 'red', 'purple', 'orange',
... |
def ani_depthplot2(ani_file='rmag_anisotropy.txt', meas_file='magic_measurements.txt', samp_file='er_samples.txt', age_file=None, sum_file=None, fmt='svg', dmin=-1, dmax=-1, depth_scale='sample_core_depth', dir_path='.'):
"""
returns matplotlib figure with anisotropy data plotted against depth
available dep... | returns matplotlib figure with anisotropy data plotted against depth
available depth scales: 'sample_composite_depth', 'sample_core_depth', or 'age' (you must provide an age file to use this option) | Below is the the instruction that describes the task:
### Input:
returns matplotlib figure with anisotropy data plotted against depth
available depth scales: 'sample_composite_depth', 'sample_core_depth', or 'age' (you must provide an age file to use this option)
### Response:
def ani_depthplot2(ani_file='rmag... |
def factor_cumulative_returns(factor_data,
period,
long_short=True,
group_neutral=False,
equal_weight=False,
quantiles=None,
groups=None):
... | Simulate a portfolio using the factor in input and returns the cumulative
returns of the simulated portfolio
Parameters
----------
factor_data : pd.DataFrame - MultiIndex
A MultiIndex DataFrame indexed by date (level 0) and asset (level 1),
containing the values for a single alpha facto... | Below is the the instruction that describes the task:
### Input:
Simulate a portfolio using the factor in input and returns the cumulative
returns of the simulated portfolio
Parameters
----------
factor_data : pd.DataFrame - MultiIndex
A MultiIndex DataFrame indexed by date (level 0) and as... |
def get_chrom_for_transcript(self, transcript_id, hgnc_id):
""" obtain the sequence for a transcript from ensembl
"""
headers = {"content-type": "application/json"}
self.attempt = 0
ext = "/overlap/id/{}?feature=gene".format(transcript_id)
r = self.ense... | obtain the sequence for a transcript from ensembl | Below is the the instruction that describes the task:
### Input:
obtain the sequence for a transcript from ensembl
### Response:
def get_chrom_for_transcript(self, transcript_id, hgnc_id):
""" obtain the sequence for a transcript from ensembl
"""
headers = {"content-type": "applica... |
def _state(self):
"""The internal state of the object.
The api responses are not consistent so a retry is performed on every
call with information updating the internally saved state refreshing
the data. The info is cached for STATE_CACHING_SECONDS.
:return: The current state o... | The internal state of the object.
The api responses are not consistent so a retry is performed on every
call with information updating the internally saved state refreshing
the data. The info is cached for STATE_CACHING_SECONDS.
:return: The current state of the toons' information stat... | Below is the the instruction that describes the task:
### Input:
The internal state of the object.
The api responses are not consistent so a retry is performed on every
call with information updating the internally saved state refreshing
the data. The info is cached for STATE_CACHING_SECOND... |
def summary_by_datacenter(self):
"""Summary of the networks on the account, grouped by data center.
The resultant dictionary is primarily useful for statistical purposes.
It contains count information rather than raw data. If you want raw
information, see the :func:`list_vlans` method i... | Summary of the networks on the account, grouped by data center.
The resultant dictionary is primarily useful for statistical purposes.
It contains count information rather than raw data. If you want raw
information, see the :func:`list_vlans` method instead.
:returns: A dictionary keye... | Below is the the instruction that describes the task:
### Input:
Summary of the networks on the account, grouped by data center.
The resultant dictionary is primarily useful for statistical purposes.
It contains count information rather than raw data. If you want raw
information, see the :f... |
def pwd(self, **kwargs):
"""
Returns the cwd
Optional kwargs:
node = <node>
If specified, return only the directory name at depth <node>.
"""
b_node = False
node = 0
for key,val in kwargs.items():... | Returns the cwd
Optional kwargs:
node = <node>
If specified, return only the directory name at depth <node>. | Below is the the instruction that describes the task:
### Input:
Returns the cwd
Optional kwargs:
node = <node>
If specified, return only the directory name at depth <node>.
### Response:
def pwd(self, **kwargs):
"""
Returns the cwd
... |
def ls_command(
endpoint_plus_path,
recursive_depth_limit,
recursive,
long_output,
show_hidden,
filter_val,
):
"""
Executor for `globus ls`
"""
endpoint_id, path = endpoint_plus_path
# do autoactivation before the `ls` call so that recursive invocations
# won't do this r... | Executor for `globus ls` | Below is the the instruction that describes the task:
### Input:
Executor for `globus ls`
### Response:
def ls_command(
endpoint_plus_path,
recursive_depth_limit,
recursive,
long_output,
show_hidden,
filter_val,
):
"""
Executor for `globus ls`
"""
endpoint_id, path = endpoin... |
def _nama(self):
"""Mengembalikan representasi string untuk nama entri ini.
:returns: String representasi nama entri
:rtype: str
"""
hasil = self.nama
if self.nomor:
hasil += " [{}]".format(self.nomor)
if self.kata_dasar:
hasil = " » ".jo... | Mengembalikan representasi string untuk nama entri ini.
:returns: String representasi nama entri
:rtype: str | Below is the the instruction that describes the task:
### Input:
Mengembalikan representasi string untuk nama entri ini.
:returns: String representasi nama entri
:rtype: str
### Response:
def _nama(self):
"""Mengembalikan representasi string untuk nama entri ini.
:returns: String ... |
def calculate_auc_covar(auc_structure1, auc_structure2):
"""
determine AUC covariance due to actives (covar_a) and decoys (covar_d)
:param auc_structure1: list [(id, best_score, best_query, status, fpf, tpf), ...,]
:param auc_structure2: list [(id, best_score, best_query, status, fpf, tpf), ...,]
:r... | determine AUC covariance due to actives (covar_a) and decoys (covar_d)
:param auc_structure1: list [(id, best_score, best_query, status, fpf, tpf), ...,]
:param auc_structure2: list [(id, best_score, best_query, status, fpf, tpf), ...,]
:return (covar_a, covar_d): tuple | Below is the the instruction that describes the task:
### Input:
determine AUC covariance due to actives (covar_a) and decoys (covar_d)
:param auc_structure1: list [(id, best_score, best_query, status, fpf, tpf), ...,]
:param auc_structure2: list [(id, best_score, best_query, status, fpf, tpf), ...,]
:r... |
def _read_bytes_from_framed_body(self, b):
"""Reads the requested number of bytes from a streaming framed message body.
:param int b: Number of bytes to read
:returns: Bytes read from source stream and decrypted
:rtype: bytes
"""
plaintext = b""
final_frame = Fal... | Reads the requested number of bytes from a streaming framed message body.
:param int b: Number of bytes to read
:returns: Bytes read from source stream and decrypted
:rtype: bytes | Below is the the instruction that describes the task:
### Input:
Reads the requested number of bytes from a streaming framed message body.
:param int b: Number of bytes to read
:returns: Bytes read from source stream and decrypted
:rtype: bytes
### Response:
def _read_bytes_from_framed_bod... |
def format_string(self, fmat_string):
"""
Takes a string containing 0 or more {variables} and formats it
according to this instance's attributes.
:param fmat_string: A string, e.g. '{name}-foo.txt'
:type fmat_string: ``str``
:return: The string formatted according to th... | Takes a string containing 0 or more {variables} and formats it
according to this instance's attributes.
:param fmat_string: A string, e.g. '{name}-foo.txt'
:type fmat_string: ``str``
:return: The string formatted according to this instance. E.g.
'production-runtime-foo... | Below is the the instruction that describes the task:
### Input:
Takes a string containing 0 or more {variables} and formats it
according to this instance's attributes.
:param fmat_string: A string, e.g. '{name}-foo.txt'
:type fmat_string: ``str``
:return: The string formatted acco... |
def for_web(self, data):
"""
Convert data to web output.
Parameters
----------
data : array
Returns
-------
web data : array
"""
rgba = self._prepare_array_for_png(data)
data = ma.masked_where(rgba == self.nodata, rgba)
re... | Convert data to web output.
Parameters
----------
data : array
Returns
-------
web data : array | Below is the the instruction that describes the task:
### Input:
Convert data to web output.
Parameters
----------
data : array
Returns
-------
web data : array
### Response:
def for_web(self, data):
"""
Convert data to web output.
Paramete... |
def persist(self, context):
"""Update or insert the session document into the configured collection"""
D = self._Document
document = context.session[self.name]
D.get_collection().replace_one(D.id == document.id, document, True) | Update or insert the session document into the configured collection | Below is the the instruction that describes the task:
### Input:
Update or insert the session document into the configured collection
### Response:
def persist(self, context):
"""Update or insert the session document into the configured collection"""
D = self._Document
document = context.session[self.name... |
def preview(self, components=None, ask=0):
"""
Inspects differences between the last deployment and the current code state.
"""
ask = int(ask)
self.init()
component_order, plan_funcs = self.get_component_funcs(components=components)
print('\n%i changes found f... | Inspects differences between the last deployment and the current code state. | Below is the the instruction that describes the task:
### Input:
Inspects differences between the last deployment and the current code state.
### Response:
def preview(self, components=None, ask=0):
"""
Inspects differences between the last deployment and the current code state.
"""
... |
def dn(self, fraction, n=None):
r'''Computes the diameter at which a specified `fraction` of the
distribution falls under. Utilizes a bounded solver to search for the
desired diameter.
Parameters
----------
fraction : float
Fraction of the distribution which... | r'''Computes the diameter at which a specified `fraction` of the
distribution falls under. Utilizes a bounded solver to search for the
desired diameter.
Parameters
----------
fraction : float
Fraction of the distribution which should be under the calculated
... | Below is the the instruction that describes the task:
### Input:
r'''Computes the diameter at which a specified `fraction` of the
distribution falls under. Utilizes a bounded solver to search for the
desired diameter.
Parameters
----------
fraction : float
Fract... |
def _new(self, dx_hash, media_type=None, **kwargs):
"""
:param dx_hash: Standard hash populated in :func:`dxpy.bindings.DXDataObject.new()` containing attributes common to all data object classes.
:type dx_hash: dict
:param media_type: Internet Media Type
:type media_type: string... | :param dx_hash: Standard hash populated in :func:`dxpy.bindings.DXDataObject.new()` containing attributes common to all data object classes.
:type dx_hash: dict
:param media_type: Internet Media Type
:type media_type: string
Creates a new remote file with media type *media_type*, if giv... | Below is the the instruction that describes the task:
### Input:
:param dx_hash: Standard hash populated in :func:`dxpy.bindings.DXDataObject.new()` containing attributes common to all data object classes.
:type dx_hash: dict
:param media_type: Internet Media Type
:type media_type: string
... |
def pad(self, pad):
"""
Pad this tile by an equal amount on each side as specified by pad
>>> Tile(10).pad(2)
Tile [-2, -2, -2] -> [12, 12, 12] ([14, 14, 14])
>>> Tile(10).pad([1,2,3])
Tile [-1, -2, -3] -> [11, 12, 13] ([12, 14, 16])
"""
tile = self.copy... | Pad this tile by an equal amount on each side as specified by pad
>>> Tile(10).pad(2)
Tile [-2, -2, -2] -> [12, 12, 12] ([14, 14, 14])
>>> Tile(10).pad([1,2,3])
Tile [-1, -2, -3] -> [11, 12, 13] ([12, 14, 16]) | Below is the the instruction that describes the task:
### Input:
Pad this tile by an equal amount on each side as specified by pad
>>> Tile(10).pad(2)
Tile [-2, -2, -2] -> [12, 12, 12] ([14, 14, 14])
>>> Tile(10).pad([1,2,3])
Tile [-1, -2, -3] -> [11, 12, 13] ([12, 14, 16])
### Res... |
def get_lldp_neighbor_detail_output_lldp_neighbor_detail_remote_port_description(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_lldp_neighbor_detail = ET.Element("get_lldp_neighbor_detail")
config = get_lldp_neighbor_detail
output = ET.SubEl... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def get_lldp_neighbor_detail_output_lldp_neighbor_detail_remote_port_description(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_lldp_neighbor_detail = ET... |
def verify2(self):
"""Last verification step.
The derived keys (output, input) are returned here.
"""
output_key = hkdf_expand('MediaRemote-Salt',
'MediaRemote-Write-Encryption-Key',
self._shared)
input_key = hkd... | Last verification step.
The derived keys (output, input) are returned here. | Below is the the instruction that describes the task:
### Input:
Last verification step.
The derived keys (output, input) are returned here.
### Response:
def verify2(self):
"""Last verification step.
The derived keys (output, input) are returned here.
"""
output_key = hkd... |
def save(self):
"""Convert to JSON.
Returns
-------
`dict`
JSON data.
"""
data = super().save()
data['end_chars'] = self.end_chars
data['default_end'] = self.default_end
return data | Convert to JSON.
Returns
-------
`dict`
JSON data. | Below is the the instruction that describes the task:
### Input:
Convert to JSON.
Returns
-------
`dict`
JSON data.
### Response:
def save(self):
"""Convert to JSON.
Returns
-------
`dict`
JSON data.
"""
data = super(... |
def TextWidget(*args, **kw):
"""Forces a parameter value to be text"""
kw['value'] = str(kw['value'])
kw.pop('options', None)
return TextInput(*args,**kw) | Forces a parameter value to be text | Below is the the instruction that describes the task:
### Input:
Forces a parameter value to be text
### Response:
def TextWidget(*args, **kw):
"""Forces a parameter value to be text"""
kw['value'] = str(kw['value'])
kw.pop('options', None)
return TextInput(*args,**kw) |
def is_data_value(searchpath, searchtree, dtype = None, empty_is_false = False):
"""
Follow searchpath through the datatree in searchtree
and report if there exists a value of type dtype
searchpath is a list of keys/indices
If dtype is None check for any value
you can also supply a tuple to dty... | Follow searchpath through the datatree in searchtree
and report if there exists a value of type dtype
searchpath is a list of keys/indices
If dtype is None check for any value
you can also supply a tuple to dtype | Below is the the instruction that describes the task:
### Input:
Follow searchpath through the datatree in searchtree
and report if there exists a value of type dtype
searchpath is a list of keys/indices
If dtype is None check for any value
you can also supply a tuple to dtype
### Response:
def is... |
def __apply_nested_option(self, option_name, field_names, set_operation):
"""Apply nested options to nested fields"""
# Split nested field names on the first dot.
nested_fields = [name.split('.', 1) for name in field_names if '.' in name]
# Partition the nested field names by parent fiel... | Apply nested options to nested fields | Below is the the instruction that describes the task:
### Input:
Apply nested options to nested fields
### Response:
def __apply_nested_option(self, option_name, field_names, set_operation):
"""Apply nested options to nested fields"""
# Split nested field names on the first dot.
nested_fiel... |
def _postprocess_options(dbg, opts):
''' Handle options (`opts') that feed into the debugger (`dbg')'''
# Set dbg.settings['printset']
print_events = []
if opts.fntrace: print_events = ['c_call', 'c_return', 'call', 'return']
# if opts.linetrace: print_events += ['line']
if len(print_events):
... | Handle options (`opts') that feed into the debugger (`dbg') | Below is the the instruction that describes the task:
### Input:
Handle options (`opts') that feed into the debugger (`dbg')
### Response:
def _postprocess_options(dbg, opts):
''' Handle options (`opts') that feed into the debugger (`dbg')'''
# Set dbg.settings['printset']
print_events = []
if opts... |
def add_definition_tags(self, tags, project, definition_id):
"""AddDefinitionTags.
[Preview API] Adds multiple tags to a definition.
:param [str] tags: The tags to add.
:param str project: Project ID or project name
:param int definition_id: The ID of the definition.
:rty... | AddDefinitionTags.
[Preview API] Adds multiple tags to a definition.
:param [str] tags: The tags to add.
:param str project: Project ID or project name
:param int definition_id: The ID of the definition.
:rtype: [str] | Below is the the instruction that describes the task:
### Input:
AddDefinitionTags.
[Preview API] Adds multiple tags to a definition.
:param [str] tags: The tags to add.
:param str project: Project ID or project name
:param int definition_id: The ID of the definition.
:rtype:... |
def collect_reponames():
"""
Try to figure out a list of repos to consider by default from the contents of the working directory.
"""
reponames = []
#try to figure out the repo from git repo in current directory
try:
with open(os.devnull) as devnull:
remote_data = subprocess.check_output(["git","remote","-v... | Try to figure out a list of repos to consider by default from the contents of the working directory. | Below is the the instruction that describes the task:
### Input:
Try to figure out a list of repos to consider by default from the contents of the working directory.
### Response:
def collect_reponames():
"""
Try to figure out a list of repos to consider by default from the contents of the working directory.
""... |
def remove_user(self, name, session=None):
"""**DEPRECATED**: Remove user `name` from this :class:`Database`.
User `name` will no longer have permissions to access this
:class:`Database`.
.. note:: remove_user is deprecated and will be removed in PyMongo
4.0. Use the dropUser... | **DEPRECATED**: Remove user `name` from this :class:`Database`.
User `name` will no longer have permissions to access this
:class:`Database`.
.. note:: remove_user is deprecated and will be removed in PyMongo
4.0. Use the dropUser command instead::
db.command("dropUser",... | Below is the the instruction that describes the task:
### Input:
**DEPRECATED**: Remove user `name` from this :class:`Database`.
User `name` will no longer have permissions to access this
:class:`Database`.
.. note:: remove_user is deprecated and will be removed in PyMongo
4.0. U... |
def render(self, name=None, template=None, context={}):
''''Render Template meta from jinja2 templates.
'''
if isinstance(template, Template):
_template = template
else:
_template = Template.objects.get(name=name)
# Maybe cache or save local ?
r... | Render Template meta from jinja2 templates. | Below is the the instruction that describes the task:
### Input:
Render Template meta from jinja2 templates.
### Response:
def render(self, name=None, template=None, context={}):
''''Render Template meta from jinja2 templates.
'''
if isinstance(template, Template):
_template =... |
def slew(self, value):
'''move to a given position in the file'''
if float(value) != self.filepos:
pos = float(value) * self.filesize
self.mlog.f.seek(int(pos))
self.find_message() | move to a given position in the file | Below is the the instruction that describes the task:
### Input:
move to a given position in the file
### Response:
def slew(self, value):
'''move to a given position in the file'''
if float(value) != self.filepos:
pos = float(value) * self.filesize
self.mlog.f.seek(int(pos)... |
def do_mode(self, target, msg, nick, send):
"""reop and handle guard violations."""
mode_changes = irc.modes.parse_channel_modes(msg)
with self.data_lock:
for change in mode_changes:
if change[1] == 'v':
self.voiced[target][change[2]] = True if cha... | reop and handle guard violations. | Below is the the instruction that describes the task:
### Input:
reop and handle guard violations.
### Response:
def do_mode(self, target, msg, nick, send):
"""reop and handle guard violations."""
mode_changes = irc.modes.parse_channel_modes(msg)
with self.data_lock:
for change ... |
def randomWalkFunction(requestContext, name, step=60):
"""
Short Alias: randomWalk()
Returns a random walk starting at 0. This is great for testing when there
is no real data in whisper.
Example::
&target=randomWalk("The.time.series")
This would create a series named "The.time.series... | Short Alias: randomWalk()
Returns a random walk starting at 0. This is great for testing when there
is no real data in whisper.
Example::
&target=randomWalk("The.time.series")
This would create a series named "The.time.series" that contains points
where x(t) == x(t-1)+random()-0.5, and x... | Below is the the instruction that describes the task:
### Input:
Short Alias: randomWalk()
Returns a random walk starting at 0. This is great for testing when there
is no real data in whisper.
Example::
&target=randomWalk("The.time.series")
This would create a series named "The.time.seri... |
def unpause_topic(self, topic):
"""Resume message flow to channels of an existing, paused, topic."""
nsq.assert_valid_topic_name(topic)
return self._request('POST', '/topic/unpause', fields={'topic': topic}) | Resume message flow to channels of an existing, paused, topic. | Below is the the instruction that describes the task:
### Input:
Resume message flow to channels of an existing, paused, topic.
### Response:
def unpause_topic(self, topic):
"""Resume message flow to channels of an existing, paused, topic."""
nsq.assert_valid_topic_name(topic)
return self._... |
def send_script_async(self, conn_id, data, progress_callback, callback):
"""Asynchronously send a a script to this IOTile device
Args:
conn_id (int): A unique identifer that will refer to this connection
data (string): the script to send to the device
progress_callba... | Asynchronously send a a script to this IOTile device
Args:
conn_id (int): A unique identifer that will refer to this connection
data (string): the script to send to the device
progress_callback (callable): A function to be called with status on our progress, called as:
... | Below is the the instruction that describes the task:
### Input:
Asynchronously send a a script to this IOTile device
Args:
conn_id (int): A unique identifer that will refer to this connection
data (string): the script to send to the device
progress_callback (callable): ... |
def _apply_updates(self, gradients):
"""Apply AdaGrad update to parameters.
Parameters
----------
gradients
Returns
-------
"""
if not hasattr(self, 'optimizers'):
self.optimizers = \
{obj: AdaGradOptimizer(self.learning_rate... | Apply AdaGrad update to parameters.
Parameters
----------
gradients
Returns
------- | Below is the the instruction that describes the task:
### Input:
Apply AdaGrad update to parameters.
Parameters
----------
gradients
Returns
-------
### Response:
def _apply_updates(self, gradients):
"""Apply AdaGrad update to parameters.
Parameters
... |
def configure(self, width, height):
"""See :meth:`set_window_size`."""
self._imgwin_set = True
self.set_window_size(width, height) | See :meth:`set_window_size`. | Below is the the instruction that describes the task:
### Input:
See :meth:`set_window_size`.
### Response:
def configure(self, width, height):
"""See :meth:`set_window_size`."""
self._imgwin_set = True
self.set_window_size(width, height) |
def merge_entities(self, from_entity_ids, to_entity_id, force=False, mount_point=DEFAULT_MOUNT_POINT):
"""Merge many entities into one entity.
Supported methods:
POST: /{mount_point}/entity/merge. Produces: 204 (empty body)
:param from_entity_ids: Entity IDs which needs to get merg... | Merge many entities into one entity.
Supported methods:
POST: /{mount_point}/entity/merge. Produces: 204 (empty body)
:param from_entity_ids: Entity IDs which needs to get merged.
:type from_entity_ids: array
:param to_entity_id: Entity ID into which all the other entities ... | Below is the the instruction that describes the task:
### Input:
Merge many entities into one entity.
Supported methods:
POST: /{mount_point}/entity/merge. Produces: 204 (empty body)
:param from_entity_ids: Entity IDs which needs to get merged.
:type from_entity_ids: array
... |
def execute_command(self, generator, write_concern, session):
"""Execute using write commands.
"""
# nModified is only reported for write commands, not legacy ops.
full_result = {
"writeErrors": [],
"writeConcernErrors": [],
"nInserted": 0,
... | Execute using write commands. | Below is the the instruction that describes the task:
### Input:
Execute using write commands.
### Response:
def execute_command(self, generator, write_concern, session):
"""Execute using write commands.
"""
# nModified is only reported for write commands, not legacy ops.
full_resul... |
def OnCellFontSize(self, event):
"""Cell font size event handler"""
with undo.group(_("Font size")):
self.grid.actions.set_attr("pointsize", event.size)
self.grid.ForceRefresh()
self.grid.update_attribute_toolbar()
event.Skip() | Cell font size event handler | Below is the the instruction that describes the task:
### Input:
Cell font size event handler
### Response:
def OnCellFontSize(self, event):
"""Cell font size event handler"""
with undo.group(_("Font size")):
self.grid.actions.set_attr("pointsize", event.size)
self.grid.ForceR... |
def history_json(self, nb=0):
"""Return the history in ISO JSON format"""
return [(i[0].isoformat(), i[1]) for i in self._history[-nb:]] | Return the history in ISO JSON format | Below is the the instruction that describes the task:
### Input:
Return the history in ISO JSON format
### Response:
def history_json(self, nb=0):
"""Return the history in ISO JSON format"""
return [(i[0].isoformat(), i[1]) for i in self._history[-nb:]] |
def _writeBlock(block, blockID):
'''writes the block to a file with the id'''
with open("blockIDs.txt", "a") as fp:
fp.write("blockID: " + str(blockID) + "\n")
sentences = ""
for sentence in block:
sentences += sentence+","
fp.write("block sentences: "+sentences[:-1]+... | writes the block to a file with the id | Below is the the instruction that describes the task:
### Input:
writes the block to a file with the id
### Response:
def _writeBlock(block, blockID):
'''writes the block to a file with the id'''
with open("blockIDs.txt", "a") as fp:
fp.write("blockID: " + str(blockID) + "\n")
sentences = "... |
def _calc_dimension(self, dim_val, dim_max, font_dim):
"Calculate final pos and size (auto, absolute in pixels & relativa)"
if dim_val is None:
return -1 # let wx automatic pos/size
elif isinstance(dim_val, int):
return dim_val # use fixed pixel value (absolute)
... | Calculate final pos and size (auto, absolute in pixels & relativa) | Below is the the instruction that describes the task:
### Input:
Calculate final pos and size (auto, absolute in pixels & relativa)
### Response:
def _calc_dimension(self, dim_val, dim_max, font_dim):
"Calculate final pos and size (auto, absolute in pixels & relativa)"
if dim_val is None:
... |
def upload(self):
"""
upload via the method configured
:return:
"""
if self.upload_method == "setup":
self.upload_by_setup()
if self.upload_method == "twine":
self.upload_by_twine()
if self.upload_method == "gemfury":
self.uploa... | upload via the method configured
:return: | Below is the the instruction that describes the task:
### Input:
upload via the method configured
:return:
### Response:
def upload(self):
"""
upload via the method configured
:return:
"""
if self.upload_method == "setup":
self.upload_by_setup()
i... |
def move(src, dst):
"""Recursively move a file or directory to another location. This is
similar to the Unix "mv" command.
If the destination is a directory or a symlink to a directory, the source
is moved inside the directory. The destination path must not already
exist.
If the destination al... | Recursively move a file or directory to another location. This is
similar to the Unix "mv" command.
If the destination is a directory or a symlink to a directory, the source
is moved inside the directory. The destination path must not already
exist.
If the destination already exists but is not a d... | Below is the the instruction that describes the task:
### Input:
Recursively move a file or directory to another location. This is
similar to the Unix "mv" command.
If the destination is a directory or a symlink to a directory, the source
is moved inside the directory. The destination path must not alr... |
def _write_cdx_header(self):
'''Write the CDX header.
It writes the fields:
1. a: original URL
2. b: UNIX timestamp
3. m: MIME Type from the HTTP Content-type
4. s: response code
5. k: new style checksum
6. S: raw file record size
7. V: offset in... | Write the CDX header.
It writes the fields:
1. a: original URL
2. b: UNIX timestamp
3. m: MIME Type from the HTTP Content-type
4. s: response code
5. k: new style checksum
6. S: raw file record size
7. V: offset in raw file
8. g: filename of raw ... | Below is the the instruction that describes the task:
### Input:
Write the CDX header.
It writes the fields:
1. a: original URL
2. b: UNIX timestamp
3. m: MIME Type from the HTTP Content-type
4. s: response code
5. k: new style checksum
6. S: raw file record... |
def _secret_yaml(loader, node):
"""Load secrets and embed it into the configuration YAML."""
fname = os.path.join(os.path.dirname(loader.name), "secrets.yaml")
try:
with open(fname, encoding="utf-8") as secret_file:
secrets = YAML(typ="safe").load(secret_file)
except FileNotFoundErr... | Load secrets and embed it into the configuration YAML. | Below is the the instruction that describes the task:
### Input:
Load secrets and embed it into the configuration YAML.
### Response:
def _secret_yaml(loader, node):
"""Load secrets and embed it into the configuration YAML."""
fname = os.path.join(os.path.dirname(loader.name), "secrets.yaml")
try:
... |
def push_channel(self, content, channel, content_url=None):
'''Push a notification to a Pushed channel.
Param: content -> content of Pushed notification message
channel -> string identifying a Pushed channel
content_url (optional) -> enrich message with URL
Returns... | Push a notification to a Pushed channel.
Param: content -> content of Pushed notification message
channel -> string identifying a Pushed channel
content_url (optional) -> enrich message with URL
Returns Shipment ID as string | Below is the the instruction that describes the task:
### Input:
Push a notification to a Pushed channel.
Param: content -> content of Pushed notification message
channel -> string identifying a Pushed channel
content_url (optional) -> enrich message with URL
Returns S... |
def has_frames(self, destination):
"""
Whether specified queue has any frames.
@param destination: The queue name (destinationination).
@type destination: C{str}
@return: Whether there are any frames in the specified queue.
@rtype: C{bool}
"""
session = ... | Whether specified queue has any frames.
@param destination: The queue name (destinationination).
@type destination: C{str}
@return: Whether there are any frames in the specified queue.
@rtype: C{bool} | Below is the the instruction that describes the task:
### Input:
Whether specified queue has any frames.
@param destination: The queue name (destinationination).
@type destination: C{str}
@return: Whether there are any frames in the specified queue.
@rtype: C{bool}
### Response:
d... |
def move_top_cards(self, other, number=1):
"""
Move the top `number` of cards to the top of some `other` deck.
By default only one card will be moved if `number` is not specified.
"""
other.cards.append(reversed(self.cards[-number:])) | Move the top `number` of cards to the top of some `other` deck.
By default only one card will be moved if `number` is not specified. | Below is the the instruction that describes the task:
### Input:
Move the top `number` of cards to the top of some `other` deck.
By default only one card will be moved if `number` is not specified.
### Response:
def move_top_cards(self, other, number=1):
"""
Move the top `number` of cards ... |
def set_onscreen_message(self, text, redraw=True):
"""Called by a subclass to update the onscreen message.
Parameters
----------
text : str
The text to show in the display.
"""
width, height = self.get_window_size()
font = self.t_.get('onscreen_font... | Called by a subclass to update the onscreen message.
Parameters
----------
text : str
The text to show in the display. | Below is the the instruction that describes the task:
### Input:
Called by a subclass to update the onscreen message.
Parameters
----------
text : str
The text to show in the display.
### Response:
def set_onscreen_message(self, text, redraw=True):
"""Called by a subcla... |
def by_geopoint(self, lat, long):
"""
Perform a Yelp Neighborhood API Search based on a geopoint.
Args:
lat - geopoint latitude
long - geopoint longitude
"""
header, content = self._http_request(self.BASE_URL, lat=lat, long=long)
return... | Perform a Yelp Neighborhood API Search based on a geopoint.
Args:
lat - geopoint latitude
long - geopoint longitude | Below is the the instruction that describes the task:
### Input:
Perform a Yelp Neighborhood API Search based on a geopoint.
Args:
lat - geopoint latitude
long - geopoint longitude
### Response:
def by_geopoint(self, lat, long):
"""
Perform a Yelp Neighborhood... |
def login(self, user=None, password=None, restrict_login=None):
"""
Attempt to log in using the given username and password. Subsequent
method calls will use this username and password. Returns False if
login fails, otherwise returns some kind of login info - typically
either a n... | Attempt to log in using the given username and password. Subsequent
method calls will use this username and password. Returns False if
login fails, otherwise returns some kind of login info - typically
either a numeric userid, or a dict of user info.
If user is not set, the value of Bug... | Below is the the instruction that describes the task:
### Input:
Attempt to log in using the given username and password. Subsequent
method calls will use this username and password. Returns False if
login fails, otherwise returns some kind of login info - typically
either a numeric userid, ... |
def make_request(self, resource, params=None):
"""
Performs the API request. Most methods are a wrapper around this one.
"""
if params is None:
params = {}
url = self.request_url(resource)
params['format'] = 'json'
r = self.session.get(url=url, param... | Performs the API request. Most methods are a wrapper around this one. | Below is the the instruction that describes the task:
### Input:
Performs the API request. Most methods are a wrapper around this one.
### Response:
def make_request(self, resource, params=None):
"""
Performs the API request. Most methods are a wrapper around this one.
"""
if params... |
def boottime():
"""Returns boot time if remotely possible, or None if not."""
global __boottime
if __boottime is None:
up = uptime()
if up is None:
return None
if __boottime is None:
_boottime_linux()
if datetime is None:
raise RuntimeError('datetime mod... | Returns boot time if remotely possible, or None if not. | Below is the the instruction that describes the task:
### Input:
Returns boot time if remotely possible, or None if not.
### Response:
def boottime():
"""Returns boot time if remotely possible, or None if not."""
global __boottime
if __boottime is None:
up = uptime()
if up is None:
... |
def set_params(self, deep=False, force=False, **parameters):
"""
sets an object's paramters
Parameters
----------
deep : boolean, default: False
when True, also sets non-user-facing paramters
force : boolean, default: False
when True, also sets pa... | sets an object's paramters
Parameters
----------
deep : boolean, default: False
when True, also sets non-user-facing paramters
force : boolean, default: False
when True, also sets parameters that the object does not already
have
**parameters :... | Below is the the instruction that describes the task:
### Input:
sets an object's paramters
Parameters
----------
deep : boolean, default: False
when True, also sets non-user-facing paramters
force : boolean, default: False
when True, also sets parameters tha... |
def read_line(self, sep=six.b('\n')):
"""Read the data stream until a given separator is found (default \n)
:param sep: Separator to read until. Must by of the bytes type (str in python 2,
bytes in python 3)
:return: The str of the data read until sep
"""
start = 0
... | Read the data stream until a given separator is found (default \n)
:param sep: Separator to read until. Must by of the bytes type (str in python 2,
bytes in python 3)
:return: The str of the data read until sep | Below is the the instruction that describes the task:
### Input:
Read the data stream until a given separator is found (default \n)
:param sep: Separator to read until. Must by of the bytes type (str in python 2,
bytes in python 3)
:return: The str of the data read until sep
### Respons... |
def by_median_household_income(self,
lower=-1,
upper=2 ** 31,
zipcode_type=ZipcodeType.Standard,
sort_by=SimpleZipcode.median_household_income.name,
... | Search zipcode information by median household income. | Below is the the instruction that describes the task:
### Input:
Search zipcode information by median household income.
### Response:
def by_median_household_income(self,
lower=-1,
upper=2 ** 31,
zipcode_type=Z... |
def on_left_click(self, event, grid, choices):
"""
creates popup menu when user clicks on the column
if that column is in the list of choices that get a drop-down menu.
allows user to edit the column, but only from available values
"""
row, col = event.GetRow(), event.Get... | creates popup menu when user clicks on the column
if that column is in the list of choices that get a drop-down menu.
allows user to edit the column, but only from available values | Below is the the instruction that describes the task:
### Input:
creates popup menu when user clicks on the column
if that column is in the list of choices that get a drop-down menu.
allows user to edit the column, but only from available values
### Response:
def on_left_click(self, event, grid, ch... |
def get_engine(name):
"""
get an engine from string (engine class without Engine)
"""
name = name.capitalize() + 'Engine'
if name in globals():
return globals()[name]
raise KeyError("engine '%s' does not exist" % name) | get an engine from string (engine class without Engine) | Below is the the instruction that describes the task:
### Input:
get an engine from string (engine class without Engine)
### Response:
def get_engine(name):
"""
get an engine from string (engine class without Engine)
"""
name = name.capitalize() + 'Engine'
if name in globals():
return ... |
def register_extension_method(ext, base, *args, **kwargs):
"""Register the given extension method as a public attribute of the given base.
README: The expected protocol here is that the given extension method is an unbound function.
It will be bound to the specified base as a method, and then set as a publ... | Register the given extension method as a public attribute of the given base.
README: The expected protocol here is that the given extension method is an unbound function.
It will be bound to the specified base as a method, and then set as a public attribute of that
base. | Below is the the instruction that describes the task:
### Input:
Register the given extension method as a public attribute of the given base.
README: The expected protocol here is that the given extension method is an unbound function.
It will be bound to the specified base as a method, and then set as a p... |
def _viewdata_to_view(self, p_data):
"""
Converts a dictionary describing a view to an actual UIView instance.
"""
sorter = Sorter(p_data['sortexpr'], p_data['groupexpr'])
filters = []
if not p_data['show_all']:
filters.append(DependencyFilter(self.todolist))... | Converts a dictionary describing a view to an actual UIView instance. | Below is the the instruction that describes the task:
### Input:
Converts a dictionary describing a view to an actual UIView instance.
### Response:
def _viewdata_to_view(self, p_data):
"""
Converts a dictionary describing a view to an actual UIView instance.
"""
sorter = Sorter(p_d... |
def namespace(self, namespace):
"""Setter method; for a description see the getter method."""
# pylint: disable=attribute-defined-outside-init
self._namespace = _ensure_unicode(namespace)
if self._namespace is not None:
# In Python 3, a byte string cannot be stripped by a uni... | Setter method; for a description see the getter method. | Below is the the instruction that describes the task:
### Input:
Setter method; for a description see the getter method.
### Response:
def namespace(self, namespace):
"""Setter method; for a description see the getter method."""
# pylint: disable=attribute-defined-outside-init
self._namespa... |
def _extract_model_params(self, defaults, **kwargs):
"""this method allows django managers use `objects.get_or_create` and
`objects.update_or_create` on a hashable object.
"""
obj = kwargs.pop(self.object_property_name, None)
if obj is not None:
kwargs['object_hash'] ... | this method allows django managers use `objects.get_or_create` and
`objects.update_or_create` on a hashable object. | Below is the the instruction that describes the task:
### Input:
this method allows django managers use `objects.get_or_create` and
`objects.update_or_create` on a hashable object.
### Response:
def _extract_model_params(self, defaults, **kwargs):
"""this method allows django managers use `objects.... |
def add_line(self, line='', *, empty=False):
"""Adds a line to the current page.
If the line exceeds the :attr:`max_size` then an exception
is raised.
Parameters
-----------
line: :class:`str`
The line to add.
empty: :class:`bool`
Indicat... | Adds a line to the current page.
If the line exceeds the :attr:`max_size` then an exception
is raised.
Parameters
-----------
line: :class:`str`
The line to add.
empty: :class:`bool`
Indicates if another empty line should be added.
Raise... | Below is the the instruction that describes the task:
### Input:
Adds a line to the current page.
If the line exceeds the :attr:`max_size` then an exception
is raised.
Parameters
-----------
line: :class:`str`
The line to add.
empty: :class:`bool`
... |
def create_js_pay_params(self, **package):
"""
签名 js 需要的参数
详情请参考 支付开发文档
::
wxclient.create_js_pay_params(
body=标题, out_trade_no=本地订单号, total_fee=价格单位分,
notify_url=通知url,
spbill_create_ip=建议为支付人ip,
)
:param... | 签名 js 需要的参数
详情请参考 支付开发文档
::
wxclient.create_js_pay_params(
body=标题, out_trade_no=本地订单号, total_fee=价格单位分,
notify_url=通知url,
spbill_create_ip=建议为支付人ip,
)
:param package: 需要签名的的参数
:return: 支付需要的对象 | Below is the the instruction that describes the task:
### Input:
签名 js 需要的参数
详情请参考 支付开发文档
::
wxclient.create_js_pay_params(
body=标题, out_trade_no=本地订单号, total_fee=价格单位分,
notify_url=通知url,
spbill_create_ip=建议为支付人ip,
)
... |
def _on_bytes_read(self, num_bytes_read):
"""
Record our progress so we can validate that we receive all the data
:param num_bytes_read: int: number of bytes we received as part of one chunk
"""
self.actual_bytes_read += num_bytes_read
if self.actual_bytes_read > self.byt... | Record our progress so we can validate that we receive all the data
:param num_bytes_read: int: number of bytes we received as part of one chunk | Below is the the instruction that describes the task:
### Input:
Record our progress so we can validate that we receive all the data
:param num_bytes_read: int: number of bytes we received as part of one chunk
### Response:
def _on_bytes_read(self, num_bytes_read):
"""
Record our progress s... |
def _get_method_full_name(func):
"""
Return fully qualified function name.
This method will attempt to find "full name" of the given function object. This full name is either of
the form "<class name>.<method name>" if the function is a class method, or "<module name>.<func name>"
if it's a regular... | Return fully qualified function name.
This method will attempt to find "full name" of the given function object. This full name is either of
the form "<class name>.<method name>" if the function is a class method, or "<module name>.<func name>"
if it's a regular function. Thus, this is an attempt to back-p... | Below is the the instruction that describes the task:
### Input:
Return fully qualified function name.
This method will attempt to find "full name" of the given function object. This full name is either of
the form "<class name>.<method name>" if the function is a class method, or "<module name>.<func name... |
def check_argument_list(kernel_name, kernel_string, args):
""" raise an exception if a kernel arguments do not match host arguments """
kernel_arguments = list()
collected_errors = list()
for iterator in re.finditer(kernel_name + "[ \n\t]*" + "\(", kernel_string):
kernel_start = iterator.end()
... | raise an exception if a kernel arguments do not match host arguments | Below is the the instruction that describes the task:
### Input:
raise an exception if a kernel arguments do not match host arguments
### Response:
def check_argument_list(kernel_name, kernel_string, args):
""" raise an exception if a kernel arguments do not match host arguments """
kernel_arguments = list... |
def _print(self, *data, **kw):
"""
_print(self, *data, sep=' ', end='\n', file=None)
Alternative 'print' function that prints back into the SSH channel.
"""
# Pop keyword-only arguments. (We cannot use the syntax from the
# signature. Otherwise, Python2 will give a synta... | _print(self, *data, sep=' ', end='\n', file=None)
Alternative 'print' function that prints back into the SSH channel. | Below is the the instruction that describes the task:
### Input:
_print(self, *data, sep=' ', end='\n', file=None)
Alternative 'print' function that prints back into the SSH channel.
### Response:
def _print(self, *data, **kw):
"""
_print(self, *data, sep=' ', end='\n', file=None)
... |
def get_work_kind(self):
"""
We'll have a kind_slug like 'movies'.
We need to translate that into a work `kind` like 'movie'.
"""
slugs_to_kinds = {v:k for k,v in Work.KIND_SLUGS.items()}
return slugs_to_kinds.get(self.kind_slug, None) | We'll have a kind_slug like 'movies'.
We need to translate that into a work `kind` like 'movie'. | Below is the the instruction that describes the task:
### Input:
We'll have a kind_slug like 'movies'.
We need to translate that into a work `kind` like 'movie'.
### Response:
def get_work_kind(self):
"""
We'll have a kind_slug like 'movies'.
We need to translate that into a work `k... |
def writeToken(self):
"""
Store details of the current connection in the named file.
This can be used by :meth:`readToken` to re-authenticate at a later time.
"""
# Write token file privately.
with os.fdopen(os.open(self.tokenFile, os.O_WRONLY | os.O_CREAT, 0o600), "w") ... | Store details of the current connection in the named file.
This can be used by :meth:`readToken` to re-authenticate at a later time. | Below is the the instruction that describes the task:
### Input:
Store details of the current connection in the named file.
This can be used by :meth:`readToken` to re-authenticate at a later time.
### Response:
def writeToken(self):
"""
Store details of the current connection in the named... |
def strip(self, col: str):
"""
Remove leading and trailing white spaces in a column's values
:param col: name of the column
:type col: str
:example: ``ds.strip("mycol")``
"""
def remove_ws(row):
val = str(row[col])
if " " in val.startswit... | Remove leading and trailing white spaces in a column's values
:param col: name of the column
:type col: str
:example: ``ds.strip("mycol")`` | Below is the the instruction that describes the task:
### Input:
Remove leading and trailing white spaces in a column's values
:param col: name of the column
:type col: str
:example: ``ds.strip("mycol")``
### Response:
def strip(self, col: str):
"""
Remove leading and trai... |
def create_hitor_calibration(output_filename, plot_pixel_calibrations=False):
'''Generating HitOr calibration file (_calibration.h5) from raw data file and plotting of calibration data.
Parameters
----------
output_filename : string
Input raw data file name.
plot_pixel_calibrations :... | Generating HitOr calibration file (_calibration.h5) from raw data file and plotting of calibration data.
Parameters
----------
output_filename : string
Input raw data file name.
plot_pixel_calibrations : bool, iterable
If True, genearating additional pixel calibration plots. If l... | Below is the the instruction that describes the task:
### Input:
Generating HitOr calibration file (_calibration.h5) from raw data file and plotting of calibration data.
Parameters
----------
output_filename : string
Input raw data file name.
plot_pixel_calibrations : bool, iterable
... |
def set_dimensional_calibrations(self, dimensional_calibrations: typing.List[CalibrationModule.Calibration]) -> None:
"""Set the dimensional calibrations.
:param dimensional_calibrations: A list of calibrations, must match the dimensions of the data.
.. versionadded:: 1.0
Scriptable: ... | Set the dimensional calibrations.
:param dimensional_calibrations: A list of calibrations, must match the dimensions of the data.
.. versionadded:: 1.0
Scriptable: Yes | Below is the the instruction that describes the task:
### Input:
Set the dimensional calibrations.
:param dimensional_calibrations: A list of calibrations, must match the dimensions of the data.
.. versionadded:: 1.0
Scriptable: Yes
### Response:
def set_dimensional_calibrations(self, di... |
def pp_event(seq):
"""Returns pretty representation of an Event or keypress"""
if isinstance(seq, Event):
return str(seq)
# Get the original sequence back if seq is a pretty name already
rev_curses = dict((v, k) for k, v in CURSES_NAMES.items())
rev_curtsies = dict((v, k) for k, v in CURTS... | Returns pretty representation of an Event or keypress | Below is the the instruction that describes the task:
### Input:
Returns pretty representation of an Event or keypress
### Response:
def pp_event(seq):
"""Returns pretty representation of an Event or keypress"""
if isinstance(seq, Event):
return str(seq)
# Get the original sequence back if se... |
def create_business_rules(self, hosts, services, hostgroups, servicegroups,
macromodulations, timeperiods, running=False):
# pylint: disable=too-many-locals
"""Create business rules if necessary (cmd contains bp_rule)
:param hosts: Hosts object to look for objects
... | Create business rules if necessary (cmd contains bp_rule)
:param hosts: Hosts object to look for objects
:type hosts: alignak.objects.host.Hosts
:param services: Services object to look for objects
:type services: alignak.objects.service.Services
:param running: flag used in eva... | Below is the the instruction that describes the task:
### Input:
Create business rules if necessary (cmd contains bp_rule)
:param hosts: Hosts object to look for objects
:type hosts: alignak.objects.host.Hosts
:param services: Services object to look for objects
:type services: alig... |
def purge(gandi, email, background, force, alias):
"""Purge a mailbox."""
login, domain = email
if alias:
if not force:
proceed = click.confirm('Are you sure to purge all aliases for '
'mailbox %s@%s ?' % (login, domain))
if not proceed:
... | Purge a mailbox. | Below is the the instruction that describes the task:
### Input:
Purge a mailbox.
### Response:
def purge(gandi, email, background, force, alias):
"""Purge a mailbox."""
login, domain = email
if alias:
if not force:
proceed = click.confirm('Are you sure to purge all aliases for '
... |
def fetch(self, remote, branch, local_branch = None, force=False):
'''Pull a repository
:param remote: git-remote instance
:param branch: name of the branch to pull
'''
pb = ProgressBar()
pb.setup(self.name)
if local_branch:
branch = ':'.join([branch,... | Pull a repository
:param remote: git-remote instance
:param branch: name of the branch to pull | Below is the the instruction that describes the task:
### Input:
Pull a repository
:param remote: git-remote instance
:param branch: name of the branch to pull
### Response:
def fetch(self, remote, branch, local_branch = None, force=False):
'''Pull a repository
:param remote: git-re... |
def set_current_thumbnail(self, thumbnail):
"""Set the currently selected thumbnail."""
self.current_thumbnail = thumbnail
self.figure_viewer.load_figure(
thumbnail.canvas.fig, thumbnail.canvas.fmt)
for thumbnail in self._thumbnails:
thumbnail.highlight_canvas... | Set the currently selected thumbnail. | Below is the the instruction that describes the task:
### Input:
Set the currently selected thumbnail.
### Response:
def set_current_thumbnail(self, thumbnail):
"""Set the currently selected thumbnail."""
self.current_thumbnail = thumbnail
self.figure_viewer.load_figure(
thu... |
def dealias_image(alias):
'''Remove an image alias.'''
with Session() as session:
try:
result = session.Image.dealiasImage(alias)
except Exception as e:
print_error(e)
sys.exit(1)
if result['ok']:
print("alias {0} removed.".format(alias))
... | Remove an image alias. | Below is the the instruction that describes the task:
### Input:
Remove an image alias.
### Response:
def dealias_image(alias):
'''Remove an image alias.'''
with Session() as session:
try:
result = session.Image.dealiasImage(alias)
except Exception as e:
print_error(... |
def wrap(cls, private_key, algorithm):
"""
Wraps a private key in a PrivateKeyInfo structure
:param private_key:
A byte string or Asn1Value object of the private key
:param algorithm:
A unicode string of "rsa", "dsa" or "ec"
:return:
A Priva... | Wraps a private key in a PrivateKeyInfo structure
:param private_key:
A byte string or Asn1Value object of the private key
:param algorithm:
A unicode string of "rsa", "dsa" or "ec"
:return:
A PrivateKeyInfo object | Below is the the instruction that describes the task:
### Input:
Wraps a private key in a PrivateKeyInfo structure
:param private_key:
A byte string or Asn1Value object of the private key
:param algorithm:
A unicode string of "rsa", "dsa" or "ec"
:return:
... |
def find(cls, id='', slug=None):
"""
Similar to :py:meth:`.PanoptesObject.find`, but allows lookup by slug
as well as ID.
Examples::
collection_1234 = Collection.find(1234)
my_collection = Collection.find(slug="example/my-collection")
"""
if not... | Similar to :py:meth:`.PanoptesObject.find`, but allows lookup by slug
as well as ID.
Examples::
collection_1234 = Collection.find(1234)
my_collection = Collection.find(slug="example/my-collection") | Below is the the instruction that describes the task:
### Input:
Similar to :py:meth:`.PanoptesObject.find`, but allows lookup by slug
as well as ID.
Examples::
collection_1234 = Collection.find(1234)
my_collection = Collection.find(slug="example/my-collection")
### Respons... |
def iresolve(self, *keys):
'''
Iterates over resolved instances for given provider keys.
:param keys: Provider keys
:type keys: tuple
:return: Iterator of resolved instances
:rtype: generator
'''
for key in keys:
missing = self.get_missing_dep... | Iterates over resolved instances for given provider keys.
:param keys: Provider keys
:type keys: tuple
:return: Iterator of resolved instances
:rtype: generator | Below is the the instruction that describes the task:
### Input:
Iterates over resolved instances for given provider keys.
:param keys: Provider keys
:type keys: tuple
:return: Iterator of resolved instances
:rtype: generator
### Response:
def iresolve(self, *keys):
'''
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.