INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
-----
Brief
-----
With this plotting function it will be possible to plot simultaneously (in pairs) "Original"/
"Filtered"/"Differentiated"/"Rectified"/"Integrated" ECG signals used at "Pan-Tompkins R Peaks
Detection Algorithm".
-----------
Description
-----------
Function intended ... | def plot_ecg_pan_tompkins_steps(time, orig_ecg, pre_process_ecg, sampling_rate, titles):
"""
-----
Brief
-----
With this plotting function it will be possible to plot simultaneously (in pairs) "Original"/
"Filtered"/"Differentiated"/"Rectified"/"Integrated" ECG signals used at "Pan-Tompkins R Pe... |
-----
Brief
-----
With this plotting function it will be possible to demonstrate which "peaks" are being
detected in each stage of Pan-Tompkins Algorithm (possible, probable, definitive).
-----------
Description
-----------
Function intended to generate a Bokeh figure containing all pea... | def plot_ecg_pan_tompkins_peaks(time, orig_ecg, integrated_ecg, sampling_rate, possible_peaks,
probable_peaks, definitive_peaks):
"""
-----
Brief
-----
With this plotting function it will be possible to demonstrate which "peaks" are being
detected in each stage of... |
-----
Brief
-----
This plotting function ensures a graphical representation of maximum, minimum and average time
durations of the muscular activation periods.
-----------
Description
-----------
Function intended to generate a single Bokeh figure graphically describing and identifying
... | def plot_emg_graphical_durations(max_time, min_time, avg_time, std_time):
"""
-----
Brief
-----
This plotting function ensures a graphical representation of maximum, minimum and average time
durations of the muscular activation periods.
-----------
Description
-----------
Functi... |
-----
Brief
-----
This plotting function ensures a graphical representation of maximum, minimum and average sample
values registered on the entire EMG acquisition.
-----------
Description
-----------
Function intended to generate a single Bokeh figure with graphically describing and ide... | def plot_emg_graphical_statistical(time, signal, max_sample_value, min_sample_value, avg_sample_value,
std_sample_value):
"""
-----
Brief
-----
This plotting function ensures a graphical representation of maximum, minimum and average sample
values registered on... |
-----
Brief
-----
With the current function it will be plotted the EMG signals together with RMS line and the time-series that
describes the evolution of the cumulative area.
-----------
Description
-----------
Function intended to generate a single Bokeh figure graphically describing a... | def plot_emg_rms_area(time, signal, rms, area):
"""
-----
Brief
-----
With the current function it will be plotted the EMG signals together with RMS line and the time-series that
describes the evolution of the cumulative area.
-----------
Description
-----------
Function intende... |
-----
Brief
-----
A plot with frequency power spectrum of the input EMG signal is presented graphically, highlighting maximum and
median power frequency.
-----------
Description
-----------
Function intended to generate a single Bokeh figure graphically describing and identifying maximu... | def plot_emg_spect_freq(freq_axis, power_axis, max_freq, median_freq):
"""
-----
Brief
-----
A plot with frequency power spectrum of the input EMG signal is presented graphically, highlighting maximum and
median power frequency.
-----------
Description
-----------
Function inten... |
-----
Brief
-----
By invoking this function, a gridplot will be presented, in order to show the effect in muscular
activation detection, when some input parameters of the algorithm are changed.
-----------
Description
-----------
It will be generated a Bokeh figure with 3x2 format, comp... | def plot_compare_act_config(signal, sample_rate, file_name=None):
"""
-----
Brief
-----
By invoking this function, a gridplot will be presented, in order to show the effect in muscular
activation detection, when some input parameters of the algorithm are changed.
-----------
Description... |
-----
Brief
-----
Graphical representation of the EMG median power frequency evolution time series.
-----------
Description
-----------
Function intended to generate a Bokeh figure with 2x1 format, where each muscular activation
period is identified through a colored box and the plot th... | def plot_median_freq_evol(time_signal, signal, time_median_freq, median_freq, activations_begin,
activations_end, sample_rate, file_name=None):
"""
-----
Brief
-----
Graphical representation of the EMG median power frequency evolution time series.
-----------
Descr... |
-----
Brief
-----
With this function it is possible to present a plot containing the FFT Power Spectrum of an ECG
signal, highlighting the informative frequency band.
-----------
Description
-----------
The FFT Power Spectrum, of an input signal, can be generated through plotfft functio... | def plot_informational_band(freqs, power, signal, sr, band_begin, band_end,
legend="Signal Power Spectrum", x_lim=[], y_lim=[],
show_plot=False, file_name=None):
"""
-----
Brief
-----
With this function it is possible to present a plot containi... |
-----
Brief
-----
The use of the current function is very useful for comparing two power spectrum's (before and
after filtering the signal).
This function invokes "plot_informational_band" in order to get the power spectrum before
applying the signal to the lowpass filter.
-----------
D... | def plot_before_after_filter(signal, sr, band_begin, band_end, order=1, x_lim=[], y_lim=[],
orientation="hor", show_plot=False, file_name=None):
"""
-----
Brief
-----
The use of the current function is very useful for comparing two power spectrum's (before and
after ... |
-----
Brief
-----
Taking into consideration the generic transfer function that defines the frequency response of
a low-pass filter (|H|=1/(sqrt(1+(f/fc)^2n), where fc is the corner frequency and n is the
filter order), the current function will generate a figure for comparing the frequency response
... | def plot_low_pass_filter_response(show_plot=False, file_name=None):
"""
-----
Brief
-----
Taking into consideration the generic transfer function that defines the frequency response of
a low-pass filter (|H|=1/(sqrt(1+(f/fc)^2n), where fc is the corner frequency and n is the
filter order), t... |
-----
Brief
-----
With the current function it will be presented a gridplot with 2 rows, where three plots are graphically
represented
-----------
Description
-----------
Acquiring data with a right resolution ensures that posterior conclusions will be more reliable and effective.
... | def plot_compare_resolutions(time, signal_res_1, signal_res_2, sampling_rate):
"""
-----
Brief
-----
With the current function it will be presented a gridplot with 2 rows, where three plots are graphically
represented
-----------
Description
-----------
Acquiring data with a rig... |
-----
Brief
-----
Figure intended to represent the acquired RIP signal together with a rectangular signal defining
inhalation and exhalation periods.
-----------
Description
-----------
Function design to generate a Bokeh figure containing the evolution of RIP signal, when
slow resp... | def plot_resp_slow(signal, rect_signal, sample_rate):
"""
-----
Brief
-----
Figure intended to represent the acquired RIP signal together with a rectangular signal defining
inhalation and exhalation periods.
-----------
Description
-----------
Function design to generate a Bokeh... |
Function design to generate a Bokeh figure containing the evolution of RIP signal, when
respiration was suspended for a long period, the rectangular signal that defines the
stages of inhalation and exhalation and the first derivative of the RIP signal.
Applied in the Notebook "Particularities of Inductive ... | def plot_resp_diff(signal, rect_signal, sample_rate):
"""
Function design to generate a Bokeh figure containing the evolution of RIP signal, when
respiration was suspended for a long period, the rectangular signal that defines the
stages of inhalation and exhalation and the first derivative of the RIP s... |
Downloading data from websites, such as previously acquired physiological signals, is an extremely relevant task,
taking into consideration that, without data, processing cannot take place.
With the current function a file can be easily downloaded through the "link" input.
----------
Parameters
--... | def download(link, out):
"""
Downloading data from websites, such as previously acquired physiological signals, is an extremely relevant task,
taking into consideration that, without data, processing cannot take place.
With the current function a file can be easily downloaded through the "link" input.
... |
Auxiliary function used to plot each inhalation/exhalation segment.
----------
Parameters
----------
fig : Bokeh figure
Figure where inhalation/exhalation segments will be plotted.
time : list
Time axis.
signal : list
Data samples of the acquired/processed signal.
... | def _inhal_exhal_segments(fig, time, signal, inhal_begin, inhal_end, exhal_begin, exhal_end):
"""
Auxiliary function used to plot each inhalation/exhalation segment.
----------
Parameters
----------
fig : Bokeh figure
Figure where inhalation/exhalation segments will be plotted.
tim... |
Calculate the relative extrema of `data`.
Relative extrema are calculated by finding locations where
``comparator(data[n], data[n+1:n+order+1])`` is True.
Parameters
----------
data : ndarray
Array in which to find the relative extrema.
comparator : callable
Function to use to ... | def _boolrelextrema(data, comparator,
axis=0, order=1, mode='clip'):
"""
Calculate the relative extrema of `data`.
Relative extrema are calculated by finding locations where
``comparator(data[n], data[n+1:n+order+1])`` is True.
Parameters
----------
data : ndarray
... |
Calculate the relative minima of `data`.
.. versionadded:: 0.11.0
Parameters
----------
data : ndarray
Array in which to find the relative minima.
axis : int, optional
Axis over which to select from `data`. Default is 0.
order : int, optional
How many points on each si... | def argrelmin(data, axis=0, order=1, mode='clip'):
"""
Calculate the relative minima of `data`.
.. versionadded:: 0.11.0
Parameters
----------
data : ndarray
Array in which to find the relative minima.
axis : int, optional
Axis over which to select from `data`. Default is ... |
Calculate the relative maxima of `data`.
.. versionadded:: 0.11.0
Parameters
----------
data : ndarray
Array in which to find the relative maxima.
axis : int, optional
Axis over which to select from `data`. Default is 0.
order : int, optional
How many points on each si... | def argrelmax(data, axis=0, order=1, mode='clip'):
"""
Calculate the relative maxima of `data`.
.. versionadded:: 0.11.0
Parameters
----------
data : ndarray
Array in which to find the relative maxima.
axis : int, optional
Axis over which to select from `data`. Default is ... |
Calculate the relative extrema of `data`.
.. versionadded:: 0.11.0
Parameters
----------
data : ndarray
Array in which to find the relative extrema.
comparator : callable
Function to use to compare two data points.
Should take 2 numbers as arguments.
axis : int, optiona... | def argrelextrema(data, comparator, axis=0, order=1, mode='clip'):
"""
Calculate the relative extrema of `data`.
.. versionadded:: 0.11.0
Parameters
----------
data : ndarray
Array in which to find the relative extrema.
comparator : callable
Function to use to compare two d... |
This function detects all the peaks of a signal and returns those time
positions. To reduce the amount of peaks detected, a threshold is
introduced so only the peaks above that value are considered.
Parameters
----------
x: array-like
the signal with the peaks to detect.
tol: int
the... | def peaks(signal, tol=None):
""" This function detects all the peaks of a signal and returns those time
positions. To reduce the amount of peaks detected, a threshold is
introduced so only the peaks above that value are considered.
Parameters
----------
x: array-like
the signal with the pe... |
Given an array with all the peaks of the signal ('peaks') and a
distance value ('min_distance') and the signal, by argument, this function
erases all the unnecessary peaks and returns an array with only the maximum
peak for each period of the signal (the period is given by the
min_distance).
Parame... | def clean_near_peaks(signal, peaks_, min_distance):
""" Given an array with all the peaks of the signal ('peaks') and a
distance value ('min_distance') and the signal, by argument, this function
erases all the unnecessary peaks and returns an array with only the maximum
peak for each period of the signa... |
Given an array with some specific points of the signal and a distance
value, this function erases all the surplus points and returns an array
with only one point (the first point) per distance samples values
Parameters
----------
points: array-like
the events to filter.
min_distance: int
... | def clean_near_events(points, min_distance):
""" Given an array with some specific points of the signal and a distance
value, this function erases all the surplus points and returns an array
with only one point (the first point) per distance samples values
Parameters
----------
points: array-li... |
Retrieve and return the KE-chain project to be used throughout an app.
This helper is made to bootstrap a pykechain enabled python script or an jupyter notebook with the correct
project (technically this is a `pykechain.models.Scope` model).
When no parameters are passed in this function, it will try to r... | def get_project(url=None, username=None, password=None, token=None, scope=None, scope_id=None,
env_filename=None, status=ScopeStatus.ACTIVE):
"""
Retrieve and return the KE-chain project to be used throughout an app.
This helper is made to bootstrap a pykechain enabled python script or an j... |
:return: None | def populate(self, priority, address, rtr, data):
"""
:return: None
"""
assert isinstance(data, bytes)
self.needs_high_priority(priority)
self.needs_no_rtr(rtr)
self.needs_data(data, 3)
self.set_attributes(priority, address, rtr)
self.closed = self... |
:return: str | def to_json(self):
"""
:return: str
"""
json_dict = self.to_json_basic()
json_dict['closed_channels'] = self.closed
json_dict['opened_channels'] = self.opened
json_dict['closed_long_channels'] = self.closed_long
return json.dumps(json_dict) |
:return: bytes | def data_to_binary(self):
"""
:return: bytes
"""
return bytes([
COMMAND_CODE,
self.channels_to_byte(self.closed),
self.channels_to_byte(self.opened),
self.channels_to_byte(self.closed_long)
]) |
Rebuild the internal key to index mapping. | def _rebuild_key_ids(self):
"""Rebuild the internal key to index mapping."""
self._key_ids = collections.defaultdict(list)
for i, x in enumerate(self._pairs):
self._key_ids[x[0]].append(i) |
Force a given key/value pair into a certain form.
Override the _conform_key and _conform_value if you want to change
the mapping behaviour. | def _conform_pair(self, pair):
"""Force a given key/value pair into a certain form.
Override the _conform_key and _conform_value if you want to change
the mapping behaviour.
"""
pair = tuple(pair)
if len(pair) != 2:
raise ValueError('MultiMap... |
A list of all the values stored under this key.
Returns an empty list if there are no values under this key.
>>> m = MultiMap([('a', 1), ('b', 2), ('b', 3), ('c', 4), ('d', 5), ('c', 6)])
>>> m.getall('a')
[1]
>>> m.getall('b')
[2, 3]
>>> m.getal... | def getall(self, key):
"""A list of all the values stored under this key.
Returns an empty list if there are no values under this key.
>>> m = MultiMap([('a', 1), ('b', 2), ('b', 3), ('c', 4), ('d', 5), ('c', 6)])
>>> m.getall('a')
[1]
>>> m.getall('b')
... |
Iterator across all the non-duplicate keys and their values.
Only yields the first key of duplicates. | def iteritems(self):
"""Iterator across all the non-duplicate keys and their values.
Only yields the first key of duplicates.
"""
keys_yielded = set()
for k, v in self._pairs:
if k not in keys_yielded:
keys_yielded.add(k)
... |
Remove the pairs identified by the given indices into _pairs.
Removes the pair, and updates the _key_ids mapping to be accurate.
Removing the ids from the _key_ids is your own responsibility.
Params:
ids_to_remove -- The indices to remove. MUST be sorted. | def _remove_pairs(self, ids_to_remove):
"""Remove the pairs identified by the given indices into _pairs.
Removes the pair, and updates the _key_ids mapping to be accurate.
Removing the ids from the _key_ids is your own responsibility.
Params:
ids_to_remove -... |
Insert some new pairs, and keep the _key_ids updated.
Params:
ids_and_pairs -- A list of (index, (key, value)) tuples. | def _insert_pairs(self, ids_and_pairs):
"""Insert some new pairs, and keep the _key_ids updated.
Params:
ids_and_pairs -- A list of (index, (key, value)) tuples.
"""
ids_to_insert = [x[0] for x in ids_and_pairs]
# We use the bisect to tell u... |
Set more than one value for a given key.
Replaces all the existing values for the given key with new values,
removes extra values that are already set if we don't suply enough,
and appends values to the end if there are not enough existing spots.
>>> m = MutableMultiMap... | def setall(self, key, values):
"""Set more than one value for a given key.
Replaces all the existing values for the given key with new values,
removes extra values that are already set if we don't suply enough,
and appends values to the end if there are not enough existing spots... |
Sort the MultiMap.
Takes the same arguments as list.sort, and operates on tuples of
(key, value) pairs.
>>> m = MutableMultiMap()
>>> m['c'] = 1
>>> m['b'] = 3
>>> m['a'] = 2
>>> m.sort()
>>> m.keys()
['a', 'b', 'c']
>>> m... | def sort(self, *args, **kwargs):
"""Sort the MultiMap.
Takes the same arguments as list.sort, and operates on tuples of
(key, value) pairs.
>>> m = MutableMultiMap()
>>> m['c'] = 1
>>> m['b'] = 3
>>> m['a'] = 2
>>> m.sort()
>>> m.... |
Remove first of given key and return corresponding value.
If key is not found, default is returned if given.
>>> m = MutableMultiMap([('a', 1), ('b', 2), ('b', 3), ('c', 4)])
>>> m.popone('b')
2
>>> m.items()
[('a', 1), ('b', 3), ('c', 4)]
>>> m.... | def popone(self, key, *default):
"""Remove first of given key and return corresponding value.
If key is not found, default is returned if given.
>>> m = MutableMultiMap([('a', 1), ('b', 2), ('b', 3), ('c', 4)])
>>> m.popone('b')
2
>>> m.items()
[... |
Remove specified key and return all corresponding values.
If they key is not found, an empty list is return.
>>> m = MutableMultiMap([('a', 1), ('b', 2), ('b', 3), ('c', 4)])
>>> m.popall('a')
[1]
>>> m.popall('b')
[2, 3]
>>> m.popall('x')
... | def popall(self, key):
"""Remove specified key and return all corresponding values.
If they key is not found, an empty list is return.
>>> m = MutableMultiMap([('a', 1), ('b', 2), ('b', 3), ('c', 4)])
>>> m.popall('a')
[1]
>>> m.popall('b')
[2, 3... |
Update the object. | def _update(self, resource, update_dict=None, params=None, **kwargs):
"""Update the object."""
url = self._client._build_url(resource, **kwargs)
response = self._client._request('PUT', url, json=update_dict, params=params)
if response.status_code != requests.codes.ok: # pragma: no cove... |
Members of the team.
You may provide the role in the team, to retrieve only the teammmber with that role. Normally there is a
single owner, that has administration rights of the team. Normal team members do not have any rights to
administer the team itself such as altering the teamname, team im... | def members(self, role=None):
"""Members of the team.
You may provide the role in the team, to retrieve only the teammmber with that role. Normally there is a
single owner, that has administration rights of the team. Normal team members do not have any rights to
administer the team itse... |
Members to add to a team.
:param members: list of members, either `User` objects or usernames
:type members: List of `User` or List of pk
:param role: (optional) role of the users to add (default `TeamRoles.MEMBER`)
:type role: basestring
:raises IllegalArgumentError: when provi... | def add_members(self, users=None, role=TeamRoles.MEMBER):
"""Members to add to a team.
:param members: list of members, either `User` objects or usernames
:type members: List of `User` or List of pk
:param role: (optional) role of the users to add (default `TeamRoles.MEMBER`)
:t... |
Members to add to a team.
:param members: list of members, either `User` objects or usernames
:type members: List of `User` or List of pk
:raises IllegalArgumentError: when providing incorrect roles
Example
-------
>>> my_team = client.team(name='My own team')
... | def remove_members(self, users=None):
"""Members to add to a team.
:param members: list of members, either `User` objects or usernames
:type members: List of `User` or List of pk
:raises IllegalArgumentError: when providing incorrect roles
Example
-------
>>> m... |
Scopes associated to the team. | def scopes(self, **kwargs):
"""Scopes associated to the team."""
return self._client.scopes(team=self.id, **kwargs) |
Insert a hash based on the content into the path after the first dot.
hash_length 7 matches git commit short references | def insert_hash(path: Path, content: Union[str, bytes], *, hash_length=7, hash_algorithm=hashlib.md5):
"""
Insert a hash based on the content into the path after the first dot.
hash_length 7 matches git commit short references
"""
if isinstance(content, str):
content = content.encode()
... |
Provide a sorted list of options. | def options(cls):
"""Provide a sorted list of options."""
return sorted((value, name) for (name, value) in cls.__dict__.items() if not name.startswith('__')) |
Provide access to the Navigation Bar.
Returns:
:py:class:`NavBar`: FoxPuppet NavBar object. | def navbar(self):
"""Provide access to the Navigation Bar.
Returns:
:py:class:`NavBar`: FoxPuppet NavBar object.
"""
window = BaseWindow(self.selenium, self.selenium.current_window_handle)
with self.selenium.context(self.selenium.CONTEXT_CHROME):
el = se... |
Provide access to the currently displayed notification.
Returns:
:py:class:`BaseNotification`: FoxPuppet BaseNotification object. | def notification(self):
"""Provide access to the currently displayed notification.
Returns:
:py:class:`BaseNotification`: FoxPuppet BaseNotification object.
"""
with self.selenium.context(self.selenium.CONTEXT_CHROME):
try:
root = self.selenium.f... |
Wait for the specified notification to be displayed.
Args:
notification_class (:py:class:`BaseNotification`, optional):
The notification class to wait for. If `None` is specified it
will wait for any notification to be closed. Defaults to
`BaseNotific... | def wait_for_notification(self, notification_class=BaseNotification):
"""Wait for the specified notification to be displayed.
Args:
notification_class (:py:class:`BaseNotification`, optional):
The notification class to wait for. If `None` is specified it
will... |
Property that checks if the specified window is private or not.
Returns:
bool: True if this is a Private Browsing window. | def is_private(self):
"""Property that checks if the specified window is private or not.
Returns:
bool: True if this is a Private Browsing window.
"""
self.switch_to()
with self.selenium.context(self.selenium.CONTEXT_CHROME):
return self.selenium.execute... |
Open a new browser window.
Args:
private (bool): Optional parameter to open a private browsing
window. Defaults to False.
Returns:
:py:class:`BrowserWindow`: Opened window. | def open_window(self, private=False):
"""Open a new browser window.
Args:
private (bool): Optional parameter to open a private browsing
window. Defaults to False.
Returns:
:py:class:`BrowserWindow`: Opened window.
"""
handles_before = se... |
An alias for `todict` | def to_serializable_dict(self, attrs_to_serialize=None,
rels_to_expand=None,
rels_to_serialize=None,
key_modifications=None):
"""
An alias for `todict`
"""
return self.todict(
attrs_to_seri... |
dict_struct:
{
'attrs': ['id', 'created_at'],
'rels': {
'merchandise': {
'attrs': ['id', 'label']
}
}
} | def todict_using_struct(self, dict_struct=None, dict_post_processors=None):
"""
dict_struct:
{
'attrs': ['id', 'created_at'],
'rels': {
'merchandise': {
'attrs': ['id', 'label']
}
... |
Converts an instance to a dictionary form
Args:
attrs_to_serialize (list of str): The columns which should
be serialized as a part of the output dictionary
key_modifications (dict of str,str): A dictionary used to map
the display names of columns whos... | def todict(self, attrs_to_serialize=None,
rels_to_expand=None,
rels_to_serialize=None,
group_listrels_by=None,
key_modifications=None,
dict_struct=None,
dict_post_processors=None):
"""Converts an instance to a dictionary ... |
Converts and instance to a dictionary with only the specified
attributes as keys
Args:
*args (list): The attributes to serialize
Examples:
>>> customer = Customer.create(name="James Bond", email="007@mi.com",
phone="007", city... | def serialize_attrs(self, *args):
"""Converts and instance to a dictionary with only the specified
attributes as keys
Args:
*args (list): The attributes to serialize
Examples:
>>> customer = Customer.create(name="James Bond", email="007@mi.com",
... |
Compute fundamental frequency along the specified axes.
Parameters
----------
s: ndarray
input from which fundamental frequency is computed.
FS: int
sampling frequency
Returns
-------
f0: int
its integer multiple best explain the content of the signal spectrum. | def fundamental_frequency(s,FS):
# TODO: review fundamental frequency to guarantee that f0 exists
# suggestion peak level should be bigger
# TODO: explain code
"""Compute fundamental frequency along the specified axes.
Parameters
----------
s: ndarray
input from which fundamental ... |
Compute max frequency along the specified axes.
Parameters
----------
sig: ndarray
input from which max frequency is computed.
FS: int
sampling frequency
Returns
-------
f_max: int
0.95 of max_frequency using cumsum. | def max_frequency (sig,FS):
"""Compute max frequency along the specified axes.
Parameters
----------
sig: ndarray
input from which max frequency is computed.
FS: int
sampling frequency
Returns
-------
f_max: int
0.95 of max_frequency using cumsum.
"""
... |
Compute median frequency along the specified axes.
Parameters
----------
sig: ndarray
input from which median frequency is computed.
FS: int
sampling frequency
Returns
-------
f_max: int
0.50 of max_frequency using cumsum. | def median_frequency(sig,FS):
"""Compute median frequency along the specified axes.
Parameters
----------
sig: ndarray
input from which median frequency is computed.
FS: int
sampling frequency
Returns
-------
f_max: int
0.50 of max_frequency using cumsum.
... |
Call a subcommand passing the args. | def call(subcommand, args):
"""Call a subcommand passing the args."""
args['<napp>'] = parse_napps(args['<napp>'])
func = getattr(NAppsAPI, subcommand)
func(args) |
Convert a napp_id in tuple with username, napp name and version.
Args:
napp_id: String with the form 'username/napp[:version]' (version is
optional). If no version is found, it will be None.
Returns:
tuple: A tuple with (username, napp, version)
Raises:
KytosExce... | def parse_napp(napp_id):
"""Convert a napp_id in tuple with username, napp name and version.
Args:
napp_id: String with the form 'username/napp[:version]' (version is
optional). If no version is found, it will be None.
Returns:
tuple: A tuple with (username, napp, version... |
-----
Brief
-----
Function that generates the OpenSignalsTools Notebooks File Hierarchy programatically.
-----------
Description
-----------
OpenSignalsTools Notebooks folder obey to a predefined hierarchy that allows to run the code of online available
notebooks and using the sample fi... | def opensignals_hierarchy(root=None, update=False, clone=False):
"""
-----
Brief
-----
Function that generates the OpenSignalsTools Notebooks File Hierarchy programatically.
-----------
Description
-----------
OpenSignalsTools Notebooks folder obey to a predefined hierarchy that all... |
Internal function that is used for generation of the generic notebooks header.
----------
Parameters
----------
notebook_object : notebook object
Object of "notebook" class where the header will be created.
notebook_type : str
Notebook type: - "Main_Files_Signal_Samples"
... | def _generate_notebook_header(notebook_object, notebook_type, notebook_title="Notebook Title",
tags="tags", difficulty_stars=1,
notebook_description="Notebook Description"):
"""
Internal function that is used for generation of the generic notebooks hea... |
Internal function that is used for generation of the page "Notebooks by Category".
----------
Parameters
----------
notebook_object : notebook object
Object of "notebook" class where the body will be created.
dict_by_tag : dict
Dictionary where each key is a tag and the respective ... | def _generate_notebooks_by_category(notebook_object, dict_by_tag):
"""
Internal function that is used for generation of the page "Notebooks by Category".
----------
Parameters
----------
notebook_object : notebook object
Object of "notebook" class where the body will be created.
di... |
Internal function that is used for generation of the GitHub and PyPI README file.
----------
Parameters
----------
notebook_object : notebook object
Object of "notebook" class where the body will be created.
dict_by_tag : dict
Dictionary where each key is a tag and the respective v... | def _generate_github_readme(notebook_object, dict_by_tag):
"""
Internal function that is used for generation of the GitHub and PyPI README file.
----------
Parameters
----------
notebook_object : notebook object
Object of "notebook" class where the body will be created.
dict_by_tag... |
Make the actual request and returns the parsed response. | def _request(self, method, path, params=None):
"""Make the actual request and returns the parsed response."""
url = self._base_url + path
try:
if method == 'GET':
response = requests.get(url, timeout=TIMEOUT)
elif method == "POST":
respons... |
data bytes (high + low)
1 + 2 = current temp
3 + 4 = min temp
5 + 6 = max temp
:return: None | def populate(self, priority, address, rtr, data):
"""
data bytes (high + low)
1 + 2 = current temp
3 + 4 = min temp
5 + 6 = max temp
:return: None
"""
assert isinstance(data, bytes)
self.needs_no_rtr(rtr)
self.needs_data(d... |
:return: str | def to_json(self):
"""
:return: str
"""
json_dict = self.to_json_basic()
json_dict['cur'] = self.cur
json_dict['min'] = self.min
json_dict['max'] = self.max
return json.dumps(json_dict) |
Hook into Gunicorn to display message after launching.
This mimics the behaviour of Django's stock runserver command. | def post_worker_init(worker):
"""Hook into Gunicorn to display message after launching.
This mimics the behaviour of Django's stock runserver command.
"""
quit_command = 'CTRL-BREAK' if sys.platform == 'win32' else 'CONTROL-C'
sys.stdout.write(
"Django version {djangover}, Gunicorn version ... |
@brief: for a given signal s rejects (attenuates) the frequencies lower
then the cuttof frequency f and passes the frequencies higher than that
value by applying a Butterworth digital filter
@params:
s: array-like
signal
f: int
the cutoff frequency
order: int
Butterworth filter o... | def highpass(s, f, order=2, fs=1000.0, use_filtfilt=False):
'''
@brief: for a given signal s rejects (attenuates) the frequencies lower
then the cuttof frequency f and passes the frequencies higher than that
value by applying a Butterworth digital filter
@params:
s: array-like
signal
... |
Retrieve the data value of this attachment.
Will show the filename of the attachment if there is an attachment available otherwise None
Use save_as in order to download as a file.
Example
-------
>>> file_attachment_property = project.part('Bike').property('file_attachment')
... | def value(self):
"""Retrieve the data value of this attachment.
Will show the filename of the attachment if there is an attachment available otherwise None
Use save_as in order to download as a file.
Example
-------
>>> file_attachment_property = project.part('Bike').p... |
Filename of the attachment, without the full 'attachment' path. | def filename(self):
"""Filename of the attachment, without the full 'attachment' path."""
if self.value and 'value' in self._json_data and self._json_data['value']:
return self._json_data['value'].split('/')[-1]
return None |
Upload a file to the attachment property.
When providing a :class:`matplotlib.figure.Figure` object as data, the figure is uploaded as PNG.
For this, `matplotlib`_ should be installed.
:param filename: File path
:type filename: basestring
:raises APIError: When unable to upload... | def upload(self, data, **kwargs):
"""Upload a file to the attachment property.
When providing a :class:`matplotlib.figure.Figure` object as data, the figure is uploaded as PNG.
For this, `matplotlib`_ should be installed.
:param filename: File path
:type filename: basestring
... |
Download the attachment to a file.
:param filename: File path
:type filename: basestring
:raises APIError: When unable to download the data
:raises OSError: When unable to save the data to disk | def save_as(self, filename):
"""Download the attachment to a file.
:param filename: File path
:type filename: basestring
:raises APIError: When unable to download the data
:raises OSError: When unable to save the data to disk
"""
with open(filename, 'w+b') as f:
... |
Load theme when `theme` parameter is 'semantic-ui'. | def devpiserver_cmdline_run(xom):
'''
Load theme when `theme` parameter is 'semantic-ui'.
'''
if xom.config.args.theme == 'semantic-ui':
xom.config.args.theme = resource_filename('devpi_semantic_ui', '')
xom.log.info("Semantic UI Theme loaded") |
Check if a switch is turned on
:return: bool | def is_on(self, channel):
"""
Check if a switch is turned on
:return: bool
"""
if channel in self._is_on:
return self._is_on[channel]
return False |
Turn on switch.
:return: None | def turn_on(self, channel, callback=None):
"""
Turn on switch.
:return: None
"""
if callback is None:
def callb():
"""No-op"""
pass
callback = callb
message = velbus.SwitchRelayOnMessage(self._address)
messa... |
Turn off switch.
:return: None | def turn_off(self, channel, callback=None):
"""
Turn off switch.
:return: None
"""
if callback is None:
def callb():
"""No-op"""
pass
callback = callb
message = velbus.SwitchRelayOffMessage(self._address)
me... |
With t and rh provided, does not access the hardware. | def read_dew_point(self, t=None, rh=None):
'With t and rh provided, does not access the hardware.'
if t is None: t, rh = self.read_t(), None
if rh is None: rh = self.read_rh(t)
t_range = 'water' if t >= 0 else 'ice'
tn, m = self.c.tn[t_range], self.c.m[t_range]
return ( # ch 4.4
tn * (math.log(rh / 100.0... |
Save the options to KE-chain.
Makes a single API call.
:param options_list: list of options to set.
:raises APIError: when unable to update the options | def _put_options(self, options_list):
"""Save the options to KE-chain.
Makes a single API call.
:param options_list: list of options to set.
:raises APIError: when unable to update the options
"""
new_options = self._options.copy() # make a full copy of the dict not to... |
Take a Form or FormSet and set all fields to not required. | def make_form_or_formset_fields_not_required(form_or_formset):
"""Take a Form or FormSet and set all fields to not required."""
if isinstance(form_or_formset, BaseFormSet):
for single_form in form_or_formset:
make_form_fields_not_required(single_form)
else:
make_form_fields_not_r... |
-DB1 last 2 bits = channel
-DB1 first 6 bist = pulses
-DB2-5 = pulse counter
-DB6-7 = ms/pulse
:return: None | def populate(self, priority, address, rtr, data):
"""
-DB1 last 2 bits = channel
-DB1 first 6 bist = pulses
-DB2-5 = pulse counter
-DB6-7 = ms/pulse
:return: None
"""
assert isinstance(data, bytes)
... |
Align various waves in a specific point.
Given a mode of alignment, this function computes the specific time point of
a wave where all the waves would be aligned. With the difference between the
time point of the reference wave and the time points of all the other waves,
we have the amount of sam... | def align(w,signals,mode):
""" Align various waves in a specific point.
Given a mode of alignment, this function computes the specific time point of
a wave where all the waves would be aligned. With the difference between the
time point of the reference wave and the time points of all the other wa... |
Move a signal in time.
This function returns a signal created by a shifting in time on the original
signal.
Parameters
----------
w: array-like
the input signal to move.
move: int
the ammount of samples to shift the signal (if <0 the signal moves back,
if >0 the sign... | def moveWave(w,move):
""" Move a signal in time.
This function returns a signal created by a shifting in time on the original
signal.
Parameters
----------
w: array-like
the input signal to move.
move: int
the ammount of samples to shift the signal (if <0 the signal mov... |
Difference between the maximum peak positions of the signals.
This function returns the difference, in samples, between the peaks position
of the signals. If the reference signal has various peaks, the one
chosen is the peak which is closer to the middle of the signal, and if the
other signal ha... | def peakAlign(refw,w):
""" Difference between the maximum peak positions of the signals.
This function returns the difference, in samples, between the peaks position
of the signals. If the reference signal has various peaks, the one
chosen is the peak which is closer to the middle of the signal, ... |
ID of the scope this Activity belongs to.
This property will always produce a scope_id, even when the scope object was not included in an earlier
response.
When the :class:`Scope` is not included in this task, it will make an additional call to the KE-chain API.
:return: the scope id ... | def scope_id(self):
"""
ID of the scope this Activity belongs to.
This property will always produce a scope_id, even when the scope object was not included in an earlier
response.
When the :class:`Scope` is not included in this task, it will make an additional call to the KE-ch... |
Determine if Activity is at the root level of a project.
:return: Return True if it is a root level activity, otherwise return False
:rtype: bool | def is_rootlevel(self):
"""
Determine if Activity is at the root level of a project.
:return: Return True if it is a root level activity, otherwise return False
:rtype: bool
"""
container_id = self._json_data.get('container')
if container_id:
return c... |
Determine if the Activity is configured with input and output properties.
Makes an additional lightweight call to the API to determine if any associated models are there.
:return: Return True if it is configured, otherwise return False
:rtype: bool | def is_configured(self):
"""
Determine if the Activity is configured with input and output properties.
Makes an additional lightweight call to the API to determine if any associated models are there.
:return: Return True if it is configured, otherwise return False
:rtype: bool
... |
Retrieve parts belonging to this activity.
Without any arguments it retrieves the Instances related to this task only.
This call only returns the configured properties in an activity. So properties that are not configured
are not in the returned parts.
See :class:`pykechain.Client.par... | def parts(self, *args, **kwargs):
"""Retrieve parts belonging to this activity.
Without any arguments it retrieves the Instances related to this task only.
This call only returns the configured properties in an activity. So properties that are not configured
are not in the returned par... |
Retrieve models and instances belonging to this activity.
This is a convenience method for the :func:`Activity.parts()` method, which is used to retrieve both the
`Category.MODEL` as well as the `Category.INSTANCE` in a tuple.
This call only returns the configured properties in an activity. So... | def associated_parts(self, *args, **kwargs):
"""Retrieve models and instances belonging to this activity.
This is a convenience method for the :func:`Activity.parts()` method, which is used to retrieve both the
`Category.MODEL` as well as the `Category.INSTANCE` in a tuple.
This call o... |
Configure activity input and output.
You need to provide a list of input and output :class:`Property`. Does not work with lists of propery id's.
:param inputs: iterable of input property models
:type inputs: list(:class:`Property`)
:param outputs: iterable of output property models
... | def configure(self, inputs, outputs):
"""Configure activity input and output.
You need to provide a list of input and output :class:`Property`. Does not work with lists of propery id's.
:param inputs: iterable of input property models
:type inputs: list(:class:`Property`)
:para... |
Retrieve the subprocess in which this activity is defined.
If this is a task on top level, it raises NotFounderror.
:return: a subprocess :class:`Activity`
:raises NotFoundError: when it is a task in the top level of a project
:raises APIError: when other error occurs
Example
... | def subprocess(self):
"""Retrieve the subprocess in which this activity is defined.
If this is a task on top level, it raises NotFounderror.
:return: a subprocess :class:`Activity`
:raises NotFoundError: when it is a task in the top level of a project
:raises APIError: when oth... |
Retrieve the direct activities of this subprocess.
It returns a combination of Tasks (a.o. UserTasks) and Subprocesses on the direct descending level.
Only when the activity is a Subprocess, otherwise it raises a NotFoundError
:param kwargs: Additional search arguments, check :func:`pykechain.... | def children(self, **kwargs):
"""Retrieve the direct activities of this subprocess.
It returns a combination of Tasks (a.o. UserTasks) and Subprocesses on the direct descending level.
Only when the activity is a Subprocess, otherwise it raises a NotFoundError
:param kwargs: Additional ... |
Retrieve the other activities that also belong to the subprocess.
It returns a combination of Tasks (a.o. UserTasks) and Subprocesses on the level of the current task, including
itself. This also works if the activity is of type `ActivityType.SUBPROCESS`.
:param kwargs: Additional search argum... | def siblings(self, **kwargs):
"""Retrieve the other activities that also belong to the subprocess.
It returns a combination of Tasks (a.o. UserTasks) and Subprocesses on the level of the current task, including
itself. This also works if the activity is of type `ActivityType.SUBPROCESS`.
... |
Create a new activity belonging to this subprocess.
See :func:`pykechain.Client.create_activity` for available parameters.
:raises IllegalArgumentError: if the `Activity` is not a `SUBPROCESS`.
:raises APIError: if an Error occurs. | def create(self, *args, **kwargs):
"""Create a new activity belonging to this subprocess.
See :func:`pykechain.Client.create_activity` for available parameters.
:raises IllegalArgumentError: if the `Activity` is not a `SUBPROCESS`.
:raises APIError: if an Error occurs.
"""
... |
Edit the details of an activity.
:param name: (optionally) edit the name of the activity
:type name: basestring or None
:param description: (optionally) edit the description of the activity
:type description: basestring or None
:param start_date: (optionally) edit the start date... | def edit(self, name=None, description=None, start_date=None, due_date=None, assignees=None, status=None):
"""Edit the details of an activity.
:param name: (optionally) edit the name of the activity
:type name: basestring or None
:param description: (optionally) edit the description of t... |
Get a customization object representing the customization of the activity.
.. versionadded:: 1.11
:return: An instance of :class:`customization.ExtCustomization`
Example
-------
>>> activity = project.activity(name='Customizable activity')
>>> customization = activity.... | def customization(self):
"""
Get a customization object representing the customization of the activity.
.. versionadded:: 1.11
:return: An instance of :class:`customization.ExtCustomization`
Example
-------
>>> activity = project.activity(name='Customizable act... |
Generate GraphQL query | def get_gql_query(self):
"""Generate GraphQL query"""
template_string = """query(
$stops: [String],
$quays: [String],
$whitelist: InputWhiteListed,
$numberOfDepartures: Int = 2,
$omitNonBoarding: Boolean = true){\n"""
if self.stops:
... |
Get all stop places and quays | def all_stop_places_quays(self) -> list:
"""Get all stop places and quays"""
all_places = self.stops.copy()
for quay in self.quays:
all_places.append(quay)
return all_places |
Find all quays from stop places. | async def expand_all_quays(self) -> None:
"""Find all quays from stop places."""
if not self.stops:
return
headers = {'ET-Client-Name': self._client_name}
request = {
'query': GRAPHQL_STOP_TO_QUAY_TEMPLATE,
'variables': {
'stops': self... |
Get the latest data from api.entur.org. | async def update(self) -> None:
"""Get the latest data from api.entur.org."""
headers = {'ET-Client-Name': self._client_name}
request = {
'query': self.get_gql_query(),
'variables': {
'stops': self.stops,
'quays': self.quays,
... |
Extract information from place dictionary. | def _process_place(self, place: dict, is_platform: bool) -> None:
"""Extract information from place dictionary."""
place_id = place['id']
self.info[place_id] = Place(place, is_platform) |
Converts a list of model instances to a list of dictionaries
using their `todict` method.
Args:
olist (list): The list of instances to convert
attrs_to_serialize (list, optional): To be passed as an argument
to the `todict` method
rels_to_expand (list, optional): To be passe... | def serializable_list(
olist, attrs_to_serialize=None, rels_to_expand=None,
group_listrels_by=None, rels_to_serialize=None,
key_modifications=None, groupby=None, keyvals_to_merge=None,
preserve_order=False, dict_struct=None, dict_post_processors=None):
"""
Converts a list of mode... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.