code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def create_class(self, method):
"""
Build the estimator class.
Returns
-------
:return : string
The built class as string.
"""
self.__dict__.update(dict(method=method))
temp_class = self.temp('separated.class')
return temp_class.format... | Build the estimator class.
Returns
-------
:return : string
The built class as string. | Below is the the instruction that describes the task:
### Input:
Build the estimator class.
Returns
-------
:return : string
The built class as string.
### Response:
def create_class(self, method):
"""
Build the estimator class.
Returns
-------
... |
def align(data, align='hyper', normalize=None, ndims=None, method=None,
format_data=True):
"""
Aligns a list of arrays
This function takes a list of high dimensional arrays and 'hyperaligns' them
to a 'common' space, or coordinate system following the approach outlined by
Haxby et al, 201... | Aligns a list of arrays
This function takes a list of high dimensional arrays and 'hyperaligns' them
to a 'common' space, or coordinate system following the approach outlined by
Haxby et al, 2011. Hyperalignment uses linear transformations (rotation,
reflection, translation, scaling) to register a grou... | Below is the the instruction that describes the task:
### Input:
Aligns a list of arrays
This function takes a list of high dimensional arrays and 'hyperaligns' them
to a 'common' space, or coordinate system following the approach outlined by
Haxby et al, 2011. Hyperalignment uses linear transformation... |
def get_all_xml_file_paths(self, raw_data_directory: str) -> List[str]:
""" Loads all XML-files that are located in the folder.
:param raw_data_directory: Path to the raw directory, where the MUSCIMA++ dataset was extracted to
"""
raw_data_directory = os.path.join(raw_data_directory, "v1... | Loads all XML-files that are located in the folder.
:param raw_data_directory: Path to the raw directory, where the MUSCIMA++ dataset was extracted to | Below is the the instruction that describes the task:
### Input:
Loads all XML-files that are located in the folder.
:param raw_data_directory: Path to the raw directory, where the MUSCIMA++ dataset was extracted to
### Response:
def get_all_xml_file_paths(self, raw_data_directory: str) -> List[str]:
... |
def get_objects_apk(self, filename=None, digest=None):
"""
Returns APK, DalvikVMFormat and Analysis of a specified APK.
You must specify either `filename` or `digest`.
It is possible to use both, but in this case only `digest` is used.
example::
s = Session()
... | Returns APK, DalvikVMFormat and Analysis of a specified APK.
You must specify either `filename` or `digest`.
It is possible to use both, but in this case only `digest` is used.
example::
s = Session()
digest = s.add("some.apk")
a, d, dx = s.get_objects_apk(... | Below is the the instruction that describes the task:
### Input:
Returns APK, DalvikVMFormat and Analysis of a specified APK.
You must specify either `filename` or `digest`.
It is possible to use both, but in this case only `digest` is used.
example::
s = Session()
... |
def add_network_profile(self, obj, params):
"""Add an AP profile for connecting to afterward."""
network_id = self._send_cmd_to_wpas(obj['name'], 'ADD_NETWORK', True)
network_id = network_id.strip()
params.process_akm()
self._send_cmd_to_wpas(
obj['name'],
... | Add an AP profile for connecting to afterward. | Below is the the instruction that describes the task:
### Input:
Add an AP profile for connecting to afterward.
### Response:
def add_network_profile(self, obj, params):
"""Add an AP profile for connecting to afterward."""
network_id = self._send_cmd_to_wpas(obj['name'], 'ADD_NETWORK', True)
... |
def get_namespaced_custom_object(self, group, version, namespace, plural, name, **kwargs):
"""
Returns a namespace scoped custom object
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_n... | Returns a namespace scoped custom object
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_namespaced_custom_object(group, version, namespace, plural, name, async_req=True)
>>> result = thread.ge... | Below is the the instruction that describes the task:
### Input:
Returns a namespace scoped custom object
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_namespaced_custom_object(group, version, na... |
async def stop(wallet_name: str) -> None:
"""
Gracefully stop an external revocation registry builder, waiting for its current.
The indy-sdk toolkit uses a temporary directory for tails file mustration,
and shutting down the toolkit removes the directory, crashing the external
t... | Gracefully stop an external revocation registry builder, waiting for its current.
The indy-sdk toolkit uses a temporary directory for tails file mustration,
and shutting down the toolkit removes the directory, crashing the external
tails file write. This method allows a graceful stop to wait fo... | Below is the the instruction that describes the task:
### Input:
Gracefully stop an external revocation registry builder, waiting for its current.
The indy-sdk toolkit uses a temporary directory for tails file mustration,
and shutting down the toolkit removes the directory, crashing the external
... |
def extract_object_properties(self, o, limit_size=False):
"""Extracts all properties from an object (eg. f_locals, f_globals,
user dict, instance ...) and returns them as an array of variables.
"""
try:
prop_str = repr(o)[:512]
except:
prop_str = "Error w... | Extracts all properties from an object (eg. f_locals, f_globals,
user dict, instance ...) and returns them as an array of variables. | Below is the the instruction that describes the task:
### Input:
Extracts all properties from an object (eg. f_locals, f_globals,
user dict, instance ...) and returns them as an array of variables.
### Response:
def extract_object_properties(self, o, limit_size=False):
"""Extracts all properties f... |
def _handle_response(response):
"""
Handle the response and possible failures.
:param Response response: Response data.
:return: A dictionary or a string with response data.
:raises: NeverBounceAPIError if the API call fails.
"""
if not response.ok:
ra... | Handle the response and possible failures.
:param Response response: Response data.
:return: A dictionary or a string with response data.
:raises: NeverBounceAPIError if the API call fails. | Below is the the instruction that describes the task:
### Input:
Handle the response and possible failures.
:param Response response: Response data.
:return: A dictionary or a string with response data.
:raises: NeverBounceAPIError if the API call fails.
### Response:
def _handle_response(r... |
def exclude_reference_link(self, exclude):
"""Sets `sysparm_exclude_reference_link` to a bool value
:param exclude: bool
"""
if not isinstance(exclude, bool):
raise InvalidUsage('exclude_reference_link must be of type bool')
self._sysparms['sysparm_exclude_reference... | Sets `sysparm_exclude_reference_link` to a bool value
:param exclude: bool | Below is the the instruction that describes the task:
### Input:
Sets `sysparm_exclude_reference_link` to a bool value
:param exclude: bool
### Response:
def exclude_reference_link(self, exclude):
"""Sets `sysparm_exclude_reference_link` to a bool value
:param exclude: bool
"""
... |
def _walk_issuers(self, path, paths, failed_paths):
"""
Recursively looks through the list of known certificates for the issuer
of the certificate specified, stopping once the certificate in question
is one contained within the CA certs list
:param path:
A Validation... | Recursively looks through the list of known certificates for the issuer
of the certificate specified, stopping once the certificate in question
is one contained within the CA certs list
:param path:
A ValidationPath object representing the current traversal of
possible p... | Below is the the instruction that describes the task:
### Input:
Recursively looks through the list of known certificates for the issuer
of the certificate specified, stopping once the certificate in question
is one contained within the CA certs list
:param path:
A ValidationPat... |
def GetAncestorControl(self, condition: Callable) -> 'Control':
"""
Get a ancestor control that matches the condition.
condition: Callable, function (control: Control, depth: int)->bool,
depth starts with -1 and decreses when search goes up.
Return `Control` subclass o... | Get a ancestor control that matches the condition.
condition: Callable, function (control: Control, depth: int)->bool,
depth starts with -1 and decreses when search goes up.
Return `Control` subclass or None. | Below is the the instruction that describes the task:
### Input:
Get a ancestor control that matches the condition.
condition: Callable, function (control: Control, depth: int)->bool,
depth starts with -1 and decreses when search goes up.
Return `Control` subclass or None.
### Res... |
def draw(self, current_time, frame_time):
"""
Calls the superclass ``draw()`` methods and checks ``HEADLESS_FRAMES``/``HEADLESS_DURATION``
"""
super().draw(current_time, frame_time)
if self.headless_duration and current_time >= self.headless_duration:
self.close() | Calls the superclass ``draw()`` methods and checks ``HEADLESS_FRAMES``/``HEADLESS_DURATION`` | Below is the the instruction that describes the task:
### Input:
Calls the superclass ``draw()`` methods and checks ``HEADLESS_FRAMES``/``HEADLESS_DURATION``
### Response:
def draw(self, current_time, frame_time):
"""
Calls the superclass ``draw()`` methods and checks ``HEADLESS_FRAMES``/``HEADLESS... |
def getChildren(self, name=None, ns=None):
"""
Get a list of children by (optional) name and/or (optional) namespace.
@param name: The name of a child element (may contain a prefix).
@type name: basestring
@param ns: An optional namespace used to match the child.
@type n... | Get a list of children by (optional) name and/or (optional) namespace.
@param name: The name of a child element (may contain a prefix).
@type name: basestring
@param ns: An optional namespace used to match the child.
@type ns: (I{prefix}, I{name})
@return: The list of matching c... | Below is the the instruction that describes the task:
### Input:
Get a list of children by (optional) name and/or (optional) namespace.
@param name: The name of a child element (may contain a prefix).
@type name: basestring
@param ns: An optional namespace used to match the child.
@... |
def sweep(self):
'''
This methods runs in a separate thread. So long as
`self.sweep_flag` is set, it expires keys according to
the process explained in the docstring for the `TimedDict`
class. The thread is halted by calling `self.stop_sweep()`,
which sets the `self.sweep... | This methods runs in a separate thread. So long as
`self.sweep_flag` is set, it expires keys according to
the process explained in the docstring for the `TimedDict`
class. The thread is halted by calling `self.stop_sweep()`,
which sets the `self.sweep_flag` to `False`. | Below is the the instruction that describes the task:
### Input:
This methods runs in a separate thread. So long as
`self.sweep_flag` is set, it expires keys according to
the process explained in the docstring for the `TimedDict`
class. The thread is halted by calling `self.stop_sweep()`,
... |
def add_rup_params(self, rupture):
"""
Add .REQUIRES_RUPTURE_PARAMETERS to the rupture
"""
for param in self.REQUIRES_RUPTURE_PARAMETERS:
if param == 'mag':
value = rupture.mag
elif param == 'strike':
value = rupture.surface.get_str... | Add .REQUIRES_RUPTURE_PARAMETERS to the rupture | Below is the the instruction that describes the task:
### Input:
Add .REQUIRES_RUPTURE_PARAMETERS to the rupture
### Response:
def add_rup_params(self, rupture):
"""
Add .REQUIRES_RUPTURE_PARAMETERS to the rupture
"""
for param in self.REQUIRES_RUPTURE_PARAMETERS:
if par... |
def clean_time(sltime, in_format='%Y-%m-%dT%H:%M:%S%z', out_format='%Y-%m-%d %H:%M'):
"""Easy way to format time strings
:param string sltime: A softlayer formatted time string
:param string in_format: Datetime format for strptime
:param string out_format: Datetime format for strftime
"""
try:
... | Easy way to format time strings
:param string sltime: A softlayer formatted time string
:param string in_format: Datetime format for strptime
:param string out_format: Datetime format for strftime | Below is the the instruction that describes the task:
### Input:
Easy way to format time strings
:param string sltime: A softlayer formatted time string
:param string in_format: Datetime format for strptime
:param string out_format: Datetime format for strftime
### Response:
def clean_time(sltime, in_... |
def get_small_file(context, path):
"""
Basic in-memory caching module fetcher. This generates one roundtrip for
every previously unseen file, so it is only a temporary solution.
:param context:
Context we should direct FileService requests to. For now (and probably
forever) this is just... | Basic in-memory caching module fetcher. This generates one roundtrip for
every previously unseen file, so it is only a temporary solution.
:param context:
Context we should direct FileService requests to. For now (and probably
forever) this is just the top-level Mitogen connection manager proce... | Below is the the instruction that describes the task:
### Input:
Basic in-memory caching module fetcher. This generates one roundtrip for
every previously unseen file, so it is only a temporary solution.
:param context:
Context we should direct FileService requests to. For now (and probably
... |
def _comparison_generator(old_list, new_list, compare_fn):
"""
:type old_list: sorted list
:type new_list: sorted list
:type compare_fn: function
:param compare_fn:
takes two arguments, A and B
returns 0 if equal
returns -1 if A is less than B
else returns 1
"""
... | :type old_list: sorted list
:type new_list: sorted list
:type compare_fn: function
:param compare_fn:
takes two arguments, A and B
returns 0 if equal
returns -1 if A is less than B
else returns 1 | Below is the the instruction that describes the task:
### Input:
:type old_list: sorted list
:type new_list: sorted list
:type compare_fn: function
:param compare_fn:
takes two arguments, A and B
returns 0 if equal
returns -1 if A is less than B
else returns 1
### Respon... |
def get_pretty_xml(self, encoding='unicode'):
"""Returns:
str : Current state of the wrapper as a pretty printed XML string.
"""
return d1_common.xml.reformat_to_pretty_xml(
xml.etree.ElementTree.tostring(self._root_el, encoding)
) | Returns:
str : Current state of the wrapper as a pretty printed XML string. | Below is the the instruction that describes the task:
### Input:
Returns:
str : Current state of the wrapper as a pretty printed XML string.
### Response:
def get_pretty_xml(self, encoding='unicode'):
"""Returns:
str : Current state of the wrapper as a pretty printed XML string.
... |
def checkPassword(self, password):
"""
Check the given plaintext password against the response in this
credentials object.
@type password: C{str}
@param password: The known correct password associated with
C{self.username}.
@return: A C{bool}, C{True} if thi... | Check the given plaintext password against the response in this
credentials object.
@type password: C{str}
@param password: The known correct password associated with
C{self.username}.
@return: A C{bool}, C{True} if this credentials object agrees with the
given ... | Below is the the instruction that describes the task:
### Input:
Check the given plaintext password against the response in this
credentials object.
@type password: C{str}
@param password: The known correct password associated with
C{self.username}.
@return: A C{bool}, ... |
def project(self, n):
"""
Convenience method for projection of a tensor into a
vector. Returns the tensor dotted into a unit vector
along the input n.
Args:
n (3x1 array-like): direction to project onto
Returns (float):
scalar value correspondin... | Convenience method for projection of a tensor into a
vector. Returns the tensor dotted into a unit vector
along the input n.
Args:
n (3x1 array-like): direction to project onto
Returns (float):
scalar value corresponding to the projection of
the ten... | Below is the the instruction that describes the task:
### Input:
Convenience method for projection of a tensor into a
vector. Returns the tensor dotted into a unit vector
along the input n.
Args:
n (3x1 array-like): direction to project onto
Returns (float):
... |
def get_lock_config(self, device_label):
""" Get lock configuration
Args:
device_label (str): device label of lock
"""
response = None
try:
response = requests.get(
urls.lockconfig(self._giid, device_label),
headers={
... | Get lock configuration
Args:
device_label (str): device label of lock | Below is the the instruction that describes the task:
### Input:
Get lock configuration
Args:
device_label (str): device label of lock
### Response:
def get_lock_config(self, device_label):
""" Get lock configuration
Args:
device_label (str): device label of lock
... |
def transform_relations(rdf, relationmap):
"""Transform YSO-style concept relations into SKOS equivalents."""
affected_types = (SKOS.Concept, SKOS.Collection,
SKOSEXT.DeprecatedConcept)
props = set()
for t in affected_types:
for conc in rdf.subjects(RDF.type, t):
... | Transform YSO-style concept relations into SKOS equivalents. | Below is the the instruction that describes the task:
### Input:
Transform YSO-style concept relations into SKOS equivalents.
### Response:
def transform_relations(rdf, relationmap):
"""Transform YSO-style concept relations into SKOS equivalents."""
affected_types = (SKOS.Concept, SKOS.Collection,
... |
def initialize_options(self):
"""Set command option defaults."""
setuptools.command.build_py.build_py.initialize_options(self)
self.meteor = 'meteor'
self.meteor_debug = False
self.build_lib = None
self.package_dir = None
self.meteor_builds = []
self.no_pr... | Set command option defaults. | Below is the the instruction that describes the task:
### Input:
Set command option defaults.
### Response:
def initialize_options(self):
"""Set command option defaults."""
setuptools.command.build_py.build_py.initialize_options(self)
self.meteor = 'meteor'
self.meteor_debug = False... |
def ezplot(f,xlim,ylim=None,ax = None,vectorized=True,N=None,contour = False,args=None,kwargs=None,dry_run=False,show=None,include_endpoints=False):
'''
Plot polynomial approximation.
:param vectorized: `f` can handle an array of inputs
'''
kwargs = kwargs or {}
args = args or []
d = 1 ... | Plot polynomial approximation.
:param vectorized: `f` can handle an array of inputs | Below is the the instruction that describes the task:
### Input:
Plot polynomial approximation.
:param vectorized: `f` can handle an array of inputs
### Response:
def ezplot(f,xlim,ylim=None,ax = None,vectorized=True,N=None,contour = False,args=None,kwargs=None,dry_run=False,show=None,include_endpoints=Fa... |
def __snake_case(self, descriptor):
"""
Utility method to convert camelcase to snake
:param descriptor: The dictionary to convert
"""
newdict = {}
for i, (k, v) in enumerate(descriptor.items()):
newkey = ""
for j, c in enumerate(k):
... | Utility method to convert camelcase to snake
:param descriptor: The dictionary to convert | Below is the the instruction that describes the task:
### Input:
Utility method to convert camelcase to snake
:param descriptor: The dictionary to convert
### Response:
def __snake_case(self, descriptor):
"""
Utility method to convert camelcase to snake
:param descriptor: The dictio... |
def _set_vcpus_ram(self, vcpus, ram):
"""
Set the number of vCPU cores and amount of RAM for the GNS3 VM.
:param vcpus: number of vCPU cores
:param ram: amount of RAM
"""
# memory must be a multiple of 4 (VMware requirement)
if ram % 4 != 0:
raise GN... | Set the number of vCPU cores and amount of RAM for the GNS3 VM.
:param vcpus: number of vCPU cores
:param ram: amount of RAM | Below is the the instruction that describes the task:
### Input:
Set the number of vCPU cores and amount of RAM for the GNS3 VM.
:param vcpus: number of vCPU cores
:param ram: amount of RAM
### Response:
def _set_vcpus_ram(self, vcpus, ram):
"""
Set the number of vCPU cores and amo... |
def altshuler_debyetemp(v, v0, gamma0, gamma_inf, beta, theta0):
"""
calculate Debye temperature for Altshuler equation
:param v: unit-cell volume in A^3
:param v0: unit-cell volume in A^3 at 1 bar
:param gamma0: Gruneisen parameter at 1 bar
:param gamma_inf: Gruneisen parameter at infinite pre... | calculate Debye temperature for Altshuler equation
:param v: unit-cell volume in A^3
:param v0: unit-cell volume in A^3 at 1 bar
:param gamma0: Gruneisen parameter at 1 bar
:param gamma_inf: Gruneisen parameter at infinite pressure
:param beta: volume dependence of Gruneisen parameter
:param th... | Below is the the instruction that describes the task:
### Input:
calculate Debye temperature for Altshuler equation
:param v: unit-cell volume in A^3
:param v0: unit-cell volume in A^3 at 1 bar
:param gamma0: Gruneisen parameter at 1 bar
:param gamma_inf: Gruneisen parameter at infinite pressure
... |
def reload(self, result=None):
"""
Reloads the resource.
"""
if result is None:
result = self._client._get(
self.__class__.base_url(
self.sys['space'].id,
self.sys['id'],
environment_id=self._environ... | Reloads the resource. | Below is the the instruction that describes the task:
### Input:
Reloads the resource.
### Response:
def reload(self, result=None):
"""
Reloads the resource.
"""
if result is None:
result = self._client._get(
self.__class__.base_url(
... |
def change_options(self, **kwargs):
'''
Change one of the track's options in the viewconf
'''
new_options = json.loads(json.dumps(self.viewconf['options']))
new_options = {**new_options, **kwargs}
return self.change_attributes(options=new_options) | Change one of the track's options in the viewconf | Below is the the instruction that describes the task:
### Input:
Change one of the track's options in the viewconf
### Response:
def change_options(self, **kwargs):
'''
Change one of the track's options in the viewconf
'''
new_options = json.loads(json.dumps(self.viewconf['options']... |
def load(cls, path, fmt=None, backend=None):
r"""Load a graph from a file.
Edge weights are retrieved as an edge attribute named "weight".
Signals are retrieved from node attributes,
and stored in the :attr:`signals` dictionary under the attribute name.
`N`-dimensional signals ... | r"""Load a graph from a file.
Edge weights are retrieved as an edge attribute named "weight".
Signals are retrieved from node attributes,
and stored in the :attr:`signals` dictionary under the attribute name.
`N`-dimensional signals that were broken during export are joined.
P... | Below is the the instruction that describes the task:
### Input:
r"""Load a graph from a file.
Edge weights are retrieved as an edge attribute named "weight".
Signals are retrieved from node attributes,
and stored in the :attr:`signals` dictionary under the attribute name.
`N`-dime... |
def switch_led_on(self, ids):
""" Switches on the LED of the motors with the specified ids. """
self._set_LED(dict(zip(ids, itertools.repeat(True)))) | Switches on the LED of the motors with the specified ids. | Below is the the instruction that describes the task:
### Input:
Switches on the LED of the motors with the specified ids.
### Response:
def switch_led_on(self, ids):
""" Switches on the LED of the motors with the specified ids. """
self._set_LED(dict(zip(ids, itertools.repeat(True)))) |
def is_article(self, response, url):
"""
Tests if the given response is an article by calling and checking
the heuristics set in config.cfg and sitelist.json
:param obj response: The response of the site.
:param str url: The base_url (needed to get the site-specific config
... | Tests if the given response is an article by calling and checking
the heuristics set in config.cfg and sitelist.json
:param obj response: The response of the site.
:param str url: The base_url (needed to get the site-specific config
from the JSON-file)
:return bo... | Below is the the instruction that describes the task:
### Input:
Tests if the given response is an article by calling and checking
the heuristics set in config.cfg and sitelist.json
:param obj response: The response of the site.
:param str url: The base_url (needed to get the site-specific ... |
def seek(self, offset, whence=SEEK_SET):
"""
Change the stream position to the given byte offset.
Args:
offset: Offset is interpreted relative to the position indicated by
whence.
whence: The default value for whence is SEEK_SET.
Values fo... | Change the stream position to the given byte offset.
Args:
offset: Offset is interpreted relative to the position indicated by
whence.
whence: The default value for whence is SEEK_SET.
Values for whence are:
SEEK_SET or 0 – start of the st... | Below is the the instruction that describes the task:
### Input:
Change the stream position to the given byte offset.
Args:
offset: Offset is interpreted relative to the position indicated by
whence.
whence: The default value for whence is SEEK_SET.
V... |
def cmd(self, fun, arg=None, pub_data=None, kwarg=None, print_event=True, full_return=False):
'''
Execute a function
.. code-block:: python
>>> wheel.cmd('key.finger', ['jerry'])
{'minions': {'jerry': '5d:f6:79:43:5e:d4:42:3f:57:b8:45:a8:7e:a4:6e:ca'}}
'''
... | Execute a function
.. code-block:: python
>>> wheel.cmd('key.finger', ['jerry'])
{'minions': {'jerry': '5d:f6:79:43:5e:d4:42:3f:57:b8:45:a8:7e:a4:6e:ca'}} | Below is the the instruction that describes the task:
### Input:
Execute a function
.. code-block:: python
>>> wheel.cmd('key.finger', ['jerry'])
{'minions': {'jerry': '5d:f6:79:43:5e:d4:42:3f:57:b8:45:a8:7e:a4:6e:ca'}}
### Response:
def cmd(self, fun, arg=None, pub_data=None, kwa... |
def read(self):
"""
This module is lazy-loaded by default. You can read all internal
structure by calling this method.
"""
stack = [self[0].child]
while stack:
current = stack.pop()
if current.right:
stack.append(current.right)
... | This module is lazy-loaded by default. You can read all internal
structure by calling this method. | Below is the the instruction that describes the task:
### Input:
This module is lazy-loaded by default. You can read all internal
structure by calling this method.
### Response:
def read(self):
"""
This module is lazy-loaded by default. You can read all internal
structure by calling... |
def make_diag_scale(loc=None,
scale_diag=None,
scale_identity_multiplier=None,
shape_hint=None,
validate_args=False,
assert_positive=False,
name=None,
dtype=None):
"""Creates a L... | Creates a LinearOperator representing a diagonal matrix.
Args:
loc: Floating-point `Tensor`. This is used for inferring shape in the case
where only `scale_identity_multiplier` is set.
scale_diag: Floating-point `Tensor` representing the diagonal matrix.
`scale_diag` has shape [N1, N2, ... k], w... | Below is the the instruction that describes the task:
### Input:
Creates a LinearOperator representing a diagonal matrix.
Args:
loc: Floating-point `Tensor`. This is used for inferring shape in the case
where only `scale_identity_multiplier` is set.
scale_diag: Floating-point `Tensor` representing ... |
def decipher(self, string):
"""Decipher string using Playfair cipher according to initialised key. Punctuation and whitespace
are removed from the input. The ciphertext should be an even number of characters. If the input ciphertext is not an even number of characters, an 'X' will be appended.
... | Decipher string using Playfair cipher according to initialised key. Punctuation and whitespace
are removed from the input. The ciphertext should be an even number of characters. If the input ciphertext is not an even number of characters, an 'X' will be appended.
Example::
plaintext = Play... | Below is the the instruction that describes the task:
### Input:
Decipher string using Playfair cipher according to initialised key. Punctuation and whitespace
are removed from the input. The ciphertext should be an even number of characters. If the input ciphertext is not an even number of characters, an '... |
def get_xeditable_form_kwargs(self):
""" Returns a dict of keyword arguments to be sent to the xeditable form class. """
kwargs = {
'model': self.get_queryset().model,
}
if self.request.method in ('POST', 'PUT'):
kwargs.update({
'data': self.reques... | Returns a dict of keyword arguments to be sent to the xeditable form class. | Below is the the instruction that describes the task:
### Input:
Returns a dict of keyword arguments to be sent to the xeditable form class.
### Response:
def get_xeditable_form_kwargs(self):
""" Returns a dict of keyword arguments to be sent to the xeditable form class. """
kwargs = {
... |
def use(self, key, value):
"""
Temporarily set a parameter value using the with statement.
Aliasing allowed.
"""
old_value = self[key]
try:
self[key] = value
yield self
finally:
self[key] = old_value | Temporarily set a parameter value using the with statement.
Aliasing allowed. | Below is the the instruction that describes the task:
### Input:
Temporarily set a parameter value using the with statement.
Aliasing allowed.
### Response:
def use(self, key, value):
"""
Temporarily set a parameter value using the with statement.
Aliasing allowed.
"""
... |
def build(self, connection, grammar):
"""
Execute the blueprint against the database.
:param connection: The connection to use
:type connection: orator.connections.Connection
:param grammar: The grammar to user
:type grammar: orator.query.grammars.QueryGrammar
"... | Execute the blueprint against the database.
:param connection: The connection to use
:type connection: orator.connections.Connection
:param grammar: The grammar to user
:type grammar: orator.query.grammars.QueryGrammar | Below is the the instruction that describes the task:
### Input:
Execute the blueprint against the database.
:param connection: The connection to use
:type connection: orator.connections.Connection
:param grammar: The grammar to user
:type grammar: orator.query.grammars.QueryGramma... |
def allow_create(function):
"""
Decorate the `form_valid` method in a Create/Update class to create new
values if necessary.
.. warning::
Make sure that this decorator **only** decorates the ``form_valid()``
method and **only** this one.
"""
@wraps(function)
def _wrapped_f... | Decorate the `form_valid` method in a Create/Update class to create new
values if necessary.
.. warning::
Make sure that this decorator **only** decorates the ``form_valid()``
method and **only** this one. | Below is the the instruction that describes the task:
### Input:
Decorate the `form_valid` method in a Create/Update class to create new
values if necessary.
.. warning::
Make sure that this decorator **only** decorates the ``form_valid()``
method and **only** this one.
### Response:
def ... |
def hmmsearch(self, output_path, input_path, unpack, seq_type, threads, cutoff, orfm):
'''
hmmsearch - Search raw reads for hits using search_hmm list
Parameters
----------
output_path : str
path to output domtblout table
input_path : str
path to ... | hmmsearch - Search raw reads for hits using search_hmm list
Parameters
----------
output_path : str
path to output domtblout table
input_path : str
path to input sequences to search
unpack : UnpackRawReads
UnpackRawReads object, returns string... | Below is the the instruction that describes the task:
### Input:
hmmsearch - Search raw reads for hits using search_hmm list
Parameters
----------
output_path : str
path to output domtblout table
input_path : str
path to input sequences to search
unpa... |
def extract_features_using_pefile(self, pef):
''' Process the PE File using the Python pefile module. '''
# Store all extracted features into feature lists
extracted_dense = {}
extracted_sparse = {}
# Now slog through the info and extract the features
feature_not_found_... | Process the PE File using the Python pefile module. | Below is the the instruction that describes the task:
### Input:
Process the PE File using the Python pefile module.
### Response:
def extract_features_using_pefile(self, pef):
''' Process the PE File using the Python pefile module. '''
# Store all extracted features into feature lists
ext... |
def configure_args(self, arguments):
"""
Create configuration has from command line arguments
:type arguments: :py:class:`argparse.Namespace`
:params arguments: arguments produced by :py:meth:`Cli.parse_args()`
"""
module, key, config_path = self.check_file_paths(argume... | Create configuration has from command line arguments
:type arguments: :py:class:`argparse.Namespace`
:params arguments: arguments produced by :py:meth:`Cli.parse_args()` | Below is the the instruction that describes the task:
### Input:
Create configuration has from command line arguments
:type arguments: :py:class:`argparse.Namespace`
:params arguments: arguments produced by :py:meth:`Cli.parse_args()`
### Response:
def configure_args(self, arguments):
"""
... |
def get_credit_notes_per_page(self, per_page=1000, page=1, params=None):
"""
Get credit notes per page
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:param params: Search parameters. Default: {}
:return: list
"""
... | Get credit notes per page
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:param params: Search parameters. Default: {}
:return: list | Below is the the instruction that describes the task:
### Input:
Get credit notes per page
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:param params: Search parameters. Default: {}
:return: list
### Response:
def get_credit_notes_pe... |
def get_variant_genotypes(self, variant):
"""Get the genotypes from a well formed variant instance.
Args:
marker (Variant): A Variant instance.
Returns:
A list of Genotypes instance containing a pointer to the variant as
well as a vector of encoded genotypes... | Get the genotypes from a well formed variant instance.
Args:
marker (Variant): A Variant instance.
Returns:
A list of Genotypes instance containing a pointer to the variant as
well as a vector of encoded genotypes. | Below is the the instruction that describes the task:
### Input:
Get the genotypes from a well formed variant instance.
Args:
marker (Variant): A Variant instance.
Returns:
A list of Genotypes instance containing a pointer to the variant as
well as a vector of e... |
def checkOneValue(self,v,strict=0):
"""Checks a single value to see if it is in range or choice list
Allows indirection strings starting with ")". Assumes
v has already been converted to right value by
_coerceOneValue. Returns value if OK, or raises
ValueError if not OK.
... | Checks a single value to see if it is in range or choice list
Allows indirection strings starting with ")". Assumes
v has already been converted to right value by
_coerceOneValue. Returns value if OK, or raises
ValueError if not OK. | Below is the the instruction that describes the task:
### Input:
Checks a single value to see if it is in range or choice list
Allows indirection strings starting with ")". Assumes
v has already been converted to right value by
_coerceOneValue. Returns value if OK, or raises
Value... |
def inverse(self):
""" Inverts image (all nonzeros become zeros and vice verse)
Returns
-------
:obj:`BinaryImage`
inverse of this binary image
"""
data = np.zeros(self.shape).astype(np.uint8)
ind = np.where(self.data == 0)
data[ind[0], ind[1],... | Inverts image (all nonzeros become zeros and vice verse)
Returns
-------
:obj:`BinaryImage`
inverse of this binary image | Below is the the instruction that describes the task:
### Input:
Inverts image (all nonzeros become zeros and vice verse)
Returns
-------
:obj:`BinaryImage`
inverse of this binary image
### Response:
def inverse(self):
""" Inverts image (all nonzeros become zeros and vic... |
def log_to_history(logger, name):
"""Decorate function, adding a logger handler stored in FITS."""
def log_to_history_decorator(method):
def l2h_method(self, ri):
history_header = fits.Header()
fh = FITSHistoryHandler(history_header)
fh.setLevel(logging.INFO)
... | Decorate function, adding a logger handler stored in FITS. | Below is the the instruction that describes the task:
### Input:
Decorate function, adding a logger handler stored in FITS.
### Response:
def log_to_history(logger, name):
"""Decorate function, adding a logger handler stored in FITS."""
def log_to_history_decorator(method):
def l2h_method(self, r... |
def get_rgb_image_as_bytes(self, format='png', quality=90):
"""Get the current image shown in the viewer, with any overlaid
graphics, in the form of a buffer in the form of bytes.
Parameters
----------
format : str
See :meth:`get_rgb_image_as_buffer`.
qualit... | Get the current image shown in the viewer, with any overlaid
graphics, in the form of a buffer in the form of bytes.
Parameters
----------
format : str
See :meth:`get_rgb_image_as_buffer`.
quality: int
See :meth:`get_rgb_image_as_buffer`.
Return... | Below is the the instruction that describes the task:
### Input:
Get the current image shown in the viewer, with any overlaid
graphics, in the form of a buffer in the form of bytes.
Parameters
----------
format : str
See :meth:`get_rgb_image_as_buffer`.
quality:... |
def map_words(self, start, end):
"""Return a memory-map of the elements `start` through `end`.
The memory map will offer the 8-byte double-precision floats
("elements") in the file from index `start` through to the index
`end`, inclusive, both counting the first float as element 1.
... | Return a memory-map of the elements `start` through `end`.
The memory map will offer the 8-byte double-precision floats
("elements") in the file from index `start` through to the index
`end`, inclusive, both counting the first float as element 1.
Memory maps must begin on a page boundar... | Below is the the instruction that describes the task:
### Input:
Return a memory-map of the elements `start` through `end`.
The memory map will offer the 8-byte double-precision floats
("elements") in the file from index `start` through to the index
`end`, inclusive, both counting the first... |
def mode(name, num, minimum=0, maximum=0, ref=None):
'''
Calculates the mode of the ``num`` most recent values. Requires a list.
USAGE:
.. code-block:: yaml
foo:
calc.mode:
- name: myregentry
- num: 5
'''
return calc(
name=name,
num=nu... | Calculates the mode of the ``num`` most recent values. Requires a list.
USAGE:
.. code-block:: yaml
foo:
calc.mode:
- name: myregentry
- num: 5 | Below is the the instruction that describes the task:
### Input:
Calculates the mode of the ``num`` most recent values. Requires a list.
USAGE:
.. code-block:: yaml
foo:
calc.mode:
- name: myregentry
- num: 5
### Response:
def mode(name, num, minimum=0, maximum=... |
async def async_enqueue_download(self, resource):
'''
Enqueue the download of the given foreign resource.
'''
worker = self.pick_sticky(resource.url_string)
await worker.enqueue(enums.Task.DOWNLOAD, (resource,)) | Enqueue the download of the given foreign resource. | Below is the the instruction that describes the task:
### Input:
Enqueue the download of the given foreign resource.
### Response:
async def async_enqueue_download(self, resource):
'''
Enqueue the download of the given foreign resource.
'''
worker = self.pick_sticky(resource.url_str... |
def set_cursor_position(self, position):
"""Set cursor position"""
position = self.get_position(position)
cursor = self.textCursor()
cursor.setPosition(position)
self.setTextCursor(cursor)
self.ensureCursorVisible() | Set cursor position | Below is the the instruction that describes the task:
### Input:
Set cursor position
### Response:
def set_cursor_position(self, position):
"""Set cursor position"""
position = self.get_position(position)
cursor = self.textCursor()
cursor.setPosition(position)
self.setT... |
def strip_inserts(fasta):
"""
remove insertion columns from aligned fasta file
"""
for seq in parse_fasta(fasta):
seq[1] = ''.join([b for b in seq[1] if b == '-' or b.isupper()])
yield seq | remove insertion columns from aligned fasta file | Below is the the instruction that describes the task:
### Input:
remove insertion columns from aligned fasta file
### Response:
def strip_inserts(fasta):
"""
remove insertion columns from aligned fasta file
"""
for seq in parse_fasta(fasta):
seq[1] = ''.join([b for b in seq[1] if b == '-' o... |
def _pfp__set_value(self, new_val):
"""Set the value of the String, taking into account
escaping and such as well
"""
if not isinstance(new_val, Field):
new_val = utils.binary(utils.string_escape(new_val))
super(String, self)._pfp__set_value(new_val) | Set the value of the String, taking into account
escaping and such as well | Below is the the instruction that describes the task:
### Input:
Set the value of the String, taking into account
escaping and such as well
### Response:
def _pfp__set_value(self, new_val):
"""Set the value of the String, taking into account
escaping and such as well
"""
if ... |
def delete_entity(sender, instance, **kwargs):
"""Delete Entity when last Data object is deleted."""
# 1 means that the last Data object is going to be deleted.
Entity.objects.annotate(num_data=Count('data')).filter(data=instance, num_data=1).delete() | Delete Entity when last Data object is deleted. | Below is the the instruction that describes the task:
### Input:
Delete Entity when last Data object is deleted.
### Response:
def delete_entity(sender, instance, **kwargs):
"""Delete Entity when last Data object is deleted."""
# 1 means that the last Data object is going to be deleted.
Entity.objects.... |
def deregister_calendar(self, name):
"""
If a calendar is registered with the given name, it is de-registered.
Parameters
----------
cal_name : str
The name of the calendar to be deregistered.
"""
self._calendars.pop(name, None)
self._calendar... | If a calendar is registered with the given name, it is de-registered.
Parameters
----------
cal_name : str
The name of the calendar to be deregistered. | Below is the the instruction that describes the task:
### Input:
If a calendar is registered with the given name, it is de-registered.
Parameters
----------
cal_name : str
The name of the calendar to be deregistered.
### Response:
def deregister_calendar(self, name):
""... |
def load(self, pathname):
"""Loads entry from directory."""
match = self._entry_re.match(pathname)
if not match:
return None
self.ignore = (match.group(1) == "ignore")
if not os.path.isdir(pathname):
raise ValueError("%s: not a directory" % pathname)
... | Loads entry from directory. | Below is the the instruction that describes the task:
### Input:
Loads entry from directory.
### Response:
def load(self, pathname):
"""Loads entry from directory."""
match = self._entry_re.match(pathname)
if not match:
return None
self.ignore = (match.group(1) == "ignor... |
def stat(path, format):
"""Call stat on file
:param path: HDFS Path
:param format: Stat format
:returns: Stat output
:raises: IOError: If unsuccessful
"""
cmd = "hadoop fs -stat %s %s" % (format, path)
rcode, stdout, stderr = _checked_hadoop_fs_command(cmd)
return stdout.rstrip() | Call stat on file
:param path: HDFS Path
:param format: Stat format
:returns: Stat output
:raises: IOError: If unsuccessful | Below is the the instruction that describes the task:
### Input:
Call stat on file
:param path: HDFS Path
:param format: Stat format
:returns: Stat output
:raises: IOError: If unsuccessful
### Response:
def stat(path, format):
"""Call stat on file
:param path: HDFS Path
:param format:... |
def sle(actual, predicted):
"""
Computes the squared log error.
This function computes the squared log error between two numbers,
or for element between a pair of lists or numpy arrays.
Parameters
----------
actual : int, float, list of numbers, numpy array
The ground truth va... | Computes the squared log error.
This function computes the squared log error between two numbers,
or for element between a pair of lists or numpy arrays.
Parameters
----------
actual : int, float, list of numbers, numpy array
The ground truth value
predicted : same type as actual
... | Below is the the instruction that describes the task:
### Input:
Computes the squared log error.
This function computes the squared log error between two numbers,
or for element between a pair of lists or numpy arrays.
Parameters
----------
actual : int, float, list of numbers, numpy array
... |
def _set_rpc(self, rpc_type: str) -> None:
"""
Sets rpc based on the type
:param rpc_type: The type of connection: like infura, ganache, localhost
:return:
"""
if rpc_type == "infura":
self.set_api_rpc_infura()
elif rpc_type == "localhost":
... | Sets rpc based on the type
:param rpc_type: The type of connection: like infura, ganache, localhost
:return: | Below is the the instruction that describes the task:
### Input:
Sets rpc based on the type
:param rpc_type: The type of connection: like infura, ganache, localhost
:return:
### Response:
def _set_rpc(self, rpc_type: str) -> None:
"""
Sets rpc based on the type
:param rpc_ty... |
def str2chars(strings) -> numpy.ndarray:
"""Return |numpy.ndarray| containing the byte characters (second axis)
of all given strings (first axis).
>>> from hydpy.core.netcdftools import str2chars
>>> str2chars(['zeros', 'ones'])
array([[b'z', b'e', b'r', b'o', b's'],
[b'o', b'n', b'e', b... | Return |numpy.ndarray| containing the byte characters (second axis)
of all given strings (first axis).
>>> from hydpy.core.netcdftools import str2chars
>>> str2chars(['zeros', 'ones'])
array([[b'z', b'e', b'r', b'o', b's'],
[b'o', b'n', b'e', b's', b'']],
dtype='|S1')
>>> str2... | Below is the the instruction that describes the task:
### Input:
Return |numpy.ndarray| containing the byte characters (second axis)
of all given strings (first axis).
>>> from hydpy.core.netcdftools import str2chars
>>> str2chars(['zeros', 'ones'])
array([[b'z', b'e', b'r', b'o', b's'],
... |
def receive_hardbounce_post(self, post_params):
"""
Hard bounce postbacks
"""
if isinstance(post_params, dict):
required_params = ['action', 'email', 'sig']
if not self.check_for_valid_postback_actions(required_params, post_params):
return False
... | Hard bounce postbacks | Below is the the instruction that describes the task:
### Input:
Hard bounce postbacks
### Response:
def receive_hardbounce_post(self, post_params):
"""
Hard bounce postbacks
"""
if isinstance(post_params, dict):
required_params = ['action', 'email', 'sig']
i... |
def load(cls, webfinger, pypump):
""" Load JSON from disk into store object """
filename = cls.get_filename()
if os.path.isfile(filename):
data = open(filename).read()
data = json.loads(data)
store = cls(data, filename=filename)
else:
stor... | Load JSON from disk into store object | Below is the the instruction that describes the task:
### Input:
Load JSON from disk into store object
### Response:
def load(cls, webfinger, pypump):
""" Load JSON from disk into store object """
filename = cls.get_filename()
if os.path.isfile(filename):
data = open(filename).... |
def sk_log_loss(y_true: Union[List[List[float]], List[List[int]], np.ndarray],
y_predicted: Union[List[List[float]], List[List[int]], np.ndarray]) -> float:
"""
Calculates log loss.
Args:
y_true: list or array of true values
y_predicted: list or array of predicted values
... | Calculates log loss.
Args:
y_true: list or array of true values
y_predicted: list or array of predicted values
Returns:
Log loss | Below is the the instruction that describes the task:
### Input:
Calculates log loss.
Args:
y_true: list or array of true values
y_predicted: list or array of predicted values
Returns:
Log loss
### Response:
def sk_log_loss(y_true: Union[List[List[float]], List[List[int]], np.ndar... |
def from_raw(self, raw: RawScalar) -> Optional[bool]:
"""Override superclass method."""
if isinstance(raw, bool):
return raw | Override superclass method. | Below is the the instruction that describes the task:
### Input:
Override superclass method.
### Response:
def from_raw(self, raw: RawScalar) -> Optional[bool]:
"""Override superclass method."""
if isinstance(raw, bool):
return raw |
def simple_cnn(actns:Collection[int], kernel_szs:Collection[int]=None,
strides:Collection[int]=None, bn=False) -> nn.Sequential:
"CNN with `conv_layer` defined by `actns`, `kernel_szs` and `strides`, plus batchnorm if `bn`."
nl = len(actns)-1
kernel_szs = ifnone(kernel_szs, [3]*nl)
stride... | CNN with `conv_layer` defined by `actns`, `kernel_szs` and `strides`, plus batchnorm if `bn`. | Below is the the instruction that describes the task:
### Input:
CNN with `conv_layer` defined by `actns`, `kernel_szs` and `strides`, plus batchnorm if `bn`.
### Response:
def simple_cnn(actns:Collection[int], kernel_szs:Collection[int]=None,
strides:Collection[int]=None, bn=False) -> nn.Sequential... |
def eval_input(self, expr):
"""eval_input: testlist NEWLINE* ENDMARKER"""
return ast.Expression(body=[expr], loc=expr.loc) | eval_input: testlist NEWLINE* ENDMARKER | Below is the the instruction that describes the task:
### Input:
eval_input: testlist NEWLINE* ENDMARKER
### Response:
def eval_input(self, expr):
"""eval_input: testlist NEWLINE* ENDMARKER"""
return ast.Expression(body=[expr], loc=expr.loc) |
def from_file(cls,
source,
distance_weights=None,
merge_same_words=False,
group_marker_opening='<<',
group_marker_closing='>>'):
"""
Read a string from a file and derive a ``Graph`` from it.
This is a conv... | Read a string from a file and derive a ``Graph`` from it.
This is a convenience function for opening a file and passing its
contents to ``Graph.from_string()`` (see that for more detail)
Args:
source (str): the file to read and derive the graph from
distance_weights (di... | Below is the the instruction that describes the task:
### Input:
Read a string from a file and derive a ``Graph`` from it.
This is a convenience function for opening a file and passing its
contents to ``Graph.from_string()`` (see that for more detail)
Args:
source (str): the fi... |
def getActiveCompactions(self, login, tserver):
"""
Parameters:
- login
- tserver
"""
self.send_getActiveCompactions(login, tserver)
return self.recv_getActiveCompactions() | Parameters:
- login
- tserver | Below is the the instruction that describes the task:
### Input:
Parameters:
- login
- tserver
### Response:
def getActiveCompactions(self, login, tserver):
"""
Parameters:
- login
- tserver
"""
self.send_getActiveCompactions(login, tserver)
return self.recv_getActiveCompact... |
def _update(self):
"""Initialize the 1D interpolation."""
if self.strains.size and self.strains.size == self.values.size:
x = np.log(self.strains)
y = self.values
if x.size < 4:
self._interpolater = interp1d(
x,
... | Initialize the 1D interpolation. | Below is the the instruction that describes the task:
### Input:
Initialize the 1D interpolation.
### Response:
def _update(self):
"""Initialize the 1D interpolation."""
if self.strains.size and self.strains.size == self.values.size:
x = np.log(self.strains)
y = self.values... |
def RenderJson(self, pretty=False):
"""
Render a Tropo object into a Json string.
"""
steps = self._steps
topdict = {}
topdict['tropo'] = steps
if pretty:
try:
json = jsonlib.dumps(topdict, indent=4, sort_keys=False)
except ... | Render a Tropo object into a Json string. | Below is the the instruction that describes the task:
### Input:
Render a Tropo object into a Json string.
### Response:
def RenderJson(self, pretty=False):
"""
Render a Tropo object into a Json string.
"""
steps = self._steps
topdict = {}
topdict['tropo'] = steps
... |
def get(cls, id_):
"""Return a workflow object from id."""
with db.session.no_autoflush:
query = cls.dbmodel.query.filter_by(id=id_)
try:
model = query.one()
except NoResultFound:
raise WorkflowsMissingObject("No object for for id {0}".... | Return a workflow object from id. | Below is the the instruction that describes the task:
### Input:
Return a workflow object from id.
### Response:
def get(cls, id_):
"""Return a workflow object from id."""
with db.session.no_autoflush:
query = cls.dbmodel.query.filter_by(id=id_)
try:
model = ... |
def configure(self, rhsm=None, repositories=None):
"""This method will configure the host0 and run the hypervisor."""
if rhsm is not None:
self.rhsm_register(rhsm)
if repositories is not None:
self.enable_repositories(repositories)
self.create_stack_user()
... | This method will configure the host0 and run the hypervisor. | Below is the the instruction that describes the task:
### Input:
This method will configure the host0 and run the hypervisor.
### Response:
def configure(self, rhsm=None, repositories=None):
"""This method will configure the host0 and run the hypervisor."""
if rhsm is not None:
self.rhs... |
def word_similarity_explorer_gensim(corpus,
category,
target_term,
category_name=None,
not_category_name=None,
word2vec=None,
... | Parameters
----------
corpus : Corpus
Corpus to use.
category : str
Name of category column as it appears in original data frame.
category_name : str
Name of category to use. E.g., "5-star reviews."
not_category_name : str
Name of ... | Below is the the instruction that describes the task:
### Input:
Parameters
----------
corpus : Corpus
Corpus to use.
category : str
Name of category column as it appears in original data frame.
category_name : str
Name of category to use. E.g., "... |
def _end_sessions(self, session_ids):
"""Send endSessions command(s) with the given session ids."""
try:
# Use SocketInfo.command directly to avoid implicitly creating
# another session.
with self._socket_for_reads(
ReadPreference.PRIMARY_PREFERRED... | Send endSessions command(s) with the given session ids. | Below is the the instruction that describes the task:
### Input:
Send endSessions command(s) with the given session ids.
### Response:
def _end_sessions(self, session_ids):
"""Send endSessions command(s) with the given session ids."""
try:
# Use SocketInfo.command directly to avoid impl... |
def get_resource(self):
'''use the user provided endpoint and keys (from environment) to
connect to the resource. We can share the aws environment
variables:
AWS_ACCESS_KEY_ID
AWS_SECRET_ACCESS_KEY
https://docs.aws.amazon.com/cli/latest/userguide/cli-conf... | use the user provided endpoint and keys (from environment) to
connect to the resource. We can share the aws environment
variables:
AWS_ACCESS_KEY_ID
AWS_SECRET_ACCESS_KEY
https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-envvars.html | Below is the the instruction that describes the task:
### Input:
use the user provided endpoint and keys (from environment) to
connect to the resource. We can share the aws environment
variables:
AWS_ACCESS_KEY_ID
AWS_SECRET_ACCESS_KEY
https://docs.aws.amazon... |
def _call_init_upload(file_name, file_size, metadata, tags, project, samples_resource):
"""Call init_upload at the One Codex API and return data used to upload the file.
Parameters
----------
file_name : `string`
The file_name you wish to associate this fastx file with at One Codex.
file_si... | Call init_upload at the One Codex API and return data used to upload the file.
Parameters
----------
file_name : `string`
The file_name you wish to associate this fastx file with at One Codex.
file_size : `integer`
Accurate size of file to be uploaded, in bytes.
metadata : `dict`, o... | Below is the the instruction that describes the task:
### Input:
Call init_upload at the One Codex API and return data used to upload the file.
Parameters
----------
file_name : `string`
The file_name you wish to associate this fastx file with at One Codex.
file_size : `integer`
Acc... |
def start(self):
"""
Extension of Pusher.connect() method, which registers all callbacks with
the relevant channels, before initializing a connection.
:return:
"""
super(BitstampWSS, self).start()
self.pusher = pusherclient.Pusher(self.addr, **self.__pusher_optio... | Extension of Pusher.connect() method, which registers all callbacks with
the relevant channels, before initializing a connection.
:return: | Below is the the instruction that describes the task:
### Input:
Extension of Pusher.connect() method, which registers all callbacks with
the relevant channels, before initializing a connection.
:return:
### Response:
def start(self):
"""
Extension of Pusher.connect() method, which ... |
def run_attack(sess, model, x, y, attack, attack_params, batch_size=None,
devices=None, feed=None, pass_y=False):
"""
Run attack on every example in a dataset.
:param sess: tf.Session
:param model: cleverhans.model.Model
:param x: numpy array containing input examples (e.g. MNIST().x_test )
:... | Run attack on every example in a dataset.
:param sess: tf.Session
:param model: cleverhans.model.Model
:param x: numpy array containing input examples (e.g. MNIST().x_test )
:param y: numpy array containing example labels (e.g. MNIST().y_test )
:param attack: cleverhans.attack.Attack
:param attack_params: d... | Below is the the instruction that describes the task:
### Input:
Run attack on every example in a dataset.
:param sess: tf.Session
:param model: cleverhans.model.Model
:param x: numpy array containing input examples (e.g. MNIST().x_test )
:param y: numpy array containing example labels (e.g. MNIST().y_test ... |
def _get_provitem_from_args(xs):
"""Retrieve processed item from list of input arguments.
"""
for i, x in enumerate(xs):
if _has_provenance(x):
return i, x
return -1, None | Retrieve processed item from list of input arguments. | Below is the the instruction that describes the task:
### Input:
Retrieve processed item from list of input arguments.
### Response:
def _get_provitem_from_args(xs):
"""Retrieve processed item from list of input arguments.
"""
for i, x in enumerate(xs):
if _has_provenance(x):
return... |
def merge(self, subordinate_graph):
"""
merge rules:
00 + 00 == 00 00 + 0B == 0B
0A + 00 == 0A 0A + 0B == 0A
A0 + 00 == A0 A0 + 0B == AB
AA + 00 == AA AA + 0B == AB
00 + B0 == B0 00 + BB == BB
0A + B0 == BA 0A + BB == BA
A0 + B0 ... | merge rules:
00 + 00 == 00 00 + 0B == 0B
0A + 00 == 0A 0A + 0B == 0A
A0 + 00 == A0 A0 + 0B == AB
AA + 00 == AA AA + 0B == AB
00 + B0 == B0 00 + BB == BB
0A + B0 == BA 0A + BB == BA
A0 + B0 == A0 A0 + BB == AB
AA + B0 == AA AA + BB ... | Below is the the instruction that describes the task:
### Input:
merge rules:
00 + 00 == 00 00 + 0B == 0B
0A + 00 == 0A 0A + 0B == 0A
A0 + 00 == A0 A0 + 0B == AB
AA + 00 == AA AA + 0B == AB
00 + B0 == B0 00 + BB == BB
0A + B0 == BA 0A + BB == BA
... |
def handle_msec_timestamp(self, m, master):
'''special handling for MAVLink packets with a time_boot_ms field'''
if m.get_type() == 'GLOBAL_POSITION_INT':
# this is fix time, not boot time
return
msec = m.time_boot_ms
if msec + 30000 < master.highest_msec:
... | special handling for MAVLink packets with a time_boot_ms field | Below is the the instruction that describes the task:
### Input:
special handling for MAVLink packets with a time_boot_ms field
### Response:
def handle_msec_timestamp(self, m, master):
'''special handling for MAVLink packets with a time_boot_ms field'''
if m.get_type() == 'GLOBAL_POSITION_INT':
... |
def change_cell(self, x, y, ch, fg, bg):
"""Change cell in position (x;y).
"""
self.console.draw_char(x, y, ch, fg, bg) | Change cell in position (x;y). | Below is the the instruction that describes the task:
### Input:
Change cell in position (x;y).
### Response:
def change_cell(self, x, y, ch, fg, bg):
"""Change cell in position (x;y).
"""
self.console.draw_char(x, y, ch, fg, bg) |
def get_condition_value(self, operator, value):
"""
Gets the condition value based on the operator and value
:param operator: the condition operator name
:type operator: str
:param value: the value to be formatted based on the condition operator
:type value: object
... | Gets the condition value based on the operator and value
:param operator: the condition operator name
:type operator: str
:param value: the value to be formatted based on the condition operator
:type value: object
:return: the comparison operator from the Where class's comparis... | Below is the the instruction that describes the task:
### Input:
Gets the condition value based on the operator and value
:param operator: the condition operator name
:type operator: str
:param value: the value to be formatted based on the condition operator
:type value: object
... |
def _print_stats(cls, stats: Statistics, human_format_speed: bool=True):
'''Log the final statistics to the user.'''
time_length = datetime.timedelta(
seconds=int(stats.stop_time - stats.start_time)
)
file_size = wpull.string.format_size(stats.size)
if stats.bandwidt... | Log the final statistics to the user. | Below is the the instruction that describes the task:
### Input:
Log the final statistics to the user.
### Response:
def _print_stats(cls, stats: Statistics, human_format_speed: bool=True):
'''Log the final statistics to the user.'''
time_length = datetime.timedelta(
seconds=int(stats.s... |
def format(self, formatter, link_resolver, output):
"""
Banana banana
"""
if not self.title and self.name:
title = os.path.splitext(self.name)[0]
self.title = os.path.basename(title).replace('-', ' ')
self.formatted_contents = u''
self.build_pat... | Banana banana | Below is the the instruction that describes the task:
### Input:
Banana banana
### Response:
def format(self, formatter, link_resolver, output):
"""
Banana banana
"""
if not self.title and self.name:
title = os.path.splitext(self.name)[0]
self.title = os.pat... |
def send_cmd(self, command, connId='default'):
"""
Sends any command to FTP server. Returns server output.
Parameters:
- command - any valid command to be sent (invalid will result in exception).
- connId(optional) - connection identifier. By default equals 'default'
Exam... | Sends any command to FTP server. Returns server output.
Parameters:
- command - any valid command to be sent (invalid will result in exception).
- connId(optional) - connection identifier. By default equals 'default'
Example:
| send cmd | HELP | | Below is the the instruction that describes the task:
### Input:
Sends any command to FTP server. Returns server output.
Parameters:
- command - any valid command to be sent (invalid will result in exception).
- connId(optional) - connection identifier. By default equals 'default'
Ex... |
def from_label(cls, label):
r"""Take pauli string to construct pauli.
The qubit index of pauli label is q_{n-1} ... q_0.
E.g., a pauli is $P_{n-1} \otimes ... \otimes P_0$
Args:
label (str): pauli label
Returns:
Pauli: the constructed pauli
Rai... | r"""Take pauli string to construct pauli.
The qubit index of pauli label is q_{n-1} ... q_0.
E.g., a pauli is $P_{n-1} \otimes ... \otimes P_0$
Args:
label (str): pauli label
Returns:
Pauli: the constructed pauli
Raises:
QiskitError: invali... | Below is the the instruction that describes the task:
### Input:
r"""Take pauli string to construct pauli.
The qubit index of pauli label is q_{n-1} ... q_0.
E.g., a pauli is $P_{n-1} \otimes ... \otimes P_0$
Args:
label (str): pauli label
Returns:
Pauli: t... |
def print_progress_bar(iteration, total, prefix='', suffix='', decimals=1, length=100, fill='█'):
"""
Call in a loop to create terminal progress bar
@params:
iteration - Required : current iteration (Int)
total - Required : total iterations (Int)
prefix - Optional : p... | Call in a loop to create terminal progress bar
@params:
iteration - Required : current iteration (Int)
total - Required : total iterations (Int)
prefix - Optional : prefix string (Str)
suffix - Optional : suffix string (Str)
decimals - Optional : pos... | Below is the the instruction that describes the task:
### Input:
Call in a loop to create terminal progress bar
@params:
iteration - Required : current iteration (Int)
total - Required : total iterations (Int)
prefix - Optional : prefix string (Str)
suffix - ... |
def set_atten(self, idx, value):
"""Sets the attenuation value for a particular signal path.
Args:
idx: Zero-based index int which is the identifier for a particular
signal path in an instrument. For instruments that only has one
channel, this is ignored by t... | Sets the attenuation value for a particular signal path.
Args:
idx: Zero-based index int which is the identifier for a particular
signal path in an instrument. For instruments that only has one
channel, this is ignored by the device.
value: A float that i... | Below is the the instruction that describes the task:
### Input:
Sets the attenuation value for a particular signal path.
Args:
idx: Zero-based index int which is the identifier for a particular
signal path in an instrument. For instruments that only has one
chan... |
def __calculate_current_value(self, asset_class: AssetClass):
""" Calculate totals for asset class by adding all the children values """
# Is this the final asset class, the one with stocks?
if asset_class.stocks:
# add all the stocks
stocks_sum = Decimal(0)
f... | Calculate totals for asset class by adding all the children values | Below is the the instruction that describes the task:
### Input:
Calculate totals for asset class by adding all the children values
### Response:
def __calculate_current_value(self, asset_class: AssetClass):
""" Calculate totals for asset class by adding all the children values """
# Is this the fi... |
def get_image_platform_digest(self, image, platform):
"""Get digest of specified image and platform
:param ImageName image: image
:param str platform: name of the platform/arch (x86_64, ppc64le, ...)
:raises KeyError: when digest is not found
:rtype: str
:return: digest ... | Get digest of specified image and platform
:param ImageName image: image
:param str platform: name of the platform/arch (x86_64, ppc64le, ...)
:raises KeyError: when digest is not found
:rtype: str
:return: digest of the specified image (fedora@sha256:...) | Below is the the instruction that describes the task:
### Input:
Get digest of specified image and platform
:param ImageName image: image
:param str platform: name of the platform/arch (x86_64, ppc64le, ...)
:raises KeyError: when digest is not found
:rtype: str
:return: dig... |
def _query_k(k, i, P, oracle, query, trn, state_cache, dist_cache, smooth=False, D=None, weight=0.5):
"""A helper function for query-matching function`s iteration over observations.
Args:
k - index of the candidate path
i - index of the frames of the observations
P - the path matrix... | A helper function for query-matching function`s iteration over observations.
Args:
k - index of the candidate path
i - index of the frames of the observations
P - the path matrix of size K x N, K the number for paths initiated,
N the frame number of observations
ora... | Below is the the instruction that describes the task:
### Input:
A helper function for query-matching function`s iteration over observations.
Args:
k - index of the candidate path
i - index of the frames of the observations
P - the path matrix of size K x N, K the number for paths i... |
def parse_notification_xml(xml: str) -> Union[AliasRegistration, Payment]:
""""
Both alias registration and payments are received here.
We can differentiate them by looking at the use-alias user-parameter (and verifying the amount is o).
"""
body = fromstring(xml).find('body')
transaction = bod... | Both alias registration and payments are received here.
We can differentiate them by looking at the use-alias user-parameter (and verifying the amount is o). | Below is the the instruction that describes the task:
### Input:
Both alias registration and payments are received here.
We can differentiate them by looking at the use-alias user-parameter (and verifying the amount is o).
### Response:
def parse_notification_xml(xml: str) -> Union[AliasRegistration, Payment]:... |
def diff(**kwargs):
'''
Returns the difference between the candidate and the current configuration
id : 0
The rollback ID value (0-49)
CLI Example:
.. code-block:: bash
salt 'device_name' junos.diff 3
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
id_ = kwargs.po... | Returns the difference between the candidate and the current configuration
id : 0
The rollback ID value (0-49)
CLI Example:
.. code-block:: bash
salt 'device_name' junos.diff 3 | Below is the the instruction that describes the task:
### Input:
Returns the difference between the candidate and the current configuration
id : 0
The rollback ID value (0-49)
CLI Example:
.. code-block:: bash
salt 'device_name' junos.diff 3
### Response:
def diff(**kwargs):
'''... |
def toc(self):
""" stops the timer """
elapsed = self._time() - self.tstart
if self.verbose:
self.write('...toc(%r)=%.4fs\n' % (self.label, elapsed))
self.flush()
return elapsed | stops the timer | Below is the the instruction that describes the task:
### Input:
stops the timer
### Response:
def toc(self):
""" stops the timer """
elapsed = self._time() - self.tstart
if self.verbose:
self.write('...toc(%r)=%.4fs\n' % (self.label, elapsed))
self.flush()
r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.