repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
mattja/nsim
nsim/analyses1/phase.py
periods
def periods(ts, phi=0.0): """For a single variable timeseries representing the phase of an oscillator, measure the period of each successive oscillation. An individual oscillation is defined to start and end when the phase passes phi (by default zero) after completing a full cycle. If the timeser...
python
def periods(ts, phi=0.0): """For a single variable timeseries representing the phase of an oscillator, measure the period of each successive oscillation. An individual oscillation is defined to start and end when the phase passes phi (by default zero) after completing a full cycle. If the timeser...
[ "def", "periods", "(", "ts", ",", "phi", "=", "0.0", ")", ":", "ts", "=", "np", ".", "squeeze", "(", "ts", ")", "if", "ts", ".", "ndim", "<=", "1", ":", "return", "np", ".", "diff", "(", "phase_crossings", "(", "ts", ",", "phi", ")", ")", "el...
For a single variable timeseries representing the phase of an oscillator, measure the period of each successive oscillation. An individual oscillation is defined to start and end when the phase passes phi (by default zero) after completing a full cycle. If the timeseries begins (or ends) exactly at p...
[ "For", "a", "single", "variable", "timeseries", "representing", "the", "phase", "of", "an", "oscillator", "measure", "the", "period", "of", "each", "successive", "oscillation", "." ]
train
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/analyses1/phase.py#L85-L106
mattja/nsim
nsim/analyses1/phase.py
circmean
def circmean(ts, axis=2): """Circular mean phase""" return np.exp(1.0j * ts).mean(axis=axis).angle()
python
def circmean(ts, axis=2): """Circular mean phase""" return np.exp(1.0j * ts).mean(axis=axis).angle()
[ "def", "circmean", "(", "ts", ",", "axis", "=", "2", ")", ":", "return", "np", ".", "exp", "(", "1.0j", "*", "ts", ")", ".", "mean", "(", "axis", "=", "axis", ")", ".", "angle", "(", ")" ]
Circular mean phase
[ "Circular", "mean", "phase" ]
train
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/analyses1/phase.py#L109-L111
mattja/nsim
nsim/analyses1/phase.py
order_param
def order_param(ts, axis=2): """Order parameter of phase synchronization""" return np.abs(np.exp(1.0j * ts).mean(axis=axis))
python
def order_param(ts, axis=2): """Order parameter of phase synchronization""" return np.abs(np.exp(1.0j * ts).mean(axis=axis))
[ "def", "order_param", "(", "ts", ",", "axis", "=", "2", ")", ":", "return", "np", ".", "abs", "(", "np", ".", "exp", "(", "1.0j", "*", "ts", ")", ".", "mean", "(", "axis", "=", "axis", ")", ")" ]
Order parameter of phase synchronization
[ "Order", "parameter", "of", "phase", "synchronization" ]
train
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/analyses1/phase.py#L114-L116
mattja/nsim
nsim/analyses1/_cwtmorlet.py
cwtmorlet
def cwtmorlet(points, width): """complex morlet wavelet function compatible with scipy.signal.cwt Parameters: points: int Number of points in `vector`. width: scalar Width parameter of wavelet. Equals (sample rate / fundamental frequenc...
python
def cwtmorlet(points, width): """complex morlet wavelet function compatible with scipy.signal.cwt Parameters: points: int Number of points in `vector`. width: scalar Width parameter of wavelet. Equals (sample rate / fundamental frequenc...
[ "def", "cwtmorlet", "(", "points", ",", "width", ")", ":", "omega", "=", "5.0", "s", "=", "points", "/", "(", "2.0", "*", "omega", "*", "width", ")", "return", "wavelets", ".", "morlet", "(", "points", ",", "omega", ",", "s", ",", "complete", "=", ...
complex morlet wavelet function compatible with scipy.signal.cwt Parameters: points: int Number of points in `vector`. width: scalar Width parameter of wavelet. Equals (sample rate / fundamental frequency of wavelet) Returns: `vector`: ...
[ "complex", "morlet", "wavelet", "function", "compatible", "with", "scipy", ".", "signal", ".", "cwt", "Parameters", ":", "points", ":", "int", "Number", "of", "points", "in", "vector", ".", "width", ":", "scalar", "Width", "parameter", "of", "wavelet", ".", ...
train
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/analyses1/_cwtmorlet.py#L5-L16
mattja/nsim
nsim/analyses1/_cwtmorlet.py
roughcwt
def roughcwt(data, wavelet, widths): """ Continuous wavelet transform. Performs a continuous wavelet transform on `data`, using the `wavelet` function. A CWT performs a convolution with `data` using the `wavelet` function, which is characterized by a width parameter and length parameter. P...
python
def roughcwt(data, wavelet, widths): """ Continuous wavelet transform. Performs a continuous wavelet transform on `data`, using the `wavelet` function. A CWT performs a convolution with `data` using the `wavelet` function, which is characterized by a width parameter and length parameter. P...
[ "def", "roughcwt", "(", "data", ",", "wavelet", ",", "widths", ")", ":", "out_dtype", "=", "wavelet", "(", "widths", "[", "0", "]", ",", "widths", "[", "0", "]", ")", ".", "dtype", "output", "=", "np", ".", "zeros", "(", "[", "len", "(", "widths"...
Continuous wavelet transform. Performs a continuous wavelet transform on `data`, using the `wavelet` function. A CWT performs a convolution with `data` using the `wavelet` function, which is characterized by a width parameter and length parameter. Parameters ---------- data : (N,) ndarray ...
[ "Continuous", "wavelet", "transform", "." ]
train
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/analyses1/_cwtmorlet.py#L20-L69
mattja/nsim
nsim/analyses1/epochs.py
variability_fp
def variability_fp(ts, freqs=None, ncycles=6, plot=True): """Example variability function. Gives two continuous, time-resolved measures of the variability of a time series, ranging between -1 and 1. The two measures are based on variance of the centroid frequency and variance of the height of the ...
python
def variability_fp(ts, freqs=None, ncycles=6, plot=True): """Example variability function. Gives two continuous, time-resolved measures of the variability of a time series, ranging between -1 and 1. The two measures are based on variance of the centroid frequency and variance of the height of the ...
[ "def", "variability_fp", "(", "ts", ",", "freqs", "=", "None", ",", "ncycles", "=", "6", ",", "plot", "=", "True", ")", ":", "if", "freqs", "is", "None", ":", "freqs", "=", "np", ".", "logspace", "(", "np", ".", "log10", "(", "1.0", ")", ",", "...
Example variability function. Gives two continuous, time-resolved measures of the variability of a time series, ranging between -1 and 1. The two measures are based on variance of the centroid frequency and variance of the height of the spectral peak, respectively. (Centroid frequency meaning the ...
[ "Example", "variability", "function", ".", "Gives", "two", "continuous", "time", "-", "resolved", "measures", "of", "the", "variability", "of", "a", "time", "series", "ranging", "between", "-", "1", "and", "1", ".", "The", "two", "measures", "are", "based", ...
train
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/analyses1/epochs.py#L31-L102
mattja/nsim
nsim/analyses1/epochs.py
_rescale
def _rescale(ar): """Shift and rescale array ar to the interval [-1, 1]""" max = np.nanmax(ar) min = np.nanmin(ar) midpoint = (max + min) / 2.0 return 2.0 * (ar - midpoint) / (max - min)
python
def _rescale(ar): """Shift and rescale array ar to the interval [-1, 1]""" max = np.nanmax(ar) min = np.nanmin(ar) midpoint = (max + min) / 2.0 return 2.0 * (ar - midpoint) / (max - min)
[ "def", "_rescale", "(", "ar", ")", ":", "max", "=", "np", ".", "nanmax", "(", "ar", ")", "min", "=", "np", ".", "nanmin", "(", "ar", ")", "midpoint", "=", "(", "max", "+", "min", ")", "/", "2.0", "return", "2.0", "*", "(", "ar", "-", "midpoin...
Shift and rescale array ar to the interval [-1, 1]
[ "Shift", "and", "rescale", "array", "ar", "to", "the", "interval", "[", "-", "1", "1", "]" ]
train
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/analyses1/epochs.py#L105-L110
mattja/nsim
nsim/analyses1/epochs.py
_get_color_list
def _get_color_list(): """Get cycle of colors in a way compatible with all matplotlib versions""" if 'axes.prop_cycle' in plt.rcParams: return [p['color'] for p in list(plt.rcParams['axes.prop_cycle'])] else: return plt.rcParams['axes.color_cycle']
python
def _get_color_list(): """Get cycle of colors in a way compatible with all matplotlib versions""" if 'axes.prop_cycle' in plt.rcParams: return [p['color'] for p in list(plt.rcParams['axes.prop_cycle'])] else: return plt.rcParams['axes.color_cycle']
[ "def", "_get_color_list", "(", ")", ":", "if", "'axes.prop_cycle'", "in", "plt", ".", "rcParams", ":", "return", "[", "p", "[", "'color'", "]", "for", "p", "in", "list", "(", "plt", ".", "rcParams", "[", "'axes.prop_cycle'", "]", ")", "]", "else", ":",...
Get cycle of colors in a way compatible with all matplotlib versions
[ "Get", "cycle", "of", "colors", "in", "a", "way", "compatible", "with", "all", "matplotlib", "versions" ]
train
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/analyses1/epochs.py#L113-L118
mattja/nsim
nsim/analyses1/epochs.py
_plot_variability
def _plot_variability(ts, variability, threshold=None, epochs=None): """Plot the timeseries and variability. Optionally plot epochs.""" import matplotlib.style import matplotlib as mpl mpl.style.use('classic') import matplotlib.pyplot as plt if variability.ndim is 1: variability = variab...
python
def _plot_variability(ts, variability, threshold=None, epochs=None): """Plot the timeseries and variability. Optionally plot epochs.""" import matplotlib.style import matplotlib as mpl mpl.style.use('classic') import matplotlib.pyplot as plt if variability.ndim is 1: variability = variab...
[ "def", "_plot_variability", "(", "ts", ",", "variability", ",", "threshold", "=", "None", ",", "epochs", "=", "None", ")", ":", "import", "matplotlib", ".", "style", "import", "matplotlib", "as", "mpl", "mpl", ".", "style", ".", "use", "(", "'classic'", ...
Plot the timeseries and variability. Optionally plot epochs.
[ "Plot", "the", "timeseries", "and", "variability", ".", "Optionally", "plot", "epochs", "." ]
train
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/analyses1/epochs.py#L121-L184
mattja/nsim
nsim/analyses1/epochs.py
epochs
def epochs(ts, variability=None, threshold=0.0, minlength=1.0, plot=True): """Identify "stationary" epochs within a time series, based on a continuous measure of variability. Epochs are defined to contain the points of minimal variability, and to extend as wide as possible with variability not exceedi...
python
def epochs(ts, variability=None, threshold=0.0, minlength=1.0, plot=True): """Identify "stationary" epochs within a time series, based on a continuous measure of variability. Epochs are defined to contain the points of minimal variability, and to extend as wide as possible with variability not exceedi...
[ "def", "epochs", "(", "ts", ",", "variability", "=", "None", ",", "threshold", "=", "0.0", ",", "minlength", "=", "1.0", ",", "plot", "=", "True", ")", ":", "if", "variability", "is", "None", ":", "variability", "=", "ts", ".", "variability_fp", "(", ...
Identify "stationary" epochs within a time series, based on a continuous measure of variability. Epochs are defined to contain the points of minimal variability, and to extend as wide as possible with variability not exceeding the threshold. Args: ts Timeseries of m variables, shape (n, m). ...
[ "Identify", "stationary", "epochs", "within", "a", "time", "series", "based", "on", "a", "continuous", "measure", "of", "variability", ".", "Epochs", "are", "defined", "to", "contain", "the", "points", "of", "minimal", "variability", "and", "to", "extend", "as...
train
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/analyses1/epochs.py#L187-L273
mattja/nsim
nsim/analyses1/epochs.py
epochs_distributed
def epochs_distributed(ts, variability=None, threshold=0.0, minlength=1.0, plot=True): """Same as `epochs()`, but computes channels in parallel for speed. (Note: This requires an IPython cluster to be started first, e.g. on a workstation type 'ipcluster start') Identify...
python
def epochs_distributed(ts, variability=None, threshold=0.0, minlength=1.0, plot=True): """Same as `epochs()`, but computes channels in parallel for speed. (Note: This requires an IPython cluster to be started first, e.g. on a workstation type 'ipcluster start') Identify...
[ "def", "epochs_distributed", "(", "ts", ",", "variability", "=", "None", ",", "threshold", "=", "0.0", ",", "minlength", "=", "1.0", ",", "plot", "=", "True", ")", ":", "import", "distob", "if", "ts", ".", "ndim", "is", "1", ":", "ts", "=", "ts", "...
Same as `epochs()`, but computes channels in parallel for speed. (Note: This requires an IPython cluster to be started first, e.g. on a workstation type 'ipcluster start') Identify "stationary" epochs within a time series, based on a continuous measure of variability. Epochs are defined t...
[ "Same", "as", "epochs", "()", "but", "computes", "channels", "in", "parallel", "for", "speed", "." ]
train
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/analyses1/epochs.py#L276-L322
mattja/nsim
nsim/analyses1/epochs.py
epochs_joint
def epochs_joint(ts, variability=None, threshold=0.0, minlength=1.0, proportion=0.75, plot=True): """Identify epochs within a multivariate time series where at least a certain proportion of channels are "stationary", based on a previously computed variability measure. (Note: This req...
python
def epochs_joint(ts, variability=None, threshold=0.0, minlength=1.0, proportion=0.75, plot=True): """Identify epochs within a multivariate time series where at least a certain proportion of channels are "stationary", based on a previously computed variability measure. (Note: This req...
[ "def", "epochs_joint", "(", "ts", ",", "variability", "=", "None", ",", "threshold", "=", "0.0", ",", "minlength", "=", "1.0", ",", "proportion", "=", "0.75", ",", "plot", "=", "True", ")", ":", "variability", ",", "allchannels_epochs", "=", "ts", ".", ...
Identify epochs within a multivariate time series where at least a certain proportion of channels are "stationary", based on a previously computed variability measure. (Note: This requires an IPython cluster to be started first, e.g. on a workstation type 'ipcluster start') Args: ts Tim...
[ "Identify", "epochs", "within", "a", "multivariate", "time", "series", "where", "at", "least", "a", "certain", "proportion", "of", "channels", "are", "stationary", "based", "on", "a", "previously", "computed", "variability", "measure", "." ]
train
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/analyses1/epochs.py#L325-L379
mattja/nsim
nsim/analyses1/plots.py
plot
def plot(ts, title=None, show=True): """Plot a Timeseries Args: ts Timeseries title str show bool whether to display the figure or just return a figure object """ ts = _remove_pi_crossings(ts) fig = plt.figure() ylabelprops = dict(rotation=0, hor...
python
def plot(ts, title=None, show=True): """Plot a Timeseries Args: ts Timeseries title str show bool whether to display the figure or just return a figure object """ ts = _remove_pi_crossings(ts) fig = plt.figure() ylabelprops = dict(rotation=0, hor...
[ "def", "plot", "(", "ts", ",", "title", "=", "None", ",", "show", "=", "True", ")", ":", "ts", "=", "_remove_pi_crossings", "(", "ts", ")", "fig", "=", "plt", ".", "figure", "(", ")", "ylabelprops", "=", "dict", "(", "rotation", "=", "0", ",", "h...
Plot a Timeseries Args: ts Timeseries title str show bool whether to display the figure or just return a figure object
[ "Plot", "a", "Timeseries", "Args", ":", "ts", "Timeseries", "title", "str", "show", "bool", "whether", "to", "display", "the", "figure", "or", "just", "return", "a", "figure", "object" ]
train
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/analyses1/plots.py#L31-L81
mattja/nsim
nsim/analyses1/plots.py
_remove_pi_crossings
def _remove_pi_crossings(ts): """For each variable in the Timeseries, checks whether it represents a phase variable ranging from -pi to pi. If so, set all points where the phase crosses pi to 'nan' so that spurious lines will not be plotted. If ts does not need adjustment, then return ts. Otherwis...
python
def _remove_pi_crossings(ts): """For each variable in the Timeseries, checks whether it represents a phase variable ranging from -pi to pi. If so, set all points where the phase crosses pi to 'nan' so that spurious lines will not be plotted. If ts does not need adjustment, then return ts. Otherwis...
[ "def", "_remove_pi_crossings", "(", "ts", ")", ":", "orig_ts", "=", "ts", "if", "ts", ".", "ndim", "is", "1", ":", "ts", "=", "ts", "[", ":", ",", "np", ".", "newaxis", ",", "np", ".", "newaxis", "]", "elif", "ts", ".", "ndim", "is", "2", ":", ...
For each variable in the Timeseries, checks whether it represents a phase variable ranging from -pi to pi. If so, set all points where the phase crosses pi to 'nan' so that spurious lines will not be plotted. If ts does not need adjustment, then return ts. Otherwise return a modified copy.
[ "For", "each", "variable", "in", "the", "Timeseries", "checks", "whether", "it", "represents", "a", "phase", "variable", "ranging", "from", "-", "pi", "to", "pi", ".", "If", "so", "set", "all", "points", "where", "the", "phase", "crosses", "pi", "to", "n...
train
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/analyses1/plots.py#L84-L116
mattja/nsim
nsim/readfile.py
timeseries_from_mat
def timeseries_from_mat(filename, varname=None, fs=1.0): """load a multi-channel Timeseries from a MATLAB .mat file Args: filename (str): .mat file to load varname (str): variable name. only needed if there is more than one variable saved in the .mat file fs (scalar): sample rate of t...
python
def timeseries_from_mat(filename, varname=None, fs=1.0): """load a multi-channel Timeseries from a MATLAB .mat file Args: filename (str): .mat file to load varname (str): variable name. only needed if there is more than one variable saved in the .mat file fs (scalar): sample rate of t...
[ "def", "timeseries_from_mat", "(", "filename", ",", "varname", "=", "None", ",", "fs", "=", "1.0", ")", ":", "import", "scipy", ".", "io", "as", "sio", "if", "varname", "is", "None", ":", "mat_dict", "=", "sio", ".", "loadmat", "(", "filename", ")", ...
load a multi-channel Timeseries from a MATLAB .mat file Args: filename (str): .mat file to load varname (str): variable name. only needed if there is more than one variable saved in the .mat file fs (scalar): sample rate of timeseries in Hz. (constant timestep assumed) Returns: ...
[ "load", "a", "multi", "-", "channel", "Timeseries", "from", "a", "MATLAB", ".", "mat", "file" ]
train
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/readfile.py#L21-L42
mattja/nsim
nsim/readfile.py
save_mat
def save_mat(ts, filename): """save a Timeseries to a MATLAB .mat file Args: ts (Timeseries): the timeseries to save filename (str): .mat filename to save to """ import scipy.io as sio tspan = ts.tspan fs = (1.0*len(tspan) - 1) / (tspan[-1] - tspan[0]) mat_dict = {'data': np.asar...
python
def save_mat(ts, filename): """save a Timeseries to a MATLAB .mat file Args: ts (Timeseries): the timeseries to save filename (str): .mat filename to save to """ import scipy.io as sio tspan = ts.tspan fs = (1.0*len(tspan) - 1) / (tspan[-1] - tspan[0]) mat_dict = {'data': np.asar...
[ "def", "save_mat", "(", "ts", ",", "filename", ")", ":", "import", "scipy", ".", "io", "as", "sio", "tspan", "=", "ts", ".", "tspan", "fs", "=", "(", "1.0", "*", "len", "(", "tspan", ")", "-", "1", ")", "/", "(", "tspan", "[", "-", "1", "]", ...
save a Timeseries to a MATLAB .mat file Args: ts (Timeseries): the timeseries to save filename (str): .mat filename to save to
[ "save", "a", "Timeseries", "to", "a", "MATLAB", ".", "mat", "file", "Args", ":", "ts", "(", "Timeseries", ")", ":", "the", "timeseries", "to", "save", "filename", "(", "str", ")", ":", ".", "mat", "filename", "to", "save", "to" ]
train
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/readfile.py#L45-L58
mattja/nsim
nsim/readfile.py
timeseries_from_file
def timeseries_from_file(filename): """Load a multi-channel Timeseries from any file type supported by `biosig` Supported file formats include EDF/EDF+, BDF/BDF+, EEG, CNT and GDF. Full list is here: http://pub.ist.ac.at/~schloegl/biosig/TESTED For EDF, EDF+, BDF and BDF+ files, we will use python-edf...
python
def timeseries_from_file(filename): """Load a multi-channel Timeseries from any file type supported by `biosig` Supported file formats include EDF/EDF+, BDF/BDF+, EEG, CNT and GDF. Full list is here: http://pub.ist.ac.at/~schloegl/biosig/TESTED For EDF, EDF+, BDF and BDF+ files, we will use python-edf...
[ "def", "timeseries_from_file", "(", "filename", ")", ":", "if", "not", "path", ".", "isfile", "(", "filename", ")", ":", "raise", "Error", "(", "\"file not found: '%s'\"", "%", "filename", ")", "is_edf_bdf", "=", "(", "filename", "[", "-", "4", ":", "]", ...
Load a multi-channel Timeseries from any file type supported by `biosig` Supported file formats include EDF/EDF+, BDF/BDF+, EEG, CNT and GDF. Full list is here: http://pub.ist.ac.at/~schloegl/biosig/TESTED For EDF, EDF+, BDF and BDF+ files, we will use python-edf if it is installed, otherwise will fa...
[ "Load", "a", "multi", "-", "channel", "Timeseries", "from", "any", "file", "type", "supported", "by", "biosig" ]
train
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/readfile.py#L61-L96
mattja/nsim
nsim/readfile.py
_load_edflib
def _load_edflib(filename): """load a multi-channel Timeseries from an EDF (European Data Format) file or EDF+ file, using edflib. Args: filename: EDF+ file Returns: Timeseries """ import edflib e = edflib.EdfReader(filename, annotations_mode='all') if np.ptp(e.get_samples_...
python
def _load_edflib(filename): """load a multi-channel Timeseries from an EDF (European Data Format) file or EDF+ file, using edflib. Args: filename: EDF+ file Returns: Timeseries """ import edflib e = edflib.EdfReader(filename, annotations_mode='all') if np.ptp(e.get_samples_...
[ "def", "_load_edflib", "(", "filename", ")", ":", "import", "edflib", "e", "=", "edflib", ".", "EdfReader", "(", "filename", ",", "annotations_mode", "=", "'all'", ")", "if", "np", ".", "ptp", "(", "e", ".", "get_samples_per_signal", "(", ")", ")", "!=",...
load a multi-channel Timeseries from an EDF (European Data Format) file or EDF+ file, using edflib. Args: filename: EDF+ file Returns: Timeseries
[ "load", "a", "multi", "-", "channel", "Timeseries", "from", "an", "EDF", "(", "European", "Data", "Format", ")", "file", "or", "EDF", "+", "file", "using", "edflib", "." ]
train
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/readfile.py#L125-L154
mattja/nsim
nsim/readfile.py
annotations_from_file
def annotations_from_file(filename): """Get a list of event annotations from an EDF (European Data Format file or EDF+ file, using edflib. Args: filename: EDF+ file Returns: list: annotation events, each in the form [start_time, duration, text] """ import edflib e = edflib.EdfR...
python
def annotations_from_file(filename): """Get a list of event annotations from an EDF (European Data Format file or EDF+ file, using edflib. Args: filename: EDF+ file Returns: list: annotation events, each in the form [start_time, duration, text] """ import edflib e = edflib.EdfR...
[ "def", "annotations_from_file", "(", "filename", ")", ":", "import", "edflib", "e", "=", "edflib", ".", "EdfReader", "(", "filename", ",", "annotations_mode", "=", "'all'", ")", "return", "e", ".", "read_annotations", "(", ")" ]
Get a list of event annotations from an EDF (European Data Format file or EDF+ file, using edflib. Args: filename: EDF+ file Returns: list: annotation events, each in the form [start_time, duration, text]
[ "Get", "a", "list", "of", "event", "annotations", "from", "an", "EDF", "(", "European", "Data", "Format", "file", "or", "EDF", "+", "file", "using", "edflib", "." ]
train
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/readfile.py#L157-L169
mattja/nsim
nsim/nsim.py
_ufunc_wrap
def _ufunc_wrap(out_arr, ufunc, method, i, inputs, **kwargs): """After using the superclass __numpy_ufunc__ to route ufunc computations on the array data, convert any resulting ndarray, RemoteArray and DistArray instances into Timeseries, RemoteTimeseries and DistTimeseries instances if appropriate""" ...
python
def _ufunc_wrap(out_arr, ufunc, method, i, inputs, **kwargs): """After using the superclass __numpy_ufunc__ to route ufunc computations on the array data, convert any resulting ndarray, RemoteArray and DistArray instances into Timeseries, RemoteTimeseries and DistTimeseries instances if appropriate""" ...
[ "def", "_ufunc_wrap", "(", "out_arr", ",", "ufunc", ",", "method", ",", "i", ",", "inputs", ",", "*", "*", "kwargs", ")", ":", "# Assigns tspan/labels to an axis only if inputs do not disagree on them.", "shape", "=", "out_arr", ".", "shape", "ndim", "=", "out_arr...
After using the superclass __numpy_ufunc__ to route ufunc computations on the array data, convert any resulting ndarray, RemoteArray and DistArray instances into Timeseries, RemoteTimeseries and DistTimeseries instances if appropriate
[ "After", "using", "the", "superclass", "__numpy_ufunc__", "to", "route", "ufunc", "computations", "on", "the", "array", "data", "convert", "any", "resulting", "ndarray", "RemoteArray", "and", "DistArray", "instances", "into", "Timeseries", "RemoteTimeseries", "and", ...
train
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/nsim.py#L660-L700
mattja/nsim
nsim/nsim.py
_rts_from_ra
def _rts_from_ra(ra, tspan, labels, block=True): """construct a RemoteTimeseries from a RemoteArray""" def _convert(a, tspan, labels): from nsim import Timeseries return Timeseries(a, tspan, labels) return distob.call( _convert, ra, tspan, labels, prefer_local=False, block=block)
python
def _rts_from_ra(ra, tspan, labels, block=True): """construct a RemoteTimeseries from a RemoteArray""" def _convert(a, tspan, labels): from nsim import Timeseries return Timeseries(a, tspan, labels) return distob.call( _convert, ra, tspan, labels, prefer_local=False, block=block)
[ "def", "_rts_from_ra", "(", "ra", ",", "tspan", ",", "labels", ",", "block", "=", "True", ")", ":", "def", "_convert", "(", "a", ",", "tspan", ",", "labels", ")", ":", "from", "nsim", "import", "Timeseries", "return", "Timeseries", "(", "a", ",", "ts...
construct a RemoteTimeseries from a RemoteArray
[ "construct", "a", "RemoteTimeseries", "from", "a", "RemoteArray" ]
train
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/nsim.py#L703-L709
mattja/nsim
nsim/nsim.py
_dts_from_da
def _dts_from_da(da, tspan, labels): """construct a DistTimeseries from a DistArray""" sublabels = labels[:] new_subarrays = [] for i, ra in enumerate(da._subarrays): if isinstance(ra, RemoteTimeseries): new_subarrays.append(ra) else: if labels[da._distaxis]: ...
python
def _dts_from_da(da, tspan, labels): """construct a DistTimeseries from a DistArray""" sublabels = labels[:] new_subarrays = [] for i, ra in enumerate(da._subarrays): if isinstance(ra, RemoteTimeseries): new_subarrays.append(ra) else: if labels[da._distaxis]: ...
[ "def", "_dts_from_da", "(", "da", ",", "tspan", ",", "labels", ")", ":", "sublabels", "=", "labels", "[", ":", "]", "new_subarrays", "=", "[", "]", "for", "i", ",", "ra", "in", "enumerate", "(", "da", ".", "_subarrays", ")", ":", "if", "isinstance", ...
construct a DistTimeseries from a DistArray
[ "construct", "a", "DistTimeseries", "from", "a", "DistArray" ]
train
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/nsim.py#L712-L730
mattja/nsim
nsim/nsim.py
newsim
def newsim(f, G, y0, name='NewModel', modelType=ItoModel, T=60.0, dt=0.005, repeat=1, identical=True): """Make a simulation of the system defined by functions f and G. dy = f(y,t)dt + G(y,t).dW with initial condition y0 This helper function is for convenience, making it easy to define one-off simulati...
python
def newsim(f, G, y0, name='NewModel', modelType=ItoModel, T=60.0, dt=0.005, repeat=1, identical=True): """Make a simulation of the system defined by functions f and G. dy = f(y,t)dt + G(y,t).dW with initial condition y0 This helper function is for convenience, making it easy to define one-off simulati...
[ "def", "newsim", "(", "f", ",", "G", ",", "y0", ",", "name", "=", "'NewModel'", ",", "modelType", "=", "ItoModel", ",", "T", "=", "60.0", ",", "dt", "=", "0.005", ",", "repeat", "=", "1", ",", "identical", "=", "True", ")", ":", "NewModel", "=", ...
Make a simulation of the system defined by functions f and G. dy = f(y,t)dt + G(y,t).dW with initial condition y0 This helper function is for convenience, making it easy to define one-off simulations interactively in ipython. Args: f: callable(y, t) (defined in global scope) returning (n,) arra...
[ "Make", "a", "simulation", "of", "the", "system", "defined", "by", "functions", "f", "and", "G", "." ]
train
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/nsim.py#L1758-L1791
mattja/nsim
nsim/nsim.py
newmodel
def newmodel(f, G, y0, name='NewModel', modelType=ItoModel): """Use the functions f and G to define a new Model class for simulations. It will take functions f and G from global scope and make a new Model class out of them. It will automatically gather any globals used in the definition of f and G and...
python
def newmodel(f, G, y0, name='NewModel', modelType=ItoModel): """Use the functions f and G to define a new Model class for simulations. It will take functions f and G from global scope and make a new Model class out of them. It will automatically gather any globals used in the definition of f and G and...
[ "def", "newmodel", "(", "f", ",", "G", ",", "y0", ",", "name", "=", "'NewModel'", ",", "modelType", "=", "ItoModel", ")", ":", "if", "not", "issubclass", "(", "modelType", ",", "Model", ")", ":", "raise", "SimTypeError", "(", "'modelType must be a subclass...
Use the functions f and G to define a new Model class for simulations. It will take functions f and G from global scope and make a new Model class out of them. It will automatically gather any globals used in the definition of f and G and turn them into attributes of the new Model. Args: f: cal...
[ "Use", "the", "functions", "f", "and", "G", "to", "define", "a", "new", "Model", "class", "for", "simulations", "." ]
train
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/nsim.py#L1794-L1851
mattja/nsim
nsim/nsim.py
__clone_function
def __clone_function(f, name=None): """Make a new version of a function that has its own independent copy of any globals that it uses directly, and has its own name. All other attributes are assigned from the original function. Args: f: the function to clone name (str): the name for the ...
python
def __clone_function(f, name=None): """Make a new version of a function that has its own independent copy of any globals that it uses directly, and has its own name. All other attributes are assigned from the original function. Args: f: the function to clone name (str): the name for the ...
[ "def", "__clone_function", "(", "f", ",", "name", "=", "None", ")", ":", "if", "not", "isinstance", "(", "f", ",", "types", ".", "FunctionType", ")", ":", "raise", "SimTypeError", "(", "'Given parameter is not a function.'", ")", "if", "name", "is", "None", ...
Make a new version of a function that has its own independent copy of any globals that it uses directly, and has its own name. All other attributes are assigned from the original function. Args: f: the function to clone name (str): the name for the new function (if None, keep the same name) ...
[ "Make", "a", "new", "version", "of", "a", "function", "that", "has", "its", "own", "independent", "copy", "of", "any", "globals", "that", "it", "uses", "directly", "and", "has", "its", "own", "name", ".", "All", "other", "attributes", "are", "assigned", ...
train
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/nsim.py#L1884-L1917
mattja/nsim
nsim/nsim.py
DistTimeseries.expand_dims
def expand_dims(self, axis): """Insert a new axis, at a given position in the array shape Args: axis (int): Position (amongst axes) where new axis is to be inserted. """ if axis <= self._distaxis: subaxis = axis new_distaxis = self._distaxis + 1 ...
python
def expand_dims(self, axis): """Insert a new axis, at a given position in the array shape Args: axis (int): Position (amongst axes) where new axis is to be inserted. """ if axis <= self._distaxis: subaxis = axis new_distaxis = self._distaxis + 1 ...
[ "def", "expand_dims", "(", "self", ",", "axis", ")", ":", "if", "axis", "<=", "self", ".", "_distaxis", ":", "subaxis", "=", "axis", "new_distaxis", "=", "self", ".", "_distaxis", "+", "1", "else", ":", "subaxis", "=", "axis", "-", "1", "new_distaxis",...
Insert a new axis, at a given position in the array shape Args: axis (int): Position (amongst axes) where new axis is to be inserted.
[ "Insert", "a", "new", "axis", "at", "a", "given", "position", "in", "the", "array", "shape", "Args", ":", "axis", "(", "int", ")", ":", "Position", "(", "amongst", "axes", ")", "where", "new", "axis", "is", "to", "be", "inserted", "." ]
train
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/nsim.py#L608-L625
mattja/nsim
nsim/nsim.py
DistTimeseries.absolute
def absolute(self): """Calculate the absolute value element-wise. Returns: absolute (Timeseries): Absolute value. For complex input (a + b*j) gives sqrt(a**a + b**2) """ da = distob.vectorize(np.absolute)(self) return _dts_from_da(da, self.tspan, self.label...
python
def absolute(self): """Calculate the absolute value element-wise. Returns: absolute (Timeseries): Absolute value. For complex input (a + b*j) gives sqrt(a**a + b**2) """ da = distob.vectorize(np.absolute)(self) return _dts_from_da(da, self.tspan, self.label...
[ "def", "absolute", "(", "self", ")", ":", "da", "=", "distob", ".", "vectorize", "(", "np", ".", "absolute", ")", "(", "self", ")", "return", "_dts_from_da", "(", "da", ",", "self", ".", "tspan", ",", "self", ".", "labels", ")" ]
Calculate the absolute value element-wise. Returns: absolute (Timeseries): Absolute value. For complex input (a + b*j) gives sqrt(a**a + b**2)
[ "Calculate", "the", "absolute", "value", "element", "-", "wise", "." ]
train
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/nsim.py#L627-L635
mattja/nsim
nsim/nsim.py
DistTimeseries.angle
def angle(self, deg=False): """Return the angle of a complex Timeseries Args: deg (bool, optional): Return angle in degrees if True, radians if False (default). Returns: angle (Timeseries): The counterclockwise angle from the positive real axis on ...
python
def angle(self, deg=False): """Return the angle of a complex Timeseries Args: deg (bool, optional): Return angle in degrees if True, radians if False (default). Returns: angle (Timeseries): The counterclockwise angle from the positive real axis on ...
[ "def", "angle", "(", "self", ",", "deg", "=", "False", ")", ":", "if", "self", ".", "dtype", ".", "str", "[", "1", "]", "!=", "'c'", ":", "warnings", ".", "warn", "(", "'angle() is intended for complex-valued timeseries'", ",", "RuntimeWarning", ",", "1", ...
Return the angle of a complex Timeseries Args: deg (bool, optional): Return angle in degrees if True, radians if False (default). Returns: angle (Timeseries): The counterclockwise angle from the positive real axis on the complex plane, with dtype...
[ "Return", "the", "angle", "of", "a", "complex", "Timeseries" ]
train
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/nsim.py#L641-L657
mattja/nsim
nsim/nsim.py
NetworkModel.coupling
def coupling(self, source_y, target_y, weight): """How to couple the output of one subsystem to the input of another. This is a fallback default coupling function that should usually be replaced with your own. This example coupling function takes the mean of all variables of the ...
python
def coupling(self, source_y, target_y, weight): """How to couple the output of one subsystem to the input of another. This is a fallback default coupling function that should usually be replaced with your own. This example coupling function takes the mean of all variables of the ...
[ "def", "coupling", "(", "self", ",", "source_y", ",", "target_y", ",", "weight", ")", ":", "return", "np", ".", "ones_like", "(", "target_y", ")", "*", "np", ".", "mean", "(", "source_y", ")", "*", "weight" ]
How to couple the output of one subsystem to the input of another. This is a fallback default coupling function that should usually be replaced with your own. This example coupling function takes the mean of all variables of the source subsystem and uses that value weighted by the conn...
[ "How", "to", "couple", "the", "output", "of", "one", "subsystem", "to", "the", "input", "of", "another", "." ]
train
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/nsim.py#L1113-L1132
mattja/nsim
nsim/nsim.py
NetworkModel.f
def f(self, y, t): """Deterministic term f of the complete network system dy = f(y, t)dt + G(y, t).dot(dW) (or for an ODE network system without noise, dy/dt = f(y, t)) Args: y (array of shape (d,)): where d is the dimension of the overall state space of the compl...
python
def f(self, y, t): """Deterministic term f of the complete network system dy = f(y, t)dt + G(y, t).dot(dW) (or for an ODE network system without noise, dy/dt = f(y, t)) Args: y (array of shape (d,)): where d is the dimension of the overall state space of the compl...
[ "def", "f", "(", "self", ",", "y", ",", "t", ")", ":", "coupling", "=", "self", ".", "coupling_function", "[", "0", "]", "res", "=", "np", ".", "empty_like", "(", "self", ".", "y0", ")", "for", "j", ",", "m", "in", "enumerate", "(", "self", "."...
Deterministic term f of the complete network system dy = f(y, t)dt + G(y, t).dot(dW) (or for an ODE network system without noise, dy/dt = f(y, t)) Args: y (array of shape (d,)): where d is the dimension of the overall state space of the complete network system. ...
[ "Deterministic", "term", "f", "of", "the", "complete", "network", "system", "dy", "=", "f", "(", "y", "t", ")", "dt", "+", "G", "(", "y", "t", ")", ".", "dot", "(", "dW", ")" ]
train
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/nsim.py#L1134-L1160
mattja/nsim
nsim/nsim.py
NetworkModel.G
def G(self, y, t): """Noise coefficient matrix G of the complete network system dy = f(y, t)dt + G(y, t).dot(dW) (for an ODE network system without noise this function is not used) Args: y (array of shape (d,)): where d is the dimension of the overall state space ...
python
def G(self, y, t): """Noise coefficient matrix G of the complete network system dy = f(y, t)dt + G(y, t).dot(dW) (for an ODE network system without noise this function is not used) Args: y (array of shape (d,)): where d is the dimension of the overall state space ...
[ "def", "G", "(", "self", ",", "y", ",", "t", ")", ":", "if", "self", ".", "_independent_noise", ":", "# then G matrix consists of submodel Gs diagonally concatenated:", "res", "=", "np", ".", "zeros", "(", "(", "self", ".", "dimension", ",", "self", ".", "nn...
Noise coefficient matrix G of the complete network system dy = f(y, t)dt + G(y, t).dot(dW) (for an ODE network system without noise this function is not used) Args: y (array of shape (d,)): where d is the dimension of the overall state space of the complete network system...
[ "Noise", "coefficient", "matrix", "G", "of", "the", "complete", "network", "system", "dy", "=", "f", "(", "y", "t", ")", "dt", "+", "G", "(", "y", "t", ")", ".", "dot", "(", "dW", ")" ]
train
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/nsim.py#L1162-L1193
mattja/nsim
nsim/nsim.py
NetworkModel._scalar_to_vector
def _scalar_to_vector(self, m): """Allow submodels with scalar equations. Convert to 1D vector systems. Args: m (Model) """ if not isinstance(m.y0, numbers.Number): return m else: m = copy.deepcopy(m) t0 = 0.0 if isinstanc...
python
def _scalar_to_vector(self, m): """Allow submodels with scalar equations. Convert to 1D vector systems. Args: m (Model) """ if not isinstance(m.y0, numbers.Number): return m else: m = copy.deepcopy(m) t0 = 0.0 if isinstanc...
[ "def", "_scalar_to_vector", "(", "self", ",", "m", ")", ":", "if", "not", "isinstance", "(", "m", ".", "y0", ",", "numbers", ".", "Number", ")", ":", "return", "m", "else", ":", "m", "=", "copy", ".", "deepcopy", "(", "m", ")", "t0", "=", "0.0", ...
Allow submodels with scalar equations. Convert to 1D vector systems. Args: m (Model)
[ "Allow", "submodels", "with", "scalar", "equations", ".", "Convert", "to", "1D", "vector", "systems", ".", "Args", ":", "m", "(", "Model", ")" ]
train
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/nsim.py#L1228-L1267
mattja/nsim
nsim/nsim.py
NetworkModel._reshape_timeseries
def _reshape_timeseries(self, ts): """Introduce a new axis 2 that ranges across nodes of the network""" if np.count_nonzero(np.diff(self._sublengths)) == 0: # then all submodels have the same dimension, so can reshape array # in place without copying data: subdim = se...
python
def _reshape_timeseries(self, ts): """Introduce a new axis 2 that ranges across nodes of the network""" if np.count_nonzero(np.diff(self._sublengths)) == 0: # then all submodels have the same dimension, so can reshape array # in place without copying data: subdim = se...
[ "def", "_reshape_timeseries", "(", "self", ",", "ts", ")", ":", "if", "np", ".", "count_nonzero", "(", "np", ".", "diff", "(", "self", ".", "_sublengths", ")", ")", "==", "0", ":", "# then all submodels have the same dimension, so can reshape array", "# in place w...
Introduce a new axis 2 that ranges across nodes of the network
[ "Introduce", "a", "new", "axis", "2", "that", "ranges", "across", "nodes", "of", "the", "network" ]
train
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/nsim.py#L1272-L1301
mattja/nsim
nsim/nsim.py
NetworkModel._reshape_output
def _reshape_output(self, ts): """Introduce a new axis 2 that ranges across nodes of the network""" subodim = len(self.submodels[0].output_vars) shp = list(ts.shape) shp[1] = subodim shp.insert(2, self._n) ts = ts.reshape(tuple(shp)) ts.labels[2] = self._node_labe...
python
def _reshape_output(self, ts): """Introduce a new axis 2 that ranges across nodes of the network""" subodim = len(self.submodels[0].output_vars) shp = list(ts.shape) shp[1] = subodim shp.insert(2, self._n) ts = ts.reshape(tuple(shp)) ts.labels[2] = self._node_labe...
[ "def", "_reshape_output", "(", "self", ",", "ts", ")", ":", "subodim", "=", "len", "(", "self", ".", "submodels", "[", "0", "]", ".", "output_vars", ")", "shp", "=", "list", "(", "ts", ".", "shape", ")", "shp", "[", "1", "]", "=", "subodim", "shp...
Introduce a new axis 2 that ranges across nodes of the network
[ "Introduce", "a", "new", "axis", "2", "that", "ranges", "across", "nodes", "of", "the", "network" ]
train
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/nsim.py#L1303-L1311
mattja/nsim
nsim/nsim.py
Simulation.timeseries
def timeseries(self): """Simulated time series""" if self._timeseries is None: self.compute() if isinstance(self.system, NetworkModel): return self.system._reshape_timeseries(self._timeseries) else: return self._timeseries
python
def timeseries(self): """Simulated time series""" if self._timeseries is None: self.compute() if isinstance(self.system, NetworkModel): return self.system._reshape_timeseries(self._timeseries) else: return self._timeseries
[ "def", "timeseries", "(", "self", ")", ":", "if", "self", ".", "_timeseries", "is", "None", ":", "self", ".", "compute", "(", ")", "if", "isinstance", "(", "self", ".", "system", ",", "NetworkModel", ")", ":", "return", "self", ".", "system", ".", "_...
Simulated time series
[ "Simulated", "time", "series" ]
train
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/nsim.py#L1362-L1369
mattja/nsim
nsim/nsim.py
Simulation.output
def output(self): """Simulated model output""" if self._timeseries is None: self.compute() output = self._timeseries[:, self.system.output_vars] if isinstance(self.system, NetworkModel): return self.system._reshape_output(output) else: return o...
python
def output(self): """Simulated model output""" if self._timeseries is None: self.compute() output = self._timeseries[:, self.system.output_vars] if isinstance(self.system, NetworkModel): return self.system._reshape_output(output) else: return o...
[ "def", "output", "(", "self", ")", ":", "if", "self", ".", "_timeseries", "is", "None", ":", "self", ".", "compute", "(", ")", "output", "=", "self", ".", "_timeseries", "[", ":", ",", "self", ".", "system", ".", "output_vars", "]", "if", "isinstance...
Simulated model output
[ "Simulated", "model", "output" ]
train
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/nsim.py#L1372-L1380
mattja/nsim
nsim/nsim.py
MultipleSim.output
def output(self): """Rank 3 array representing output time series. Axis 0 is time, axis 1 ranges across output variables of a single simulation, axis 2 ranges across different simulation instances.""" subts = [s.output for s in self.sims] sub_ndim = subts[0].ndim if sub...
python
def output(self): """Rank 3 array representing output time series. Axis 0 is time, axis 1 ranges across output variables of a single simulation, axis 2 ranges across different simulation instances.""" subts = [s.output for s in self.sims] sub_ndim = subts[0].ndim if sub...
[ "def", "output", "(", "self", ")", ":", "subts", "=", "[", "s", ".", "output", "for", "s", "in", "self", ".", "sims", "]", "sub_ndim", "=", "subts", "[", "0", "]", ".", "ndim", "if", "sub_ndim", "is", "1", ":", "subts", "=", "[", "distob", ".",...
Rank 3 array representing output time series. Axis 0 is time, axis 1 ranges across output variables of a single simulation, axis 2 ranges across different simulation instances.
[ "Rank", "3", "array", "representing", "output", "time", "series", ".", "Axis", "0", "is", "time", "axis", "1", "ranges", "across", "output", "variables", "of", "a", "single", "simulation", "axis", "2", "ranges", "across", "different", "simulation", "instances"...
train
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/nsim.py#L1450-L1463
mattja/nsim
nsim/nsim.py
DistSim._tosub
def _tosub(self, ix): """Given an integer index ix into the list of sims, returns the pair (s, m) where s is the relevant subsim and m is the subindex into s. So self[ix] == self._subsims[s][m] """ N = self._n if ix >= N or ix < -N: raise IndexError( ...
python
def _tosub(self, ix): """Given an integer index ix into the list of sims, returns the pair (s, m) where s is the relevant subsim and m is the subindex into s. So self[ix] == self._subsims[s][m] """ N = self._n if ix >= N or ix < -N: raise IndexError( ...
[ "def", "_tosub", "(", "self", ",", "ix", ")", ":", "N", "=", "self", ".", "_n", "if", "ix", ">=", "N", "or", "ix", "<", "-", "N", ":", "raise", "IndexError", "(", "'index %d out of bounds for list of %d sims'", "%", "(", "ix", ",", "N", ")", ")", "...
Given an integer index ix into the list of sims, returns the pair (s, m) where s is the relevant subsim and m is the subindex into s. So self[ix] == self._subsims[s][m]
[ "Given", "an", "integer", "index", "ix", "into", "the", "list", "of", "sims", "returns", "the", "pair", "(", "s", "m", ")", "where", "s", "is", "the", "relevant", "subsim", "and", "m", "is", "the", "subindex", "into", "s", ".", "So", "self", "[", "...
train
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/nsim.py#L1577-L1592
mattja/nsim
nsim/nsim.py
DistSim._tosubs
def _tosubs(self, ixlist): """Maps a list of integer indices to sub-indices. ixlist can contain repeated indices and does not need to be sorted. Returns pair (ss, ms) where ss is a list of subsim numbers and ms is a list of lists of subindices m (one list for each subsim in ss). ...
python
def _tosubs(self, ixlist): """Maps a list of integer indices to sub-indices. ixlist can contain repeated indices and does not need to be sorted. Returns pair (ss, ms) where ss is a list of subsim numbers and ms is a list of lists of subindices m (one list for each subsim in ss). ...
[ "def", "_tosubs", "(", "self", ",", "ixlist", ")", ":", "n", "=", "len", "(", "ixlist", ")", "N", "=", "self", ".", "_n", "ss", "=", "[", "]", "ms", "=", "[", "]", "if", "n", "==", "0", ":", "return", "ss", ",", "ms", "j", "=", "0", "# th...
Maps a list of integer indices to sub-indices. ixlist can contain repeated indices and does not need to be sorted. Returns pair (ss, ms) where ss is a list of subsim numbers and ms is a list of lists of subindices m (one list for each subsim in ss).
[ "Maps", "a", "list", "of", "integer", "indices", "to", "sub", "-", "indices", ".", "ixlist", "can", "contain", "repeated", "indices", "and", "does", "not", "need", "to", "be", "sorted", ".", "Returns", "pair", "(", "ss", "ms", ")", "where", "ss", "is",...
train
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/nsim.py#L1594-L1636
mattja/nsim
nsim/nsim.py
DistSim.output
def output(self): """Rank 3 array representing output time series. Axis 0 is time, axis 1 ranges across output variables of a single simulation, axis 2 ranges across different simulation instances.""" subts = [rms.output for rms in self._subsims] distaxis = subts[0].ndim - 1 ...
python
def output(self): """Rank 3 array representing output time series. Axis 0 is time, axis 1 ranges across output variables of a single simulation, axis 2 ranges across different simulation instances.""" subts = [rms.output for rms in self._subsims] distaxis = subts[0].ndim - 1 ...
[ "def", "output", "(", "self", ")", ":", "subts", "=", "[", "rms", ".", "output", "for", "rms", "in", "self", ".", "_subsims", "]", "distaxis", "=", "subts", "[", "0", "]", ".", "ndim", "-", "1", "return", "DistTimeseries", "(", "subts", ",", "dista...
Rank 3 array representing output time series. Axis 0 is time, axis 1 ranges across output variables of a single simulation, axis 2 ranges across different simulation instances.
[ "Rank", "3", "array", "representing", "output", "time", "series", ".", "Axis", "0", "is", "time", "axis", "1", "ranges", "across", "output", "variables", "of", "a", "single", "simulation", "axis", "2", "ranges", "across", "different", "simulation", "instances"...
train
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/nsim.py#L1676-L1682
mattja/nsim
nsim/analyses1/misc.py
crossing_times
def crossing_times(ts, c=0.0, d=0.0): """For a single variable timeseries, find the times at which the value crosses ``c`` from above or below. Can optionally set a non-zero ``d`` to impose the condition that the value must wander at least ``d`` units away from ``c`` between crossings. If the time...
python
def crossing_times(ts, c=0.0, d=0.0): """For a single variable timeseries, find the times at which the value crosses ``c`` from above or below. Can optionally set a non-zero ``d`` to impose the condition that the value must wander at least ``d`` units away from ``c`` between crossings. If the time...
[ "def", "crossing_times", "(", "ts", ",", "c", "=", "0.0", ",", "d", "=", "0.0", ")", ":", "#TODO support multivariate time series", "ts", "=", "ts", ".", "squeeze", "(", ")", "if", "ts", ".", "ndim", "is", "not", "1", ":", "raise", "ValueError", "(", ...
For a single variable timeseries, find the times at which the value crosses ``c`` from above or below. Can optionally set a non-zero ``d`` to impose the condition that the value must wander at least ``d`` units away from ``c`` between crossings. If the timeseries begins (or ends) exactly at ``c``, the...
[ "For", "a", "single", "variable", "timeseries", "find", "the", "times", "at", "which", "the", "value", "crosses", "c", "from", "above", "or", "below", ".", "Can", "optionally", "set", "a", "non", "-", "zero", "d", "to", "impose", "the", "condition", "tha...
train
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/analyses1/misc.py#L18-L71
mattja/nsim
nsim/analyses1/misc.py
first_return_times
def first_return_times(ts, c=None, d=0.0): """For a single variable time series, first wait until the time series attains the value c for the first time. Then record the time intervals between successive returns to c. If c is not given, the default is the mean of the time series. Args: t...
python
def first_return_times(ts, c=None, d=0.0): """For a single variable time series, first wait until the time series attains the value c for the first time. Then record the time intervals between successive returns to c. If c is not given, the default is the mean of the time series. Args: t...
[ "def", "first_return_times", "(", "ts", ",", "c", "=", "None", ",", "d", "=", "0.0", ")", ":", "ts", "=", "np", ".", "squeeze", "(", "ts", ")", "if", "c", "is", "None", ":", "c", "=", "ts", ".", "mean", "(", ")", "if", "ts", ".", "ndim", "<...
For a single variable time series, first wait until the time series attains the value c for the first time. Then record the time intervals between successive returns to c. If c is not given, the default is the mean of the time series. Args: ts: Timeseries (single variable) c (float): ...
[ "For", "a", "single", "variable", "time", "series", "first", "wait", "until", "the", "time", "series", "attains", "the", "value", "c", "for", "the", "first", "time", ".", "Then", "record", "the", "time", "intervals", "between", "successive", "returns", "to",...
train
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/analyses1/misc.py#L74-L98
mattja/nsim
nsim/analyses1/misc.py
autocorrelation
def autocorrelation(ts, normalized=False, unbiased=False): """ Returns the discrete, linear convolution of a time series with itself, optionally using unbiased normalization. N.B. Autocorrelation estimates are necessarily inaccurate for longer lags, as there are less pairs of points to convolve s...
python
def autocorrelation(ts, normalized=False, unbiased=False): """ Returns the discrete, linear convolution of a time series with itself, optionally using unbiased normalization. N.B. Autocorrelation estimates are necessarily inaccurate for longer lags, as there are less pairs of points to convolve s...
[ "def", "autocorrelation", "(", "ts", ",", "normalized", "=", "False", ",", "unbiased", "=", "False", ")", ":", "ts", "=", "np", ".", "squeeze", "(", "ts", ")", "if", "ts", ".", "ndim", "<=", "1", ":", "if", "normalized", ":", "ts", "=", "(", "ts"...
Returns the discrete, linear convolution of a time series with itself, optionally using unbiased normalization. N.B. Autocorrelation estimates are necessarily inaccurate for longer lags, as there are less pairs of points to convolve separated by that lag. Therefore best to throw out the results excep...
[ "Returns", "the", "discrete", "linear", "convolution", "of", "a", "time", "series", "with", "itself", "optionally", "using", "unbiased", "normalization", "." ]
train
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/analyses1/misc.py#L101-L145
Roastero/freshroastsr700
freshroastsr700/__init__.py
freshroastsr700.fan_speed
def fan_speed(self, value): """Verifies the value is between 1 and 9 inclusively.""" if value not in range(1, 10): raise exceptions.RoasterValueError self._fan_speed.value = value
python
def fan_speed(self, value): """Verifies the value is between 1 and 9 inclusively.""" if value not in range(1, 10): raise exceptions.RoasterValueError self._fan_speed.value = value
[ "def", "fan_speed", "(", "self", ",", "value", ")", ":", "if", "value", "not", "in", "range", "(", "1", ",", "10", ")", ":", "raise", "exceptions", ".", "RoasterValueError", "self", ".", "_fan_speed", ".", "value", "=", "value" ]
Verifies the value is between 1 and 9 inclusively.
[ "Verifies", "the", "value", "is", "between", "1", "and", "9", "inclusively", "." ]
train
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/__init__.py#L238-L243
Roastero/freshroastsr700
freshroastsr700/__init__.py
freshroastsr700.heat_setting
def heat_setting(self, value): """Verifies that the heat setting is between 0 and 3.""" if value not in range(0, 4): raise exceptions.RoasterValueError self._heat_setting.value = value
python
def heat_setting(self, value): """Verifies that the heat setting is between 0 and 3.""" if value not in range(0, 4): raise exceptions.RoasterValueError self._heat_setting.value = value
[ "def", "heat_setting", "(", "self", ",", "value", ")", ":", "if", "value", "not", "in", "range", "(", "0", ",", "4", ")", ":", "raise", "exceptions", ".", "RoasterValueError", "self", ".", "_heat_setting", ".", "value", "=", "value" ]
Verifies that the heat setting is between 0 and 3.
[ "Verifies", "that", "the", "heat", "setting", "is", "between", "0", "and", "3", "." ]
train
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/__init__.py#L259-L264
Roastero/freshroastsr700
freshroastsr700/__init__.py
freshroastsr700.heater_level
def heater_level(self, value): """Verifies that the heater_level is between 0 and heater_segments. Can only be called when freshroastsr700 object is initialized with ext_sw_heater_drive=True. Will throw RoasterValueError otherwise.""" if self._ext_sw_heater_drive: ...
python
def heater_level(self, value): """Verifies that the heater_level is between 0 and heater_segments. Can only be called when freshroastsr700 object is initialized with ext_sw_heater_drive=True. Will throw RoasterValueError otherwise.""" if self._ext_sw_heater_drive: ...
[ "def", "heater_level", "(", "self", ",", "value", ")", ":", "if", "self", ".", "_ext_sw_heater_drive", ":", "if", "value", "not", "in", "range", "(", "0", ",", "self", ".", "_heater_bangbang_segments", "+", "1", ")", ":", "raise", "exceptions", ".", "Roa...
Verifies that the heater_level is between 0 and heater_segments. Can only be called when freshroastsr700 object is initialized with ext_sw_heater_drive=True. Will throw RoasterValueError otherwise.
[ "Verifies", "that", "the", "heater_level", "is", "between", "0", "and", "heater_segments", ".", "Can", "only", "be", "called", "when", "freshroastsr700", "object", "is", "initialized", "with", "ext_sw_heater_drive", "=", "True", ".", "Will", "throw", "RoasterValue...
train
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/__init__.py#L352-L362
Roastero/freshroastsr700
freshroastsr700/__init__.py
freshroastsr700.set_state_transition_func
def set_state_transition_func(self, func): """THIS FUNCTION MUST BE CALLED BEFORE CALLING freshroastsr700.auto_connect(). Set, or re-set, the state transition function callback. The supplied function will be called from a separate thread within freshroastsr700, triggered by a se...
python
def set_state_transition_func(self, func): """THIS FUNCTION MUST BE CALLED BEFORE CALLING freshroastsr700.auto_connect(). Set, or re-set, the state transition function callback. The supplied function will be called from a separate thread within freshroastsr700, triggered by a se...
[ "def", "set_state_transition_func", "(", "self", ",", "func", ")", ":", "if", "self", ".", "_connected", ".", "value", ":", "logging", ".", "error", "(", "\"freshroastsr700.set_state_transition_func must be \"", "\"called before freshroastsr700.auto_connect().\"", "\" Not r...
THIS FUNCTION MUST BE CALLED BEFORE CALLING freshroastsr700.auto_connect(). Set, or re-set, the state transition function callback. The supplied function will be called from a separate thread within freshroastsr700, triggered by a separate, internal child process. This function ...
[ "THIS", "FUNCTION", "MUST", "BE", "CALLED", "BEFORE", "CALLING", "freshroastsr700", ".", "auto_connect", "()", "." ]
train
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/__init__.py#L391-L417
Roastero/freshroastsr700
freshroastsr700/__init__.py
freshroastsr700.update_data_run
def update_data_run(self, event_to_wait_on): """This is the thread that listens to an event from the comm process to execute the update_data_func callback in the context of the main process. """ # with the daemon=Turue setting, this thread should # quit 'automati...
python
def update_data_run(self, event_to_wait_on): """This is the thread that listens to an event from the comm process to execute the update_data_func callback in the context of the main process. """ # with the daemon=Turue setting, this thread should # quit 'automati...
[ "def", "update_data_run", "(", "self", ",", "event_to_wait_on", ")", ":", "# with the daemon=Turue setting, this thread should", "# quit 'automatically'", "while", "event_to_wait_on", ".", "wait", "(", ")", ":", "event_to_wait_on", ".", "clear", "(", ")", "if", "self", ...
This is the thread that listens to an event from the comm process to execute the update_data_func callback in the context of the main process.
[ "This", "is", "the", "thread", "that", "listens", "to", "an", "event", "from", "the", "comm", "process", "to", "execute", "the", "update_data_func", "callback", "in", "the", "context", "of", "the", "main", "process", "." ]
train
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/__init__.py#L419-L430
Roastero/freshroastsr700
freshroastsr700/__init__.py
freshroastsr700.state_transition_run
def state_transition_run(self, event_to_wait_on): """This is the thread that listens to an event from the timer process to execute the state_transition_func callback in the context of the main process. """ # with the daemon=Turue setting, this thread should # qui...
python
def state_transition_run(self, event_to_wait_on): """This is the thread that listens to an event from the timer process to execute the state_transition_func callback in the context of the main process. """ # with the daemon=Turue setting, this thread should # qui...
[ "def", "state_transition_run", "(", "self", ",", "event_to_wait_on", ")", ":", "# with the daemon=Turue setting, this thread should", "# quit 'automatically'", "while", "event_to_wait_on", ".", "wait", "(", ")", ":", "event_to_wait_on", ".", "clear", "(", ")", "if", "se...
This is the thread that listens to an event from the timer process to execute the state_transition_func callback in the context of the main process.
[ "This", "is", "the", "thread", "that", "listens", "to", "an", "event", "from", "the", "timer", "process", "to", "execute", "the", "state_transition_func", "callback", "in", "the", "context", "of", "the", "main", "process", "." ]
train
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/__init__.py#L432-L443
Roastero/freshroastsr700
freshroastsr700/__init__.py
freshroastsr700._connect
def _connect(self): """Do not call this directly - call auto_connect() or connect(), which will call _connect() for you. Connects to the roaster and creates communication thread. Raises a RoasterLokkupError exception if the hardware is not found. """ # the following call...
python
def _connect(self): """Do not call this directly - call auto_connect() or connect(), which will call _connect() for you. Connects to the roaster and creates communication thread. Raises a RoasterLokkupError exception if the hardware is not found. """ # the following call...
[ "def", "_connect", "(", "self", ")", ":", "# the following call raises a RoasterLookupException when the device", "# is not found. It is", "port", "=", "utils", ".", "find_device", "(", "'1A86:5523'", ")", "# on some systems, after the device port is added to the device list,", "# ...
Do not call this directly - call auto_connect() or connect(), which will call _connect() for you. Connects to the roaster and creates communication thread. Raises a RoasterLokkupError exception if the hardware is not found.
[ "Do", "not", "call", "this", "directly", "-", "call", "auto_connect", "()", "or", "connect", "()", "which", "will", "call", "_connect", "()", "for", "you", "." ]
train
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/__init__.py#L445-L483
Roastero/freshroastsr700
freshroastsr700/__init__.py
freshroastsr700._initialize
def _initialize(self): """Sends the initialization packet to the roaster.""" self._header.value = b'\xAA\x55' self._current_state.value = b'\x00\x00' s = self._generate_packet() self._ser.write(s) self._header.value = b'\xAA\xAA' self._current_state.value = b'\x02...
python
def _initialize(self): """Sends the initialization packet to the roaster.""" self._header.value = b'\xAA\x55' self._current_state.value = b'\x00\x00' s = self._generate_packet() self._ser.write(s) self._header.value = b'\xAA\xAA' self._current_state.value = b'\x02...
[ "def", "_initialize", "(", "self", ")", ":", "self", ".", "_header", ".", "value", "=", "b'\\xAA\\x55'", "self", ".", "_current_state", ".", "value", "=", "b'\\x00\\x00'", "s", "=", "self", ".", "_generate_packet", "(", ")", "self", ".", "_ser", ".", "wr...
Sends the initialization packet to the roaster.
[ "Sends", "the", "initialization", "packet", "to", "the", "roaster", "." ]
train
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/__init__.py#L485-L494
Roastero/freshroastsr700
freshroastsr700/__init__.py
freshroastsr700.connect
def connect(self): """Attempt to connect to hardware immediately. Will not retry. Check freshroastsr700.connected or freshroastsr700.connect_state to verify result. Raises: freshroastsr700.exeptions.RoasterLookupError No hardware connected to the computer. ...
python
def connect(self): """Attempt to connect to hardware immediately. Will not retry. Check freshroastsr700.connected or freshroastsr700.connect_state to verify result. Raises: freshroastsr700.exeptions.RoasterLookupError No hardware connected to the computer. ...
[ "def", "connect", "(", "self", ")", ":", "self", ".", "_start_connect", "(", "self", ".", "CA_SINGLE_SHOT", ")", "while", "(", "self", ".", "_connect_state", ".", "value", "==", "self", ".", "CS_ATTEMPTING_CONNECT", "or", "self", ".", "_connect_state", ".", ...
Attempt to connect to hardware immediately. Will not retry. Check freshroastsr700.connected or freshroastsr700.connect_state to verify result. Raises: freshroastsr700.exeptions.RoasterLookupError No hardware connected to the computer.
[ "Attempt", "to", "connect", "to", "hardware", "immediately", ".", "Will", "not", "retry", ".", "Check", "freshroastsr700", ".", "connected", "or", "freshroastsr700", ".", "connect_state", "to", "verify", "result", ".", "Raises", ":", "freshroastsr700", ".", "exe...
train
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/__init__.py#L539-L552
Roastero/freshroastsr700
freshroastsr700/__init__.py
freshroastsr700._start_connect
def _start_connect(self, connect_type): """Starts the connection process, as called (internally) from the user context, either from auto_connect() or connect(). Never call this from the _comm() process context. """ if self._connect_state.value != self.CS_NOT_CONNECTED: ...
python
def _start_connect(self, connect_type): """Starts the connection process, as called (internally) from the user context, either from auto_connect() or connect(). Never call this from the _comm() process context. """ if self._connect_state.value != self.CS_NOT_CONNECTED: ...
[ "def", "_start_connect", "(", "self", ",", "connect_type", ")", ":", "if", "self", ".", "_connect_state", ".", "value", "!=", "self", ".", "CS_NOT_CONNECTED", ":", "# already done or in process, assume success", "return", "self", ".", "_connected", ".", "value", "...
Starts the connection process, as called (internally) from the user context, either from auto_connect() or connect(). Never call this from the _comm() process context.
[ "Starts", "the", "connection", "process", "as", "called", "(", "internally", ")", "from", "the", "user", "context", "either", "from", "auto_connect", "()", "or", "connect", "()", ".", "Never", "call", "this", "from", "the", "_comm", "()", "process", "context...
train
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/__init__.py#L559-L588
Roastero/freshroastsr700
freshroastsr700/__init__.py
freshroastsr700._auto_connect
def _auto_connect(self): """Attempts to connect to the roaster every quarter of a second.""" while not self._teardown.value: try: self._connect() return True except exceptions.RoasterLookupError: time.sleep(.25) return False
python
def _auto_connect(self): """Attempts to connect to the roaster every quarter of a second.""" while not self._teardown.value: try: self._connect() return True except exceptions.RoasterLookupError: time.sleep(.25) return False
[ "def", "_auto_connect", "(", "self", ")", ":", "while", "not", "self", ".", "_teardown", ".", "value", ":", "try", ":", "self", ".", "_connect", "(", ")", "return", "True", "except", "exceptions", ".", "RoasterLookupError", ":", "time", ".", "sleep", "("...
Attempts to connect to the roaster every quarter of a second.
[ "Attempts", "to", "connect", "to", "the", "roaster", "every", "quarter", "of", "a", "second", "." ]
train
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/__init__.py#L590-L598
Roastero/freshroastsr700
freshroastsr700/__init__.py
freshroastsr700._comm
def _comm(self, thermostat=False, kp=0.06, ki=0.0075, kd=0.01, heater_segments=8, ext_sw_heater_drive=False, update_data_event=None): """Do not call this directly - call auto_connect(), which will spawn comm() for you. This is the main communications lo...
python
def _comm(self, thermostat=False, kp=0.06, ki=0.0075, kd=0.01, heater_segments=8, ext_sw_heater_drive=False, update_data_event=None): """Do not call this directly - call auto_connect(), which will spawn comm() for you. This is the main communications lo...
[ "def", "_comm", "(", "self", ",", "thermostat", "=", "False", ",", "kp", "=", "0.06", ",", "ki", "=", "0.0075", ",", "kd", "=", "0.01", ",", "heater_segments", "=", "8", ",", "ext_sw_heater_drive", "=", "False", ",", "update_data_event", "=", "None", "...
Do not call this directly - call auto_connect(), which will spawn comm() for you. This is the main communications loop to the roaster. whenever a valid packet is received from the device, if an update_data_event is available, it will be signalled. Args: thermostat (...
[ "Do", "not", "call", "this", "directly", "-", "call", "auto_connect", "()", "which", "will", "spawn", "comm", "()", "for", "you", "." ]
train
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/__init__.py#L616-L814
Roastero/freshroastsr700
freshroastsr700/__init__.py
freshroastsr700._timer
def _timer(self, state_transition_event=None): """Timer loop used to keep track of the time while roasting or cooling. If the time remaining reaches zero, the roaster will call the supplied state transistion function or the roaster will be set to the idle state.""" while not self...
python
def _timer(self, state_transition_event=None): """Timer loop used to keep track of the time while roasting or cooling. If the time remaining reaches zero, the roaster will call the supplied state transistion function or the roaster will be set to the idle state.""" while not self...
[ "def", "_timer", "(", "self", ",", "state_transition_event", "=", "None", ")", ":", "while", "not", "self", ".", "_teardown", ".", "value", ":", "state", "=", "self", ".", "get_roaster_state", "(", ")", "if", "(", "state", "==", "'roasting'", "or", "stat...
Timer loop used to keep track of the time while roasting or cooling. If the time remaining reaches zero, the roaster will call the supplied state transistion function or the roaster will be set to the idle state.
[ "Timer", "loop", "used", "to", "keep", "track", "of", "the", "time", "while", "roasting", "or", "cooling", ".", "If", "the", "time", "remaining", "reaches", "zero", "the", "roaster", "will", "call", "the", "supplied", "state", "transistion", "function", "or"...
train
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/__init__.py#L889-L907
Roastero/freshroastsr700
freshroastsr700/__init__.py
freshroastsr700.get_roaster_state
def get_roaster_state(self): """Returns a string based upon the current state of the roaster. Will raise an exception if the state is unknown. Returns: 'idle' if idle, 'sleeping' if sleeping, 'cooling' if cooling, 'roasting' if roasting, ...
python
def get_roaster_state(self): """Returns a string based upon the current state of the roaster. Will raise an exception if the state is unknown. Returns: 'idle' if idle, 'sleeping' if sleeping, 'cooling' if cooling, 'roasting' if roasting, ...
[ "def", "get_roaster_state", "(", "self", ")", ":", "value", "=", "self", ".", "_current_state", ".", "value", "if", "(", "value", "==", "b'\\x02\\x01'", ")", ":", "return", "'idle'", "elif", "(", "value", "==", "b'\\x04\\x04'", ")", ":", "return", "'coolin...
Returns a string based upon the current state of the roaster. Will raise an exception if the state is unknown. Returns: 'idle' if idle, 'sleeping' if sleeping, 'cooling' if cooling, 'roasting' if roasting, 'connecting' if in hardware connectio...
[ "Returns", "a", "string", "based", "upon", "the", "current", "state", "of", "the", "roaster", ".", "Will", "raise", "an", "exception", "if", "the", "state", "is", "unknown", "." ]
train
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/__init__.py#L909-L934
Roastero/freshroastsr700
freshroastsr700/__init__.py
freshroastsr700._generate_packet
def _generate_packet(self): """Generates a packet based upon the current class variables. Note that current temperature is not sent, as the original application sent zeros to the roaster for the current temperature.""" roaster_time = utils.seconds_to_float(self._time_remaining.value) ...
python
def _generate_packet(self): """Generates a packet based upon the current class variables. Note that current temperature is not sent, as the original application sent zeros to the roaster for the current temperature.""" roaster_time = utils.seconds_to_float(self._time_remaining.value) ...
[ "def", "_generate_packet", "(", "self", ")", ":", "roaster_time", "=", "utils", ".", "seconds_to_float", "(", "self", ".", "_time_remaining", ".", "value", ")", "packet", "=", "(", "self", ".", "_header", ".", "value", "+", "self", ".", "_temp_unit", ".", ...
Generates a packet based upon the current class variables. Note that current temperature is not sent, as the original application sent zeros to the roaster for the current temperature.
[ "Generates", "a", "packet", "based", "upon", "the", "current", "class", "variables", ".", "Note", "that", "current", "temperature", "is", "not", "sent", "as", "the", "original", "application", "sent", "zeros", "to", "the", "roaster", "for", "the", "current", ...
train
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/__init__.py#L936-L952
Roastero/freshroastsr700
freshroastsr700/__init__.py
heat_controller.heat_level
def heat_level(self, value): """Set the desired output level. Must be between 0 and number_of_segments inclusive.""" if value < 0: self._heat_level = 0 elif round(value) > self._num_segments: self._heat_level = self._num_segments else: self._he...
python
def heat_level(self, value): """Set the desired output level. Must be between 0 and number_of_segments inclusive.""" if value < 0: self._heat_level = 0 elif round(value) > self._num_segments: self._heat_level = self._num_segments else: self._he...
[ "def", "heat_level", "(", "self", ",", "value", ")", ":", "if", "value", "<", "0", ":", "self", ".", "_heat_level", "=", "0", "elif", "round", "(", "value", ")", ">", "self", ".", "_num_segments", ":", "self", ".", "_heat_level", "=", "self", ".", ...
Set the desired output level. Must be between 0 and number_of_segments inclusive.
[ "Set", "the", "desired", "output", "level", ".", "Must", "be", "between", "0", "and", "number_of_segments", "inclusive", "." ]
train
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/__init__.py#L1061-L1069
Roastero/freshroastsr700
freshroastsr700/__init__.py
heat_controller.generate_bangbang_output
def generate_bangbang_output(self): """Generates the latest on or off pulse in the string of on (True) or off (False) pulses according to the desired heat_level setting. Successive calls to this function will return the next value in the on/off array series. Call th...
python
def generate_bangbang_output(self): """Generates the latest on or off pulse in the string of on (True) or off (False) pulses according to the desired heat_level setting. Successive calls to this function will return the next value in the on/off array series. Call th...
[ "def", "generate_bangbang_output", "(", "self", ")", ":", "if", "self", ".", "_current_index", ">=", "self", ".", "_num_segments", ":", "# we're due to switch over to the next", "# commanded heat_level", "self", ".", "_heat_level_now", "=", "self", ".", "_heat_level", ...
Generates the latest on or off pulse in the string of on (True) or off (False) pulses according to the desired heat_level setting. Successive calls to this function will return the next value in the on/off array series. Call this at control loop rate to obtain th...
[ "Generates", "the", "latest", "on", "or", "off", "pulse", "in", "the", "string", "of", "on", "(", "True", ")", "or", "off", "(", "False", ")", "pulses", "according", "to", "the", "desired", "heat_level", "setting", ".", "Successive", "calls", "to", "this...
train
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/__init__.py#L1071-L1092
Roastero/freshroastsr700
examples/pid_tune_aid.py
Roaster.update_data
def update_data(self): """This is a method that will be called every time a packet is opened from the roaster.""" time_elapsed = datetime.datetime.now() - self.start_time crntTemp = self.roaster.current_temp targetTemp = self.roaster.target_temp heaterLevel = self.roaster...
python
def update_data(self): """This is a method that will be called every time a packet is opened from the roaster.""" time_elapsed = datetime.datetime.now() - self.start_time crntTemp = self.roaster.current_temp targetTemp = self.roaster.target_temp heaterLevel = self.roaster...
[ "def", "update_data", "(", "self", ")", ":", "time_elapsed", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "-", "self", ".", "start_time", "crntTemp", "=", "self", ".", "roaster", ".", "current_temp", "targetTemp", "=", "self", ".", "roaster", ...
This is a method that will be called every time a packet is opened from the roaster.
[ "This", "is", "a", "method", "that", "will", "be", "called", "every", "time", "a", "packet", "is", "opened", "from", "the", "roaster", "." ]
train
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/examples/pid_tune_aid.py#L122-L134
Roastero/freshroastsr700
examples/pid_tune_aid.py
Roaster.next_state
def next_state(self): """This is a method that will be called when the time remaining ends. The current state can be: roasting, cooling, idle, sleeping, connecting, or unkown.""" self.active_recipe_item += 1 if self.active_recipe_item >= len(self.recipe): # we're done...
python
def next_state(self): """This is a method that will be called when the time remaining ends. The current state can be: roasting, cooling, idle, sleeping, connecting, or unkown.""" self.active_recipe_item += 1 if self.active_recipe_item >= len(self.recipe): # we're done...
[ "def", "next_state", "(", "self", ")", ":", "self", ".", "active_recipe_item", "+=", "1", "if", "self", ".", "active_recipe_item", ">=", "len", "(", "self", ".", "recipe", ")", ":", "# we're done!", "return", "# show state step on screen", "print", "(", "\"---...
This is a method that will be called when the time remaining ends. The current state can be: roasting, cooling, idle, sleeping, connecting, or unkown.
[ "This", "is", "a", "method", "that", "will", "be", "called", "when", "the", "time", "remaining", "ends", ".", "The", "current", "state", "can", "be", ":", "roasting", "cooling", "idle", "sleeping", "connecting", "or", "unkown", "." ]
train
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/examples/pid_tune_aid.py#L136-L169
dmippolitov/pydnsbl
pydnsbl/checker.py
DNSBLResult.process_results
def process_results(self): """ Process results by providers """ for result in self._results: provider = result.provider self.providers.append(provider) if result.error: self.failed_providers.append(provider) continue if not ...
python
def process_results(self): """ Process results by providers """ for result in self._results: provider = result.provider self.providers.append(provider) if result.error: self.failed_providers.append(provider) continue if not ...
[ "def", "process_results", "(", "self", ")", ":", "for", "result", "in", "self", ".", "_results", ":", "provider", "=", "result", ".", "provider", "self", ".", "providers", ".", "append", "(", "provider", ")", "if", "result", ".", "error", ":", "self", ...
Process results by providers
[ "Process", "results", "by", "providers" ]
train
https://github.com/dmippolitov/pydnsbl/blob/76c460f1118213d66498ddafde2053d8de4ccbdb/pydnsbl/checker.py#L39-L54
dmippolitov/pydnsbl
pydnsbl/checker.py
DNSBLChecker.dnsbl_request
async def dnsbl_request(self, addr, provider): """ Make lookup to dnsbl provider Parameters: * addr (string) - ip address to check * provider (string) - dnsbl provider Returns: * DNSBLResponse object Raises: * ValueError "...
python
async def dnsbl_request(self, addr, provider): """ Make lookup to dnsbl provider Parameters: * addr (string) - ip address to check * provider (string) - dnsbl provider Returns: * DNSBLResponse object Raises: * ValueError "...
[ "async", "def", "dnsbl_request", "(", "self", ",", "addr", ",", "provider", ")", ":", "response", "=", "None", "error", "=", "None", "try", ":", "socket", ".", "inet_aton", "(", "addr", ")", "except", "socket", ".", "error", ":", "raise", "ValueError", ...
Make lookup to dnsbl provider Parameters: * addr (string) - ip address to check * provider (string) - dnsbl provider Returns: * DNSBLResponse object Raises: * ValueError
[ "Make", "lookup", "to", "dnsbl", "provider", "Parameters", ":", "*", "addr", "(", "string", ")", "-", "ip", "address", "to", "check", "*", "provider", "(", "string", ")", "-", "dnsbl", "provider" ]
train
https://github.com/dmippolitov/pydnsbl/blob/76c460f1118213d66498ddafde2053d8de4ccbdb/pydnsbl/checker.py#L92-L120
dmippolitov/pydnsbl
pydnsbl/checker.py
DNSBLChecker._check_ip
async def _check_ip(self, addr): """ Async check ip with dnsbl providers. Parameters: * addr - ip address to check Returns: * DNSBLResult object """ tasks = [] for provider in self.providers: tasks.append(self.dnsbl_request(ad...
python
async def _check_ip(self, addr): """ Async check ip with dnsbl providers. Parameters: * addr - ip address to check Returns: * DNSBLResult object """ tasks = [] for provider in self.providers: tasks.append(self.dnsbl_request(ad...
[ "async", "def", "_check_ip", "(", "self", ",", "addr", ")", ":", "tasks", "=", "[", "]", "for", "provider", "in", "self", ".", "providers", ":", "tasks", ".", "append", "(", "self", ".", "dnsbl_request", "(", "addr", ",", "provider", ")", ")", "resul...
Async check ip with dnsbl providers. Parameters: * addr - ip address to check Returns: * DNSBLResult object
[ "Async", "check", "ip", "with", "dnsbl", "providers", ".", "Parameters", ":", "*", "addr", "-", "ip", "address", "to", "check" ]
train
https://github.com/dmippolitov/pydnsbl/blob/76c460f1118213d66498ddafde2053d8de4ccbdb/pydnsbl/checker.py#L122-L136
dmippolitov/pydnsbl
pydnsbl/checker.py
DNSBLChecker.check_ips
def check_ips(self, addrs): """ sync check multiple ips """ tasks = [] for addr in addrs: tasks.append(self._check_ip(addr)) return self._loop.run_until_complete(asyncio.gather(*tasks))
python
def check_ips(self, addrs): """ sync check multiple ips """ tasks = [] for addr in addrs: tasks.append(self._check_ip(addr)) return self._loop.run_until_complete(asyncio.gather(*tasks))
[ "def", "check_ips", "(", "self", ",", "addrs", ")", ":", "tasks", "=", "[", "]", "for", "addr", "in", "addrs", ":", "tasks", ".", "append", "(", "self", ".", "_check_ip", "(", "addr", ")", ")", "return", "self", ".", "_loop", ".", "run_until_complete...
sync check multiple ips
[ "sync", "check", "multiple", "ips" ]
train
https://github.com/dmippolitov/pydnsbl/blob/76c460f1118213d66498ddafde2053d8de4ccbdb/pydnsbl/checker.py#L150-L157
Roastero/freshroastsr700
freshroastsr700/utils.py
frange
def frange(start, stop, step, precision): """A generator that will generate a range of floats.""" value = start while round(value, precision) < stop: yield round(value, precision) value += step
python
def frange(start, stop, step, precision): """A generator that will generate a range of floats.""" value = start while round(value, precision) < stop: yield round(value, precision) value += step
[ "def", "frange", "(", "start", ",", "stop", ",", "step", ",", "precision", ")", ":", "value", "=", "start", "while", "round", "(", "value", ",", "precision", ")", "<", "stop", ":", "yield", "round", "(", "value", ",", "precision", ")", "value", "+=",...
A generator that will generate a range of floats.
[ "A", "generator", "that", "will", "generate", "a", "range", "of", "floats", "." ]
train
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/utils.py#L11-L16
Roastero/freshroastsr700
freshroastsr700/utils.py
find_device
def find_device(vidpid): """Finds a connected device with the given VID:PID. Returns the serial port url.""" for port in list_ports.comports(): if re.search(vidpid, port[2], flags=re.IGNORECASE): return port[0] raise exceptions.RoasterLookupError
python
def find_device(vidpid): """Finds a connected device with the given VID:PID. Returns the serial port url.""" for port in list_ports.comports(): if re.search(vidpid, port[2], flags=re.IGNORECASE): return port[0] raise exceptions.RoasterLookupError
[ "def", "find_device", "(", "vidpid", ")", ":", "for", "port", "in", "list_ports", ".", "comports", "(", ")", ":", "if", "re", ".", "search", "(", "vidpid", ",", "port", "[", "2", "]", ",", "flags", "=", "re", ".", "IGNORECASE", ")", ":", "return", ...
Finds a connected device with the given VID:PID. Returns the serial port url.
[ "Finds", "a", "connected", "device", "with", "the", "given", "VID", ":", "PID", ".", "Returns", "the", "serial", "port", "url", "." ]
train
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/utils.py#L19-L26
Roastero/freshroastsr700
freshroastsr700/pid.py
PID.update
def update(self, currentTemp, targetTemp): """Calculate PID output value for given reference input and feedback.""" # in this implementation, ki includes the dt multiplier term, # and kd includes the dt divisor term. This is typical practice in # industry. self.targetTemp = targ...
python
def update(self, currentTemp, targetTemp): """Calculate PID output value for given reference input and feedback.""" # in this implementation, ki includes the dt multiplier term, # and kd includes the dt divisor term. This is typical practice in # industry. self.targetTemp = targ...
[ "def", "update", "(", "self", ",", "currentTemp", ",", "targetTemp", ")", ":", "# in this implementation, ki includes the dt multiplier term,", "# and kd includes the dt divisor term. This is typical practice in", "# industry.", "self", ".", "targetTemp", "=", "targetTemp", "sel...
Calculate PID output value for given reference input and feedback.
[ "Calculate", "PID", "output", "value", "for", "given", "reference", "input", "and", "feedback", "." ]
train
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/pid.py#L28-L59
Roastero/freshroastsr700
freshroastsr700/pid.py
PID.setPoint
def setPoint(self, targetTemp): """Initilize the setpoint of PID.""" self.targetTemp = targetTemp self.Integrator = 0 self.Derivator = 0
python
def setPoint(self, targetTemp): """Initilize the setpoint of PID.""" self.targetTemp = targetTemp self.Integrator = 0 self.Derivator = 0
[ "def", "setPoint", "(", "self", ",", "targetTemp", ")", ":", "self", ".", "targetTemp", "=", "targetTemp", "self", ".", "Integrator", "=", "0", "self", ".", "Derivator", "=", "0" ]
Initilize the setpoint of PID.
[ "Initilize", "the", "setpoint", "of", "PID", "." ]
train
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/pid.py#L61-L65
Roastero/freshroastsr700
examples/advanced.py
Roaster.next_state
def next_state(self): """This is a method that will be called when the time remaining ends. The current state can be: roasting, cooling, idle, sleeping, connecting, or unkown.""" if(self.roaster.get_roaster_state() == 'roasting'): self.roaster.time_remaining = 20 ...
python
def next_state(self): """This is a method that will be called when the time remaining ends. The current state can be: roasting, cooling, idle, sleeping, connecting, or unkown.""" if(self.roaster.get_roaster_state() == 'roasting'): self.roaster.time_remaining = 20 ...
[ "def", "next_state", "(", "self", ")", ":", "if", "(", "self", ".", "roaster", ".", "get_roaster_state", "(", ")", "==", "'roasting'", ")", ":", "self", ".", "roaster", ".", "time_remaining", "=", "20", "self", ".", "roaster", ".", "cool", "(", ")", ...
This is a method that will be called when the time remaining ends. The current state can be: roasting, cooling, idle, sleeping, connecting, or unkown.
[ "This", "is", "a", "method", "that", "will", "be", "called", "when", "the", "time", "remaining", "ends", ".", "The", "current", "state", "can", "be", ":", "roasting", "cooling", "idle", "sleeping", "connecting", "or", "unkown", "." ]
train
https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/examples/advanced.py#L21-L29
tomislater/RandomWords
random_words/random_words.py
Random.load_nouns
def load_nouns(self, file): """ Load dict from file for random words. :param str file: filename """ with open(os.path.join(main_dir, file + '.dat'), 'r') as f: self.nouns = json.load(f)
python
def load_nouns(self, file): """ Load dict from file for random words. :param str file: filename """ with open(os.path.join(main_dir, file + '.dat'), 'r') as f: self.nouns = json.load(f)
[ "def", "load_nouns", "(", "self", ",", "file", ")", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "main_dir", ",", "file", "+", "'.dat'", ")", ",", "'r'", ")", "as", "f", ":", "self", ".", "nouns", "=", "json", ".", "load", "("...
Load dict from file for random words. :param str file: filename
[ "Load", "dict", "from", "file", "for", "random", "words", "." ]
train
https://github.com/tomislater/RandomWords/blob/601aa48732d3c389f4c17ba0ed98ffe0e4821d78/random_words/random_words.py#L30-L37
tomislater/RandomWords
random_words/random_words.py
Random.load_dmails
def load_dmails(self, file): """ Load list from file for random mails :param str file: filename """ with open(os.path.join(main_dir, file + '.dat'), 'r') as f: self.dmails = frozenset(json.load(f))
python
def load_dmails(self, file): """ Load list from file for random mails :param str file: filename """ with open(os.path.join(main_dir, file + '.dat'), 'r') as f: self.dmails = frozenset(json.load(f))
[ "def", "load_dmails", "(", "self", ",", "file", ")", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "main_dir", ",", "file", "+", "'.dat'", ")", ",", "'r'", ")", "as", "f", ":", "self", ".", "dmails", "=", "frozenset", "(", "json"...
Load list from file for random mails :param str file: filename
[ "Load", "list", "from", "file", "for", "random", "mails" ]
train
https://github.com/tomislater/RandomWords/blob/601aa48732d3c389f4c17ba0ed98ffe0e4821d78/random_words/random_words.py#L39-L46
tomislater/RandomWords
random_words/random_words.py
Random.load_nicknames
def load_nicknames(self, file): """ Load dict from file for random nicknames. :param str file: filename """ with open(os.path.join(main_dir, file + '.dat'), 'r') as f: self.nicknames = json.load(f)
python
def load_nicknames(self, file): """ Load dict from file for random nicknames. :param str file: filename """ with open(os.path.join(main_dir, file + '.dat'), 'r') as f: self.nicknames = json.load(f)
[ "def", "load_nicknames", "(", "self", ",", "file", ")", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "main_dir", ",", "file", "+", "'.dat'", ")", ",", "'r'", ")", "as", "f", ":", "self", ".", "nicknames", "=", "json", ".", "load...
Load dict from file for random nicknames. :param str file: filename
[ "Load", "dict", "from", "file", "for", "random", "nicknames", "." ]
train
https://github.com/tomislater/RandomWords/blob/601aa48732d3c389f4c17ba0ed98ffe0e4821d78/random_words/random_words.py#L48-L55
tomislater/RandomWords
random_words/random_words.py
RandomWords.random_words
def random_words(self, letter=None, count=1): """ Returns list of random words. :param str letter: letter :param int count: how much words :rtype: list :returns: list of random words :raises: ValueError """ self.check_count(count) words =...
python
def random_words(self, letter=None, count=1): """ Returns list of random words. :param str letter: letter :param int count: how much words :rtype: list :returns: list of random words :raises: ValueError """ self.check_count(count) words =...
[ "def", "random_words", "(", "self", ",", "letter", "=", "None", ",", "count", "=", "1", ")", ":", "self", ".", "check_count", "(", "count", ")", "words", "=", "[", "]", "if", "letter", "is", "None", ":", "all_words", "=", "list", "(", "chain", ".",...
Returns list of random words. :param str letter: letter :param int count: how much words :rtype: list :returns: list of random words :raises: ValueError
[ "Returns", "list", "of", "random", "words", "." ]
train
https://github.com/tomislater/RandomWords/blob/601aa48732d3c389f4c17ba0ed98ffe0e4821d78/random_words/random_words.py#L88-L129
tomislater/RandomWords
random_words/random_words.py
RandomNicknames.random_nicks
def random_nicks(self, letter=None, gender='u', count=1): """ Return list of random nicks. :param str letter: letter :param str gender: ``'f'`` for female, ``'m'`` for male and None for both :param int count: how much nicks :rtype: list :returns: list of random n...
python
def random_nicks(self, letter=None, gender='u', count=1): """ Return list of random nicks. :param str letter: letter :param str gender: ``'f'`` for female, ``'m'`` for male and None for both :param int count: how much nicks :rtype: list :returns: list of random n...
[ "def", "random_nicks", "(", "self", ",", "letter", "=", "None", ",", "gender", "=", "'u'", ",", "count", "=", "1", ")", ":", "self", ".", "check_count", "(", "count", ")", "nicks", "=", "[", "]", "if", "gender", "not", "in", "(", "'f'", ",", "'m'...
Return list of random nicks. :param str letter: letter :param str gender: ``'f'`` for female, ``'m'`` for male and None for both :param int count: how much nicks :rtype: list :returns: list of random nicks :raises: ValueError
[ "Return", "list", "of", "random", "nicks", "." ]
train
https://github.com/tomislater/RandomWords/blob/601aa48732d3c389f4c17ba0ed98ffe0e4821d78/random_words/random_words.py#L153-L199
tomislater/RandomWords
random_words/random_words.py
RandomEmails.randomMails
def randomMails(self, count=1): """ Return random e-mails. :rtype: list :returns: list of random e-mails """ self.check_count(count) random_nicks = self.rn.random_nicks(count=count) random_domains = sample(self.dmails, count) return [ ...
python
def randomMails(self, count=1): """ Return random e-mails. :rtype: list :returns: list of random e-mails """ self.check_count(count) random_nicks = self.rn.random_nicks(count=count) random_domains = sample(self.dmails, count) return [ ...
[ "def", "randomMails", "(", "self", ",", "count", "=", "1", ")", ":", "self", ".", "check_count", "(", "count", ")", "random_nicks", "=", "self", ".", "rn", ".", "random_nicks", "(", "count", "=", "count", ")", "random_domains", "=", "sample", "(", "sel...
Return random e-mails. :rtype: list :returns: list of random e-mails
[ "Return", "random", "e", "-", "mails", "." ]
train
https://github.com/tomislater/RandomWords/blob/601aa48732d3c389f4c17ba0ed98ffe0e4821d78/random_words/random_words.py#L218-L233
tomislater/RandomWords
random_words/lorem_ipsum.py
LoremIpsum.get_sentences_list
def get_sentences_list(self, sentences=1): """ Return sentences in list. :param int sentences: how many sentences :returns: list of strings with sentence :rtype: list """ if sentences < 1: raise ValueError('Param "sentences" must be greater than 0.') ...
python
def get_sentences_list(self, sentences=1): """ Return sentences in list. :param int sentences: how many sentences :returns: list of strings with sentence :rtype: list """ if sentences < 1: raise ValueError('Param "sentences" must be greater than 0.') ...
[ "def", "get_sentences_list", "(", "self", ",", "sentences", "=", "1", ")", ":", "if", "sentences", "<", "1", ":", "raise", "ValueError", "(", "'Param \"sentences\" must be greater than 0.'", ")", "sentences_list", "=", "[", "]", "while", "sentences", ":", "num_r...
Return sentences in list. :param int sentences: how many sentences :returns: list of strings with sentence :rtype: list
[ "Return", "sentences", "in", "list", "." ]
train
https://github.com/tomislater/RandomWords/blob/601aa48732d3c389f4c17ba0ed98ffe0e4821d78/random_words/lorem_ipsum.py#L27-L49
tomislater/RandomWords
random_words/lorem_ipsum.py
LoremIpsum.make_sentence
def make_sentence(list_words): """ Return a sentence from list of words. :param list list_words: list of words :returns: sentence :rtype: str """ lw_len = len(list_words) if lw_len > 6: list_words.insert(lw_len // 2 + random.choice(range(-2, ...
python
def make_sentence(list_words): """ Return a sentence from list of words. :param list list_words: list of words :returns: sentence :rtype: str """ lw_len = len(list_words) if lw_len > 6: list_words.insert(lw_len // 2 + random.choice(range(-2, ...
[ "def", "make_sentence", "(", "list_words", ")", ":", "lw_len", "=", "len", "(", "list_words", ")", "if", "lw_len", ">", "6", ":", "list_words", ".", "insert", "(", "lw_len", "//", "2", "+", "random", ".", "choice", "(", "range", "(", "-", "2", ",", ...
Return a sentence from list of words. :param list list_words: list of words :returns: sentence :rtype: str
[ "Return", "a", "sentence", "from", "list", "of", "words", "." ]
train
https://github.com/tomislater/RandomWords/blob/601aa48732d3c389f4c17ba0ed98ffe0e4821d78/random_words/lorem_ipsum.py#L62-L77
paulocheque/epub-meta
epub_meta/collector.py
_discover_cover_image
def _discover_cover_image(zf, opf_xmldoc, opf_filepath): ''' Find the cover image path in the OPF file. Returns a tuple: (image content in base64, file extension) ''' content = None filepath = None extension = None # Strategies to discover the cover-image path: # e.g.: <meta name="...
python
def _discover_cover_image(zf, opf_xmldoc, opf_filepath): ''' Find the cover image path in the OPF file. Returns a tuple: (image content in base64, file extension) ''' content = None filepath = None extension = None # Strategies to discover the cover-image path: # e.g.: <meta name="...
[ "def", "_discover_cover_image", "(", "zf", ",", "opf_xmldoc", ",", "opf_filepath", ")", ":", "content", "=", "None", "filepath", "=", "None", "extension", "=", "None", "# Strategies to discover the cover-image path:", "# e.g.: <meta name=\"cover\" content=\"cover\"/>", "tag...
Find the cover image path in the OPF file. Returns a tuple: (image content in base64, file extension)
[ "Find", "the", "cover", "image", "path", "in", "the", "OPF", "file", ".", "Returns", "a", "tuple", ":", "(", "image", "content", "in", "base64", "file", "extension", ")" ]
train
https://github.com/paulocheque/epub-meta/blob/3f0efb9f29a286b1a6896ad05422b23f10e10164/epub_meta/collector.py#L183-L215
paulocheque/epub-meta
epub_meta/collector.py
_discover_toc
def _discover_toc(zf, opf_xmldoc, opf_filepath): ''' Returns a list of objects: {title: str, src: str, level: int, index: int} ''' toc = None # ePub 3.x tag = find_tag(opf_xmldoc, 'item', 'properties', 'nav') if tag and 'href' in tag.attributes.keys(): filepath = unquote(tag.attribu...
python
def _discover_toc(zf, opf_xmldoc, opf_filepath): ''' Returns a list of objects: {title: str, src: str, level: int, index: int} ''' toc = None # ePub 3.x tag = find_tag(opf_xmldoc, 'item', 'properties', 'nav') if tag and 'href' in tag.attributes.keys(): filepath = unquote(tag.attribu...
[ "def", "_discover_toc", "(", "zf", ",", "opf_xmldoc", ",", "opf_filepath", ")", ":", "toc", "=", "None", "# ePub 3.x", "tag", "=", "find_tag", "(", "opf_xmldoc", ",", "'item'", ",", "'properties'", ",", "'nav'", ")", "if", "tag", "and", "'href'", "in", "...
Returns a list of objects: {title: str, src: str, level: int, index: int}
[ "Returns", "a", "list", "of", "objects", ":", "{", "title", ":", "str", "src", ":", "str", "level", ":", "int", "index", ":", "int", "}" ]
train
https://github.com/paulocheque/epub-meta/blob/3f0efb9f29a286b1a6896ad05422b23f10e10164/epub_meta/collector.py#L218-L332
paulocheque/epub-meta
epub_meta/collector.py
get_epub_metadata
def get_epub_metadata(filepath, read_cover_image=True, read_toc=True): ''' References: http://idpf.org/epub/201 and http://idpf.org/epub/301 1. Parse META-INF/container.xml file and find the .OPF file path. 2. In the .OPF file, find the metadata ''' if not zipfile.is_zipfile(filepath): r...
python
def get_epub_metadata(filepath, read_cover_image=True, read_toc=True): ''' References: http://idpf.org/epub/201 and http://idpf.org/epub/301 1. Parse META-INF/container.xml file and find the .OPF file path. 2. In the .OPF file, find the metadata ''' if not zipfile.is_zipfile(filepath): r...
[ "def", "get_epub_metadata", "(", "filepath", ",", "read_cover_image", "=", "True", ",", "read_toc", "=", "True", ")", ":", "if", "not", "zipfile", ".", "is_zipfile", "(", "filepath", ")", ":", "raise", "EPubException", "(", "'Unknown file'", ")", "# print('Rea...
References: http://idpf.org/epub/201 and http://idpf.org/epub/301 1. Parse META-INF/container.xml file and find the .OPF file path. 2. In the .OPF file, find the metadata
[ "References", ":", "http", ":", "//", "idpf", ".", "org", "/", "epub", "/", "201", "and", "http", ":", "//", "idpf", ".", "org", "/", "epub", "/", "301", "1", ".", "Parse", "META", "-", "INF", "/", "container", ".", "xml", "file", "and", "find", ...
train
https://github.com/paulocheque/epub-meta/blob/3f0efb9f29a286b1a6896ad05422b23f10e10164/epub_meta/collector.py#L335-L395
paulocheque/epub-meta
epub_meta/collector.py
get_epub_opf_xml
def get_epub_opf_xml(filepath): ''' Returns the file.OPF contents of the ePub file ''' if not zipfile.is_zipfile(filepath): raise EPubException('Unknown file') # print('Reading ePub file: {}'.format(filepath)) zf = zipfile.ZipFile(filepath, 'r', compression=zipfile.ZIP_DEFLATED, allowZi...
python
def get_epub_opf_xml(filepath): ''' Returns the file.OPF contents of the ePub file ''' if not zipfile.is_zipfile(filepath): raise EPubException('Unknown file') # print('Reading ePub file: {}'.format(filepath)) zf = zipfile.ZipFile(filepath, 'r', compression=zipfile.ZIP_DEFLATED, allowZi...
[ "def", "get_epub_opf_xml", "(", "filepath", ")", ":", "if", "not", "zipfile", ".", "is_zipfile", "(", "filepath", ")", ":", "raise", "EPubException", "(", "'Unknown file'", ")", "# print('Reading ePub file: {}'.format(filepath))", "zf", "=", "zipfile", ".", "ZipFile...
Returns the file.OPF contents of the ePub file
[ "Returns", "the", "file", ".", "OPF", "contents", "of", "the", "ePub", "file" ]
train
https://github.com/paulocheque/epub-meta/blob/3f0efb9f29a286b1a6896ad05422b23f10e10164/epub_meta/collector.py#L398-L411
damirazo/Petrovich
petrovich/main.py
Petrovich.firstname
def firstname(self, value, case, gender=None): u""" Склонение имени :param value: Значение для склонения :param case: Падеж для склонения (значение из класса Case) :param gender: Грамматический род """ if not value: raise ValueError('Firstname cannot ...
python
def firstname(self, value, case, gender=None): u""" Склонение имени :param value: Значение для склонения :param case: Падеж для склонения (значение из класса Case) :param gender: Грамматический род """ if not value: raise ValueError('Firstname cannot ...
[ "def", "firstname", "(", "self", ",", "value", ",", "case", ",", "gender", "=", "None", ")", ":", "if", "not", "value", ":", "raise", "ValueError", "(", "'Firstname cannot be empty.'", ")", "return", "self", ".", "__inflect", "(", "value", ",", "case", "...
u""" Склонение имени :param value: Значение для склонения :param case: Падеж для склонения (значение из класса Case) :param gender: Грамматический род
[ "u", "Склонение", "имени" ]
train
https://github.com/damirazo/Petrovich/blob/b587158896a87d21ad6520d8e2e570d71e4338b4/petrovich/main.py#L43-L54
damirazo/Petrovich
petrovich/main.py
Petrovich.lastname
def lastname(self, value, case, gender=None): u""" Склонение фамилии :param value: Значение для склонения :param case: Падеж для склонения (значение из класса Case) :param gender: Грамматический род """ if not value: raise ValueError('Lastname cannot ...
python
def lastname(self, value, case, gender=None): u""" Склонение фамилии :param value: Значение для склонения :param case: Падеж для склонения (значение из класса Case) :param gender: Грамматический род """ if not value: raise ValueError('Lastname cannot ...
[ "def", "lastname", "(", "self", ",", "value", ",", "case", ",", "gender", "=", "None", ")", ":", "if", "not", "value", ":", "raise", "ValueError", "(", "'Lastname cannot be empty.'", ")", "return", "self", ".", "__inflect", "(", "value", ",", "case", ","...
u""" Склонение фамилии :param value: Значение для склонения :param case: Падеж для склонения (значение из класса Case) :param gender: Грамматический род
[ "u", "Склонение", "фамилии" ]
train
https://github.com/damirazo/Petrovich/blob/b587158896a87d21ad6520d8e2e570d71e4338b4/petrovich/main.py#L56-L67
damirazo/Petrovich
petrovich/main.py
Petrovich.middlename
def middlename(self, value, case, gender=None): u""" Склонение отчества :param value: Значение для склонения :param case: Падеж для склонения (значение из класса Case) :param gender: Грамматический род """ if not value: raise ValueError('Middlename ca...
python
def middlename(self, value, case, gender=None): u""" Склонение отчества :param value: Значение для склонения :param case: Падеж для склонения (значение из класса Case) :param gender: Грамматический род """ if not value: raise ValueError('Middlename ca...
[ "def", "middlename", "(", "self", ",", "value", ",", "case", ",", "gender", "=", "None", ")", ":", "if", "not", "value", ":", "raise", "ValueError", "(", "'Middlename cannot be empty.'", ")", "return", "self", ".", "__inflect", "(", "value", ",", "case", ...
u""" Склонение отчества :param value: Значение для склонения :param case: Падеж для склонения (значение из класса Case) :param gender: Грамматический род
[ "u", "Склонение", "отчества" ]
train
https://github.com/damirazo/Petrovich/blob/b587158896a87d21ad6520d8e2e570d71e4338b4/petrovich/main.py#L69-L80
damirazo/Petrovich
petrovich/main.py
Petrovich.__split_name
def __split_name(self, name): u""" Разделяет имя на сегменты по разделителям в self.separators :param name: имя :return: разделённое имя вместе с разделителями """ def gen(name, separators): if len(separators) == 0: yield name else:...
python
def __split_name(self, name): u""" Разделяет имя на сегменты по разделителям в self.separators :param name: имя :return: разделённое имя вместе с разделителями """ def gen(name, separators): if len(separators) == 0: yield name else:...
[ "def", "__split_name", "(", "self", ",", "name", ")", ":", "def", "gen", "(", "name", ",", "separators", ")", ":", "if", "len", "(", "separators", ")", "==", "0", ":", "yield", "name", "else", ":", "segments", "=", "name", ".", "split", "(", "separ...
u""" Разделяет имя на сегменты по разделителям в self.separators :param name: имя :return: разделённое имя вместе с разделителями
[ "u", "Разделяет", "имя", "на", "сегменты", "по", "разделителям", "в", "self", ".", "separators", ":", "param", "name", ":", "имя", ":", "return", ":", "разделённое", "имя", "вместе", "с", "разделителями" ]
train
https://github.com/damirazo/Petrovich/blob/b587158896a87d21ad6520d8e2e570d71e4338b4/petrovich/main.py#L82-L100
xigt/xigt
xigt/ref.py
expand
def expand(expression): """ Expand a reference expression to individual spans. Also works on space-separated ID lists, although a sequence of space characters will be considered a delimiter. >>> expand('a1') 'a1' >>> expand('a1[3:5]') 'a1[3:5]' >>> expand('a1[3:5+6:7]') 'a1[3:5]...
python
def expand(expression): """ Expand a reference expression to individual spans. Also works on space-separated ID lists, although a sequence of space characters will be considered a delimiter. >>> expand('a1') 'a1' >>> expand('a1[3:5]') 'a1[3:5]' >>> expand('a1[3:5+6:7]') 'a1[3:5]...
[ "def", "expand", "(", "expression", ")", ":", "tokens", "=", "[", "]", "for", "(", "pre", ",", "_id", ",", "_range", ")", "in", "robust_ref_re", ".", "findall", "(", "expression", ")", ":", "if", "not", "_range", ":", "tokens", ".", "append", "(", ...
Expand a reference expression to individual spans. Also works on space-separated ID lists, although a sequence of space characters will be considered a delimiter. >>> expand('a1') 'a1' >>> expand('a1[3:5]') 'a1[3:5]' >>> expand('a1[3:5+6:7]') 'a1[3:5]+a1[6:7]' >>> expand('a1 a2 a3'...
[ "Expand", "a", "reference", "expression", "to", "individual", "spans", ".", "Also", "works", "on", "space", "-", "separated", "ID", "lists", "although", "a", "sequence", "of", "space", "characters", "will", "be", "considered", "a", "delimiter", "." ]
train
https://github.com/xigt/xigt/blob/3736fbb6d26887181de57bd189cbd731cec91289/xigt/ref.py#L36-L62
xigt/xigt
xigt/ref.py
compress
def compress(expression): """ Compress a reference expression to group spans on the same id. Also works on space-separated ID lists, although a sequence of space characters will be considered a delimiter. >>> compress('a1') 'a1' >>> compress('a1[3:5]') 'a1[3:5]' >>> compress('a1[3:5...
python
def compress(expression): """ Compress a reference expression to group spans on the same id. Also works on space-separated ID lists, although a sequence of space characters will be considered a delimiter. >>> compress('a1') 'a1' >>> compress('a1[3:5]') 'a1[3:5]' >>> compress('a1[3:5...
[ "def", "compress", "(", "expression", ")", ":", "tokens", "=", "[", "]", "selection", "=", "[", "]", "last_id", "=", "None", "for", "(", "pre", ",", "_id", ",", "_range", ")", "in", "robust_ref_re", ".", "findall", "(", "expression", ")", ":", "if", ...
Compress a reference expression to group spans on the same id. Also works on space-separated ID lists, although a sequence of space characters will be considered a delimiter. >>> compress('a1') 'a1' >>> compress('a1[3:5]') 'a1[3:5]' >>> compress('a1[3:5+6:7]') 'a1[3:5+6:7]' >>> comp...
[ "Compress", "a", "reference", "expression", "to", "group", "spans", "on", "the", "same", "id", ".", "Also", "works", "on", "space", "-", "separated", "ID", "lists", "although", "a", "sequence", "of", "space", "characters", "will", "be", "considered", "a", ...
train
https://github.com/xigt/xigt/blob/3736fbb6d26887181de57bd189cbd731cec91289/xigt/ref.py#L65-L101
xigt/xigt
xigt/ref.py
selections
def selections(expression, keep_delimiters=True): """ Split the expression into individual selection expressions. The delimiters will be kept as separate items if keep_delimters=True. Also works on space-separated ID lists, although a sequence of space characters will be considered a delimiter. ...
python
def selections(expression, keep_delimiters=True): """ Split the expression into individual selection expressions. The delimiters will be kept as separate items if keep_delimters=True. Also works on space-separated ID lists, although a sequence of space characters will be considered a delimiter. ...
[ "def", "selections", "(", "expression", ",", "keep_delimiters", "=", "True", ")", ":", "tokens", "=", "[", "]", "for", "(", "pre", ",", "_id", ",", "_range", ")", "in", "robust_ref_re", ".", "findall", "(", "expression", ")", ":", "if", "keep_delimiters"...
Split the expression into individual selection expressions. The delimiters will be kept as separate items if keep_delimters=True. Also works on space-separated ID lists, although a sequence of space characters will be considered a delimiter. >>> selections('a1') ['a1'] >>> selections('a1[3:5]')...
[ "Split", "the", "expression", "into", "individual", "selection", "expressions", ".", "The", "delimiters", "will", "be", "kept", "as", "separate", "items", "if", "keep_delimters", "=", "True", ".", "Also", "works", "on", "space", "-", "separated", "ID", "lists"...
train
https://github.com/xigt/xigt/blob/3736fbb6d26887181de57bd189cbd731cec91289/xigt/ref.py#L104-L134
xigt/xigt
xigt/ref.py
resolve
def resolve(container, expression): """ Return the string that is the resolution of the alignment expression `expression`, which selects ids from `container`. """ itemgetter = getattr(container, 'get_item', container.get) tokens = [] expression = expression.strip() for sel_delim, _id, _r...
python
def resolve(container, expression): """ Return the string that is the resolution of the alignment expression `expression`, which selects ids from `container`. """ itemgetter = getattr(container, 'get_item', container.get) tokens = [] expression = expression.strip() for sel_delim, _id, _r...
[ "def", "resolve", "(", "container", ",", "expression", ")", ":", "itemgetter", "=", "getattr", "(", "container", ",", "'get_item'", ",", "container", ".", "get", ")", "tokens", "=", "[", "]", "expression", "=", "expression", ".", "strip", "(", ")", "for"...
Return the string that is the resolution of the alignment expression `expression`, which selects ids from `container`.
[ "Return", "the", "string", "that", "is", "the", "resolution", "of", "the", "alignment", "expression", "expression", "which", "selects", "ids", "from", "container", "." ]
train
https://github.com/xigt/xigt/blob/3736fbb6d26887181de57bd189cbd731cec91289/xigt/ref.py#L181-L210
xigt/xigt
xigt/ref.py
referents
def referents(igt, id, refattrs=None): """ Return a list of ids denoting objects (tiers or items) in `igt` that are referred by the object denoted by `id` using a reference attribute in `refattrs`. If `refattrs` is None, then consider all known reference attributes for the type of object denoted by ...
python
def referents(igt, id, refattrs=None): """ Return a list of ids denoting objects (tiers or items) in `igt` that are referred by the object denoted by `id` using a reference attribute in `refattrs`. If `refattrs` is None, then consider all known reference attributes for the type of object denoted by ...
[ "def", "referents", "(", "igt", ",", "id", ",", "refattrs", "=", "None", ")", ":", "obj", "=", "igt", ".", "get_any", "(", "id", ")", "if", "obj", "is", "None", ":", "raise", "XigtLookupError", "(", "id", ")", "if", "refattrs", "is", "None", ":", ...
Return a list of ids denoting objects (tiers or items) in `igt` that are referred by the object denoted by `id` using a reference attribute in `refattrs`. If `refattrs` is None, then consider all known reference attributes for the type of object denoted by _id_. In other words, if 'b1' refers to 'a1' us...
[ "Return", "a", "list", "of", "ids", "denoting", "objects", "(", "tiers", "or", "items", ")", "in", "igt", "that", "are", "referred", "by", "the", "object", "denoted", "by", "id", "using", "a", "reference", "attribute", "in", "refattrs", ".", "If", "refat...
train
https://github.com/xigt/xigt/blob/3736fbb6d26887181de57bd189cbd731cec91289/xigt/ref.py#L213-L227
xigt/xigt
xigt/ref.py
referrers
def referrers(igt, id, refattrs=None): """ Return a list of ids denoting objects (tiers or items) in `igt` that refer to the given `id`. In other words, if 'b1' refers to 'a1', then `referrers(igt, 'a1')` returns `['b1']`. """ if refattrs is None: result = {} else: result = {...
python
def referrers(igt, id, refattrs=None): """ Return a list of ids denoting objects (tiers or items) in `igt` that refer to the given `id`. In other words, if 'b1' refers to 'a1', then `referrers(igt, 'a1')` returns `['b1']`. """ if refattrs is None: result = {} else: result = {...
[ "def", "referrers", "(", "igt", ",", "id", ",", "refattrs", "=", "None", ")", ":", "if", "refattrs", "is", "None", ":", "result", "=", "{", "}", "else", ":", "result", "=", "{", "ra", ":", "[", "]", "for", "ra", "in", "refattrs", "}", "# if the i...
Return a list of ids denoting objects (tiers or items) in `igt` that refer to the given `id`. In other words, if 'b1' refers to 'a1', then `referrers(igt, 'a1')` returns `['b1']`.
[ "Return", "a", "list", "of", "ids", "denoting", "objects", "(", "tiers", "or", "items", ")", "in", "igt", "that", "refer", "to", "the", "given", "id", ".", "In", "other", "words", "if", "b1", "refers", "to", "a1", "then", "referrers", "(", "igt", "a1...
train
https://github.com/xigt/xigt/blob/3736fbb6d26887181de57bd189cbd731cec91289/xigt/ref.py#L230-L265
xigt/xigt
xigt/query.py
ancestors
def ancestors(obj, refattrs=(ALIGNMENT, SEGMENTATION)): """ >>> for anc in query.ancestors(igt.get_item('g1'), refattrs=(ALIGNMENT, SEGMENTATION)): ... print(anc) (<Tier object (id: g type: glosses) at ...>, 'alignment', <Tier object (id: m type: morphemes) at ...>, [<Item object (id: m1) at ...>]) ...
python
def ancestors(obj, refattrs=(ALIGNMENT, SEGMENTATION)): """ >>> for anc in query.ancestors(igt.get_item('g1'), refattrs=(ALIGNMENT, SEGMENTATION)): ... print(anc) (<Tier object (id: g type: glosses) at ...>, 'alignment', <Tier object (id: m type: morphemes) at ...>, [<Item object (id: m1) at ...>]) ...
[ "def", "ancestors", "(", "obj", ",", "refattrs", "=", "(", "ALIGNMENT", ",", "SEGMENTATION", ")", ")", ":", "if", "hasattr", "(", "obj", ",", "'tier'", ")", ":", "tier", "=", "obj", ".", "tier", "items", "=", "[", "obj", "]", "else", ":", "tier", ...
>>> for anc in query.ancestors(igt.get_item('g1'), refattrs=(ALIGNMENT, SEGMENTATION)): ... print(anc) (<Tier object (id: g type: glosses) at ...>, 'alignment', <Tier object (id: m type: morphemes) at ...>, [<Item object (id: m1) at ...>]) (<Tier object (id: m type: morphemes) at ...>, 'segmentation', <...
[ ">>>", "for", "anc", "in", "query", ".", "ancestors", "(", "igt", ".", "get_item", "(", "g1", ")", "refattrs", "=", "(", "ALIGNMENT", "SEGMENTATION", "))", ":", "...", "print", "(", "anc", ")", "(", "<Tier", "object", "(", "id", ":", "g", "type", "...
train
https://github.com/xigt/xigt/blob/3736fbb6d26887181de57bd189cbd731cec91289/xigt/query.py#L13-L46
xigt/xigt
xigt/query.py
descendants
def descendants(obj, refattrs=(SEGMENTATION, ALIGNMENT), follow='first'): """ >>> for des in query.descendants(igt.get_item('p1'), refattrs=(SEGMENTATION, ALIGNMENT)): ... print(des) (<Tier object (id: p type: phrases) at ...>, 'segmentation', <Tier object (id: w type: words) at ...>, [<Item object ...
python
def descendants(obj, refattrs=(SEGMENTATION, ALIGNMENT), follow='first'): """ >>> for des in query.descendants(igt.get_item('p1'), refattrs=(SEGMENTATION, ALIGNMENT)): ... print(des) (<Tier object (id: p type: phrases) at ...>, 'segmentation', <Tier object (id: w type: words) at ...>, [<Item object ...
[ "def", "descendants", "(", "obj", ",", "refattrs", "=", "(", "SEGMENTATION", ",", "ALIGNMENT", ")", ",", "follow", "=", "'first'", ")", ":", "if", "hasattr", "(", "obj", ",", "'tier'", ")", ":", "tier", "=", "obj", ".", "tier", "items", "=", "[", "...
>>> for des in query.descendants(igt.get_item('p1'), refattrs=(SEGMENTATION, ALIGNMENT)): ... print(des) (<Tier object (id: p type: phrases) at ...>, 'segmentation', <Tier object (id: w type: words) at ...>, [<Item object (id: w1) at ...>]) (<Tier object (id: p type: phrases) at ...>, 'alignment', <Tier...
[ ">>>", "for", "des", "in", "query", ".", "descendants", "(", "igt", ".", "get_item", "(", "p1", ")", "refattrs", "=", "(", "SEGMENTATION", "ALIGNMENT", "))", ":", "...", "print", "(", "des", ")", "(", "<Tier", "object", "(", "id", ":", "p", "type", ...
train
https://github.com/xigt/xigt/blob/3736fbb6d26887181de57bd189cbd731cec91289/xigt/query.py#L49-L93
xigt/xigt
xigt/codecs/xigtxml.py
default_decode
def default_decode(events, mode='full'): """Decode a XigtCorpus element.""" event, elem = next(events) root = elem # store root for later instantiation while (event, elem.tag) not in [('start', 'igt'), ('end', 'xigt-corpus')]: event, elem = next(events) igts = None if event == 'start' a...
python
def default_decode(events, mode='full'): """Decode a XigtCorpus element.""" event, elem = next(events) root = elem # store root for later instantiation while (event, elem.tag) not in [('start', 'igt'), ('end', 'xigt-corpus')]: event, elem = next(events) igts = None if event == 'start' a...
[ "def", "default_decode", "(", "events", ",", "mode", "=", "'full'", ")", ":", "event", ",", "elem", "=", "next", "(", "events", ")", "root", "=", "elem", "# store root for later instantiation", "while", "(", "event", ",", "elem", ".", "tag", ")", "not", ...
Decode a XigtCorpus element.
[ "Decode", "a", "XigtCorpus", "element", "." ]
train
https://github.com/xigt/xigt/blob/3736fbb6d26887181de57bd189cbd731cec91289/xigt/codecs/xigtxml.py#L212-L227
willkg/socorro-siggen
siggen/siglists_utils.py
_get_file_content
def _get_file_content(source): """Return a tuple, each value being a line of the source file. Remove empty lines and comments (lines starting with a '#'). """ filepath = os.path.join('siglists', source + '.txt') lines = [] with resource_stream(__name__, filepath) as f: for i, line in ...
python
def _get_file_content(source): """Return a tuple, each value being a line of the source file. Remove empty lines and comments (lines starting with a '#'). """ filepath = os.path.join('siglists', source + '.txt') lines = [] with resource_stream(__name__, filepath) as f: for i, line in ...
[ "def", "_get_file_content", "(", "source", ")", ":", "filepath", "=", "os", ".", "path", ".", "join", "(", "'siglists'", ",", "source", "+", "'.txt'", ")", "lines", "=", "[", "]", "with", "resource_stream", "(", "__name__", ",", "filepath", ")", "as", ...
Return a tuple, each value being a line of the source file. Remove empty lines and comments (lines starting with a '#').
[ "Return", "a", "tuple", "each", "value", "being", "a", "line", "of", "the", "source", "file", "." ]
train
https://github.com/willkg/socorro-siggen/blob/db7e3233e665a458a961c48da22e93a69b1d08d6/siggen/siglists_utils.py#L30-L61
JohnDoee/thomas
thomas/processors/rar.py
_get_rar_version
def _get_rar_version(xfile): """Check quickly whether file is rar archive. """ buf = xfile.read(len(RAR5_ID)) if buf.startswith(RAR_ID): return 3 elif buf.startswith(RAR5_ID): xfile.read(1) return 5 return 0
python
def _get_rar_version(xfile): """Check quickly whether file is rar archive. """ buf = xfile.read(len(RAR5_ID)) if buf.startswith(RAR_ID): return 3 elif buf.startswith(RAR5_ID): xfile.read(1) return 5 return 0
[ "def", "_get_rar_version", "(", "xfile", ")", ":", "buf", "=", "xfile", ".", "read", "(", "len", "(", "RAR5_ID", ")", ")", "if", "buf", ".", "startswith", "(", "RAR_ID", ")", ":", "return", "3", "elif", "buf", ".", "startswith", "(", "RAR5_ID", ")", ...
Check quickly whether file is rar archive.
[ "Check", "quickly", "whether", "file", "is", "rar", "archive", "." ]
train
https://github.com/JohnDoee/thomas/blob/51916dd110098b189a1c2fbcb71794fd9ec94832/thomas/processors/rar.py#L155-L164
JohnDoee/thomas
thomas/processors/rar.py
VirtualDirectReader._open_next
def _open_next(self): """Proceed to next volume.""" # is the file split over archives? if (self._cur.flags & rarfile.RAR_FILE_SPLIT_AFTER) == 0: return False if self._fd: self._fd.close() self._fd = None # open next part self._volfil...
python
def _open_next(self): """Proceed to next volume.""" # is the file split over archives? if (self._cur.flags & rarfile.RAR_FILE_SPLIT_AFTER) == 0: return False if self._fd: self._fd.close() self._fd = None # open next part self._volfil...
[ "def", "_open_next", "(", "self", ")", ":", "# is the file split over archives?", "if", "(", "self", ".", "_cur", ".", "flags", "&", "rarfile", ".", "RAR_FILE_SPLIT_AFTER", ")", "==", "0", ":", "return", "False", "if", "self", ".", "_fd", ":", "self", ".",...
Proceed to next volume.
[ "Proceed", "to", "next", "volume", "." ]
train
https://github.com/JohnDoee/thomas/blob/51916dd110098b189a1c2fbcb71794fd9ec94832/thomas/processors/rar.py#L168-L200
JohnDoee/thomas
thomas/processors/rar.py
VirtualDirectReader._check
def _check(self): # TODO: fix? """Do not check final CRC.""" if self._returncode: rarfile.check_returncode(self, '') if self._remain != 0: raise rarfile.BadRarFile("Failed the read enough data")
python
def _check(self): # TODO: fix? """Do not check final CRC.""" if self._returncode: rarfile.check_returncode(self, '') if self._remain != 0: raise rarfile.BadRarFile("Failed the read enough data")
[ "def", "_check", "(", "self", ")", ":", "# TODO: fix?", "if", "self", ".", "_returncode", ":", "rarfile", ".", "check_returncode", "(", "self", ",", "''", ")", "if", "self", ".", "_remain", "!=", "0", ":", "raise", "rarfile", ".", "BadRarFile", "(", "\...
Do not check final CRC.
[ "Do", "not", "check", "final", "CRC", "." ]
train
https://github.com/JohnDoee/thomas/blob/51916dd110098b189a1c2fbcb71794fd9ec94832/thomas/processors/rar.py#L202-L207