code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def bind(self, fn: Callable[[Any], 'Observable']) -> 'Observable':
r"""Chain continuation passing functions.
Haskell: m >>= k = Cont $ \c -> runCont m $ \a -> runCont (k a) c
"""
source = self
return Observable(lambda on_next: source.subscribe(lambda a: fn(a).subscribe(on_next))... | r"""Chain continuation passing functions.
Haskell: m >>= k = Cont $ \c -> runCont m $ \a -> runCont (k a) c | Below is the the instruction that describes the task:
### Input:
r"""Chain continuation passing functions.
Haskell: m >>= k = Cont $ \c -> runCont m $ \a -> runCont (k a) c
### Response:
def bind(self, fn: Callable[[Any], 'Observable']) -> 'Observable':
r"""Chain continuation passing functions.
... |
def eccentricity(self):
"""
The eccentricity of the 2D Gaussian function that has the same
second-order moments as the source.
The eccentricity is the fraction of the distance along the
semimajor axis at which the focus lies.
.. math:: e = \\sqrt{1 - \\frac{b^2}{a^2}}
... | The eccentricity of the 2D Gaussian function that has the same
second-order moments as the source.
The eccentricity is the fraction of the distance along the
semimajor axis at which the focus lies.
.. math:: e = \\sqrt{1 - \\frac{b^2}{a^2}}
where :math:`a` and :math:`b` are th... | Below is the the instruction that describes the task:
### Input:
The eccentricity of the 2D Gaussian function that has the same
second-order moments as the source.
The eccentricity is the fraction of the distance along the
semimajor axis at which the focus lies.
.. math:: e = \\sqr... |
def shrink(self, shrink):
"""
Remove unnecessary parts
:param shrink: Object to shringk
:type shrink: dict | list
:return: Shrunk object
:rtype: dict | list
"""
if isinstance(shrink, list):
return self._shrink_list(shrink)
if isinstanc... | Remove unnecessary parts
:param shrink: Object to shringk
:type shrink: dict | list
:return: Shrunk object
:rtype: dict | list | Below is the the instruction that describes the task:
### Input:
Remove unnecessary parts
:param shrink: Object to shringk
:type shrink: dict | list
:return: Shrunk object
:rtype: dict | list
### Response:
def shrink(self, shrink):
"""
Remove unnecessary parts
... |
def submit_batch_prediction(job_request, job_id=None):
"""Submit a batch prediction job.
Args:
job_request: the arguments of the training job in a dict. For example,
{
'version_name': 'projects/my-project/models/my-model/versions/my-version',
'data_format': 'TEXT',
... | Submit a batch prediction job.
Args:
job_request: the arguments of the training job in a dict. For example,
{
'version_name': 'projects/my-project/models/my-model/versions/my-version',
'data_format': 'TEXT',
'input_paths': ['gs://my_bucket/my_file.csv'],
... | Below is the the instruction that describes the task:
### Input:
Submit a batch prediction job.
Args:
job_request: the arguments of the training job in a dict. For example,
{
'version_name': 'projects/my-project/models/my-model/versions/my-version',
'data_format': 'TEXT'... |
def select_connected_bonds():
'''Select the bonds connected to the currently selected atoms.'''
s = current_system()
start, end = s.bonds.transpose()
selected = np.zeros(s.n_bonds, 'bool')
for i in selected_atoms():
selected |= (i == start) | (i == end)
csel = current_selection()
bs... | Select the bonds connected to the currently selected atoms. | Below is the the instruction that describes the task:
### Input:
Select the bonds connected to the currently selected atoms.
### Response:
def select_connected_bonds():
'''Select the bonds connected to the currently selected atoms.'''
s = current_system()
start, end = s.bonds.transpose()
selected =... |
def setActionManifestPath(self, pchActionManifestPath):
"""
Sets the path to the action manifest JSON file that is used by this application. If this information
was set on the Steam partner site, calls to this function are ignored. If the Steam partner site
setting and the path provided ... | Sets the path to the action manifest JSON file that is used by this application. If this information
was set on the Steam partner site, calls to this function are ignored. If the Steam partner site
setting and the path provided by this call are different, VRInputError_MismatchedActionManifest is returne... | Below is the the instruction that describes the task:
### Input:
Sets the path to the action manifest JSON file that is used by this application. If this information
was set on the Steam partner site, calls to this function are ignored. If the Steam partner site
setting and the path provided by this... |
def get_setting(key, *default):
"""Return specific search setting from Django conf."""
if default:
return get_settings().get(key, default[0])
else:
return get_settings()[key] | Return specific search setting from Django conf. | Below is the the instruction that describes the task:
### Input:
Return specific search setting from Django conf.
### Response:
def get_setting(key, *default):
"""Return specific search setting from Django conf."""
if default:
return get_settings().get(key, default[0])
else:
return get_... |
def tree_model_natsort(model, row1, row2, user_data=None):
'''用natural sorting算法对TreeModel的一个column进行排序'''
sort_column, sort_type = model.get_sort_column_id()
value1 = model.get_value(row1, sort_column)
value2 = model.get_value(row2, sort_column)
sort_list1 = util.natsort(value1)
sort_list2 = ut... | 用natural sorting算法对TreeModel的一个column进行排序 | Below is the the instruction that describes the task:
### Input:
用natural sorting算法对TreeModel的一个column进行排序
### Response:
def tree_model_natsort(model, row1, row2, user_data=None):
'''用natural sorting算法对TreeModel的一个column进行排序'''
sort_column, sort_type = model.get_sort_column_id()
value1 = model.get_valu... |
def fit(self, X, y=None):
'''
Learn the linear transformation to clipped eigenvalues.
Note that if min_eig isn't zero and any of the original eigenvalues
were exactly zero, this will leave those eigenvalues as zero.
Parameters
----------
X : array, shape [n, n]
... | Learn the linear transformation to clipped eigenvalues.
Note that if min_eig isn't zero and any of the original eigenvalues
were exactly zero, this will leave those eigenvalues as zero.
Parameters
----------
X : array, shape [n, n]
The *symmetric* input similarities... | Below is the the instruction that describes the task:
### Input:
Learn the linear transformation to clipped eigenvalues.
Note that if min_eig isn't zero and any of the original eigenvalues
were exactly zero, this will leave those eigenvalues as zero.
Parameters
----------
X... |
def keypair_delete(self, name):
'''
Delete a keypair
'''
nt_ks = self.compute_conn
nt_ks.keypairs.delete(name)
return 'Keypair deleted: {0}'.format(name) | Delete a keypair | Below is the the instruction that describes the task:
### Input:
Delete a keypair
### Response:
def keypair_delete(self, name):
'''
Delete a keypair
'''
nt_ks = self.compute_conn
nt_ks.keypairs.delete(name)
return 'Keypair deleted: {0}'.format(name) |
def setEffort(self, vehID, edgeID, effort=None, begTime=None, endTime=None):
"""setEffort(string, string, double, int, int) -> None
Inserts the information about the effort of edge "edgeID" valid from
begin time to end time into the vehicle's internal edge weights
container.
If t... | setEffort(string, string, double, int, int) -> None
Inserts the information about the effort of edge "edgeID" valid from
begin time to end time into the vehicle's internal edge weights
container.
If the time is not specified, any previously set values for that edge
are removed.
... | Below is the the instruction that describes the task:
### Input:
setEffort(string, string, double, int, int) -> None
Inserts the information about the effort of edge "edgeID" valid from
begin time to end time into the vehicle's internal edge weights
container.
If the time is not spec... |
def wrap2stub(self, customfunc):
"""
Wrapping the inspector as a stub based on the type
Args:
customfunc: function that replaces the original
Returns:
function, the spy wrapper around the customfunc
"""
if self.args_type == "MODULE_FUNCTION":
... | Wrapping the inspector as a stub based on the type
Args:
customfunc: function that replaces the original
Returns:
function, the spy wrapper around the customfunc | Below is the the instruction that describes the task:
### Input:
Wrapping the inspector as a stub based on the type
Args:
customfunc: function that replaces the original
Returns:
function, the spy wrapper around the customfunc
### Response:
def wrap2stub(self, customfunc):
... |
def max_dropback(self):
"""最大回撤
"""
return round(
float(
max(
[
(self.assets.iloc[idx] - self.assets.iloc[idx::].min())
/ self.assets.iloc[idx]
for idx in range(len(self.assets... | 最大回撤 | Below is the the instruction that describes the task:
### Input:
最大回撤
### Response:
def max_dropback(self):
"""最大回撤
"""
return round(
float(
max(
[
(self.assets.iloc[idx] - self.assets.iloc[idx::].min())
... |
def profile(name):
'''
This state module allows you to modify system tuned parameters
Example tuned.sls file to set profile to virtual-guest
tuned:
tuned:
- profile
- name: virtual-guest
name
tuned profile name to set the system to
To see a valid list of states ... | This state module allows you to modify system tuned parameters
Example tuned.sls file to set profile to virtual-guest
tuned:
tuned:
- profile
- name: virtual-guest
name
tuned profile name to set the system to
To see a valid list of states call execution module:
... | Below is the the instruction that describes the task:
### Input:
This state module allows you to modify system tuned parameters
Example tuned.sls file to set profile to virtual-guest
tuned:
tuned:
- profile
- name: virtual-guest
name
tuned profile name to set the system ... |
def cfunc(name, result, *args):
"""Build and apply a ctypes prototype complete with parameter flags."""
atypes = []
aflags = []
for arg in args:
atypes.append(arg[1])
aflags.append((arg[2], arg[0]) + arg[3:])
return CFUNCTYPE(result, *atypes)((name, _fl), tuple(aflags)) | Build and apply a ctypes prototype complete with parameter flags. | Below is the the instruction that describes the task:
### Input:
Build and apply a ctypes prototype complete with parameter flags.
### Response:
def cfunc(name, result, *args):
"""Build and apply a ctypes prototype complete with parameter flags."""
atypes = []
aflags = []
for arg in args:
a... |
def keep_absolute_resample__roc_auc(X, y, model_generator, method_name, num_fcounts=11):
""" Keep Absolute (resample)
xlabel = "Max fraction of features kept"
ylabel = "ROC AUC"
transform = "identity"
sort_order = 12
"""
return __run_measure(measures.keep_resample, X, y, model_generator, met... | Keep Absolute (resample)
xlabel = "Max fraction of features kept"
ylabel = "ROC AUC"
transform = "identity"
sort_order = 12 | Below is the the instruction that describes the task:
### Input:
Keep Absolute (resample)
xlabel = "Max fraction of features kept"
ylabel = "ROC AUC"
transform = "identity"
sort_order = 12
### Response:
def keep_absolute_resample__roc_auc(X, y, model_generator, method_name, num_fcounts=11):
"""... |
def _list_items(action, key, profile=None, subdomain=None, api_key=None):
'''
List items belonging to an API call.
This method should be in utils.pagerduty.
'''
items = _query(
profile=profile,
subdomain=subdomain,
api_key=api_key,
action=action
)
ret = {}
... | List items belonging to an API call.
This method should be in utils.pagerduty. | Below is the the instruction that describes the task:
### Input:
List items belonging to an API call.
This method should be in utils.pagerduty.
### Response:
def _list_items(action, key, profile=None, subdomain=None, api_key=None):
'''
List items belonging to an API call.
This method should be in... |
def make_segments(x, y):
"""
Create list of line segments from x and y coordinates, in the correct format
for LineCollection: an array of the form numlines x (points per line) x 2 (x
and y) array
"""
points = np.array([x, y]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], point... | Create list of line segments from x and y coordinates, in the correct format
for LineCollection: an array of the form numlines x (points per line) x 2 (x
and y) array | Below is the the instruction that describes the task:
### Input:
Create list of line segments from x and y coordinates, in the correct format
for LineCollection: an array of the form numlines x (points per line) x 2 (x
and y) array
### Response:
def make_segments(x, y):
"""
Create list of line segm... |
def to_json_file(file, data, pretty):
"""
Writes object instance in JSON formatted String to file
:param file: File to write JSON string ot
:param data: Object to convert to JSON
:param pretty: Use pretty formatting or not
"""
json_string = to_json(data, pretty)
file_utils.write_to... | Writes object instance in JSON formatted String to file
:param file: File to write JSON string ot
:param data: Object to convert to JSON
:param pretty: Use pretty formatting or not | Below is the the instruction that describes the task:
### Input:
Writes object instance in JSON formatted String to file
:param file: File to write JSON string ot
:param data: Object to convert to JSON
:param pretty: Use pretty formatting or not
### Response:
def to_json_file(file, data, pretty):... |
def clause_annotations(self):
"""The list of clause annotations in ``words`` layer."""
if not self.is_tagged(CLAUSE_ANNOTATION):
self.tag_clause_annotations()
return [word.get(CLAUSE_ANNOTATION, None) for word in self[WORDS]] | The list of clause annotations in ``words`` layer. | Below is the the instruction that describes the task:
### Input:
The list of clause annotations in ``words`` layer.
### Response:
def clause_annotations(self):
"""The list of clause annotations in ``words`` layer."""
if not self.is_tagged(CLAUSE_ANNOTATION):
self.tag_clause_annotations(... |
def read_data_to_asp(file: str) -> List[str]:
""" Reads the given JSON file and generates the ASP definition.
Args:
file: the json data file
Returns:
the asp definition.
"""
if file.endswith(".json"):
with open(file) as f:
data = json.load(f)
... | Reads the given JSON file and generates the ASP definition.
Args:
file: the json data file
Returns:
the asp definition. | Below is the the instruction that describes the task:
### Input:
Reads the given JSON file and generates the ASP definition.
Args:
file: the json data file
Returns:
the asp definition.
### Response:
def read_data_to_asp(file: str) -> List[str]:
""" Reads the given JSON f... |
def _calc_grad_tiled(self, img, t_grad, tile_size=512):
'''Compute the value of tensor t_grad over the image in a tiled way.
Random shifts are applied to the image to blur tile boundaries over
multiple iterations.'''
sz = tile_size
h, w = img.shape[:2]
sx, sy = np.random... | Compute the value of tensor t_grad over the image in a tiled way.
Random shifts are applied to the image to blur tile boundaries over
multiple iterations. | Below is the the instruction that describes the task:
### Input:
Compute the value of tensor t_grad over the image in a tiled way.
Random shifts are applied to the image to blur tile boundaries over
multiple iterations.
### Response:
def _calc_grad_tiled(self, img, t_grad, tile_size=512):
... |
def channel(self, rpc_timeout=60, lazy=False):
"""Open Channel.
:param int rpc_timeout: Timeout before we give up waiting for an RPC
response from the server.
:raises AMQPInvalidArgument: Invalid Parameters
:raises AMQPChannelError: Raises if the channel... | Open Channel.
:param int rpc_timeout: Timeout before we give up waiting for an RPC
response from the server.
:raises AMQPInvalidArgument: Invalid Parameters
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError... | Below is the the instruction that describes the task:
### Input:
Open Channel.
:param int rpc_timeout: Timeout before we give up waiting for an RPC
response from the server.
:raises AMQPInvalidArgument: Invalid Parameters
:raises AMQPChannelError: Raises if ... |
def query_subscriptions(self, subscription_query):
"""QuerySubscriptions.
[Preview API] Query for subscriptions. A subscription is returned if it matches one or more of the specified conditions.
:param :class:`<SubscriptionQuery> <azure.devops.v5_0.notification.models.SubscriptionQuery>` subscri... | QuerySubscriptions.
[Preview API] Query for subscriptions. A subscription is returned if it matches one or more of the specified conditions.
:param :class:`<SubscriptionQuery> <azure.devops.v5_0.notification.models.SubscriptionQuery>` subscription_query:
:rtype: [NotificationSubscription] | Below is the the instruction that describes the task:
### Input:
QuerySubscriptions.
[Preview API] Query for subscriptions. A subscription is returned if it matches one or more of the specified conditions.
:param :class:`<SubscriptionQuery> <azure.devops.v5_0.notification.models.SubscriptionQuery>` ... |
def get_page_url_title(self):
'''
Get the title and current url from the remote session.
Return is a 2-tuple: (page_title, page_url).
'''
cr_tab_id = self.transport._get_cr_tab_meta_for_key(self.tab_id)['id']
targets = self.Target_getTargets()
assert 'result' in targets
assert 'targetInfos' in targe... | Get the title and current url from the remote session.
Return is a 2-tuple: (page_title, page_url). | Below is the the instruction that describes the task:
### Input:
Get the title and current url from the remote session.
Return is a 2-tuple: (page_title, page_url).
### Response:
def get_page_url_title(self):
'''
Get the title and current url from the remote session.
Return is a 2-tuple: (page_title, pag... |
def to_html(data):
"""
Serializes a python object as HTML
This method uses the to_json method to turn the given data object into
formatted JSON that is displayed in an HTML page. If pygments in installed,
syntax highlighting will also be applied to the JSON.
"""
base_html_template = Templat... | Serializes a python object as HTML
This method uses the to_json method to turn the given data object into
formatted JSON that is displayed in an HTML page. If pygments in installed,
syntax highlighting will also be applied to the JSON. | Below is the the instruction that describes the task:
### Input:
Serializes a python object as HTML
This method uses the to_json method to turn the given data object into
formatted JSON that is displayed in an HTML page. If pygments in installed,
syntax highlighting will also be applied to the JSON.
##... |
def calculate(self, T, method):
r'''Method to calculate low-pressure gas thermal conductivity at
tempearture `T` with a given method.
This method has no exception handling; see `T_dependent_property`
for that.
Parameters
----------
T : float
Temperat... | r'''Method to calculate low-pressure gas thermal conductivity at
tempearture `T` with a given method.
This method has no exception handling; see `T_dependent_property`
for that.
Parameters
----------
T : float
Temperature of the gas, [K]
method : str... | Below is the the instruction that describes the task:
### Input:
r'''Method to calculate low-pressure gas thermal conductivity at
tempearture `T` with a given method.
This method has no exception handling; see `T_dependent_property`
for that.
Parameters
----------
T... |
def destination_encryption_configuration(self):
"""google.cloud.bigquery.table.EncryptionConfiguration: Custom
encryption configuration for the destination table.
Custom encryption configuration (e.g., Cloud KMS keys) or :data:`None`
if using default encryption.
See
htt... | google.cloud.bigquery.table.EncryptionConfiguration: Custom
encryption configuration for the destination table.
Custom encryption configuration (e.g., Cloud KMS keys) or :data:`None`
if using default encryption.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#... | Below is the the instruction that describes the task:
### Input:
google.cloud.bigquery.table.EncryptionConfiguration: Custom
encryption configuration for the destination table.
Custom encryption configuration (e.g., Cloud KMS keys) or :data:`None`
if using default encryption.
See
... |
def remove_user_permission(rid, uid, action='full'):
""" Removes user permission on a given resource.
:param uid: user id
:type uid: str
:param rid: resource ID
:type rid: str
:param action: read, write, update, delete or full
:type action: str
"""
rid = rid.... | Removes user permission on a given resource.
:param uid: user id
:type uid: str
:param rid: resource ID
:type rid: str
:param action: read, write, update, delete or full
:type action: str | Below is the the instruction that describes the task:
### Input:
Removes user permission on a given resource.
:param uid: user id
:type uid: str
:param rid: resource ID
:type rid: str
:param action: read, write, update, delete or full
:type action: str
### Response: ... |
def info(name, root=None):
'''
Return information for the specified user
name
User to get the information for
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.info root
'''
if root is not None:
getspnam = functools.parti... | Return information for the specified user
name
User to get the information for
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.info root | Below is the the instruction that describes the task:
### Input:
Return information for the specified user
name
User to get the information for
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' shadow.info root
### Response:
def info(name, root=No... |
def average_fft(self, fftlength=None, overlap=0, window=None):
"""Compute the averaged one-dimensional DFT of this `TimeSeries`.
This method computes a number of FFTs of duration ``fftlength``
and ``overlap`` (both given in seconds), and returns the mean
average. This method is analogou... | Compute the averaged one-dimensional DFT of this `TimeSeries`.
This method computes a number of FFTs of duration ``fftlength``
and ``overlap`` (both given in seconds), and returns the mean
average. This method is analogous to the Welch average method
for power spectra.
Paramete... | Below is the the instruction that describes the task:
### Input:
Compute the averaged one-dimensional DFT of this `TimeSeries`.
This method computes a number of FFTs of duration ``fftlength``
and ``overlap`` (both given in seconds), and returns the mean
average. This method is analogous to ... |
def send(self, raw_data = None):
"""Prepare HID raw report (unless raw_data is provided) and send
it to HID device
"""
if self.__report_kind != HidP_Output \
and self.__report_kind != HidP_Feature:
raise HIDError("Only for output or feature reports")
... | Prepare HID raw report (unless raw_data is provided) and send
it to HID device | Below is the the instruction that describes the task:
### Input:
Prepare HID raw report (unless raw_data is provided) and send
it to HID device
### Response:
def send(self, raw_data = None):
"""Prepare HID raw report (unless raw_data is provided) and send
it to HID device
"""
... |
def victim_assets(self, asset_type=None, asset_id=None):
"""Victim Asset endpoint for this resource with optional asset type.
This method will set the resource endpoint for working with Victim Assets.
The HTTP GET method will return all Victim Assets associated with this
resource or if ... | Victim Asset endpoint for this resource with optional asset type.
This method will set the resource endpoint for working with Victim Assets.
The HTTP GET method will return all Victim Assets associated with this
resource or if a asset type is provided it will return the provided asset
t... | Below is the the instruction that describes the task:
### Input:
Victim Asset endpoint for this resource with optional asset type.
This method will set the resource endpoint for working with Victim Assets.
The HTTP GET method will return all Victim Assets associated with this
resource or if... |
def spherical_angle( ra0, dec0, ra1, dec1, ra2, dec2 ):
"""
Returns the spherical angle distance between two sets of great circles defined by (ra0, dec0), (ra1, dec1) and (ra0, dec0), (ra2, dec2)
:param ra0: array or float, longitude of intersection point(s)
:param dec0: array or float, latitude of int... | Returns the spherical angle distance between two sets of great circles defined by (ra0, dec0), (ra1, dec1) and (ra0, dec0), (ra2, dec2)
:param ra0: array or float, longitude of intersection point(s)
:param dec0: array or float, latitude of intersection point(s)
:param ra1: array or float, longitude of firs... | Below is the the instruction that describes the task:
### Input:
Returns the spherical angle distance between two sets of great circles defined by (ra0, dec0), (ra1, dec1) and (ra0, dec0), (ra2, dec2)
:param ra0: array or float, longitude of intersection point(s)
:param dec0: array or float, latitude of in... |
def retrieve_crls(self, cert):
"""
:param cert:
An asn1crypto.x509.Certificate object
:param path:
A certvalidator.path.ValidationPath object for the cert
:return:
A list of asn1crypto.crl.CertificateList objects
"""
if not self._all... | :param cert:
An asn1crypto.x509.Certificate object
:param path:
A certvalidator.path.ValidationPath object for the cert
:return:
A list of asn1crypto.crl.CertificateList objects | Below is the the instruction that describes the task:
### Input:
:param cert:
An asn1crypto.x509.Certificate object
:param path:
A certvalidator.path.ValidationPath object for the cert
:return:
A list of asn1crypto.crl.CertificateList objects
### Response:
def ... |
def inference(self, state_arr, limit=1000):
'''
Infernce.
Args:
state_arr: `np.ndarray` of state.
limit: The number of inferencing.
Returns:
`list of `np.ndarray` of an optimal route.
'''
agent_x, agent_y = n... | Infernce.
Args:
state_arr: `np.ndarray` of state.
limit: The number of inferencing.
Returns:
`list of `np.ndarray` of an optimal route. | Below is the the instruction that describes the task:
### Input:
Infernce.
Args:
state_arr: `np.ndarray` of state.
limit: The number of inferencing.
Returns:
`list of `np.ndarray` of an optimal route.
### Response:
def inference(self, ... |
def get_version_info():
"""
Return astropy and photutils versions.
Returns
-------
result : str
The astropy and photutils versions.
"""
from astropy import __version__
astropy_version = __version__
from photutils import __version__
photutils_version = __version__
... | Return astropy and photutils versions.
Returns
-------
result : str
The astropy and photutils versions. | Below is the the instruction that describes the task:
### Input:
Return astropy and photutils versions.
Returns
-------
result : str
The astropy and photutils versions.
### Response:
def get_version_info():
"""
Return astropy and photutils versions.
Returns
-------
result ... |
def _init_vocab_from_file(self, filename):
"""Load vocab from a file.
Args:
filename: The file to load vocabulary from.
"""
with tf.gfile.Open(filename) as f:
tokens = [token.strip() for token in f.readlines()]
def token_gen():
for token in tokens:
yield token
self._... | Load vocab from a file.
Args:
filename: The file to load vocabulary from. | Below is the the instruction that describes the task:
### Input:
Load vocab from a file.
Args:
filename: The file to load vocabulary from.
### Response:
def _init_vocab_from_file(self, filename):
"""Load vocab from a file.
Args:
filename: The file to load vocabulary from.
"""
with... |
def schema_event_items():
"""Schema for event items."""
return {
'timestamp': And(int, lambda n: n > 0),
Optional('information', default={}): {
Optional(Regex(r'([a-z][_a-z]*)')): object
}
} | Schema for event items. | Below is the the instruction that describes the task:
### Input:
Schema for event items.
### Response:
def schema_event_items():
"""Schema for event items."""
return {
'timestamp': And(int, lambda n: n > 0),
Optional('information', default={}): {
Optional(Reg... |
def get_host_vsan_system(service_instance, host_ref, hostname=None):
'''
Returns a host's vsan system
service_instance
Service instance to the host or vCenter
host_ref
Refernce to ESXi host
hostname
Name of ESXi host. Default value is None.
'''
if not hostname:
... | Returns a host's vsan system
service_instance
Service instance to the host or vCenter
host_ref
Refernce to ESXi host
hostname
Name of ESXi host. Default value is None. | Below is the the instruction that describes the task:
### Input:
Returns a host's vsan system
service_instance
Service instance to the host or vCenter
host_ref
Refernce to ESXi host
hostname
Name of ESXi host. Default value is None.
### Response:
def get_host_vsan_system(serv... |
def add_training_data(self,
environment_id,
collection_id,
natural_language_query=None,
filter=None,
examples=None,
**kwargs):
"""
Add query to trai... | Add query to training data.
Adds a query to the training data for this collection. The query can contain a
filter and natural language query.
:param str environment_id: The ID of the environment.
:param str collection_id: The ID of the collection.
:param str natural_language_qu... | Below is the the instruction that describes the task:
### Input:
Add query to training data.
Adds a query to the training data for this collection. The query can contain a
filter and natural language query.
:param str environment_id: The ID of the environment.
:param str collection... |
def run_feature_selection(self, df_data, target, idx=0, **kwargs):
"""Run feature selection for one node: wrapper around
``self.predict_features``.
Args:
df_data (pandas.DataFrame): All the observational data
target (str): Name of the target variable
idx (int... | Run feature selection for one node: wrapper around
``self.predict_features``.
Args:
df_data (pandas.DataFrame): All the observational data
target (str): Name of the target variable
idx (int): (optional) For printing purposes
Returns:
list: scores... | Below is the the instruction that describes the task:
### Input:
Run feature selection for one node: wrapper around
``self.predict_features``.
Args:
df_data (pandas.DataFrame): All the observational data
target (str): Name of the target variable
idx (int): (optio... |
def putResourceValue(self,ep,res,data,cbfn=""):
"""
Put a value to a resource on an endpoint
:param str ep: name of endpoint
:param str res: name of resource
:param str data: data to send via PUT
:param fnptr cbfn: Optional - callback funtion to call when operation is completed
:return: successful ``.s... | Put a value to a resource on an endpoint
:param str ep: name of endpoint
:param str res: name of resource
:param str data: data to send via PUT
:param fnptr cbfn: Optional - callback funtion to call when operation is completed
:return: successful ``.status_code`` / ``.is_done``. Check the ``.error``
:rty... | Below is the the instruction that describes the task:
### Input:
Put a value to a resource on an endpoint
:param str ep: name of endpoint
:param str res: name of resource
:param str data: data to send via PUT
:param fnptr cbfn: Optional - callback funtion to call when operation is completed
:return: su... |
def all_synsets(pos=None):
"""Return all the synsets which have the provided pos.
Notes
-----
Returns thousands or tens of thousands of synsets - first time will take significant time.
Useful for initializing synsets as each returned synset is also stored in a global dictionary for fast retrieval t... | Return all the synsets which have the provided pos.
Notes
-----
Returns thousands or tens of thousands of synsets - first time will take significant time.
Useful for initializing synsets as each returned synset is also stored in a global dictionary for fast retrieval the next time.
Parameters
... | Below is the the instruction that describes the task:
### Input:
Return all the synsets which have the provided pos.
Notes
-----
Returns thousands or tens of thousands of synsets - first time will take significant time.
Useful for initializing synsets as each returned synset is also stored in a glo... |
def make_defaults_and_annotations(make_function_instr, builders):
"""
Get the AST expressions corresponding to the defaults, kwonly defaults, and
annotations for a function created by `make_function_instr`.
"""
# Integer counts.
n_defaults, n_kwonlydefaults, n_annotations = unpack_make_function_... | Get the AST expressions corresponding to the defaults, kwonly defaults, and
annotations for a function created by `make_function_instr`. | Below is the the instruction that describes the task:
### Input:
Get the AST expressions corresponding to the defaults, kwonly defaults, and
annotations for a function created by `make_function_instr`.
### Response:
def make_defaults_and_annotations(make_function_instr, builders):
"""
Get the AST expre... |
def image_summary(tag, image):
"""Outputs a `Summary` protocol buffer with image(s).
Parameters
----------
tag : str
A name for the generated summary. Will also serve as a series name in TensorBoard.
image : MXNet `NDArray` or `numpy.ndarray`
Image data that is one o... | Outputs a `Summary` protocol buffer with image(s).
Parameters
----------
tag : str
A name for the generated summary. Will also serve as a series name in TensorBoard.
image : MXNet `NDArray` or `numpy.ndarray`
Image data that is one of the following layout: (H, W), (C, H,... | Below is the the instruction that describes the task:
### Input:
Outputs a `Summary` protocol buffer with image(s).
Parameters
----------
tag : str
A name for the generated summary. Will also serve as a series name in TensorBoard.
image : MXNet `NDArray` or `numpy.ndarray`
... |
def load_model_from_file(self, filename):
"""Load one parameter set from a file which contains one value per line
No row is skipped.
Parameters
----------
filename : string, file path
Filename to loaded data from
Returns
-------
pid : int
... | Load one parameter set from a file which contains one value per line
No row is skipped.
Parameters
----------
filename : string, file path
Filename to loaded data from
Returns
-------
pid : int
ID of parameter set | Below is the the instruction that describes the task:
### Input:
Load one parameter set from a file which contains one value per line
No row is skipped.
Parameters
----------
filename : string, file path
Filename to loaded data from
Returns
-------
... |
def _sqlalchemy_on_connection_close(self):
"""
Rollsback and closes the active session, since the client disconnected before the request
could be completed.
"""
if hasattr(self, "_db_conns"):
try:
for db_conn in self._db_conns.values():
... | Rollsback and closes the active session, since the client disconnected before the request
could be completed. | Below is the the instruction that describes the task:
### Input:
Rollsback and closes the active session, since the client disconnected before the request
could be completed.
### Response:
def _sqlalchemy_on_connection_close(self):
"""
Rollsback and closes the active session, since the clie... |
def _readGQL(self, filePath, verbose=False):
"""Read a 'pretty' formatted GraphQL query file into a one-line string.
Removes line breaks and comments. Condenses white space.
Args:
filePath (str): A relative or absolute path to a file containing
a GraphQL query.
... | Read a 'pretty' formatted GraphQL query file into a one-line string.
Removes line breaks and comments. Condenses white space.
Args:
filePath (str): A relative or absolute path to a file containing
a GraphQL query.
File may use comments and multi-line formatt... | Below is the the instruction that describes the task:
### Input:
Read a 'pretty' formatted GraphQL query file into a one-line string.
Removes line breaks and comments. Condenses white space.
Args:
filePath (str): A relative or absolute path to a file containing
a GraphQ... |
def QA_fetch_get_macroindex_list(ip=None, port=None):
"""宏观指标列表
Keyword Arguments:
ip {[type]} -- [description] (default: {None})
port {[type]} -- [description] (default: {None})
38 10 宏观指标 HG
"""
global extension_market_list
extension_market_list = QA... | 宏观指标列表
Keyword Arguments:
ip {[type]} -- [description] (default: {None})
port {[type]} -- [description] (default: {None})
38 10 宏观指标 HG | Below is the the instruction that describes the task:
### Input:
宏观指标列表
Keyword Arguments:
ip {[type]} -- [description] (default: {None})
port {[type]} -- [description] (default: {None})
38 10 宏观指标 HG
### Response:
def QA_fetch_get_macroindex_list(ip=None, port=Non... |
def get(self, mac):
"""Get data from API as instance of ResponseModel.
Keyword arguments:
mac -- MAC address or OUI for searching
"""
data = {
self._FORMAT_F: 'json',
self._SEARCH_F: mac
}
response = self.__decode_str(self.__call... | Get data from API as instance of ResponseModel.
Keyword arguments:
mac -- MAC address or OUI for searching | Below is the the instruction that describes the task:
### Input:
Get data from API as instance of ResponseModel.
Keyword arguments:
mac -- MAC address or OUI for searching
### Response:
def get(self, mac):
"""Get data from API as instance of ResponseModel.
Keyword argu... |
def post(cond):
"""
Add a postcondition check to the annotated method. The condition
is passed the return value of the annotated method.
"""
source = inspect.getsource(cond).strip()
def inner(f):
if enabled:
# deal with the real function, not a wrapper
f = geta... | Add a postcondition check to the annotated method. The condition
is passed the return value of the annotated method. | Below is the the instruction that describes the task:
### Input:
Add a postcondition check to the annotated method. The condition
is passed the return value of the annotated method.
### Response:
def post(cond):
"""
Add a postcondition check to the annotated method. The condition
is passed the r... |
def _SignedVarintDecoder(mask):
"""Like _VarintDecoder() but decodes signed values."""
def DecodeVarint(buffer, pos):
result = 0
shift = 0
while 1:
if pos > len(buffer) -1:
raise NotEnoughDataException( "Not enough data to decode varint" )
b = local_ord(buffer[pos])
result |... | Like _VarintDecoder() but decodes signed values. | Below is the the instruction that describes the task:
### Input:
Like _VarintDecoder() but decodes signed values.
### Response:
def _SignedVarintDecoder(mask):
"""Like _VarintDecoder() but decodes signed values."""
def DecodeVarint(buffer, pos):
result = 0
shift = 0
while 1:
if pos > len(bu... |
def _make_short(self, data, endianness):
"""Returns a 2 byte integer."""
data = binwalk.core.compat.str2bytes(data)
return struct.unpack('%sH' % endianness, data)[0] | Returns a 2 byte integer. | Below is the the instruction that describes the task:
### Input:
Returns a 2 byte integer.
### Response:
def _make_short(self, data, endianness):
"""Returns a 2 byte integer."""
data = binwalk.core.compat.str2bytes(data)
return struct.unpack('%sH' % endianness, data)[0] |
def drawSector(self, center, point, beta, fullSector=True):
"""Draw a circle sector.
"""
center = Point(center)
point = Point(point)
l3 = "%g %g m\n"
l4 = "%g %g %g %g %g %g c\n"
l5 = "%g %g l\n"
betar = math.radians(-beta)
w360 = math.radians(math... | Draw a circle sector. | Below is the the instruction that describes the task:
### Input:
Draw a circle sector.
### Response:
def drawSector(self, center, point, beta, fullSector=True):
"""Draw a circle sector.
"""
center = Point(center)
point = Point(point)
l3 = "%g %g m\n"
l4 = "%g %g %g %... |
def system_methodHelp(self, method_name):
"""system.methodHelp('add') => "Adds two integers together"
Returns a string containing documentation for the specified method."""
method = None
if method_name in self.funcs:
method = self.funcs[method_name]
elif self.instan... | system.methodHelp('add') => "Adds two integers together"
Returns a string containing documentation for the specified method. | Below is the the instruction that describes the task:
### Input:
system.methodHelp('add') => "Adds two integers together"
Returns a string containing documentation for the specified method.
### Response:
def system_methodHelp(self, method_name):
"""system.methodHelp('add') => "Adds two integers to... |
def send_iq_and_wait_for_reply(self, iq, *,
timeout=None):
"""
Send an IQ stanza `iq` and wait for the response. If `timeout` is not
:data:`None`, it must be the time in seconds for which to wait for a
response.
If the response is a ``"result"`... | Send an IQ stanza `iq` and wait for the response. If `timeout` is not
:data:`None`, it must be the time in seconds for which to wait for a
response.
If the response is a ``"result"`` IQ, the value of the
:attr:`~aioxmpp.IQ.payload` attribute is returned. Otherwise,
the exception... | Below is the the instruction that describes the task:
### Input:
Send an IQ stanza `iq` and wait for the response. If `timeout` is not
:data:`None`, it must be the time in seconds for which to wait for a
response.
If the response is a ``"result"`` IQ, the value of the
:attr:`~aioxmp... |
def main(args=None):
"""Main function for cli."""
args = get_args(args)
utils.init_log(args.log_level)
if ".csv" not in args.input_file.lower():
logger.warning("Make sure the input file '%s' is in CSV format", args.input_file)
try:
records = csvtools.get_imported_data(args.input_f... | Main function for cli. | Below is the the instruction that describes the task:
### Input:
Main function for cli.
### Response:
def main(args=None):
"""Main function for cli."""
args = get_args(args)
utils.init_log(args.log_level)
if ".csv" not in args.input_file.lower():
logger.warning("Make sure the input file '... |
def _ReadAndCheckStorageMetadata(self, check_readable_only=False):
"""Reads storage metadata and checks that the values are valid.
Args:
check_readable_only (Optional[bool]): whether the store should only be
checked to see if it can be read. If False, the store will be checked
to see ... | Reads storage metadata and checks that the values are valid.
Args:
check_readable_only (Optional[bool]): whether the store should only be
checked to see if it can be read. If False, the store will be checked
to see if it can be read and written to. | Below is the the instruction that describes the task:
### Input:
Reads storage metadata and checks that the values are valid.
Args:
check_readable_only (Optional[bool]): whether the store should only be
checked to see if it can be read. If False, the store will be checked
to see if it... |
def cli(
paths,
dbname,
separator,
quoting,
skip_errors,
replace_tables,
table,
extract_column,
date,
datetime,
datetime_format,
primary_key,
fts,
index,
shape,
filename_column,
no_index_fks,
no_fulltext_fks,
):
"""
PATHS: paths to individu... | PATHS: paths to individual .csv files or to directories containing .csvs
DBNAME: name of the SQLite database file to create | Below is the the instruction that describes the task:
### Input:
PATHS: paths to individual .csv files or to directories containing .csvs
DBNAME: name of the SQLite database file to create
### Response:
def cli(
paths,
dbname,
separator,
quoting,
skip_errors,
replace_tables,
table,... |
def _adjacency_to_edges(adjacency):
"""determine from an adjacency the list of edges
if (u, v) in edges, then (v, u) should not be"""
edges = set()
for u in adjacency:
for v in adjacency[u]:
try:
edge = (u, v) if u <= v else (v, u)
except TypeError:
... | determine from an adjacency the list of edges
if (u, v) in edges, then (v, u) should not be | Below is the the instruction that describes the task:
### Input:
determine from an adjacency the list of edges
if (u, v) in edges, then (v, u) should not be
### Response:
def _adjacency_to_edges(adjacency):
"""determine from an adjacency the list of edges
if (u, v) in edges, then (v, u) should not be""... |
def activate_eco(self):
"""Activates the comfort temperature."""
value = struct.pack('B', PROP_ECO)
self._conn.make_request(PROP_WRITE_HANDLE, value) | Activates the comfort temperature. | Below is the the instruction that describes the task:
### Input:
Activates the comfort temperature.
### Response:
def activate_eco(self):
"""Activates the comfort temperature."""
value = struct.pack('B', PROP_ECO)
self._conn.make_request(PROP_WRITE_HANDLE, value) |
def post(self, uri, params={}, data={}):
'''A generic method to make POST requests on the given URI.'''
return requests.post(
urlparse.urljoin(self.BASE_URL, uri),
params=params, data=json.dumps(data), verify=False,
auth=self.auth, headers = {'Content-type': 'applicat... | A generic method to make POST requests on the given URI. | Below is the the instruction that describes the task:
### Input:
A generic method to make POST requests on the given URI.
### Response:
def post(self, uri, params={}, data={}):
'''A generic method to make POST requests on the given URI.'''
return requests.post(
urlparse.urljoin(self.BAS... |
def register_click_watcher(self, watcher_name, selectors, *condition_list):
"""
The watcher click on the object which has the *selectors* when conditions match.
"""
watcher = self.device.watcher(watcher_name)
for condition in condition_list:
watcher.when(**self.__unic... | The watcher click on the object which has the *selectors* when conditions match. | Below is the the instruction that describes the task:
### Input:
The watcher click on the object which has the *selectors* when conditions match.
### Response:
def register_click_watcher(self, watcher_name, selectors, *condition_list):
"""
The watcher click on the object which has the *selectors* w... |
def create_task_log(self, task_id, case_task_log):
"""
:param task_id: Task identifier
:param case_task_log: TheHive log
:type case_task_log: CaseTaskLog defined in models.py
:return: TheHive log
:rtype: json
"""
req = self.url + "/api/case/task/{}/log".... | :param task_id: Task identifier
:param case_task_log: TheHive log
:type case_task_log: CaseTaskLog defined in models.py
:return: TheHive log
:rtype: json | Below is the the instruction that describes the task:
### Input:
:param task_id: Task identifier
:param case_task_log: TheHive log
:type case_task_log: CaseTaskLog defined in models.py
:return: TheHive log
:rtype: json
### Response:
def create_task_log(self, task_id, case_task_log):... |
def ip_address(self,
container: Container
) -> Union[IPv4Address, IPv6Address]:
"""
The IP address used by a given container, or None if no IP address has
been assigned to that container.
"""
r = self.__api.get('containers/{}/ip'.format(conta... | The IP address used by a given container, or None if no IP address has
been assigned to that container. | Below is the the instruction that describes the task:
### Input:
The IP address used by a given container, or None if no IP address has
been assigned to that container.
### Response:
def ip_address(self,
container: Container
) -> Union[IPv4Address, IPv6Address]:
... |
def write(filename, samples, write_params=None, static_args=None,
injtype=None, **metadata):
"""Writes the injection samples to the given hdf file.
Parameters
----------
filename : str
The name of the file to write to.
samples : io.FieldArray
... | Writes the injection samples to the given hdf file.
Parameters
----------
filename : str
The name of the file to write to.
samples : io.FieldArray
FieldArray of parameters.
write_params : list, optional
Only write the given parameter names. Al... | Below is the the instruction that describes the task:
### Input:
Writes the injection samples to the given hdf file.
Parameters
----------
filename : str
The name of the file to write to.
samples : io.FieldArray
FieldArray of parameters.
write_params ... |
def _compile_and_collapse(self):
"""Actually compile the requested regex"""
self._real_regex = self._real_re_compile(*self._regex_args,
**self._regex_kwargs)
for attr in self._regex_attributes_to_copy:
setattr(self, attr, getattr(self.... | Actually compile the requested regex | Below is the the instruction that describes the task:
### Input:
Actually compile the requested regex
### Response:
def _compile_and_collapse(self):
"""Actually compile the requested regex"""
self._real_regex = self._real_re_compile(*self._regex_args,
... |
def get_next_state(self, state, ret, oper):
"""Returns the next state for a create or delete operation. """
if oper == fw_const.FW_CR_OP:
return self.get_next_create_state(state, ret)
else:
return self.get_next_del_state(state, ret) | Returns the next state for a create or delete operation. | Below is the the instruction that describes the task:
### Input:
Returns the next state for a create or delete operation.
### Response:
def get_next_state(self, state, ret, oper):
"""Returns the next state for a create or delete operation. """
if oper == fw_const.FW_CR_OP:
return self.g... |
def set_palette(self, background, foreground):
"""
Set text editor palette colors:
background color and caret (text cursor) color
"""
palette = QPalette()
palette.setColor(QPalette.Base, background)
palette.setColor(QPalette.Text, foreground)
self.... | Set text editor palette colors:
background color and caret (text cursor) color | Below is the the instruction that describes the task:
### Input:
Set text editor palette colors:
background color and caret (text cursor) color
### Response:
def set_palette(self, background, foreground):
"""
Set text editor palette colors:
background color and caret (text curso... |
def _opt_to_args(cls, opt, val):
"""Convert a named option and optional value to command line
argument notation, correctly handling options that take
no value or that have special representations (e.g. verify
and verbose).
"""
no_value = (
"allopti... | Convert a named option and optional value to command line
argument notation, correctly handling options that take
no value or that have special representations (e.g. verify
and verbose). | Below is the the instruction that describes the task:
### Input:
Convert a named option and optional value to command line
argument notation, correctly handling options that take
no value or that have special representations (e.g. verify
and verbose).
### Response:
def _opt_to_a... |
def _report_problem(self, problem, level=logging.ERROR):
'''Report a given problem'''
problem = self.basename + ': ' + problem
if self._logger.isEnabledFor(level):
self._problematic = True
if self._check_raises:
raise DapInvalid(problem)
self._logger.log(l... | Report a given problem | Below is the the instruction that describes the task:
### Input:
Report a given problem
### Response:
def _report_problem(self, problem, level=logging.ERROR):
'''Report a given problem'''
problem = self.basename + ': ' + problem
if self._logger.isEnabledFor(level):
self._problem... |
def if_match(self, values):
"""
Set the If-Match option of a request.
:param values: the If-Match values
:type values : list
"""
assert isinstance(values, list)
for v in values:
option = Option()
option.number = defines.OptionRegistry.IF_M... | Set the If-Match option of a request.
:param values: the If-Match values
:type values : list | Below is the the instruction that describes the task:
### Input:
Set the If-Match option of a request.
:param values: the If-Match values
:type values : list
### Response:
def if_match(self, values):
"""
Set the If-Match option of a request.
:param values: the If-Match val... |
def accept_arguments(method, number_of_arguments=1):
"""Returns True if the given method will accept the given number of arguments
method: the method to perform introspection on
number_of_arguments: the number_of_arguments
"""
if 'method' in method.__class__.__name__:
number_of_argume... | Returns True if the given method will accept the given number of arguments
method: the method to perform introspection on
number_of_arguments: the number_of_arguments | Below is the the instruction that describes the task:
### Input:
Returns True if the given method will accept the given number of arguments
method: the method to perform introspection on
number_of_arguments: the number_of_arguments
### Response:
def accept_arguments(method, number_of_arguments=1):
... |
def clear(self, asset_manager_id):
""" This method deletes all the data for an asset_manager_id.
It should be used with extreme caution. In production it
is almost always better to Inactivate rather than delete. """
self.logger.info('Clear Assets - Asset Manager: %s', asset_mana... | This method deletes all the data for an asset_manager_id.
It should be used with extreme caution. In production it
is almost always better to Inactivate rather than delete. | Below is the the instruction that describes the task:
### Input:
This method deletes all the data for an asset_manager_id.
It should be used with extreme caution. In production it
is almost always better to Inactivate rather than delete.
### Response:
def clear(self, asset_manager_id):
... |
def _communicate(self):
"""Callback for communicate."""
if (not self._communicate_first and
self._process.state() == QProcess.NotRunning):
self.communicate()
elif self._fired:
self._timer.stop() | Callback for communicate. | Below is the the instruction that describes the task:
### Input:
Callback for communicate.
### Response:
def _communicate(self):
"""Callback for communicate."""
if (not self._communicate_first and
self._process.state() == QProcess.NotRunning):
self.communicate()
... |
def answer_pre_checkout_query(token, pre_checkout_query_id, ok, error_message=None):
"""
Once the user has confirmed their payment and shipping details, the Bot API sends the final confirmation in the form of an Update with the field pre_checkout_query. Use this method to respond to such pre-checkout queries. O... | Once the user has confirmed their payment and shipping details, the Bot API sends the final confirmation in the form of an Update with the field pre_checkout_query. Use this method to respond to such pre-checkout queries. On success, True is returned. Note: The Bot API must receive an answer within 10 seconds after the... | Below is the the instruction that describes the task:
### Input:
Once the user has confirmed their payment and shipping details, the Bot API sends the final confirmation in the form of an Update with the field pre_checkout_query. Use this method to respond to such pre-checkout queries. On success, True is returned.... |
def tag(self, *tags):
"""
Tags the job with one or more unique indentifiers.
Tags must be hashable. Duplicate tags are discarded.
:param tags: A unique list of ``Hashable`` tags.
:return: The invoked job instance
"""
if not all(isinstance(tag, collections.Hashab... | Tags the job with one or more unique indentifiers.
Tags must be hashable. Duplicate tags are discarded.
:param tags: A unique list of ``Hashable`` tags.
:return: The invoked job instance | Below is the the instruction that describes the task:
### Input:
Tags the job with one or more unique indentifiers.
Tags must be hashable. Duplicate tags are discarded.
:param tags: A unique list of ``Hashable`` tags.
:return: The invoked job instance
### Response:
def tag(self, *tags):
... |
def auth_user_ldap(uname, pwd):
"""
Attempts to bind using the uname/pwd combo passed in.
If that works, returns true. Otherwise returns false.
"""
if not uname or not pwd:
logging.error("Username or password not supplied")
return False
ld = ldap.initialize(LDAP_URL)
if LDA... | Attempts to bind using the uname/pwd combo passed in.
If that works, returns true. Otherwise returns false. | Below is the the instruction that describes the task:
### Input:
Attempts to bind using the uname/pwd combo passed in.
If that works, returns true. Otherwise returns false.
### Response:
def auth_user_ldap(uname, pwd):
"""
Attempts to bind using the uname/pwd combo passed in.
If that works, returns... |
def parse_requirements(self, filename):
"""
Recursively find all the requirements needed
storing them in req_parents, req_paths, req_linenos
"""
cwd = os.path.dirname(filename)
try:
fd = open(filename, 'r')
for i, line in enumerate(fd.readlines()... | Recursively find all the requirements needed
storing them in req_parents, req_paths, req_linenos | Below is the the instruction that describes the task:
### Input:
Recursively find all the requirements needed
storing them in req_parents, req_paths, req_linenos
### Response:
def parse_requirements(self, filename):
"""
Recursively find all the requirements needed
storing them in re... |
def set_value(self, value, timeout):
"""
Sets a new value and extends its expiration.
:param value: a new cached value.
:param timeout: a expiration timeout in milliseconds.
"""
self.value = value
self.expiration = time.perf_counter() * 1000 + timeout | Sets a new value and extends its expiration.
:param value: a new cached value.
:param timeout: a expiration timeout in milliseconds. | Below is the the instruction that describes the task:
### Input:
Sets a new value and extends its expiration.
:param value: a new cached value.
:param timeout: a expiration timeout in milliseconds.
### Response:
def set_value(self, value, timeout):
"""
Sets a new value and extends... |
def reboot(self, timeout=None, wait_polling_interval=None):
"""Reboot the device, waiting for the adb connection to become stable.
:param timeout: Maximum time to wait for reboot.
:param wait_polling_interval: Interval at which to poll for device readiness.
"""
if timeout is Non... | Reboot the device, waiting for the adb connection to become stable.
:param timeout: Maximum time to wait for reboot.
:param wait_polling_interval: Interval at which to poll for device readiness. | Below is the the instruction that describes the task:
### Input:
Reboot the device, waiting for the adb connection to become stable.
:param timeout: Maximum time to wait for reboot.
:param wait_polling_interval: Interval at which to poll for device readiness.
### Response:
def reboot(self, timeout... |
def encode_dict(values_dict):
"""Encode a dictionary into protobuf ``Value``-s.
Args:
values_dict (dict): The dictionary to encode as protobuf fields.
Returns:
Dict[str, ~google.cloud.firestore_v1beta1.types.Value]: A
dictionary of string keys and ``Value`` protobufs as dictionary
... | Encode a dictionary into protobuf ``Value``-s.
Args:
values_dict (dict): The dictionary to encode as protobuf fields.
Returns:
Dict[str, ~google.cloud.firestore_v1beta1.types.Value]: A
dictionary of string keys and ``Value`` protobufs as dictionary
values. | Below is the the instruction that describes the task:
### Input:
Encode a dictionary into protobuf ``Value``-s.
Args:
values_dict (dict): The dictionary to encode as protobuf fields.
Returns:
Dict[str, ~google.cloud.firestore_v1beta1.types.Value]: A
dictionary of string keys and ``... |
def list_container_objects(container_name, profile, **libcloud_kwargs):
'''
List container objects (e.g. files) for the given container_id on the given profile
:param container_name: Container name
:type container_name: ``str``
:param profile: The profile key
:type profile: ``str``
:par... | List container objects (e.g. files) for the given container_id on the given profile
:param container_name: Container name
:type container_name: ``str``
:param profile: The profile key
:type profile: ``str``
:param libcloud_kwargs: Extra arguments for the driver's list_container_objects method
... | Below is the the instruction that describes the task:
### Input:
List container objects (e.g. files) for the given container_id on the given profile
:param container_name: Container name
:type container_name: ``str``
:param profile: The profile key
:type profile: ``str``
:param libcloud_kwa... |
def addSRNLayers(self, inc, hidc, outc):
"""
Wraps SRN.addThreeLayers() for compatibility.
"""
self.addThreeLayers(inc, hidc, outc) | Wraps SRN.addThreeLayers() for compatibility. | Below is the the instruction that describes the task:
### Input:
Wraps SRN.addThreeLayers() for compatibility.
### Response:
def addSRNLayers(self, inc, hidc, outc):
"""
Wraps SRN.addThreeLayers() for compatibility.
"""
self.addThreeLayers(inc, hidc, outc) |
def get_with_rtdcbase(self, col1, col2, method, dataset,
viscosity=None, add_px_err=False):
"""Convenience method that extracts the metadata from RTDCBase
Parameters
----------
col1: str
Name of the first feature of all isoelastics
(e.g.... | Convenience method that extracts the metadata from RTDCBase
Parameters
----------
col1: str
Name of the first feature of all isoelastics
(e.g. isoel[0][:,0])
col2: str
Name of the second feature of all isoelastics
(e.g. isoel[0][:,1])
... | Below is the the instruction that describes the task:
### Input:
Convenience method that extracts the metadata from RTDCBase
Parameters
----------
col1: str
Name of the first feature of all isoelastics
(e.g. isoel[0][:,0])
col2: str
Name of the se... |
def read_metadata(self, file_path): # type: (str) ->str
"""
Get version out of a .ini file (or .cfg)
:return:
"""
config = configparser.ConfigParser()
config.read(file_path)
try:
return unicode(config["metadata"]["version"])
except KeyError:
... | Get version out of a .ini file (or .cfg)
:return: | Below is the the instruction that describes the task:
### Input:
Get version out of a .ini file (or .cfg)
:return:
### Response:
def read_metadata(self, file_path): # type: (str) ->str
"""
Get version out of a .ini file (or .cfg)
:return:
"""
config = configparser.C... |
def load(path, name, cluster):
"""
Load a node from from the path on disk to the config files, the node name and the
cluster the node is part of.
"""
node_path = os.path.join(path, name)
filename = os.path.join(node_path, 'node.conf')
with open(filename, 'r') as f... | Load a node from from the path on disk to the config files, the node name and the
cluster the node is part of. | Below is the the instruction that describes the task:
### Input:
Load a node from from the path on disk to the config files, the node name and the
cluster the node is part of.
### Response:
def load(path, name, cluster):
"""
Load a node from from the path on disk to the config files, the no... |
def with_setup(self, colormode=None, colorpalette=None, extend_colors=False):
"""
Return a new Colorful object with the given color config.
"""
colorful = Colorful(
colormode=self.colorful.colormode,
colorpalette=copy.copy(self.colorful.colorpalette)
)
... | Return a new Colorful object with the given color config. | Below is the the instruction that describes the task:
### Input:
Return a new Colorful object with the given color config.
### Response:
def with_setup(self, colormode=None, colorpalette=None, extend_colors=False):
"""
Return a new Colorful object with the given color config.
"""
co... |
def templated_docstring(**docs):
"""
Decorator allowing the use of templated docstrings.
Examples
--------
>>> @templated_docstring(foo='bar')
... def my_func(self, foo):
... '''{foo}'''
...
>>> my_func.__doc__
'bar'
"""
def decorator(f):
f.__doc__ = format_d... | Decorator allowing the use of templated docstrings.
Examples
--------
>>> @templated_docstring(foo='bar')
... def my_func(self, foo):
... '''{foo}'''
...
>>> my_func.__doc__
'bar' | Below is the the instruction that describes the task:
### Input:
Decorator allowing the use of templated docstrings.
Examples
--------
>>> @templated_docstring(foo='bar')
... def my_func(self, foo):
... '''{foo}'''
...
>>> my_func.__doc__
'bar'
### Response:
def templated_docst... |
def findOptimalResults(expName, suite, outFile):
"""
Go through every experiment in the specified folder. For each experiment, find
the iteration with the best validation score, and return the metrics
associated with that iteration.
"""
writer = csv.writer(outFile)
headers = ["testAccuracy", "bgAccuracy",... | Go through every experiment in the specified folder. For each experiment, find
the iteration with the best validation score, and return the metrics
associated with that iteration. | Below is the the instruction that describes the task:
### Input:
Go through every experiment in the specified folder. For each experiment, find
the iteration with the best validation score, and return the metrics
associated with that iteration.
### Response:
def findOptimalResults(expName, suite, outFile):
"... |
def from_json(cls, json):
"""Creates an instance of the InputReader for the given input shard's state.
Args:
json: The InputReader state as a dict-like object.
Returns:
An instance of the InputReader configured using the given JSON parameters.
"""
# Strip out unrecognized parameters, a... | Creates an instance of the InputReader for the given input shard's state.
Args:
json: The InputReader state as a dict-like object.
Returns:
An instance of the InputReader configured using the given JSON parameters. | Below is the the instruction that describes the task:
### Input:
Creates an instance of the InputReader for the given input shard's state.
Args:
json: The InputReader state as a dict-like object.
Returns:
An instance of the InputReader configured using the given JSON parameters.
### Response: ... |
def _padding_slices_inner(lhs_arr, rhs_arr, axis, offset, pad_mode):
"""Return slices into the inner array part for a given ``pad_mode``.
When performing padding, these slices yield the values from the inner
part of a larger array that are to be assigned to the excess part
of the same array. Slices for... | Return slices into the inner array part for a given ``pad_mode``.
When performing padding, these slices yield the values from the inner
part of a larger array that are to be assigned to the excess part
of the same array. Slices for both sides ("left", "right") of
the arrays in a given ``axis`` are retu... | Below is the the instruction that describes the task:
### Input:
Return slices into the inner array part for a given ``pad_mode``.
When performing padding, these slices yield the values from the inner
part of a larger array that are to be assigned to the excess part
of the same array. Slices for both s... |
def update_member(self, member_id, peer_urls):
"""
Update the configuration of an existing member in the cluster.
:param member_id: ID of the member to update
:param peer_urls: new list of peer urls the member will use to
communicate with the cluster
""... | Update the configuration of an existing member in the cluster.
:param member_id: ID of the member to update
:param peer_urls: new list of peer urls the member will use to
communicate with the cluster | Below is the the instruction that describes the task:
### Input:
Update the configuration of an existing member in the cluster.
:param member_id: ID of the member to update
:param peer_urls: new list of peer urls the member will use to
communicate with the cluster
### Resp... |
def index(self, item, minindex=0, maxindex=None):
"""Provide an index of first occurence of item in the list. (or raise
a ValueError if item not present)
If item is not a string, will raise a TypeError.
minindex and maxindex are also optional arguments
s.index(x[, i[, j]]) return... | Provide an index of first occurence of item in the list. (or raise
a ValueError if item not present)
If item is not a string, will raise a TypeError.
minindex and maxindex are also optional arguments
s.index(x[, i[, j]]) return smallest k such that s[k] == x and i <= k < j | Below is the the instruction that describes the task:
### Input:
Provide an index of first occurence of item in the list. (or raise
a ValueError if item not present)
If item is not a string, will raise a TypeError.
minindex and maxindex are also optional arguments
s.index(x[, i[, j]]... |
def get_user_by_id(bridge_id, include_course_summary=True):
"""
:param bridge_id: integer
Return a list of BridgeUsers objects with custom fields
"""
url = author_id_url(bridge_id) + "?%s" % CUSTOM_FIELD
if include_course_summary:
url = "%s&%s" % (url, COURSE_SUMMARY)
resp = get_reso... | :param bridge_id: integer
Return a list of BridgeUsers objects with custom fields | Below is the the instruction that describes the task:
### Input:
:param bridge_id: integer
Return a list of BridgeUsers objects with custom fields
### Response:
def get_user_by_id(bridge_id, include_course_summary=True):
"""
:param bridge_id: integer
Return a list of BridgeUsers objects with custom... |
def recall(self, label=None):
"""
Returns recall or recall for a given label (category) if specified.
"""
if label is None:
return self.call("recall")
else:
return self.call("recall", float(label)) | Returns recall or recall for a given label (category) if specified. | Below is the the instruction that describes the task:
### Input:
Returns recall or recall for a given label (category) if specified.
### Response:
def recall(self, label=None):
"""
Returns recall or recall for a given label (category) if specified.
"""
if label is None:
... |
def estimate_position_angle(self,param='position_angle',burn=None,clip=10.0,alpha=0.32):
""" Estimate the position angle from the posterior dealing
with periodicity.
"""
# Transform so peak in the middle of the distribution
pa = self.samples.get(param,burn=burn,clip=clip)
... | Estimate the position angle from the posterior dealing
with periodicity. | Below is the the instruction that describes the task:
### Input:
Estimate the position angle from the posterior dealing
with periodicity.
### Response:
def estimate_position_angle(self,param='position_angle',burn=None,clip=10.0,alpha=0.32):
""" Estimate the position angle from the posterior dealing... |
def basic(request, response, verify_user, realm='simple', context=None, **kwargs):
"""Basic HTTP Authentication"""
http_auth = request.auth
response.set_header('WWW-Authenticate', 'Basic')
if http_auth is None:
return
if isinstance(http_auth, bytes):
http_auth = http_auth.decode('ut... | Basic HTTP Authentication | Below is the the instruction that describes the task:
### Input:
Basic HTTP Authentication
### Response:
def basic(request, response, verify_user, realm='simple', context=None, **kwargs):
"""Basic HTTP Authentication"""
http_auth = request.auth
response.set_header('WWW-Authenticate', 'Basic')
if ht... |
def unit(self, parameter):
"Get the unit for given parameter"
parameter = self._get_parameter_name(parameter).lower()
return self._parameters[parameter]['Unit'] | Get the unit for given parameter | Below is the the instruction that describes the task:
### Input:
Get the unit for given parameter
### Response:
def unit(self, parameter):
"Get the unit for given parameter"
parameter = self._get_parameter_name(parameter).lower()
return self._parameters[parameter]['Unit'] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.