_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q255900
get_languages
validation
def get_languages() -> set: """Get supported languages.""" try: languages = cache['languages'] except KeyError: languages = LanguageTool._get_languages() cache['languages'] = languages return languages
python
{ "resource": "" }
q255901
get_directory
validation
def get_directory(): """Get LanguageTool directory.""" try: language_check_dir = cache['language_check_dir'] except KeyError: def version_key(string): return [int(e) if e.isdigit() else e for e in re.split(r"(\d+)", string)] def get_lt_dir(base_dir): ...
python
{ "resource": "" }
q255902
set_directory
validation
def set_directory(path=None): """Set LanguageTool directory.""" old_path = get_directory() terminate_server() cache.clear() if path: cache['language_check_dir'] = path try: get_jar_info() except Error: cache['language_check_dir'] = old_path ...
python
{ "resource": "" }
q255903
LanguageTool.check
validation
def check(self, text: str, srctext=None) -> [Match]: """Match text against enabled rules.""" root = self._get_root(self._url, self._encode(text, srctext)) return [Match(e.attrib) for e in root if e.tag == 'error']
python
{ "resource": "" }
q255904
get_newest_possible_languagetool_version
validation
def get_newest_possible_languagetool_version(): """Return newest compatible version. >>> version = get_newest_possible_languagetool_version() >>> version in [JAVA_6_COMPATIBLE_VERSION, ... JAVA_7_COMPATIBLE_VERSION, ... LATEST_VERSION] True """ java_path = find_...
python
{ "resource": "" }
q255905
get_common_prefix
validation
def get_common_prefix(z): """Get common directory in a zip file if any.""" name_list = z.namelist() if name_list and all(n.startswith(name_list[0]) for n in name_list[1:]): return name_list[0] return None
python
{ "resource": "" }
q255906
_ProactorEventLoop._process_events
validation
def _process_events(self, events): """Process events from proactor.""" for f, callback, transferred, key, ov in events: try: self._logger.debug('Invoking event callback {}'.format(callback)) value = callback(transferred, key, ov) except OSError: ...
python
{ "resource": "" }
q255907
asyncClose
validation
def asyncClose(fn): """Allow to run async code before application is closed.""" @functools.wraps(fn) def wrapper(*args, **kwargs): f = asyncio.ensure_future(fn(*args, **kwargs)) while not f.done(): QApplication.instance().processEvents() return wrapper
python
{ "resource": "" }
q255908
asyncSlot
validation
def asyncSlot(*args): """Make a Qt async slot run on asyncio loop.""" def outer_decorator(fn): @Slot(*args) @functools.wraps(fn) def wrapper(*args, **kwargs): asyncio.ensure_future(fn(*args, **kwargs)) return wrapper return outer_decorator
python
{ "resource": "" }
q255909
with_logger
validation
def with_logger(cls): """Class decorator to add a logger to a class.""" attr_name = '_logger' cls_name = cls.__qualname__ module = cls.__module__ if module is not None: cls_name = module + '.' + cls_name else: raise AssertionError setattr(cls, attr_name, logging.getLogger(cls...
python
{ "resource": "" }
q255910
_SelectorEventLoop._process_event
validation
def _process_event(self, key, mask): """Selector has delivered us an event.""" self._logger.debug('Processing event with key {} and mask {}'.format(key, mask)) fileobj, (reader, writer) = key.fileobj, key.data if mask & selectors.EVENT_READ and reader is not None: if reader._...
python
{ "resource": "" }
q255911
MibCompiler.addSources
validation
def addSources(self, *sources): """Add more ASN.1 MIB source repositories. MibCompiler.compile will invoke each of configured source objects in order of their addition asking each to fetch MIB module specified by name. Args: sources: reader object(s) Return...
python
{ "resource": "" }
q255912
MibCompiler.addSearchers
validation
def addSearchers(self, *searchers): """Add more transformed MIBs repositories. MibCompiler.compile will invoke each of configured searcher objects in order of their addition asking each if already transformed MIB module already exists and is more recent than specified. Args: ...
python
{ "resource": "" }
q255913
MibCompiler.addBorrowers
validation
def addBorrowers(self, *borrowers): """Add more transformed MIBs repositories to borrow MIBs from. Whenever MibCompiler.compile encounters MIB module which neither of the *searchers* can find or fetched ASN.1 MIB module can not be parsed (due to syntax errors), these *borrowers* objects...
python
{ "resource": "" }
q255914
AIC
validation
def AIC(N, rho, k): r"""Akaike Information Criterion :param rho: rho at order k :param N: sample size :param k: AR order. If k is the AR order and N the size of the sample, then Akaike criterion is .. math:: AIC(k) = \log(\rho_k) + 2\frac{k+1}{N} :: AIC(64, [0.5,0.3,0.2], [1,2,3...
python
{ "resource": "" }
q255915
AICc
validation
def AICc(N, rho, k, norm=True): r"""corrected Akaike information criterion .. math:: AICc(k) = log(\rho_k) + 2 \frac{k+1}{N-k-2} :validation: double checked versus octave. """ from numpy import log, array p = k #todo check convention. agrees with octave res = log(rho) + 2. * (p+1) / (N-p...
python
{ "resource": "" }
q255916
KIC
validation
def KIC(N, rho, k): r"""Kullback information criterion .. math:: KIC(k) = log(\rho_k) + 3 \frac{k+1}{N} :validation: double checked versus octave. """ from numpy import log, array res = log(rho) + 3. * (k+1.) /float(N) return res
python
{ "resource": "" }
q255917
AKICc
validation
def AKICc(N, rho, k): r"""approximate corrected Kullback information .. math:: AKICc(k) = log(rho_k) + \frac{p}{N*(N-k)} + (3-\frac{k+2}{N})*\frac{k+1}{N-k-2} """ from numpy import log, array p = k res = log(rho) + p/N/(N-p) + (3.-(p+2.)/N) * (p+1.) / (N-p-2.) return res
python
{ "resource": "" }
q255918
FPE
validation
def FPE(N,rho, k=None): r"""Final prediction error criterion .. math:: FPE(k) = \frac{N + k + 1}{N - k - 1} \rho_k :validation: double checked versus octave. """ #k #todo check convention. agrees with octave fpe = rho * (N + k + 1.) / (N- k -1) return fpe
python
{ "resource": "" }
q255919
MDL
validation
def MDL(N, rho, k): r"""Minimum Description Length .. math:: MDL(k) = N log \rho_k + p \log N :validation: results """ from numpy import log #p = arange(1, len(rho)+1) mdl = N* log(rho) + k * log(N) return mdl
python
{ "resource": "" }
q255920
aic_eigen
validation
def aic_eigen(s, N): r"""AIC order-selection using eigen values :param s: a list of `p` sorted eigen values :param N: the size of the input data. To be defined precisely. :return: * an array containing the AIC values Given :math:`n` sorted eigen values :math:`\lambda_i` with :math:`0 ...
python
{ "resource": "" }
q255921
mdl_eigen
validation
def mdl_eigen(s, N): r"""MDL order-selection using eigen values :param s: a list of `p` sorted eigen values :param N: the size of the input data. To be defined precisely. :return: * an array containing the AIC values .. math:: MDL(k) = (n-k)N \ln \frac{g(k)}{a(k)} + 0.5k(2n-k) log(N) ...
python
{ "resource": "" }
q255922
generate_gallery_rst
validation
def generate_gallery_rst(app): """Generate the Main examples gallery reStructuredText Start the sphinx-gallery configuration and recursively scan the examples directories in order to populate the examples gallery """ try: plot_gallery = eval(app.builder.config.plot_gallery) except TypeE...
python
{ "resource": "" }
q255923
setup
validation
def setup(app): """Setup sphinx-gallery sphinx extension""" app.add_config_value('plot_gallery', True, 'html') app.add_config_value('abort_on_example_error', False, 'html') app.add_config_value('sphinx_gallery_conf', gallery_conf, 'html') app.add_stylesheet('gallery.css') app.connect('builder-i...
python
{ "resource": "" }
q255924
CORRELATION
validation
def CORRELATION(x, y=None, maxlags=None, norm='unbiased'): r"""Correlation function This function should give the same results as :func:`xcorr` but it returns the positive lags only. Moreover the algorithm does not use FFT as compared to other algorithms. :param array x: first data array of length...
python
{ "resource": "" }
q255925
xcorr
validation
def xcorr(x, y=None, maxlags=None, norm='biased'): """Cross-correlation using numpy.correlate Estimates the cross-correlation (and autocorrelation) sequence of a random process of length N. By default, there is no normalisation and the output sequence of the cross-correlation has a length 2*N+1. :...
python
{ "resource": "" }
q255926
MINEIGVAL
validation
def MINEIGVAL(T0, T, TOL): """Finds the minimum eigenvalue of a Hermitian Toeplitz matrix The classical power method is used together with a fast Toeplitz equation solution routine. The eigenvector is normalized to unit length. :param T0: Scalar corresponding to real matrix element t(0) :param ...
python
{ "resource": "" }
q255927
morlet
validation
def morlet(lb, ub, n): r"""Generate the Morlet waveform The Morlet waveform is defined as follows: .. math:: w[x] = \cos{5x} \exp^{-x^2/2} :param lb: lower bound :param ub: upper bound :param int n: waveform data samples .. plot:: :include-source: :width: 80% ...
python
{ "resource": "" }
q255928
chirp
validation
def chirp(t, f0=0., t1=1., f1=100., form='linear', phase=0): r"""Evaluate a chirp signal at time t. A chirp signal is a frequency swept cosine wave. .. math:: a = \pi (f_1 - f_0) / t_1 .. math:: b = 2 \pi f_0 .. math:: y = \cos\left( \pi\frac{f_1-f_0}{t_1} t^2 + 2\pi f_0 t + \rm{phase} \right)...
python
{ "resource": "" }
q255929
mexican
validation
def mexican(lb, ub, n): r"""Generate the mexican hat wavelet The Mexican wavelet is: .. math:: w[x] = \cos{5x} \exp^{-x^2/2} :param lb: lower bound :param ub: upper bound :param int n: waveform data samples :return: the waveform .. plot:: :include-source: :width: 80%...
python
{ "resource": "" }
q255930
ac2poly
validation
def ac2poly(data): """Convert autocorrelation sequence to prediction polynomial :param array data: input data (list or numpy.array) :return: * AR parameters * noise variance This is an alias to:: a, e, c = LEVINSON(data) :Example: .. doctest:: >>> from sp...
python
{ "resource": "" }
q255931
rc2poly
validation
def rc2poly(kr, r0=None): """convert reflection coefficients to prediction filter polynomial :param k: reflection coefficients """ # Initialize the recursion from .levinson import levup p = len(kr) #% p is the order of the prediction polynomial. a = numpy.array([1, kr[0]]) ...
python
{ "resource": "" }
q255932
rc2ac
validation
def rc2ac(k, R0): """Convert reflection coefficients to autocorrelation sequence. :param k: reflection coefficients :param R0: zero-lag autocorrelation :returns: the autocorrelation sequence .. seealso:: :func:`ac2rc`, :func:`poly2rc`, :func:`ac2poly`, :func:`poly2rc`, :func:`rc2poly`. """ ...
python
{ "resource": "" }
q255933
rc2is
validation
def rc2is(k): """Convert reflection coefficients to inverse sine parameters. :param k: reflection coefficients :return: inverse sine parameters .. seealso:: :func:`is2rc`, :func:`rc2poly`, :func:`rc2acC`, :func:`rc2lar`. Reference: J.R. Deller, J.G. Proakis, J.H.L. Hansen, "Discrete-Time P...
python
{ "resource": "" }
q255934
rc2lar
validation
def rc2lar(k): """Convert reflection coefficients to log area ratios. :param k: reflection coefficients :return: inverse sine parameters The log area ratio is defined by G = log((1+k)/(1-k)) , where the K parameter is the reflection coefficient. .. seealso:: :func:`lar2rc`, :func:`rc2poly`, :...
python
{ "resource": "" }
q255935
lar2rc
validation
def lar2rc(g): """Convert log area ratios to reflection coefficients. :param g: log area ratios :returns: the reflection coefficients .. seealso: :func:`rc2lar`, :func:`poly2rc`, :func:`ac2rc`, :func:`is2rc`. :References: [1] J. Makhoul, "Linear Prediction: A Tutorial Review," Proc. IEEE,...
python
{ "resource": "" }
q255936
lsf2poly
validation
def lsf2poly(lsf): """Convert line spectral frequencies to prediction filter coefficients returns a vector a containing the prediction filter coefficients from a vector lsf of line spectral frequencies. .. doctest:: >>> from spectrum import lsf2poly >>> lsf = [0.7842 , 1.5605 , 1.8776...
python
{ "resource": "" }
q255937
poly2lsf
validation
def poly2lsf(a): """Prediction polynomial to line spectral frequencies. converts the prediction polynomial specified by A, into the corresponding line spectral frequencies, LSF. normalizes the prediction polynomial by A(1). .. doctest:: >>> from spectrum import poly2lsf >>> a = [1...
python
{ "resource": "" }
q255938
_swapsides
validation
def _swapsides(data): """todo is it really useful ? Swap sides .. doctest:: >>> from spectrum import swapsides >>> x = [-2, -1, 1, 2] >>> swapsides(x) array([ 2, -2, -1]) """ N = len(data) return np.concatenate((data[N//2+1:], data[0:N//2]))
python
{ "resource": "" }
q255939
twosided_2_onesided
validation
def twosided_2_onesided(data): """Convert a one-sided PSD to a twosided PSD In order to keep the power in the onesided PSD the same as in the twosided version, the onesided values are twice as much as in the input data (except for the zero-lag value). :: >>> twosided_2_onesided([10, 2,3,3...
python
{ "resource": "" }
q255940
onesided_2_twosided
validation
def onesided_2_twosided(data): """Convert a two-sided PSD to a one-sided PSD In order to keep the power in the twosided PSD the same as in the onesided version, the twosided values are 2 times lower than the input data (except for the zero-lag and N-lag values). :: >>> twosided_2_ones...
python
{ "resource": "" }
q255941
twosided_2_centerdc
validation
def twosided_2_centerdc(data): """Convert a two-sided PSD to a center-dc PSD""" N = len(data) # could us int() or // in python 3 newpsd = np.concatenate((cshift(data[N//2:], 1), data[0:N//2])) newpsd[0] = data[-1] return newpsd
python
{ "resource": "" }
q255942
centerdc_2_twosided
validation
def centerdc_2_twosided(data): """Convert a center-dc PSD to a twosided PSD""" N = len(data) newpsd = np.concatenate((data[N//2:], (cshift(data[0:N//2], -1)))) return newpsd
python
{ "resource": "" }
q255943
_twosided_zerolag
validation
def _twosided_zerolag(data, zerolag): """Build a symmetric vector out of stricly positive lag vector and zero-lag .. doctest:: >>> data = [3,2,1] >>> zerolag = 4 >>> twosided_zerolag(data, zerolag) array([1, 2, 3, 4, 3, 2, 1]) .. seealso:: Same behaviour as :func:`twosided...
python
{ "resource": "" }
q255944
data_cosine
validation
def data_cosine(N=1024, A=0.1, sampling=1024., freq=200): r"""Return a noisy cosine at a given frequency. :param N: the final data size :param A: the strength of the noise :param float sampling: sampling frequency of the input :attr:`data`. :param float freq: the frequency :mat...
python
{ "resource": "" }
q255945
data_two_freqs
validation
def data_two_freqs(N=200): """A simple test example with two close frequencies """ nn = arange(N) xx = cos(0.257*pi*nn) + sin(0.2*pi*nn) + 0.01*randn(nn.size) return xx
python
{ "resource": "" }
q255946
spectrum_data
validation
def spectrum_data(filename): """Simple utilities to retrieve data sets from """ import os import pkg_resources info = pkg_resources.get_distribution('spectrum') location = info.location # first try develop mode share = os.sep.join([location, "spectrum", 'data']) filename2 = os.sep.join(...
python
{ "resource": "" }
q255947
TimeSeries.plot
validation
def plot(self, **kargs): """Plot the data set, using the sampling information to set the x-axis correctly.""" from pylab import plot, linspace, xlabel, ylabel, grid time = linspace(1*self.dt, self.N*self.dt, self.N) plot(time, self.data, **kargs) xlabel('Time') yl...
python
{ "resource": "" }
q255948
readwav
validation
def readwav(filename): """Read a WAV file and returns the data and sample rate :: from spectrum.io import readwav readwav() """ from scipy.io.wavfile import read as readwav samplerate, signal = readwav(filename) return signal, samplerate
python
{ "resource": "" }
q255949
_autocov
validation
def _autocov(s, **kwargs): """Returns the autocovariance of signal s at all lags. Adheres to the definition sxx[k] = E{S[n]S[n+k]} = cov{S[n],S[n+k]} where E{} is the expectation operator, and S is a zero mean process """ # only remove the mean once, if needed debias = kwargs.pop('debias', ...
python
{ "resource": "" }
q255950
_remove_bias
validation
def _remove_bias(x, axis): "Subtracts an estimate of the mean from signal x at axis" padded_slice = [slice(d) for d in x.shape] padded_slice[axis] = np.newaxis mn = np.mean(x, axis=axis) return x - mn[tuple(padded_slice)]
python
{ "resource": "" }
q255951
get_docstring_and_rest
validation
def get_docstring_and_rest(filename): """Separate `filename` content between docstring and the rest Strongly inspired from ast.get_docstring. Returns ------- docstring: str docstring of `filename` rest: str `filename` content without the docstring """ with open(filename...
python
{ "resource": "" }
q255952
split_code_and_text_blocks
validation
def split_code_and_text_blocks(source_file): """Return list with source file separated into code and text blocks. Returns ------- blocks : list of (label, content) List where each element is a tuple with the label ('text' or 'code'), and content string of block. """ docstring, r...
python
{ "resource": "" }
q255953
codestr2rst
validation
def codestr2rst(codestr, lang='python'): """Return reStructuredText code block from code string""" code_directive = "\n.. code-block:: {0}\n\n".format(lang) indented_block = indent(codestr, ' ' * 4) return code_directive + indented_block
python
{ "resource": "" }
q255954
get_md5sum
validation
def get_md5sum(src_file): """Returns md5sum of file""" with open(src_file, 'r') as src_data: src_content = src_data.read() # data needs to be encoded in python3 before hashing if sys.version_info[0] == 3: src_content = src_content.encode('utf-8') src_md5 = hashlib....
python
{ "resource": "" }
q255955
check_md5sum_change
validation
def check_md5sum_change(src_file): """Returns True if src_file has a different md5sum""" src_md5 = get_md5sum(src_file) src_md5_file = src_file + '.md5' src_file_changed = True if os.path.exists(src_md5_file): with open(src_md5_file, 'r') as file_checksum: ref_md5 = file_checks...
python
{ "resource": "" }
q255956
_plots_are_current
validation
def _plots_are_current(src_file, image_file): """Test existence of image file and no change in md5sum of example""" first_image_file = image_file.format(1) has_image = os.path.exists(first_image_file) src_file_changed = check_md5sum_change(src_file) return has_image and not src_file_changed
python
{ "resource": "" }
q255957
save_figures
validation
def save_figures(image_path, fig_count, gallery_conf): """Save all open matplotlib figures of the example code-block Parameters ---------- image_path : str Path where plots are saved (format string which accepts figure number) fig_count : int Previous figure number count. Figure num...
python
{ "resource": "" }
q255958
scale_image
validation
def scale_image(in_fname, out_fname, max_width, max_height): """Scales an image with the same aspect ratio centered in an image with a given max_width and max_height if in_fname == out_fname the image can only be scaled down """ # local import to avoid testing dependency on PIL: try: ...
python
{ "resource": "" }
q255959
save_thumbnail
validation
def save_thumbnail(image_path, base_image_name, gallery_conf): """Save the thumbnail image""" first_image_file = image_path.format(1) thumb_dir = os.path.join(os.path.dirname(first_image_file), 'thumb') if not os.path.exists(thumb_dir): os.makedirs(thumb_dir) thumb_file = os.path.join(thumb...
python
{ "resource": "" }
q255960
execute_script
validation
def execute_script(code_block, example_globals, image_path, fig_count, src_file, gallery_conf): """Executes the code block of the example file""" time_elapsed = 0 stdout = '' # We need to execute the code print('plotting code blocks in %s' % src_file) plt.close('all') cw...
python
{ "resource": "" }
q255961
_arburg2
validation
def _arburg2(X, order): """This version is 10 times faster than arburg, but the output rho is not correct. returns [1 a0,a1, an-1] """ x = np.array(X) N = len(x) if order <= 0.: raise ValueError("order must be > 0") # Initialisation # ------ rho, den rho = sum(abs(x)**2....
python
{ "resource": "" }
q255962
_numpy_cholesky
validation
def _numpy_cholesky(A, B): """Solve Ax=B using numpy cholesky solver A = LU in the case where A is square and Hermitian, A = L.L* where L* is transpoed and conjugate matrix Ly = b where Ux=y so x = U^{-1} y where U = L* and y = L^{-1} B """ L = numpy.linalg.cholesky...
python
{ "resource": "" }
q255963
_numpy_solver
validation
def _numpy_solver(A, B): """This function solve Ax=B directly without taking care of the input matrix properties. """ x = numpy.linalg.solve(A, B) return x
python
{ "resource": "" }
q255964
CHOLESKY
validation
def CHOLESKY(A, B, method='scipy'): """Solve linear system `AX=B` using CHOLESKY method. :param A: an input Hermitian matrix :param B: an array :param str method: a choice of method in [numpy, scipy, numpy_solver] * `numpy_solver` relies entirely on numpy.solver (no cholesky decomposition) ...
python
{ "resource": "" }
q255965
speriodogram
validation
def speriodogram(x, NFFT=None, detrend=True, sampling=1., scale_by_freq=True, window='hamming', axis=0): """Simple periodogram, but matrices accepted. :param x: an array or matrix of data samples. :param NFFT: length of the data before FFT is computed (zero padding) :param bool detre...
python
{ "resource": "" }
q255966
WelchPeriodogram
validation
def WelchPeriodogram(data, NFFT=None, sampling=1., **kargs): r"""Simple periodogram wrapper of numpy.psd function. :param A: the input data :param int NFFT: total length of the final data sets (padded with zero if needed; default is 4096) :param str window: :Technical documentation: ...
python
{ "resource": "" }
q255967
DaniellPeriodogram
validation
def DaniellPeriodogram(data, P, NFFT=None, detrend='mean', sampling=1., scale_by_freq=True, window='hamming'): r"""Return Daniell's periodogram. To reduce fast fluctuations of the spectrum one idea proposed by daniell is to average each value with points in its neighboorhood. It's li...
python
{ "resource": "" }
q255968
Range.centerdc_gen
validation
def centerdc_gen(self): """Return the centered frequency range as a generator. :: >>> print(list(Range(8).centerdc_gen())) [-0.5, -0.375, -0.25, -0.125, 0.0, 0.125, 0.25, 0.375] """ for a in range(0, self.N): yield (a-self.N/2) * self.df
python
{ "resource": "" }
q255969
Range.onesided_gen
validation
def onesided_gen(self): """Return the one-sided frequency range as a generator. If :attr:`N` is even, the length is N/2 + 1. If :attr:`N` is odd, the length is (N+1)/2. :: >>> print(list(Range(8).onesided())) [0.0, 0.125, 0.25, 0.375, 0.5] >>> print...
python
{ "resource": "" }
q255970
Spectrum.plot
validation
def plot(self, filename=None, norm=False, ylim=None, sides=None, **kargs): """a simple plotting routine to plot the PSD versus frequency. :param str filename: save the figure into a file :param norm: False by default. If True, the PSD is normalised. :param ylim: readjust ...
python
{ "resource": "" }
q255971
Spectrum.power
validation
def power(self): r"""Return the power contained in the PSD if scale_by_freq is False, the power is: .. math:: P = N \sum_{k=1}^{N} P_{xx}(k) else, it is .. math:: P = \sum_{k=1}^{N} P_{xx}(k) \frac{df}{2\pi} .. todo:: check these equations """ if s...
python
{ "resource": "" }
q255972
ipy_notebook_skeleton
validation
def ipy_notebook_skeleton(): """Returns a dictionary with the elements of a Jupyter notebook""" py_version = sys.version_info notebook_skeleton = { "cells": [], "metadata": { "kernelspec": { "display_name": "Python " + str(py_version[0]), "language...
python
{ "resource": "" }
q255973
rst2md
validation
def rst2md(text): """Converts the RST text from the examples docstrigs and comments into markdown text for the IPython notebooks""" top_heading = re.compile(r'^=+$\s^([\w\s-]+)^=+$', flags=re.M) text = re.sub(top_heading, r'# \1', text) math_eq = re.compile(r'^\.\. math::((?:.+)?(?:\n+^ .+)*)', f...
python
{ "resource": "" }
q255974
Notebook.add_markdown_cell
validation
def add_markdown_cell(self, text): """Add a markdown cell to the notebook Parameters ---------- code : str Cell content """ markdown_cell = { "cell_type": "markdown", "metadata": {}, "source": [rst2md(text)] } ...
python
{ "resource": "" }
q255975
Notebook.save_file
validation
def save_file(self): """Saves the notebook to a file""" with open(self.write_file, 'w') as out_nb: json.dump(self.work_notebook, out_nb, indent=2)
python
{ "resource": "" }
q255976
arma2psd
validation
def arma2psd(A=None, B=None, rho=1., T=1., NFFT=4096, sides='default', norm=False): r"""Computes power spectral density given ARMA values. This function computes the power spectral density values given the ARMA parameters of an ARMA model. It assumes that the driving sequence is a white noise p...
python
{ "resource": "" }
q255977
arma_estimate
validation
def arma_estimate(X, P, Q, lag): """Autoregressive and moving average estimators. This function provides an estimate of the autoregressive parameters, the moving average parameters, and the driving white noise variance of an ARMA(P,Q) for a complex or real data sequence. The parameters are estima...
python
{ "resource": "" }
q255978
ma
validation
def ma(X, Q, M): """Moving average estimator. This program provides an estimate of the moving average parameters and driving noise variance for a data sequence based on a long AR model and a least squares fit. :param array X: The input data array :param int Q: Desired MA model order (must be >...
python
{ "resource": "" }
q255979
CORRELOGRAMPSD
validation
def CORRELOGRAMPSD(X, Y=None, lag=-1, window='hamming', norm='unbiased', NFFT=4096, window_params={}, correlation_method='xcorr'): """PSD estimate using correlogram method. :param array X: complex or real data samples X(1) to X(N) :param array Y: complex data sample...
python
{ "resource": "" }
q255980
_get_data
validation
def _get_data(url): """Helper function to get data over http or from a local file""" if url.startswith('http://'): # Try Python 2, use Python 3 on exception try: resp = urllib.urlopen(url) encoding = resp.headers.dict.get('content-encoding', 'plain') except Attrib...
python
{ "resource": "" }
q255981
_select_block
validation
def _select_block(str_in, start_tag, end_tag): """Select first block delimited by start_tag and end_tag""" start_pos = str_in.find(start_tag) if start_pos < 0: raise ValueError('start_tag not found') depth = 0 for pos in range(start_pos, len(str_in)): if str_in[pos] == start_tag: ...
python
{ "resource": "" }
q255982
_parse_dict_recursive
validation
def _parse_dict_recursive(dict_str): """Parse a dictionary from the search index""" dict_out = dict() pos_last = 0 pos = dict_str.find(':') while pos >= 0: key = dict_str[pos_last:pos] if dict_str[pos + 1] == '[': # value is a list pos_tmp = dict_str.find(']',...
python
{ "resource": "" }
q255983
parse_sphinx_searchindex
validation
def parse_sphinx_searchindex(searchindex): """Parse a Sphinx search index Parameters ---------- searchindex : str The Sphinx search index (contents of searchindex.js) Returns ------- filenames : list of str The file names parsed from the search index. objects : dict ...
python
{ "resource": "" }
q255984
embed_code_links
validation
def embed_code_links(app, exception): """Embed hyperlinks to documentation into example code""" if exception is not None: return # No need to waste time embedding hyperlinks when not running the examples # XXX: also at the time of writing this fixes make html-noplot # for some reason I don'...
python
{ "resource": "" }
q255985
SphinxDocLinkResolver._get_link
validation
def _get_link(self, cobj): """Get a valid link, False if not found""" fname_idx = None full_name = cobj['module_short'] + '.' + cobj['name'] if full_name in self._searchindex['objects']: value = self._searchindex['objects'][full_name] if isinstance(value, dict): ...
python
{ "resource": "" }
q255986
tf2zp
validation
def tf2zp(b,a): """Convert transfer function filter parameters to zero-pole-gain form Find the zeros, poles, and gains of this continuous-time system: .. warning:: b and a must have the same length. :: from spectrum import tf2zp b = [2,3,0] a = [1, 0.4, 1] [z,p,k...
python
{ "resource": "" }
q255987
eqtflength
validation
def eqtflength(b,a): """Given two list or arrays, pad with zeros the shortest array :param b: list or array :param a: list or array .. doctest:: >>> from spectrum.transfer import eqtflength >>> a = [1,2] >>> b = [1,2,3,4] >>> a, b, = eqtflength(a,b) """ d = a...
python
{ "resource": "" }
q255988
ss2zpk
validation
def ss2zpk(a,b,c,d, input=0): """State-space representation to zero-pole-gain representation. :param A: ndarray State-space representation of linear system. :param B: ndarray State-space representation of linear system. :param C: ndarray State-space representation of linear system. :param D: ndarra...
python
{ "resource": "" }
q255989
zpk2tf
validation
def zpk2tf(z, p, k): r"""Return polynomial transfer function representation from zeros and poles :param ndarray z: Zeros of the transfer function. :param ndarray p: Poles of the transfer function. :param float k: System gain. :return: b : ndarray Numerator polynomial. a : ndarray N...
python
{ "resource": "" }
q255990
zpk2ss
validation
def zpk2ss(z, p, k): """Zero-pole-gain representation to state-space representation :param sequence z,p: Zeros and poles. :param float k: System gain. :return: * A, B, C, D : ndarray State-space matrices. .. note:: wrapper of scipy function zpk2ss """ import scipy.signal retur...
python
{ "resource": "" }
q255991
enbw
validation
def enbw(data): r"""Computes the equivalent noise bandwidth .. math:: ENBW = N \frac{\sum_{n=1}^{N} w_n^2}{\left(\sum_{n=1}^{N} w_n \right)^2} .. doctest:: >>> from spectrum import create_window, enbw >>> w = create_window(64, 'rectangular') >>> enbw(w) 1.0 The follow...
python
{ "resource": "" }
q255992
_kaiser
validation
def _kaiser(n, beta): """Independant Kaiser window For the definition of the Kaiser window, see A. V. Oppenheim & R. W. Schafer, "Discrete-Time Signal Processing". The continuous version of width n centered about x=0 is: .. note:: 2 times slower than scipy.kaiser """ from scipy.special import...
python
{ "resource": "" }
q255993
window_visu
validation
def window_visu(N=51, name='hamming', **kargs): """A Window visualisation tool :param N: length of the window :param name: name of the window :param NFFT: padding used by the FFT :param mindB: the minimum frequency power in dB :param maxdB: the maximum frequency power in dB :param kargs: op...
python
{ "resource": "" }
q255994
window_kaiser
validation
def window_kaiser(N, beta=8.6, method='numpy'): r"""Kaiser window :param N: window length :param beta: kaiser parameter (default is 8.6) To obtain a Kaiser window that designs an FIR filter with sidelobe attenuation of :math:`\alpha` dB, use the following :math:`\beta` where :math:`\beta = \pi...
python
{ "resource": "" }
q255995
window_blackman
validation
def window_blackman(N, alpha=0.16): r"""Blackman window :param N: window length .. math:: a_0 - a_1 \cos(\frac{2\pi n}{N-1}) +a_2 \cos(\frac{4\pi n }{N-1}) with .. math:: a_0 = (1-\alpha)/2, a_1=0.5, a_2=\alpha/2 \rm{\;and\; \alpha}=0.16 When :math:`\alpha=0.16`, this is the unqual...
python
{ "resource": "" }
q255996
window_gaussian
validation
def window_gaussian(N, alpha=2.5): r"""Gaussian window :param N: window length .. math:: \exp^{-0.5 \left( \sigma\frac{n}{N/2} \right)^2} with :math:`\frac{N-1}{2}\leq n \leq \frac{N-1}{2}`. .. note:: N-1 is used to be in agreement with octave convention. The ENBW of 1.4 is also in agre...
python
{ "resource": "" }
q255997
window_cosine
validation
def window_cosine(N): r"""Cosine tapering window also known as sine window. :param N: window length .. math:: w(n) = \cos\left(\frac{\pi n}{N-1} - \frac{\pi}{2}\right) = \sin \left(\frac{\pi n}{N-1}\right) .. plot:: :width: 80% :include-source: from spectrum import window_vis...
python
{ "resource": "" }
q255998
window_lanczos
validation
def window_lanczos(N): r"""Lanczos window also known as sinc window. :param N: window length .. math:: w(n) = sinc \left( \frac{2n}{N-1} - 1 \right) .. plot:: :width: 80% :include-source: from spectrum import window_visu window_visu(64, 'lanczos') .. seealso:: :...
python
{ "resource": "" }
q255999
window_bartlett_hann
validation
def window_bartlett_hann(N): r"""Bartlett-Hann window :param N: window length .. math:: w(n) = a_0 + a_1 \left| \frac{n}{N-1} -\frac{1}{2}\right| - a_2 \cos \left( \frac{2\pi n}{N-1} \right) with :math:`a_0 = 0.62`, :math:`a_1 = 0.48` and :math:`a_2=0.38` .. plot:: :width: 80% :i...
python
{ "resource": "" }