def chroma_stft(y=None, sr=<NUM_LIT>, S=None, norm=np.inf, n_fft=<NUM_LIT>,<EOL>hop_length=<NUM_LIT>, win_length=None, window='<STR_LIT>', center=True,<EOL>pad_mode='<STR_LIT>', tuning=None, **kwargs):

S, n_fft = _spectrogram(y=y, S=S, n_fft=n_fft, hop_length=hop_length, power=<NUM_LIT:2>,<EOL>win_length=win_length, window=window, center=center,<EOL>pad_mode=pad_mode)<EOL>n_chroma = kwargs.get('<STR_LIT>', <NUM_LIT:12>)<EOL>if tuning is None:<EOL><INDENT>tuning = estimate_tuning(S=S, sr=sr, bins_per_octave=n_chroma)<EOL><DEDENT>if '<STR_LIT>' not in kwargs:<EOL><INDENT>kwargs['<STR_LIT>'] = <NUM_LIT> * <NUM_LIT>**(float(tuning) / n_chroma)<EOL><DEDENT>chromafb = filters.chroma(sr, n_fft, **kwargs)<EOL>raw_chroma = np.dot(chromafb, S)<EOL>return util.normalize(raw_chroma, norm=norm, axis=<NUM_LIT:0>)<EOL>

Compute a chromagram from a waveform or power spectrogram.

    This implementation is derived from `chromagram_E` [1]_

    .. [1] Ellis, Daniel P.W.  "Chroma feature analysis and synthesis"
           2007/04/21
           http://labrosa.ee.columbia.edu/matlab/chroma-ansyn/

    Parameters
    ----------
    y : np.ndarray [shape=(n,)] or None
        audio time series

    sr : number > 0 [scalar]
        sampling rate of `y`

    S : np.ndarray [shape=(d, t)] or None
        power spectrogram

    norm : float or None
        Column-wise normalization.
        See `librosa.util.normalize` for details.

        If `None`, no normalization is performed.

    n_fft : int  > 0 [scalar]
        FFT window size if provided `y, sr` instead of `S`

    hop_length : int > 0 [scalar]
        hop length if provided `y, sr` instead of `S`

    win_length : int <= n_fft [scalar]
        Each frame of audio is windowed by `window()`.
        The window will be of length `win_length` and then padded
        with zeros to match `n_fft`.

        If unspecified, defaults to ``win_length = n_fft``.

    window : string, tuple, number, function, or np.ndarray [shape=(n_fft,)]
        - a window specification (string, tuple, or number);
          see `scipy.signal.get_window`
        - a window function, such as `scipy.signal.hanning`
        - a vector or array of length `n_fft`

        .. see also:: `filters.get_window`

    center : boolean
        - If `True`, the signal `y` is padded so that frame
          `t` is centered at `y[t * hop_length]`.
        - If `False`, then frame `t` begins at `y[t * hop_length]`

    pad_mode : string
        If `center=True`, the padding mode to use at the edges of the signal.
        By default, STFT uses reflection padding.

    tuning : float in `[-0.5, 0.5)` [scalar] or None.
        Deviation from A440 tuning in fractional bins (cents).
        If `None`, it is automatically estimated.

    kwargs : additional keyword arguments
        Arguments to parameterize chroma filters.
        See `librosa.filters.chroma` for details.

    Returns
    -------
    chromagram : np.ndarray [shape=(n_chroma, t)]
        Normalized energy for each chroma bin at each frame.

    See Also
    --------
    librosa.filters.chroma
        Chroma filter bank construction
    librosa.util.normalize
        Vector normalization

    Examples
    --------
    >>> y, sr = librosa.load(librosa.util.example_audio_file())
    >>> librosa.feature.chroma_stft(y=y, sr=sr)
    array([[ 0.974,  0.881, ...,  0.925,  1.   ],
           [ 1.   ,  0.841, ...,  0.882,  0.878],
           ...,
           [ 0.658,  0.985, ...,  0.878,  0.764],
           [ 0.969,  0.92 , ...,  0.974,  0.915]])

    Use an energy (magnitude) spectrum instead of power spectrogram

    >>> S = np.abs(librosa.stft(y))
    >>> chroma = librosa.feature.chroma_stft(S=S, sr=sr)
    >>> chroma
    array([[ 0.884,  0.91 , ...,  0.861,  0.858],
           [ 0.963,  0.785, ...,  0.968,  0.896],
           ...,
           [ 0.871,  1.   , ...,  0.928,  0.829],
           [ 1.   ,  0.982, ...,  0.93 ,  0.878]])

    Use a pre-computed power spectrogram with a larger frame

    >>> S = np.abs(librosa.stft(y, n_fft=4096))**2
    >>> chroma = librosa.feature.chroma_stft(S=S, sr=sr)
    >>> chroma
    array([[ 0.685,  0.477, ...,  0.961,  0.986],
           [ 0.674,  0.452, ...,  0.952,  0.926],
           ...,
           [ 0.844,  0.575, ...,  0.934,  0.869],
           [ 0.793,  0.663, ...,  0.964,  0.972]])

    >>> import matplotlib.pyplot as plt
    >>> plt.figure(figsize=(10, 4))
    >>> librosa.display.specshow(chroma, y_axis='chroma', x_axis='time')
    >>> plt.colorbar()
    >>> plt.title('Chromagram')
    >>> plt.tight_layout()


def chroma_cqt(y=None, sr=<NUM_LIT>, C=None, hop_length=<NUM_LIT>, fmin=None,<EOL>norm=np.inf, threshold=<NUM_LIT:0.0>, tuning=None, n_chroma=<NUM_LIT:12>,<EOL>n_octaves=<NUM_LIT:7>, window=None, bins_per_octave=None, cqt_mode='<STR_LIT>'):

cqt_func = {'<STR_LIT>': cqt, '<STR_LIT>': hybrid_cqt}<EOL>if bins_per_octave is None:<EOL><INDENT>bins_per_octave = n_chroma<EOL><DEDENT>if C is None:<EOL><INDENT>C = np.abs(cqt_func[cqt_mode](y, sr=sr,<EOL>hop_length=hop_length,<EOL>fmin=fmin,<EOL>n_bins=n_octaves * bins_per_octave,<EOL>bins_per_octave=bins_per_octave,<EOL>tuning=tuning))<EOL><DEDENT>cq_to_chr = filters.cq_to_chroma(C.shape[<NUM_LIT:0>],<EOL>bins_per_octave=bins_per_octave,<EOL>n_chroma=n_chroma,<EOL>fmin=fmin,<EOL>window=window)<EOL>chroma = cq_to_chr.dot(C)<EOL>if threshold is not None:<EOL><INDENT>chroma[chroma < threshold] = <NUM_LIT:0.0><EOL><DEDENT>if norm is not None:<EOL><INDENT>chroma = util.normalize(chroma, norm=norm, axis=<NUM_LIT:0>)<EOL><DEDENT>return chroma<EOL>

r'''Constant-Q chromagram

    Parameters
    ----------
    y : np.ndarray [shape=(n,)]
        audio time series

    sr : number > 0
        sampling rate of `y`

    C : np.ndarray [shape=(d, t)] [Optional]
        a pre-computed constant-Q spectrogram

    hop_length : int > 0
        number of samples between successive chroma frames

    fmin : float > 0
        minimum frequency to analyze in the CQT.
        Default: 'C1' ~= 32.7 Hz

    norm : int > 0, +-np.inf, or None
        Column-wise normalization of the chromagram.

    threshold : float
        Pre-normalization energy threshold.  Values below the
        threshold are discarded, resulting in a sparse chromagram.

    tuning : float
        Deviation (in cents) from A440 tuning

    n_chroma : int > 0
        Number of chroma bins to produce

    n_octaves : int > 0
        Number of octaves to analyze above `fmin`

    window : None or np.ndarray
        Optional window parameter to `filters.cq_to_chroma`

    bins_per_octave : int > 0
        Number of bins per octave in the CQT.
        Default: matches `n_chroma`

    cqt_mode : ['full', 'hybrid']
        Constant-Q transform mode

    Returns
    -------
    chromagram : np.ndarray [shape=(n_chroma, t)]
        The output chromagram

    See Also
    --------
    librosa.util.normalize
    librosa.core.cqt
    librosa.core.hybrid_cqt
    chroma_stft

    Examples
    --------
    Compare a long-window STFT chromagram to the CQT chromagram

    >>> y, sr = librosa.load(librosa.util.example_audio_file(),
    ...                      offset=10, duration=15)
    >>> chroma_stft = librosa.feature.chroma_stft(y=y, sr=sr,
    ...                                           n_chroma=12, n_fft=4096)
    >>> chroma_cq = librosa.feature.chroma_cqt(y=y, sr=sr)

    >>> import matplotlib.pyplot as plt
    >>> plt.figure()
    >>> plt.subplot(2,1,1)
    >>> librosa.display.specshow(chroma_stft, y_axis='chroma')
    >>> plt.title('chroma_stft')
    >>> plt.colorbar()
    >>> plt.subplot(2,1,2)
    >>> librosa.display.specshow(chroma_cq, y_axis='chroma', x_axis='time')
    >>> plt.title('chroma_cqt')
    >>> plt.colorbar()
    >>> plt.tight_layout()


def chroma_cens(y=None, sr=<NUM_LIT>, C=None, hop_length=<NUM_LIT>, fmin=None,<EOL>tuning=None, n_chroma=<NUM_LIT:12>,<EOL>n_octaves=<NUM_LIT:7>, bins_per_octave=None, cqt_mode='<STR_LIT>', window=None,<EOL>norm=<NUM_LIT:2>, win_len_smooth=<NUM_LIT>, smoothing_window='<STR_LIT>'):

if not ((win_len_smooth is None) or (isinstance(win_len_smooth, int) and win_len_smooth > <NUM_LIT:0>)):<EOL><INDENT>raise ParameterError('<STR_LIT>'.format(win_len_smooth))<EOL><DEDENT>chroma = chroma_cqt(y=y, C=C, sr=sr,<EOL>hop_length=hop_length,<EOL>fmin=fmin,<EOL>bins_per_octave=bins_per_octave,<EOL>tuning=tuning,<EOL>norm=None,<EOL>n_chroma=n_chroma,<EOL>n_octaves=n_octaves,<EOL>cqt_mode=cqt_mode,<EOL>window=window)<EOL>chroma = util.normalize(chroma, norm=<NUM_LIT:1>, axis=<NUM_LIT:0>)<EOL>QUANT_STEPS = [<NUM_LIT>, <NUM_LIT>, <NUM_LIT:0.1>, <NUM_LIT>]<EOL>QUANT_WEIGHTS = [<NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>]<EOL>chroma_quant = np.zeros_like(chroma)<EOL>for cur_quant_step_idx, cur_quant_step in enumerate(QUANT_STEPS):<EOL><INDENT>chroma_quant += (chroma > cur_quant_step) * QUANT_WEIGHTS[cur_quant_step_idx]<EOL><DEDENT>if win_len_smooth:<EOL><INDENT>win = filters.get_window(smoothing_window, win_len_smooth + <NUM_LIT:2>, fftbins=False)<EOL>win /= np.sum(win)<EOL>win = np.atleast_2d(win)<EOL>cens = scipy.signal.convolve2d(chroma_quant, win,<EOL>mode='<STR_LIT>', boundary='<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>cens = chroma_quant<EOL><DEDENT>return util.normalize(cens, norm=norm, axis=<NUM_LIT:0>)<EOL>

r'''Computes the chroma variant "Chroma Energy Normalized" (CENS), following [1]_.

    To compute CENS features, following steps are taken after obtaining chroma vectors using `chroma_cqt`:
    1. L-1 normalization of each chroma vector
    2. Quantization of amplitude based on "log-like" amplitude thresholds
    3. (optional) Smoothing with sliding window. Default window length = 41 frames
    4. (not implemented) Downsampling

    CENS features are robust to dynamics, timbre and articulation, thus these are commonly used in audio
    matching and retrieval applications.

    .. [1] Meinard Müller and Sebastian Ewert
           "Chroma Toolbox: MATLAB implementations for extracting variants of chroma-based audio features"
           In Proceedings of the International Conference on Music Information Retrieval (ISMIR), 2011.

    Parameters
    ----------
    y : np.ndarray [shape=(n,)]
        audio time series

    sr : number > 0
        sampling rate of `y`

    C : np.ndarray [shape=(d, t)] [Optional]
        a pre-computed constant-Q spectrogram

    hop_length : int > 0
        number of samples between successive chroma frames

    fmin : float > 0
        minimum frequency to analyze in the CQT.
        Default: 'C1' ~= 32.7 Hz

    norm : int > 0, +-np.inf, or None
        Column-wise normalization of the chromagram.

    tuning : float
        Deviation (in cents) from A440 tuning

    n_chroma : int > 0
        Number of chroma bins to produce

    n_octaves : int > 0
        Number of octaves to analyze above `fmin`

    window : None or np.ndarray
        Optional window parameter to `filters.cq_to_chroma`

    bins_per_octave : int > 0
        Number of bins per octave in the CQT.
        Default: matches `n_chroma`

    cqt_mode : ['full', 'hybrid']
        Constant-Q transform mode

    win_len_smooth : int > 0 or None
        Length of temporal smoothing window. `None` disables temporal smoothing.
        Default: 41

    smoothing_window : str, float or tuple
        Type of window function for temporal smoothing. See `filters.get_window` for possible inputs.
        Default: 'hann'

    Returns
    -------
    chroma_cens : np.ndarray [shape=(n_chroma, t)]
        The output cens-chromagram

    See Also
    --------
    chroma_cqt
        Compute a chromagram from a constant-Q transform.

    chroma_stft
        Compute a chromagram from an STFT spectrogram or waveform.

    filters.get_window
        Compute a window function.

    Examples
    --------
    Compare standard cqt chroma to CENS.

    >>> y, sr = librosa.load(librosa.util.example_audio_file(),
    ...                      offset=10, duration=15)
    >>> chroma_cens = librosa.feature.chroma_cens(y=y, sr=sr)
    >>> chroma_cq = librosa.feature.chroma_cqt(y=y, sr=sr)

    >>> import matplotlib.pyplot as plt
    >>> plt.figure()
    >>> plt.subplot(2,1,1)
    >>> librosa.display.specshow(chroma_cq, y_axis='chroma')
    >>> plt.title('chroma_cq')
    >>> plt.colorbar()
    >>> plt.subplot(2,1,2)
    >>> librosa.display.specshow(chroma_cens, y_axis='chroma', x_axis='time')
    >>> plt.title('chroma_cens')
    >>> plt.colorbar()
    >>> plt.tight_layout()


def tonnetz(y=None, sr=<NUM_LIT>, chroma=None):

if y is None and chroma is None:<EOL><INDENT>raise ParameterError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>if chroma is None:<EOL><INDENT>chroma = chroma_cqt(y=y, sr=sr)<EOL><DEDENT>dim_map = np.linspace(<NUM_LIT:0>, <NUM_LIT:12>, num=chroma.shape[<NUM_LIT:0>], endpoint=False)<EOL>scale = np.asarray([<NUM_LIT> / <NUM_LIT:6>, <NUM_LIT> / <NUM_LIT:6>,<EOL><NUM_LIT> / <NUM_LIT:2>, <NUM_LIT> / <NUM_LIT:2>,<EOL><NUM_LIT> / <NUM_LIT:3>, <NUM_LIT> / <NUM_LIT:3>])<EOL>V = np.multiply.outer(scale, dim_map)<EOL>V[::<NUM_LIT:2>] -= <NUM_LIT:0.5><EOL>R = np.array([<NUM_LIT:1>, <NUM_LIT:1>,         <EOL><NUM_LIT:1>, <NUM_LIT:1>,         <EOL><NUM_LIT:0.5>, <NUM_LIT:0.5>])    <EOL>phi = R[:, np.newaxis] * np.cos(np.pi * V)<EOL>return phi.dot(util.normalize(chroma, norm=<NUM_LIT:1>, axis=<NUM_LIT:0>))<EOL>

Computes the tonal centroid features (tonnetz), following the method of
    [1]_.

    .. [1] Harte, C., Sandler, M., & Gasser, M. (2006). "Detecting Harmonic
           Change in Musical Audio." In Proceedings of the 1st ACM Workshop
           on Audio and Music Computing Multimedia (pp. 21-26).
           Santa Barbara, CA, USA: ACM Press. doi:10.1145/1178723.1178727.

    Parameters
    ----------
    y : np.ndarray [shape=(n,)] or None
        Audio time series.

    sr : number > 0 [scalar]
        sampling rate of `y`

    chroma : np.ndarray [shape=(n_chroma, t)] or None
        Normalized energy for each chroma bin at each frame.

        If `None`, a cqt chromagram is performed.

    Returns
    -------
    tonnetz : np.ndarray [shape(6, t)]
        Tonal centroid features for each frame.

        Tonnetz dimensions:
            - 0: Fifth x-axis
            - 1: Fifth y-axis
            - 2: Minor x-axis
            - 3: Minor y-axis
            - 4: Major x-axis
            - 5: Major y-axis

    See Also
    --------
    chroma_cqt
        Compute a chromagram from a constant-Q transform.

    chroma_stft
        Compute a chromagram from an STFT spectrogram or waveform.

    Examples
    --------
    Compute tonnetz features from the harmonic component of a song

    >>> y, sr = librosa.load(librosa.util.example_audio_file())
    >>> y = librosa.effects.harmonic(y)
    >>> tonnetz = librosa.feature.tonnetz(y=y, sr=sr)
    >>> tonnetz
    array([[-0.073, -0.053, ..., -0.054, -0.073],
           [ 0.001,  0.001, ..., -0.054, -0.062],
           ...,
           [ 0.039,  0.034, ...,  0.044,  0.064],
           [ 0.005,  0.002, ...,  0.011,  0.017]])

    Compare the tonnetz features to `chroma_cqt`

    >>> import matplotlib.pyplot as plt
    >>> plt.subplot(2, 1, 1)
    >>> librosa.display.specshow(tonnetz, y_axis='tonnetz')
    >>> plt.colorbar()
    >>> plt.title('Tonal Centroids (Tonnetz)')
    >>> plt.subplot(2, 1, 2)
    >>> librosa.display.specshow(librosa.feature.chroma_cqt(y, sr=sr),
    ...                          y_axis='chroma', x_axis='time')
    >>> plt.colorbar()
    >>> plt.title('Chroma')
    >>> plt.tight_layout()


def mfcc(y=None, sr=<NUM_LIT>, S=None, n_mfcc=<NUM_LIT:20>, dct_type=<NUM_LIT:2>, norm='<STR_LIT>', **kwargs):

if S is None:<EOL><INDENT>S = power_to_db(melspectrogram(y=y, sr=sr, **kwargs))<EOL><DEDENT>return scipy.fftpack.dct(S, axis=<NUM_LIT:0>, type=dct_type, norm=norm)[:n_mfcc]<EOL>

Mel-frequency cepstral coefficients (MFCCs)

    Parameters
    ----------
    y : np.ndarray [shape=(n,)] or None
        audio time series

    sr : number > 0 [scalar]
        sampling rate of `y`

    S : np.ndarray [shape=(d, t)] or None
        log-power Mel spectrogram

    n_mfcc: int > 0 [scalar]
        number of MFCCs to return

    dct_type : None, or {1, 2, 3}
        Discrete cosine transform (DCT) type.
        By default, DCT type-2 is used.

    norm : None or 'ortho'
        If `dct_type` is `2 or 3`, setting `norm='ortho'` uses an ortho-normal
        DCT basis.

        Normalization is not supported for `dct_type=1`.

    kwargs : additional keyword arguments
        Arguments to `melspectrogram`, if operating
        on time series input

    Returns
    -------
    M : np.ndarray [shape=(n_mfcc, t)]
        MFCC sequence

    See Also
    --------
    melspectrogram
    scipy.fftpack.dct

    Examples
    --------
    Generate mfccs from a time series

    >>> y, sr = librosa.load(librosa.util.example_audio_file(), offset=30, duration=5)
    >>> librosa.feature.mfcc(y=y, sr=sr)
    array([[ -5.229e+02,  -4.944e+02, ...,  -5.229e+02,  -5.229e+02],
           [  7.105e-15,   3.787e+01, ...,  -7.105e-15,  -7.105e-15],
           ...,
           [  1.066e-14,  -7.500e+00, ...,   1.421e-14,   1.421e-14],
           [  3.109e-14,  -5.058e+00, ...,   2.931e-14,   2.931e-14]])

    Use a pre-computed log-power Mel spectrogram

    >>> S = librosa.feature.melspectrogram(y=y, sr=sr, n_mels=128,
    ...                                    fmax=8000)
    >>> librosa.feature.mfcc(S=librosa.power_to_db(S))
    array([[ -5.207e+02,  -4.898e+02, ...,  -5.207e+02,  -5.207e+02],
           [ -2.576e-14,   4.054e+01, ...,  -3.997e-14,  -3.997e-14],
           ...,
           [  7.105e-15,  -3.534e+00, ...,   0.000e+00,   0.000e+00],
           [  3.020e-14,  -2.613e+00, ...,   3.553e-14,   3.553e-14]])

    Get more components

    >>> mfccs = librosa.feature.mfcc(y=y, sr=sr, n_mfcc=40)

    Visualize the MFCC series

    >>> import matplotlib.pyplot as plt
    >>> plt.figure(figsize=(10, 4))
    >>> librosa.display.specshow(mfccs, x_axis='time')
    >>> plt.colorbar()
    >>> plt.title('MFCC')
    >>> plt.tight_layout()

    Compare different DCT bases

    >>> m_slaney = librosa.feature.mfcc(y=y, sr=sr, dct_type=2)
    >>> m_htk = librosa.feature.mfcc(y=y, sr=sr, dct_type=3)
    >>> plt.figure(figsize=(10, 6))
    >>> plt.subplot(2, 1, 1)
    >>> librosa.display.specshow(m_slaney, x_axis='time')
    >>> plt.title('RASTAMAT / Auditory toolbox (dct_type=2)')
    >>> plt.colorbar()
    >>> plt.subplot(2, 1, 2)
    >>> librosa.display.specshow(m_htk, x_axis='time')
    >>> plt.title('HTK-style (dct_type=3)')
    >>> plt.colorbar()
    >>> plt.tight_layout()


def melspectrogram(y=None, sr=<NUM_LIT>, S=None, n_fft=<NUM_LIT>, hop_length=<NUM_LIT>,<EOL>win_length=None, window='<STR_LIT>', center=True, pad_mode='<STR_LIT>',<EOL>power=<NUM_LIT>, **kwargs):

S, n_fft = _spectrogram(y=y, S=S, n_fft=n_fft, hop_length=hop_length, power=power,<EOL>win_length=win_length, window=window, center=center,<EOL>pad_mode=pad_mode)<EOL>mel_basis = filters.mel(sr, n_fft, **kwargs)<EOL>return np.dot(mel_basis, S)<EOL>

Compute a mel-scaled spectrogram.

    If a spectrogram input `S` is provided, then it is mapped directly onto
    the mel basis `mel_f` by `mel_f.dot(S)`.

    If a time-series input `y, sr` is provided, then its magnitude spectrogram
    `S` is first computed, and then mapped onto the mel scale by
    `mel_f.dot(S**power)`.  By default, `power=2` operates on a power spectrum.

    Parameters
    ----------
    y : np.ndarray [shape=(n,)] or None
        audio time-series

    sr : number > 0 [scalar]
        sampling rate of `y`

    S : np.ndarray [shape=(d, t)]
        spectrogram

    n_fft : int > 0 [scalar]
        length of the FFT window

    hop_length : int > 0 [scalar]
        number of samples between successive frames.
        See `librosa.core.stft`

    win_length : int <= n_fft [scalar]
        Each frame of audio is windowed by `window()`.
        The window will be of length `win_length` and then padded
        with zeros to match `n_fft`.

        If unspecified, defaults to ``win_length = n_fft``.

    window : string, tuple, number, function, or np.ndarray [shape=(n_fft,)]
        - a window specification (string, tuple, or number);
          see `scipy.signal.get_window`
        - a window function, such as `scipy.signal.hanning`
        - a vector or array of length `n_fft`

        .. see also:: `filters.get_window`

    center : boolean
        - If `True`, the signal `y` is padded so that frame
          `t` is centered at `y[t * hop_length]`.
        - If `False`, then frame `t` begins at `y[t * hop_length]`

    pad_mode : string
        If `center=True`, the padding mode to use at the edges of the signal.
        By default, STFT uses reflection padding.

    power : float > 0 [scalar]
        Exponent for the magnitude melspectrogram.
        e.g., 1 for energy, 2 for power, etc.

    kwargs : additional keyword arguments
      Mel filter bank parameters.
      See `librosa.filters.mel` for details.

    Returns
    -------
    S : np.ndarray [shape=(n_mels, t)]
        Mel spectrogram

    See Also
    --------
    librosa.filters.mel
        Mel filter bank construction

    librosa.core.stft
        Short-time Fourier Transform

    Examples
    --------
    >>> y, sr = librosa.load(librosa.util.example_audio_file())
    >>> librosa.feature.melspectrogram(y=y, sr=sr)
    array([[  2.891e-07,   2.548e-03, ...,   8.116e-09,   5.633e-09],
           [  1.986e-07,   1.162e-02, ...,   9.332e-08,   6.716e-09],
           ...,
           [  3.668e-09,   2.029e-08, ...,   3.208e-09,   2.864e-09],
           [  2.561e-10,   2.096e-09, ...,   7.543e-10,   6.101e-10]])

    Using a pre-computed power spectrogram

    >>> D = np.abs(librosa.stft(y))**2
    >>> S = librosa.feature.melspectrogram(S=D)

    >>> # Passing through arguments to the Mel filters
    >>> S = librosa.feature.melspectrogram(y=y, sr=sr, n_mels=128,
    ...                                     fmax=8000)

    >>> import matplotlib.pyplot as plt
    >>> plt.figure(figsize=(10, 4))
    >>> librosa.display.specshow(librosa.power_to_db(S,
    ...                                              ref=np.max),
    ...                          y_axis='mel', fmax=8000,
    ...                          x_axis='time')
    >>> plt.colorbar(format='%+2.0f dB')
    >>> plt.title('Mel spectrogram')
    >>> plt.tight_layout()


def tempogram(y=None, sr=<NUM_LIT>, onset_envelope=None, hop_length=<NUM_LIT>,<EOL>win_length=<NUM_LIT>, center=True, window='<STR_LIT>', norm=np.inf):

from ..onset import onset_strength<EOL>if win_length < <NUM_LIT:1>:<EOL><INDENT>raise ParameterError('<STR_LIT>')<EOL><DEDENT>ac_window = get_window(window, win_length, fftbins=True)<EOL>if onset_envelope is None:<EOL><INDENT>if y is None:<EOL><INDENT>raise ParameterError('<STR_LIT>')<EOL><DEDENT>onset_envelope = onset_strength(y=y, sr=sr, hop_length=hop_length)<EOL><DEDENT>else:<EOL><INDENT>onset_envelope = np.ascontiguousarray(onset_envelope)<EOL><DEDENT>if onset_envelope.ndim > <NUM_LIT:1>:<EOL><INDENT>return np.asarray([tempogram(onset_envelope=oe_subband,<EOL>hop_length=hop_length,<EOL>win_length=win_length,<EOL>center=center,<EOL>window=window,<EOL>norm=norm) for oe_subband in onset_envelope])<EOL><DEDENT>n = len(onset_envelope)<EOL>if center:<EOL><INDENT>onset_envelope = np.pad(onset_envelope, int(win_length // <NUM_LIT:2>),<EOL>mode='<STR_LIT>', end_values=[<NUM_LIT:0>, <NUM_LIT:0>])<EOL><DEDENT>odf_frame = util.frame(onset_envelope,<EOL>frame_length=win_length,<EOL>hop_length=<NUM_LIT:1>)<EOL>if center:<EOL><INDENT>odf_frame = odf_frame[:, :n]<EOL><DEDENT>return util.normalize(autocorrelate(odf_frame * ac_window[:, np.newaxis],<EOL>axis=<NUM_LIT:0>),<EOL>norm=norm, axis=<NUM_LIT:0>)<EOL>

Compute the tempogram: local autocorrelation of the onset strength envelope. [1]_

    .. [1] Grosche, Peter, Meinard Müller, and Frank Kurth.
        "Cyclic tempogram - A mid-level tempo representation for music signals."
        ICASSP, 2010.

    Parameters
    ----------
    y : np.ndarray [shape=(n,)] or None
        Audio time series.

    sr : number > 0 [scalar]
        sampling rate of `y`

    onset_envelope : np.ndarray [shape=(n,) or (m, n)] or None
        Optional pre-computed onset strength envelope as provided by
        `onset.onset_strength`.

        If multi-dimensional, tempograms are computed independently for each
        band (first dimension).

    hop_length : int > 0
        number of audio samples between successive onset measurements

    win_length : int > 0
        length of the onset autocorrelation window (in frames/onset measurements)
        The default settings (384) corresponds to `384 * hop_length / sr ~= 8.9s`.

    center : bool
        If `True`, onset autocorrelation windows are centered.
        If `False`, windows are left-aligned.

    window : string, function, number, tuple, or np.ndarray [shape=(win_length,)]
        A window specification as in `core.stft`.

    norm : {np.inf, -np.inf, 0, float > 0, None}
        Normalization mode.  Set to `None` to disable normalization.

    Returns
    -------
    tempogram : np.ndarray [shape=(win_length, n) or (m, win_length, n)]
        Localized autocorrelation of the onset strength envelope.

        If given multi-band input (`onset_envelope.shape==(m,n)`) then
        `tempogram[i]` is the tempogram of `onset_envelope[i]`.

    Raises
    ------
    ParameterError
        if neither `y` nor `onset_envelope` are provided

        if `win_length < 1`

    See Also
    --------
    librosa.onset.onset_strength
    librosa.util.normalize
    librosa.core.stft

    Examples
    --------
    >>> # Compute local onset autocorrelation
    >>> y, sr = librosa.load(librosa.util.example_audio_file())
    >>> hop_length = 512
    >>> oenv = librosa.onset.onset_strength(y=y, sr=sr, hop_length=hop_length)
    >>> tempogram = librosa.feature.tempogram(onset_envelope=oenv, sr=sr,
    ...                                       hop_length=hop_length)
    >>> # Compute global onset autocorrelation
    >>> ac_global = librosa.autocorrelate(oenv, max_size=tempogram.shape[0])
    >>> ac_global = librosa.util.normalize(ac_global)
    >>> # Estimate the global tempo for display purposes
    >>> tempo = librosa.beat.tempo(onset_envelope=oenv, sr=sr,
    ...                            hop_length=hop_length)[0]

    >>> import matplotlib.pyplot as plt
    >>> plt.figure(figsize=(8, 8))
    >>> plt.subplot(4, 1, 1)
    >>> plt.plot(oenv, label='Onset strength')
    >>> plt.xticks([])
    >>> plt.legend(frameon=True)
    >>> plt.axis('tight')
    >>> plt.subplot(4, 1, 2)
    >>> # We'll truncate the display to a narrower range of tempi
    >>> librosa.display.specshow(tempogram, sr=sr, hop_length=hop_length,
    >>>                          x_axis='time', y_axis='tempo')
    >>> plt.axhline(tempo, color='w', linestyle='--', alpha=1,
    ...             label='Estimated tempo={:g}'.format(tempo))
    >>> plt.legend(frameon=True, framealpha=0.75)
    >>> plt.subplot(4, 1, 3)
    >>> x = np.linspace(0, tempogram.shape[0] * float(hop_length) / sr,
    ...                 num=tempogram.shape[0])
    >>> plt.plot(x, np.mean(tempogram, axis=1), label='Mean local autocorrelation')
    >>> plt.plot(x, ac_global, '--', alpha=0.75, label='Global autocorrelation')
    >>> plt.xlabel('Lag (seconds)')
    >>> plt.axis('tight')
    >>> plt.legend(frameon=True)
    >>> plt.subplot(4,1,4)
    >>> # We can also plot on a BPM axis
    >>> freqs = librosa.tempo_frequencies(tempogram.shape[0], hop_length=hop_length, sr=sr)
    >>> plt.semilogx(freqs[1:], np.mean(tempogram[1:], axis=1),
    ...              label='Mean local autocorrelation', basex=2)
    >>> plt.semilogx(freqs[1:], ac_global[1:], '--', alpha=0.75,
    ...              label='Global autocorrelation', basex=2)
    >>> plt.axvline(tempo, color='black', linestyle='--', alpha=.8,
    ...             label='Estimated tempo={:g}'.format(tempo))
    >>> plt.legend(frameon=True)
    >>> plt.xlabel('BPM')
    >>> plt.axis('tight')
    >>> plt.grid()
    >>> plt.tight_layout()


@cache(level=<NUM_LIT>)<EOL>def delta(data, width=<NUM_LIT:9>, order=<NUM_LIT:1>, axis=-<NUM_LIT:1>, mode='<STR_LIT>', **kwargs):

data = np.atleast_1d(data)<EOL>if mode == '<STR_LIT>' and width > data.shape[axis]:<EOL><INDENT>raise ParameterError("<STR_LIT>"<EOL>"<STR_LIT>".format(width, data.shape[axis]))<EOL><DEDENT>if width < <NUM_LIT:3> or np.mod(width, <NUM_LIT:2>) != <NUM_LIT:1>:<EOL><INDENT>raise ParameterError('<STR_LIT>')<EOL><DEDENT>if order <= <NUM_LIT:0> or not isinstance(order, int):<EOL><INDENT>raise ParameterError('<STR_LIT>')<EOL><DEDENT>kwargs.pop('<STR_LIT>', None)<EOL>kwargs.setdefault('<STR_LIT>', order)<EOL>return scipy.signal.savgol_filter(data, width,<EOL>deriv=order,<EOL>axis=axis,<EOL>mode=mode,<EOL>**kwargs)<EOL>

r'''Compute delta features: local estimate of the derivative
    of the input data along the selected axis.

    Delta features are computed Savitsky-Golay filtering.

    Parameters
    ----------
    data      : np.ndarray
        the input data matrix (eg, spectrogram)

    width     : int, positive, odd [scalar]
        Number of frames over which to compute the delta features.
        Cannot exceed the length of `data` along the specified axis.
        If `mode='interp'`, then `width` must be at least `data.shape[axis]`.

    order     : int > 0 [scalar]
        the order of the difference operator.
        1 for first derivative, 2 for second, etc.

    axis      : int [scalar]
        the axis along which to compute deltas.
        Default is -1 (columns).

    mode : str, {'interp', 'nearest', 'mirror', 'constant', 'wrap'}
        Padding mode for estimating differences at the boundaries.

    kwargs : additional keyword arguments
        See `scipy.signal.savgol_filter`

    Returns
    -------
    delta_data   : np.ndarray [shape=(d, t)]
        delta matrix of `data` at specified order

    Notes
    -----
    This function caches at level 40.

    See Also
    --------
    scipy.signal.savgol_filter

    Examples
    --------
    Compute MFCC deltas, delta-deltas

    >>> y, sr = librosa.load(librosa.util.example_audio_file())
    >>> mfcc = librosa.feature.mfcc(y=y, sr=sr)
    >>> mfcc_delta = librosa.feature.delta(mfcc)
    >>> mfcc_delta
    array([[  1.666e+01,   1.666e+01, ...,   1.869e-15,   1.869e-15],
           [  1.784e+01,   1.784e+01, ...,   6.085e-31,   6.085e-31],
           ...,
           [  7.262e-01,   7.262e-01, ...,   9.259e-31,   9.259e-31],
           [  6.578e-01,   6.578e-01, ...,   7.597e-31,   7.597e-31]])

    >>> mfcc_delta2 = librosa.feature.delta(mfcc, order=2)
    >>> mfcc_delta2
    array([[ -1.703e+01,  -1.703e+01, ...,   3.834e-14,   3.834e-14],
           [ -1.108e+01,  -1.108e+01, ...,  -1.068e-30,  -1.068e-30],
           ...,
           [  4.075e-01,   4.075e-01, ...,  -1.565e-30,  -1.565e-30],
           [  1.676e-01,   1.676e-01, ...,  -2.104e-30,  -2.104e-30]])

    >>> import matplotlib.pyplot as plt
    >>> plt.subplot(3, 1, 1)
    >>> librosa.display.specshow(mfcc)
    >>> plt.title('MFCC')
    >>> plt.colorbar()
    >>> plt.subplot(3, 1, 2)
    >>> librosa.display.specshow(mfcc_delta)
    >>> plt.title(r'MFCC-$\Delta$')
    >>> plt.colorbar()
    >>> plt.subplot(3, 1, 3)
    >>> librosa.display.specshow(mfcc_delta2, x_axis='time')
    >>> plt.title(r'MFCC-$\Delta^2$')
    >>> plt.colorbar()
    >>> plt.tight_layout()


@cache(level=<NUM_LIT>)<EOL>def stack_memory(data, n_steps=<NUM_LIT:2>, delay=<NUM_LIT:1>, **kwargs):

if n_steps < <NUM_LIT:1>:<EOL><INDENT>raise ParameterError('<STR_LIT>')<EOL><DEDENT>if delay == <NUM_LIT:0>:<EOL><INDENT>raise ParameterError('<STR_LIT>')<EOL><DEDENT>data = np.atleast_2d(data)<EOL>t = data.shape[<NUM_LIT:1>]<EOL>kwargs.setdefault('<STR_LIT>', '<STR_LIT>')<EOL>if kwargs['<STR_LIT>'] == '<STR_LIT>':<EOL><INDENT>kwargs.setdefault('<STR_LIT>', [<NUM_LIT:0>])<EOL><DEDENT>if delay > <NUM_LIT:0>:<EOL><INDENT>padding = (int((n_steps - <NUM_LIT:1>) * delay), <NUM_LIT:0>)<EOL><DEDENT>else:<EOL><INDENT>padding = (<NUM_LIT:0>, int((n_steps - <NUM_LIT:1>) * -delay))<EOL><DEDENT>data = np.pad(data, [(<NUM_LIT:0>, <NUM_LIT:0>), padding], **kwargs)<EOL>history = data<EOL>for i in range(<NUM_LIT:1>, n_steps):<EOL><INDENT>history = np.vstack([np.roll(data, -i * delay, axis=<NUM_LIT:1>), history])<EOL><DEDENT>if delay > <NUM_LIT:0>:<EOL><INDENT>history = history[:, :t]<EOL><DEDENT>else:<EOL><INDENT>history = history[:, -t:]<EOL><DEDENT>return np.ascontiguousarray(history.T).T<EOL>

Short-term history embedding: vertically concatenate a data
    vector or matrix with delayed copies of itself.

    Each column `data[:, i]` is mapped to::

        data[:, i] ->  [data[:, i],
                        data[:, i - delay],
                        ...
                        data[:, i - (n_steps-1)*delay]]

    For columns `i < (n_steps - 1) * delay` , the data will be padded.
    By default, the data is padded with zeros, but this behavior can be
    overridden by supplying additional keyword arguments which are passed
    to `np.pad()`.

    Parameters
    ----------
    data : np.ndarray [shape=(t,) or (d, t)]
        Input data matrix.  If `data` is a vector (`data.ndim == 1`),
        it will be interpreted as a row matrix and reshaped to `(1, t)`.

    n_steps : int > 0 [scalar]
        embedding dimension, the number of steps back in time to stack

    delay : int != 0 [scalar]
        the number of columns to step.

        Positive values embed from the past (previous columns).

        Negative values embed from the future (subsequent columns).

    kwargs : additional keyword arguments
      Additional arguments to pass to `np.pad`.

    Returns
    -------
    data_history : np.ndarray [shape=(m * d, t)]
        data augmented with lagged copies of itself,
        where `m == n_steps - 1`.

    Notes
    -----
    This function caches at level 40.

    Examples
    --------
    Keep two steps (current and previous)

    >>> data = np.arange(-3, 3)
    >>> librosa.feature.stack_memory(data)
    array([[-3, -2, -1,  0,  1,  2],
           [ 0, -3, -2, -1,  0,  1]])

    Or three steps

    >>> librosa.feature.stack_memory(data, n_steps=3)
    array([[-3, -2, -1,  0,  1,  2],
           [ 0, -3, -2, -1,  0,  1],
           [ 0,  0, -3, -2, -1,  0]])

    Use reflection padding instead of zero-padding

    >>> librosa.feature.stack_memory(data, n_steps=3, mode='reflect')
    array([[-3, -2, -1,  0,  1,  2],
           [-2, -3, -2, -1,  0,  1],
           [-1, -2, -3, -2, -1,  0]])

    Or pad with edge-values, and delay by 2

    >>> librosa.feature.stack_memory(data, n_steps=3, delay=2, mode='edge')
    array([[-3, -2, -1,  0,  1,  2],
           [-3, -3, -3, -2, -1,  0],
           [-3, -3, -3, -3, -3, -2]])

    Stack time-lagged beat-synchronous chroma edge padding

    >>> y, sr = librosa.load(librosa.util.example_audio_file())
    >>> chroma = librosa.feature.chroma_stft(y=y, sr=sr)
    >>> tempo, beats = librosa.beat.beat_track(y=y, sr=sr, hop_length=512)
    >>> beats = librosa.util.fix_frames(beats, x_min=0, x_max=chroma.shape[1])
    >>> chroma_sync = librosa.util.sync(chroma, beats)
    >>> chroma_lag = librosa.feature.stack_memory(chroma_sync, n_steps=3,
    ...                                           mode='edge')

    Plot the result

    >>> import matplotlib.pyplot as plt
    >>> beat_times = librosa.frames_to_time(beats, sr=sr, hop_length=512)
    >>> librosa.display.specshow(chroma_lag, y_axis='chroma', x_axis='time',
    ...                          x_coords=beat_times)
    >>> plt.yticks([0, 12, 24], ['Lag=0', 'Lag=1', 'Lag=2'])
    >>> plt.title('Time-lagged chroma')
    >>> plt.colorbar()
    >>> plt.tight_layout()


super(ZonesTests, self).tearDown()<EOL>register.clear()<EOL>

Clear the theme registry after each test


@classmethod<EOL><INDENT>def upload_file(cls, client, filename='<STR_LIT>'):<DEDENT>

obj = DispatchMediaTestMixin()<EOL>url = reverse('<STR_LIT>')<EOL>with open(obj.get_input_file('<STR_LIT>')) as test_file:<EOL><INDENT>data = {<EOL>'<STR_LIT:name>': filename,<EOL>'<STR_LIT:file>': test_file<EOL>}<EOL>response = client.post(url, data, format='<STR_LIT>')<EOL><DEDENT>return response<EOL>


obj = DispatchMediaTestMixin()<EOL>url = reverse('<STR_LIT>')<EOL>with open(obj.get_input_file('<STR_LIT>'), '<STR_LIT:rb>') as test_image:<EOL><INDENT>response = client.post(url, { '<STR_LIT>': test_image }, format='<STR_LIT>')<EOL><DEDENT>return response<EOL>

Upload an image that can be linked by galleries


@classmethod<EOL><INDENT>def _create_gallery_only(cls, id, attachments, client):<DEDENT>

url = reverse('<STR_LIT>')<EOL>data = {<EOL>'<STR_LIT:title>': '<STR_LIT>' % id,<EOL>'<STR_LIT>': attachments<EOL>}<EOL>return client.post(url, data, format='<STR_LIT>')<EOL>

Creates a gallery instance, but does not upload images


@classmethod<EOL><INDENT>def create_gallery(cls, id, client):<DEDENT>

image_1 = cls.create_image(client)<EOL>image_2 = cls.create_image(client)<EOL>attachment = [<EOL>{<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': image_1.data['<STR_LIT:id>']<EOL>},<EOL>{<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': image_2.data['<STR_LIT:id>']<EOL>}<EOL>]<EOL>return (cls._create_gallery_only(id, attachment, client), image_1, image_2)<EOL>

Create a gallery instance for further testing


@classmethod<EOL><INDENT>def create_person(cls, client, full_name='<STR_LIT>', image='<STR_LIT>', slug='<STR_LIT>', description='<STR_LIT>'):<DEDENT>

url = reverse('<STR_LIT>')<EOL>data = {<EOL>'<STR_LIT>': full_name,<EOL>'<STR_LIT:image>': image,<EOL>'<STR_LIT>': slug,<EOL>'<STR_LIT:description>': description<EOL>}<EOL>return client.post(url, data, format='<STR_LIT>')<EOL>

A helper method that creates a simple person object with the given attributes
        and returns the response


@classmethod<EOL><INDENT>def create_user(cls, client, email, full_name='<STR_LIT>', person=None, password='<STR_LIT>', permissions=None):<DEDENT>

person = person or cls.create_person(client, full_name).data['<STR_LIT:id>']<EOL>url = reverse('<STR_LIT>')<EOL>data = {<EOL>'<STR_LIT:email>' : email,<EOL>'<STR_LIT>' : person,<EOL>'<STR_LIT>': password,<EOL>'<STR_LIT>': password,<EOL>'<STR_LIT>': permissions<EOL>}<EOL>return client.post(url, data, format='<STR_LIT>')<EOL>

A helper method that creates a simple user object with the given attributes
and returns the response


@classmethod<EOL><INDENT>def create_topic(cls, client, name='<STR_LIT>'):<DEDENT>

data = {<EOL>'<STR_LIT:name>': name<EOL>}<EOL>url = reverse('<STR_LIT>')<EOL>return client.post(url, data, format='<STR_LIT>')<EOL>


@classmethod<EOL><INDENT>def create_invite(cls, client, email, person=None, permissions='<STR_LIT>'):<DEDENT>

if person is None:<EOL><INDENT>person = cls.create_person(client, full_name='<STR_LIT>')<EOL><DEDENT>url = reverse('<STR_LIT>')<EOL>data = {<EOL>'<STR_LIT:email>': email,<EOL>'<STR_LIT>': permissions,<EOL>'<STR_LIT>': person.data['<STR_LIT:id>']<EOL>}<EOL>return client.post(url, data, format='<STR_LIT>')<EOL>


try:<EOL><INDENT>zone = ThemeManager.Zones.get(zone_id)<EOL><DEDENT>except ZoneNotFound:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>try:<EOL><INDENT>return zone.widget.render(add_context=kwargs)<EOL><DEDENT>except (WidgetNotFound, AttributeError):<EOL><INDENT>pass<EOL><DEDENT>return '<STR_LIT>'<EOL>

Renders the contents of the zone with given zone_id.


self.data = data<EOL>


result = {}<EOL>for field in self.fields:<EOL><INDENT>result[field.name] = field.to_json(self.data.get(field.name))<EOL><DEDENT>return result<EOL>

Return JSON representation for this template


result = {}<EOL>for field in self.fields:<EOL><INDENT>result[field.name] = field.prepare_data(self.data.get(field.name))<EOL><DEDENT>return result<EOL>


return slug_re.match(slug)<EOL>

Uses Django's slug regex to test if id is valid


if not has_valid_id(widget):<EOL><INDENT>raise InvalidWidget("<STR_LIT>" % widget.__name__)<EOL><DEDENT>if not has_valid_name(widget):<EOL><INDENT>raise InvalidWidget("<STR_LIT>" % widget.__name__)<EOL><DEDENT>if not has_valid_template(widget):<EOL><INDENT>raise InvalidWidget("<STR_LIT>" % widget.__name__)<EOL><DEDENT>if not hasattr(widget, '<STR_LIT>') or not widget.zones:<EOL><INDENT>raise InvalidWidget("<STR_LIT>" % widget.__name__)<EOL><DEDENT>

Checks that the given widget contains the required fields


if not has_valid_id(zone):<EOL><INDENT>raise InvalidZone("<STR_LIT>" % zone.__name__)<EOL><DEDENT>if not has_valid_name(zone):<EOL><INDENT>raise InvalidZone("<STR_LIT>" % zone.__name__)<EOL><DEDENT>

Checks that the given zone contains the required fields


return isinstance(id, int) or is_valid_uuid(id)<EOL>

Return True if id is a valid integer or UUID, False otherwise.


if not isinstance(id, basestring):<EOL><INDENT>return False<EOL><DEDENT>try:<EOL><INDENT>val = UUID(id, version=<NUM_LIT:4>)<EOL><DEDENT>except ValueError:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>

Return True if id is a valid UUID, False otherwise.


raise NotImplementedError<EOL>


return data<EOL>

Returns JSON representation of field data


return data<EOL>

Prepares field data for use in a template


return [W() for W in self._widgets]<EOL>

Return the widgets compatible with this zone.


cls._widgets = []<EOL>

Clear all widgets registered with this zone.


(zone, created) = ZoneModel.objects.get_or_create(zone_id=self.id)<EOL>zone.widget_id = validated_data['<STR_LIT>']<EOL>zone.data = validated_data['<STR_LIT:data>']<EOL>for key in list(zone.data.keys()):<EOL><INDENT>if isinstance(zone.data[key], dict) and ('<STR_LIT:id>' in zone.data[key].keys()) and ('<STR_LIT:data>' in zone.data[key].keys()):<EOL><INDENT>zone.data[key]['<STR_LIT:data>'] = self.before_save(zone.data[key]['<STR_LIT:id>'], zone.data[key]['<STR_LIT:data>'])<EOL><DEDENT><DEDENT>zone.data = self.before_save(zone.widget_id, zone.data)<EOL>return zone.save()<EOL>


ZoneModel.objects.get(zone_id=self.id).delete()<EOL>


result = {}<EOL>for field in self.fields:<EOL><INDENT>result[field.name] = self.data.get(field.name)<EOL><DEDENT>return result<EOL>


Return JSON representation for this widget.


result = {}<EOL>for field in self.fields:<EOL><INDENT>data = self.data.get(field.name)<EOL>result[field.name] = field.prepare_data(data)<EOL><DEDENT>return result<EOL>


def render(self, data=None, add_context=None):

template = loader.get_template(self.template)<EOL>if not data:<EOL><INDENT>data = self.context(self.prepare_data())<EOL><DEDENT>if add_context is not None:<EOL><INDENT>for key, value in add_context.iteritems():<EOL><INDENT>if key in self.accepted_keywords:<EOL><INDENT>data[key] = value<EOL><DEDENT><DEDENT><DEDENT>return template.render(data)<EOL>


return data<EOL>

Optional method to add additional data to the deplate context before rendering.


return data<EOL>

Optional before-save hook that is called before widgets are saved.


invite = get_object_or_404(Invite.objects.all(), id=uuid)<EOL>if invite.expiration_date < timezone.now():<EOL><INDENT>invite.delete()<EOL>raise Http404('<STR_LIT>')<EOL><DEDENT>if request.method == '<STR_LIT:POST>':<EOL><INDENT>form = SignUpForm(request.POST)<EOL>if form.is_valid():<EOL><INDENT>user = form.save(commit=False)<EOL>user.email = invite.email<EOL>user.person = invite.person<EOL>user.save()<EOL>if invite.permissions == '<STR_LIT>':<EOL><INDENT>group = Group.objects.get(name='<STR_LIT>')<EOL>user.groups.add(group)<EOL><DEDENT>invite.delete()<EOL>return redirect('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>return render(<EOL>request,<EOL>'<STR_LIT>',<EOL>{<EOL>'<STR_LIT>': form,<EOL>'<STR_LIT:email>': invite.email<EOL>}<EOL>)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>form = SignUpForm()<EOL><DEDENT>return render(<EOL>request,<EOL>'<STR_LIT>',<EOL>{<EOL>'<STR_LIT>': form,<EOL>'<STR_LIT:email>': invite.email<EOL>}<EOL>)<EOL>

Handles requests to the user signup page.


context = {<EOL>'<STR_LIT>': settings.API_URL,<EOL>'<STR_LIT>': '<STR_LIT>' % dispatch.__version__,<EOL>'<STR_LIT>': '<STR_LIT>' % dispatch.__version__<EOL>}<EOL>return render_to_response('<STR_LIT>', context)<EOL>

Render HTML entry point for manager app.


authenticated_fields = getattr(self.Meta, '<STR_LIT>', [])<EOL>if not self.is_authenticated():<EOL><INDENT>for field in authenticated_fields:<EOL><INDENT>self.fields.pop(field)<EOL><DEDENT><DEDENT>

Hides authenticated_fields if request context is missing or
        user is not authenticated


request = self.context.get('<STR_LIT>')<EOL>if request:<EOL><INDENT>exclude = request.query_params.get('<STR_LIT>', None)<EOL>if exclude is None: return<EOL>excluded_fields = exclude.split('<STR_LIT:U+002C>')<EOL>for field in excluded_fields:<EOL><INDENT>self.fields.pop(field)<EOL><DEDENT><DEDENT>

Excludes fields that are included in the queryparameters


return ImageSerializer(instance).data<EOL>


return data['<STR_LIT>']<EOL>


return Image.objects.prefetch_related('<STR_LIT>').in_bulk(ids)<EOL>

Returns a dictionary of ids to Image instances with prefetched Authors


return ImageGallerySerializer(instance).data<EOL>


return data['<STR_LIT:id>']<EOL>


return ImageGallery.objects.prefetch_related('<STR_LIT>').in_bulk(ids)<EOL>

Returns a dictionary of ids to ImageGallery instances with prefetched Authors


return map(self.sanitize_block, content)<EOL>

Convert each block in `content` to its internal value before saving.


embed_type = block.get('<STR_LIT:type>', None)<EOL>data = block.get('<STR_LIT:data>', {})<EOL>serializer = self.serializers.get(embed_type, None)<EOL>if serializer is None:<EOL><INDENT>return block<EOL><DEDENT>block['<STR_LIT:data>'] = serializer.to_internal_value(data)<EOL>return block<EOL>

Santizes the data for the given block.
        If block has a matching embed serializer, use the `to_internal_value` method.


def queue_instance(self, embed_type, data):

serializer = self.serializers.get(embed_type, None)<EOL>if serializer is None:<EOL><INDENT>return<EOL><DEDENT>instance_id = serializer.get_id(data)<EOL>if embed_type not in self.ids:<EOL><INDENT>self.ids[embed_type] = []<EOL><DEDENT>self.ids[embed_type].append(instance_id)<EOL>

Queue an instance to be fetched from the database.


def load_instances(self, embed_type, ids):

serializer = self.serializers.get(embed_type, None)<EOL>if serializer is None:<EOL><INDENT>return<EOL><DEDENT>self.instances[embed_type] = serializer.fetch(ids)<EOL>

Fetch all queued instances of type `embed_type`, save results
        to `self.instances`


embed_type = block.get('<STR_LIT:type>', None)<EOL>data = block.get('<STR_LIT:data>', {})<EOL>serializer = self.serializers.get(embed_type, None)<EOL>if serializer is None:<EOL><INDENT>return block<EOL><DEDENT>try:<EOL><INDENT>instance_id = serializer.get_id(data)<EOL>instance = self.instances[embed_type][instance_id]<EOL>data[embed_type] = serializer.serialize(instance)<EOL><DEDENT>except:<EOL><INDENT>data[embed_type] = None<EOL><DEDENT>block['<STR_LIT:data>'] = data<EOL>return block<EOL>

Insert a fetched instance into embed block.


for block in content:<EOL><INDENT>self.queue_instance(block['<STR_LIT:type>'], block['<STR_LIT:data>'])<EOL><DEDENT>

Queue data to be loaded for each embed block.


for embed_type in self.ids.keys():<EOL><INDENT>self.load_instances(embed_type, self.ids[embed_type])<EOL><DEDENT>


return map(self.insert_instance, content)<EOL>

Insert loaded data into embed data blocks.


from dispatch.theme import ThemeManager<EOL>errors = {}<EOL>if data.get('<STR_LIT>') is not None:<EOL><INDENT>try:<EOL><INDENT>widget = ThemeManager.Widgets.get(data['<STR_LIT>'])<EOL><DEDENT>except WidgetNotFound as e:<EOL><INDENT>errors['<STR_LIT>'] = str(e)<EOL><DEDENT>else:<EOL><INDENT>for field in widget.fields:<EOL><INDENT>field_data = data['<STR_LIT:data>'].get(field.name)<EOL>if field_data is not None:<EOL><INDENT>try:<EOL><INDENT>field.validate(field_data)<EOL><DEDENT>except InvalidField as e:<EOL><INDENT>errors[field.name] = str(e)<EOL><DEDENT><DEDENT>elif field.required:<EOL><INDENT>errors[field.name] = '<STR_LIT>' % field.label<EOL><DEDENT><DEDENT><DEDENT><DEDENT>if errors:<EOL><INDENT>raise ValidationError(errors)<EOL><DEDENT>return data<EOL>


if not isinstance(data, list):<EOL><INDENT>data = [data]<EOL><DEDENT>for author in data:<EOL><INDENT>if '<STR_LIT>' not in author:<EOL><INDENT>raise ValidationError('<STR_LIT>')<EOL><DEDENT>if '<STR_LIT:type>' in author and not isinstance(author['<STR_LIT:type>'], basestring):<EOL><INDENT>raise ValidationError('<STR_LIT>')<EOL><DEDENT><DEDENT>

Raise a ValidationError if data does not match the author format.


<EOL>queryset = self.get_publishable_queryset()<EOL>queryset = queryset.select_related('<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>').prefetch_related(<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'<EOL>)<EOL>queryset = queryset.order_by('<STR_LIT>')<EOL>q = self.request.query_params.get('<STR_LIT:q>', None)<EOL>section = self.request.query_params.get('<STR_LIT>', None)<EOL>tags = self.request.query_params.getlist('<STR_LIT>', None)<EOL>author = self.request.query_params.get('<STR_LIT>', None)<EOL>if q is not None:<EOL><INDENT>queryset = queryset.filter(headline__icontains=q)<EOL><DEDENT>if section is not None:<EOL><INDENT>queryset = queryset.filter(section_id=section)<EOL><DEDENT>if tags is not None:<EOL><INDENT>for tag in tags:<EOL><INDENT>queryset = queryset.filter(tags__id=tag)<EOL><DEDENT><DEDENT>if author is not None:<EOL><INDENT>queryset = queryset.filter(authors__person_id=author)<EOL><DEDENT>return queryset<EOL>

Optionally restricts the returned articles by filtering against a `topic`
        query parameter in the URL.


<EOL>queryset = self.get_publishable_queryset()<EOL>queryset = queryset.order_by('<STR_LIT>')<EOL>q = self.request.query_params.get('<STR_LIT:q>')<EOL>if q:<EOL><INDENT>queryset = queryset.filter(title__icontains=q)<EOL><DEDENT>return queryset<EOL>

Only display unpublished content to authenticated users, filter by
        query parameter if present.


attr = super(NullBooleanField, self).get_attribute(instance)<EOL>return True if attr else False<EOL>

Overrides the default get_attribute method to convert None values to False.


try:<EOL><INDENT>integration = self.get(integration_id=integration_id)<EOL>return json.loads(integration.settings)<EOL><DEDENT>except (self.model.DoesNotExist, ValueError):<EOL><INDENT>return {}<EOL><DEDENT>

Return settings for given integration as a dictionary.


def update_settings(self, integration_id, settings):

(integration, created) = self.get_or_create(integration_id=integration_id)<EOL>try:<EOL><INDENT>current_settings = json.loads(integration.settings)<EOL><DEDENT>except ValueError:<EOL><INDENT>current_settings = {}<EOL><DEDENT>current_settings.update(settings)<EOL>integration.settings = json.dumps(current_settings)<EOL>integration.save()<EOL>


return self.filter(integration_id=integration_id).delete()<EOL>

Deletes all settings for given integration.


settings = Integration.objects.get_settings(cls.ID)<EOL>if not show_hidden:<EOL><INDENT>for field in cls.HIDDEN_FIELDS:<EOL><INDENT>settings.pop(field, None)<EOL><DEDENT><DEDENT>return settings<EOL>

Retrieves the settings for this integration as a dictionary.

Removes all hidden fields if show_hidden=False


return Integration.objects.update_settings(cls.ID, settings)<EOL>

Updates setting for this integration with the given name.


@classmethod<EOL><INDENT>def callback(cls, user, query):<DEDENT>

<EOL>settings = cls.get_settings(show_hidden=True)<EOL>fb = Facebook()<EOL>payload = {<EOL>'<STR_LIT>': settings['<STR_LIT>'],<EOL>'<STR_LIT>': settings['<STR_LIT>'],<EOL>'<STR_LIT:code>': query['<STR_LIT:code>'],<EOL>'<STR_LIT>': cls.REDIRECT_URI<EOL>}<EOL>try:<EOL><INDENT>fb.get_access_token(payload)<EOL>pages = fb.list_pages('<STR_LIT>')<EOL><DEDENT>except FacebookAPIError as e:<EOL><INDENT>raise IntegrationCallbackError(e.message)<EOL><DEDENT>return {<EOL>'<STR_LIT>': pages<EOL>}<EOL>

Receive OAuth callback request from Facebook.


authorTypeString = '<STR_LIT>'<EOL>aStringA = '<STR_LIT>'<EOL>aStringB = '<STR_LIT>'<EOL>aStringC = '<STR_LIT>'<EOL>aStringD = '<STR_LIT>'<EOL>authors = dict((k, list(v)) for k, v in groupby(self.authors.all(), lambda a: a.type))<EOL>for author in authors:<EOL><INDENT>if author == '<STR_LIT>':<EOL><INDENT>aStringA += '<STR_LIT>' + self.get_author_string(authors['<STR_LIT>'])<EOL><DEDENT>if author == '<STR_LIT>':<EOL><INDENT>aStringB += '<STR_LIT>' + self.get_author_string(authors['<STR_LIT>'])<EOL><DEDENT>if author == '<STR_LIT>':<EOL><INDENT>aStringC += '<STR_LIT>' + self.get_author_string(authors['<STR_LIT>'])<EOL><DEDENT>if author == '<STR_LIT>':<EOL><INDENT>aStringD += '<STR_LIT>' + self.get_author_string(authors['<STR_LIT>'])<EOL><DEDENT><DEDENT>if aStringA != '<STR_LIT>':<EOL><INDENT>authorTypeString += aStringA<EOL><DEDENT>if aStringB != '<STR_LIT>':<EOL><INDENT>authorTypeString += '<STR_LIT:U+002CU+0020>' + aStringB<EOL><DEDENT>if aStringC != '<STR_LIT>':<EOL><INDENT>authorTypeString += '<STR_LIT:U+002CU+0020>' + aStringC<EOL><DEDENT>if aStringD != '<STR_LIT>':<EOL><INDENT>authorTypeString += '<STR_LIT:U+002CU+0020>' + aStringD<EOL><DEDENT>return authorTypeString<EOL>

Returns list of authors as a comma-separated string
        sorted by author type (with 'and' before last author).


return self.get_author_string(True)<EOL>

Returns list of authors (including hyperlinks) as a
        comma-separated string (with 'and' before last author).


def render_node(html, node, index):<EOL><INDENT>"""<STR_LIT>"""<EOL>if node['<STR_LIT:type>'] == '<STR_LIT>':<EOL><INDENT>return html + '<STR_LIT>' % node['<STR_LIT:data>']<EOL><DEDENT>else:<EOL><INDENT>if node['<STR_LIT:type>'] == '<STR_LIT>':<EOL><INDENT>id = '<STR_LIT>' + str(<NUM_LIT:10> + index) + '<STR_LIT:->' + str(article_id)<EOL>dfp_type = '<STR_LIT>' + str(index + <NUM_LIT:1>)<EOL>size = '<STR_LIT>'<EOL>if node['<STR_LIT:data>'] == '<STR_LIT>':<EOL><INDENT>size = '<STR_LIT>'<EOL><DEDENT>newString = '<STR_LIT>' + id + '<STR_LIT>' + size + '<STR_LIT>' + dfp_type + '<STR_LIT>'<EOL>return html + '<STR_LIT>' % newString<EOL><DEDENT>try:<EOL><INDENT>if node['<STR_LIT:type>'] == '<STR_LIT>':<EOL><INDENT>node['<STR_LIT:type>'] = '<STR_LIT>'<EOL>node['<STR_LIT:data>']['<STR_LIT:data>'] = node['<STR_LIT:data>']<EOL><DEDENT>return html + embeds.render(node['<STR_LIT:type>'], node['<STR_LIT:data>'])<EOL><DEDENT>except EmbedException:<EOL><INDENT>return html<EOL><DEDENT><DEDENT><DEDENT>html = '<STR_LIT>'<EOL>index = <NUM_LIT:0><EOL>for node in content:<EOL><INDENT>html = render_node(html, node, index)<EOL>if (node['<STR_LIT:type>'] == '<STR_LIT>'):<EOL><INDENT>index += <NUM_LIT:1><EOL><DEDENT><DEDENT>return mark_safe(html)<EOL>


def render_node(node):<EOL><INDENT>"""<STR_LIT>"""<EOL>if node['<STR_LIT:type>'] == '<STR_LIT>':<EOL><INDENT>return node<EOL><DEDENT>else:<EOL><INDENT>return {<EOL>'<STR_LIT:type>': node['<STR_LIT:type>'],<EOL>'<STR_LIT:data>': embeds.to_json(node['<STR_LIT:type>'], node['<STR_LIT:data>'])<EOL>}<EOL><DEDENT><DEDENT>return map(render_node, content)<EOL>


if '<STR_LIT>' in kwargs:<EOL><INDENT>kwargs['<STR_LIT>'] = kwargs['<STR_LIT>']<EOL>kwargs['<STR_LIT>'] = True<EOL>del kwargs['<STR_LIT>']<EOL><DEDENT>"""<STR_LIT>"""<EOL>if '<STR_LIT>' in kwargs:<EOL><INDENT>request = kwargs['<STR_LIT>']<EOL>version = request.GET.get('<STR_LIT:version>', None)<EOL>preview_id = request.GET.get('<STR_LIT>', None)<EOL>if (version is not None) and (preview_id is not None):<EOL><INDENT>kwargs['<STR_LIT>'] = version<EOL>kwargs['<STR_LIT>'] = preview_id<EOL>del kwargs['<STR_LIT>']<EOL><DEDENT>del kwargs['<STR_LIT>']<EOL><DEDENT>return super(PublishableManager, self).get(*args, **kwargs)<EOL>

Get the latest article with the given primary key.


return content_to_html(self.content, self.id)<EOL>


@transaction.atomic<EOL><INDENT>def save(self, revision=True, *args, **kwargs):<DEDENT>

if revision:<EOL><INDENT>self.head = True<EOL>self.revision_id += <NUM_LIT:1><EOL>previous_revision = self.get_previous_revision()<EOL>if not self.is_parent():<EOL><INDENT>type(self).objects.filter(parent=self.parent, head=True).update(head=None)<EOL>self.pk = None<EOL>self.id = None<EOL>self.is_published = None<EOL><DEDENT><DEDENT>if not self.created_at:<EOL><INDENT>self.created_at = timezone.now()<EOL>self.updated_at = timezone.now()<EOL><DEDENT>if revision:<EOL><INDENT>self.updated_at = timezone.now()<EOL><DEDENT>super(Publishable, self).save(*args, **kwargs)<EOL>if not self.parent:<EOL><INDENT>self.parent = self<EOL>super(Publishable, self).save(update_fields=['<STR_LIT>'])<EOL><DEDENT>if revision:<EOL><INDENT>type(self).objects.filter(parent=self.parent).update(latest_version=self.revision_id)<EOL>self.latest_version = self.revision_id<EOL><DEDENT>return self<EOL>

Handles the saving/updating of a Publishable instance.

Arguments:
revision - if True, a new version of this Publishable will be created.


attachment = self.featured_image<EOL>if data is None:<EOL><INDENT>if attachment:<EOL><INDENT>attachment.delete()<EOL><DEDENT>self.featured_image = None<EOL>return<EOL><DEDENT>if data['<STR_LIT>'] is None:<EOL><INDENT>if attachment:<EOL><INDENT>attachment.delete()<EOL><DEDENT>self.featured_image = None<EOL>return<EOL><DEDENT>if not attachment:<EOL><INDENT>attachment = ImageAttachment()<EOL><DEDENT>attachment.image_id = data.get('<STR_LIT>', attachment.image_id)<EOL>attachment.caption = data.get('<STR_LIT>', None)<EOL>attachment.credit = data.get('<STR_LIT>', None)<EOL>instance_type = str(type(self)).lower()<EOL>setattr(attachment, instance_type, self)<EOL>attachment.save()<EOL>self.featured_image = attachment<EOL>

Handles saving the featured image.

If data is None, the featured image will be removed.

`data` should be dictionary with the following format:
  {
    'image_id': int,
    'caption': str,
    'credit': str
  }


return "<STR_LIT>" % (settings.BASE_URL, self.section.slug, self.slug)<EOL>


return self.parent.subsection<EOL>

Returns the subsection set in the parent article


Article.objects.filter(parent_id=self.parent.id).update(subsection_id=subsection_id)<EOL>

Save the subsection to the parent article


return "<STR_LIT>" % (settings.BASE_URL, self.slug)<EOL>


return self.get_extension() in self.GIF_FORMATS<EOL>


return os.path.basename(self.img.name)<EOL>


return os.path.splitext(self.img.name)[<NUM_LIT:0>]<EOL>

Returns the filename without its extension.


ext = os.path.splitext(self.img.name)[<NUM_LIT:1>]<EOL>if ext:<EOL><INDENT>return ext[<NUM_LIT:1>:]<EOL><DEDENT>return ext<EOL>


return settings.MEDIA_URL + str(self.img)<EOL>


if self.is_gif():<EOL><INDENT>return self.get_absolute_url()<EOL><DEDENT>return '<STR_LIT>' % (settings.MEDIA_URL, self.get_name(), '<STR_LIT>')<EOL>


return '<STR_LIT>' % (settings.MEDIA_URL, self.get_name(), self.THUMBNAIL_SIZE)<EOL>


is_new = self.pk is None<EOL>if is_new:<EOL><INDENT>self.img.name = self.img.name.lower()<EOL><DEDENT>super(Image, self).save(**kwargs)<EOL>if is_new and self.img:<EOL><INDENT>data = self.img.read()<EOL>if not data:<EOL><INDENT>return<EOL><DEDENT>image = Img.open(StringIO.StringIO(data))<EOL>self.width, self.height = image.size<EOL>super(Image, self).save()<EOL>name = self.get_name()<EOL>ext = self.get_extension()<EOL>for size in self.SIZES.keys():<EOL><INDENT>self.save_thumbnail(image, self.SIZES[size], name, size, ext)<EOL><DEDENT><DEDENT>

Custom save method to process thumbnails and save image dimensions.


def save_thumbnail(self, image, size, name, label, file_type):

width, height = size<EOL>(imw, imh) = image.size<EOL>if (imw > width) or (imh > height):<EOL><INDENT>image.thumbnail(size, Img.ANTIALIAS)<EOL><DEDENT>name = "<STR_LIT>" % (name, label)<EOL>if file_type in self.JPG_FORMATS:<EOL><INDENT>file_type = '<STR_LIT>'<EOL><DEDENT>image_io = StringIO.StringIO()<EOL>image.save(image_io, format=file_type, quality=<NUM_LIT>)<EOL>thumb_file = InMemoryUploadedFile(image_io, None, name, '<STR_LIT>', image_io.len, None)<EOL>default_storage.save(name, thumb_file)<EOL>

Processes and saves a resized thumbnail version of the image.


return settings.MEDIA_URL + str(self.file)<EOL>


return PollVote.objects.filter(answer=self).count()<EOL>

Return the number of votes for this answer


return u'<STR_LIT>'.join(tag(tagname, item) for item in contents)<EOL>

Returns the HTML produced from enclosing each item in
    `contents` in a tag of type `tagname`


if self.image:<EOL><INDENT>return settings.MEDIA_URL + str(self.image)<EOL><DEDENT>


permissions = '<STR_LIT>'<EOL>if self.groups.filter(name='<STR_LIT>').exists() or self.is_superuser:<EOL><INDENT>permissions = '<STR_LIT>'<EOL><DEDENT>return permissions<EOL>


group = Group.objects.get(name='<STR_LIT>')<EOL>if permissions == '<STR_LIT>':<EOL><INDENT>self.groups.add(group)<EOL><DEDENT>else:<EOL><INDENT>self.groups.remove(group)<EOL><DEDENT>


return (jd - T0) * S_PER_DAY<EOL>

Convert a Julian Date to a number of seconds since J2000.


return T0 + seconds / S_PER_DAY<EOL>

Convert a number of seconds since J2000 to a Julian Date.


return name if name.startswith(('<STR_LIT:1>', '<STR_LIT>', '<STR_LIT>')) else name.title()<EOL>

Title-case target `name` if it looks safe to do so.


return cls(DAF(open(path, '<STR_LIT:rb>')))<EOL>

Open the file at `path` and return an SPK instance.


self.daf.file.close()<EOL>for segment in self.segments:<EOL><INDENT>if hasattr(segment, '<STR_LIT>'):<EOL><INDENT>del segment._data<EOL><DEDENT><DEDENT>self.daf._array = None<EOL>self.daf._map = None<EOL>


return self.pairs[key]<EOL>

Given (center, target) integers, return the last matching segment.


return self.daf.comments()<EOL>


center = titlecase(target_names.get(self.center, '<STR_LIT>'))<EOL>target = titlecase(target_names.get(self.target, '<STR_LIT>'))<EOL>text = ('<STR_LIT>'<EOL>'<STR_LIT>'.format(self, center, target))<EOL>if verbose:<EOL><INDENT>text += ('<STR_LIT>'<EOL>.format(self, self.source.decode('<STR_LIT:ascii>')))<EOL><DEDENT>return text<EOL>

Return a textual description of the segment.


def compute(self, tdb, tdb2=<NUM_LIT:0.0>):

for position in self.generate(tdb, tdb2):<EOL><INDENT>return position<EOL><DEDENT>

Compute the component values for the time `tdb` plus `tdb2`.


def compute_and_differentiate(self, tdb, tdb2=<NUM_LIT:0.0>):

return tuple(self.generate(tdb, tdb2))<EOL>

Compute components and differentials for time `tdb` plus `tdb2`.


if self.data_type == <NUM_LIT:2>:<EOL><INDENT>component_count = <NUM_LIT:3><EOL><DEDENT>elif self.data_type == <NUM_LIT:3>:<EOL><INDENT>component_count = <NUM_LIT:6><EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>init, intlen, rsize, n = self.daf.read_array(self.end_i - <NUM_LIT:3>, self.end_i)<EOL>initial_epoch = jd(init)<EOL>interval_length = intlen / S_PER_DAY<EOL>coefficient_count = int(rsize - <NUM_LIT:2>) // component_count<EOL>coefficients = self.daf.map_array(self.start_i, self.end_i - <NUM_LIT:4>)<EOL>coefficients.shape = (int(n), int(rsize))<EOL>coefficients = coefficients[:,<NUM_LIT:2>:]  <EOL>coefficients.shape = (int(n), component_count, coefficient_count)<EOL>coefficients = rollaxis(coefficients, <NUM_LIT:1>)<EOL>return initial_epoch, interval_length, coefficients<EOL>

Map the coefficients into memory using a NumPy array.


scalar = not getattr(tdb, '<STR_LIT>', <NUM_LIT:0>) and not getattr(tdb2, '<STR_LIT>', <NUM_LIT:0>)<EOL>if scalar:<EOL><INDENT>tdb = array((tdb,))<EOL><DEDENT>data = self._data<EOL>if data is None:<EOL><INDENT>self._data = data = self._load()<EOL><DEDENT>initial_epoch, interval_length, coefficients = data<EOL>component_count, n, coefficient_count = coefficients.shape<EOL>index, offset = divmod((tdb - initial_epoch) + tdb2, interval_length)<EOL>index = index.astype(int)<EOL>if (index < <NUM_LIT:0>).any() or (index > n).any():<EOL><INDENT>final_epoch = initial_epoch + interval_length * n<EOL>raise ValueError('<STR_LIT>'<EOL>% (initial_epoch, final_epoch))<EOL><DEDENT>omegas = (index == n)<EOL>index[omegas] -= <NUM_LIT:1><EOL>offset[omegas] += interval_length<EOL>coefficients = coefficients[:,index]<EOL>T = empty((coefficient_count, len(index)))<EOL>T[<NUM_LIT:0>] = <NUM_LIT:1.0><EOL>T[<NUM_LIT:1>] = t1 = <NUM_LIT> * offset / interval_length - <NUM_LIT:1.0><EOL>twot1 = t1 + t1<EOL>for i in range(<NUM_LIT:2>, coefficient_count):<EOL><INDENT>T[i] = twot1 * T[i-<NUM_LIT:1>] - T[i-<NUM_LIT:2>]<EOL><DEDENT>components = (T.T * coefficients).sum(axis=<NUM_LIT:2>)<EOL>if scalar:<EOL><INDENT>components = components[:,<NUM_LIT:0>]<EOL><DEDENT>yield components<EOL>dT = empty_like(T)<EOL>dT[<NUM_LIT:0>] = <NUM_LIT:0.0><EOL>dT[<NUM_LIT:1>] = <NUM_LIT:1.0><EOL>if coefficient_count > <NUM_LIT:2>:<EOL><INDENT>dT[<NUM_LIT:2>] = twot1 + twot1<EOL>for i in range(<NUM_LIT:3>, coefficient_count):<EOL><INDENT>dT[i] = twot1 * dT[i-<NUM_LIT:1>] - dT[i-<NUM_LIT:2>] + T[i-<NUM_LIT:1>] + T[i-<NUM_LIT:1>]<EOL><DEDENT><DEDENT>dT *= <NUM_LIT><EOL>dT /= interval_length<EOL>rates = (dT.T * coefficients).sum(axis=<NUM_LIT:2>)<EOL>if scalar:<EOL><INDENT>rates = rates[:,<NUM_LIT:0>]<EOL><DEDENT>yield rates<EOL>

Generate components and differentials for time `tdb` plus `tdb2`.

        Most uses will simply want to call the `compute()` method or the
        `compute_differentials()` method, for convenience.  But in those
        cases (see Skyfield) where you want to compute a position and
        examine it before deciding whether to proceed with the velocity,
        but without losing all of the work that it took to get to that
        point, this generator lets you get them as two separate steps.


if target == <NUM_LIT:3>:<EOL><INDENT>p1, v1 = spk[<NUM_LIT:0>,<NUM_LIT:3>].compute_and_differentiate(jed)<EOL>p2, v2 = spk[<NUM_LIT:3>,<NUM_LIT>].compute_and_differentiate(jed)<EOL>p = p1 + p2<EOL>v = v1 + v2<EOL><DEDENT>elif target == <NUM_LIT:10>:<EOL><INDENT>p1, v1 = spk[<NUM_LIT:0>,<NUM_LIT:3>].compute_and_differentiate(jed)<EOL>p2, v2 = spk[<NUM_LIT:3>,<NUM_LIT>].compute_and_differentiate(jed)<EOL>p = p1 + p2<EOL>v = v1 + v2<EOL><DEDENT>elif target == <NUM_LIT:11>:<EOL><INDENT>p, v = spk[<NUM_LIT:0>,<NUM_LIT:10>].compute_and_differentiate(jed)<EOL><DEDENT>elif target == <NUM_LIT:12>:<EOL><INDENT>return np.zeros((<NUM_LIT:6>,))  <EOL><DEDENT>elif target == <NUM_LIT>:<EOL><INDENT>p, v = spk[<NUM_LIT:0>,<NUM_LIT:3>].compute_and_differentiate(jed)<EOL><DEDENT>else:<EOL><INDENT>p, v = spk[<NUM_LIT:0>,target].compute_and_differentiate(jed)<EOL><DEDENT>return np.concatenate((p, v))<EOL>

Compute position given a JPL test file target integer identifier.


return T0 + seconds / S_PER_DAY<EOL>


Title-case body `name` if it looks safe to do so.


Open the file at `path` and return a binary PCK instance.


self.daf.file.close()<EOL>for segment in self.segments:<EOL><INDENT>if hasattr(segment, '<STR_LIT>'):<EOL><INDENT>del segment._data<EOL><DEDENT><DEDENT>


body = titlecase(target_names.get(self.body, '<STR_LIT>'))<EOL>text = ('<STR_LIT>'<EOL>'<STR_LIT>'.format(self, body))<EOL>if verbose:<EOL><INDENT>text += ('<STR_LIT>'<EOL>.format(self, self.source.decode('<STR_LIT:ascii>')))<EOL><DEDENT>return text<EOL>


if self.data_type == <NUM_LIT:2>:<EOL><INDENT>component_count = <NUM_LIT:3><EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>init, intlen, rsize, n = self.daf.read_array(self.end_i - <NUM_LIT:3>, self.end_i)<EOL>initial_epoch = jd(init)<EOL>interval_length = intlen / S_PER_DAY<EOL>coefficient_count = int(rsize - <NUM_LIT:2>) // component_count<EOL>coefficients = self.daf.map_array(self.start_i, self.end_i - <NUM_LIT:4>)<EOL>coefficients.shape = (int(n), int(rsize))<EOL>coefficients = coefficients[:,<NUM_LIT:2>:]  <EOL>coefficients.shape = (int(n), component_count, coefficient_count)<EOL>coefficients = rollaxis(coefficients, <NUM_LIT:1>)<EOL>return initial_epoch, interval_length, coefficients<EOL>


def compute(self, tdb, tdb2, derivative=True):

scalar = not getattr(tdb, '<STR_LIT>', <NUM_LIT:0>) and not getattr(tdb2, '<STR_LIT>', <NUM_LIT:0>)<EOL>if scalar:<EOL><INDENT>tdb = array((tdb,))<EOL><DEDENT>data = self._data<EOL>if data is None:<EOL><INDENT>self._data = data = self._load()<EOL><DEDENT>initial_epoch, interval_length, coefficients = data<EOL>component_count, n, coefficient_count = coefficients.shape<EOL>index, offset = divmod((tdb - initial_epoch) + tdb2, interval_length)<EOL>index = index.astype(int)<EOL>if (index < <NUM_LIT:0>).any() or (index > n).any():<EOL><INDENT>final_epoch = initial_epoch + interval_length * n<EOL>raise ValueError('<STR_LIT>'<EOL>% (initial_epoch, final_epoch))<EOL><DEDENT>omegas = (index == n)<EOL>index[omegas] -= <NUM_LIT:1><EOL>offset[omegas] += interval_length<EOL>coefficients = coefficients[:,index]<EOL>T = empty((coefficient_count, len(index)))<EOL>T[<NUM_LIT:0>] = <NUM_LIT:1.0><EOL>T[<NUM_LIT:1>] = t1 = <NUM_LIT> * offset / interval_length - <NUM_LIT:1.0><EOL>twot1 = t1 + t1<EOL>for i in range(<NUM_LIT:2>, coefficient_count):<EOL><INDENT>T[i] = twot1 * T[i-<NUM_LIT:1>] - T[i-<NUM_LIT:2>]<EOL><DEDENT>components = (T.T * coefficients).sum(axis=<NUM_LIT:2>)<EOL>if scalar:<EOL><INDENT>components = components[:,<NUM_LIT:0>]<EOL><DEDENT>if not derivative:<EOL><INDENT>return components<EOL><DEDENT>dT = empty_like(T)<EOL>dT[<NUM_LIT:0>] = <NUM_LIT:0.0><EOL>dT[<NUM_LIT:1>] = <NUM_LIT:1.0><EOL>if coefficient_count > <NUM_LIT:2>:<EOL><INDENT>dT[<NUM_LIT:2>] = twot1 + twot1<EOL>for i in range(<NUM_LIT:3>, coefficient_count):<EOL><INDENT>dT[i] = twot1 * dT[i-<NUM_LIT:1>] - dT[i-<NUM_LIT:2>] + T[i-<NUM_LIT:1>] + T[i-<NUM_LIT:1>]<EOL><DEDENT><DEDENT>dT *= <NUM_LIT><EOL>dT /= interval_length<EOL>rates = (dT.T * coefficients).sum(axis=<NUM_LIT:2>)<EOL>if scalar:<EOL><INDENT>rates = rates[:,<NUM_LIT:0>]<EOL><DEDENT>return components, rates<EOL>

Generate angles and derivatives for time `tdb` plus `tdb2`.

        If ``derivative`` is true, return a tuple containing both the
        angle and its derivative; otherwise simply return the angles.


self.file.seek(n * K - K)<EOL>return self.file.read(K)<EOL>

Return record `n` as 1,024 bytes; records are indexed from 1.


self.file.seek(n * K - K)<EOL>return self.file.write(data)<EOL>

Write `data` to file record `n`; records are indexed from 1.


i, j = <NUM_LIT:8> * start - <NUM_LIT:8>, <NUM_LIT:8> * end<EOL>try:<EOL><INDENT>fileno = self.file.fileno()<EOL><DEDENT>except (AttributeError, io.UnsupportedOperation):<EOL><INDENT>fileno = None<EOL><DEDENT>if fileno is None:<EOL><INDENT>skip = <NUM_LIT:0><EOL>self.file.seek(i)<EOL>m = self.file.read(j - i)<EOL><DEDENT>else:<EOL><INDENT>skip = i % mmap.ALLOCATIONGRANULARITY<EOL>r = mmap.ACCESS_READ<EOL>m = mmap.mmap(fileno, length=j-i+skip, access=r, offset=i-skip)<EOL><DEDENT>if sys.version_info > (<NUM_LIT:3>,):<EOL><INDENT>m = memoryview(m)  <EOL><DEDENT>return m, skip<EOL>

Return a memory-map of the elements `start` through `end`.

        The memory map will offer the 8-byte double-precision floats
        ("elements") in the file from index `start` through to the index
        `end`, inclusive, both counting the first float as element 1.
        Memory maps must begin on a page boundary, so `skip` returns the
        number of extra bytes at the beginning of the return value.


record_numbers = range(<NUM_LIT:2>, self.fward)<EOL>if not record_numbers:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>data = b'<STR_LIT>'.join(self.read_record(n)[<NUM_LIT:0>:<NUM_LIT:1000>] for n in record_numbers)<EOL>try:<EOL><INDENT>return data[:data.find(b'<STR_LIT>')].decode('<STR_LIT:ascii>').replace('<STR_LIT>', '<STR_LIT:\n>')<EOL><DEDENT>except IndexError:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>except UnicodeDecodeError:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>

Return the text inside the comment area of the file.


f = self.file<EOL>f.seek(<NUM_LIT:8> * (start - <NUM_LIT:1>))<EOL>length = <NUM_LIT:1> + end - start<EOL>data = f.read(<NUM_LIT:8> * length)<EOL>return ndarray(length, self.endian + '<STR_LIT:d>', data)<EOL>

Return floats from `start` to `end` inclusive, indexed from 1.

        The entire range of floats is immediately read into memory from
        the file, making this efficient for small sequences of floats
        whose values are all needed immediately.


if self._array is None:<EOL><INDENT>self._map, skip = self.map_words(<NUM_LIT:1>, self.free - <NUM_LIT:1>)<EOL>assert skip == <NUM_LIT:0><EOL>self._array = ndarray(self.free - <NUM_LIT:1>, self.endian + '<STR_LIT:d>', self._map)<EOL><DEDENT>return self._array[start - <NUM_LIT:1> : end]<EOL>

Return floats from `start` to `end` inclusive, indexed from 1.

        Instead of pausing to load all of the floats into RAM, this
        routine creates a memory map which will load data from the file
        only as it is accessed, and then will let it expire back out to
        disk later.  This is very efficient for large data sets to which
        you need random access.


record_number = self.fward<EOL>unpack = self.summary_control_struct.unpack<EOL>while record_number:<EOL><INDENT>data = self.read_record(record_number)<EOL>next_number, previous_number, n_summaries = unpack(data[:<NUM_LIT>])<EOL>yield record_number, n_summaries, data<EOL>record_number = int(next_number)<EOL><DEDENT>

Yield (record_number, n_summaries, record_data) for each record.

        Readers will only use the second two values in each tuple.
        Writers can update the record using the `record_number`.


length = self.summary_length<EOL>step = self.summary_step<EOL>for record_number, n_summaries, summary_data in self.summary_records():<EOL><INDENT>name_data = self.read_record(record_number + <NUM_LIT:1>)<EOL>for i in range(<NUM_LIT:0>, int(n_summaries) * step, step):<EOL><INDENT>j = self.summary_control_struct.size + i<EOL>name = name_data[i:i+step].strip()<EOL>data = summary_data[j:j+length]<EOL>values = self.summary_struct.unpack(data)<EOL>yield name, values<EOL><DEDENT><DEDENT>

Yield (name, (value, value, ...)) for each summary in the file.


return self.map_array(summary_values[-<NUM_LIT:2>], summary_values[-<NUM_LIT:1>])<EOL>

Return the array of floats described by a summary.

        Instead of pausing to load all of the floats into RAM, this
        routine creates a memory map which will load data from the file
        only as it is accessed, and then will let it expire back out to
        disk later.  This is very efficient for large data sets to which
        you need random access.


def add_array(self, name, values, array):

f = self.file<EOL>scs = self.summary_control_struct<EOL>record_number = self.bward<EOL>data = bytearray(self.read_record(record_number))<EOL>next_record, previous_record, n_summaries = scs.unpack(data[:<NUM_LIT>])<EOL>if n_summaries < self.summaries_per_record:<EOL><INDENT>summary_record = record_number<EOL>name_record = summary_record + <NUM_LIT:1><EOL>data[:<NUM_LIT>] = scs.pack(next_record, previous_record, n_summaries + <NUM_LIT:1>)<EOL>self.write_record(summary_record, data)<EOL><DEDENT>else:<EOL><INDENT>summary_record = ((self.free - <NUM_LIT:1>) * <NUM_LIT:8> + <NUM_LIT>) // <NUM_LIT> + <NUM_LIT:1><EOL>name_record = summary_record + <NUM_LIT:1><EOL>free_record = summary_record + <NUM_LIT:2><EOL>n_summaries = <NUM_LIT:0><EOL>data[:<NUM_LIT>] = scs.pack(summary_record, previous_record, n_summaries)<EOL>self.write_record(record_number, data)<EOL>summaries = scs.pack(<NUM_LIT:0>, record_number, <NUM_LIT:1>).ljust(<NUM_LIT>, b'<STR_LIT>')<EOL>names = b'<STR_LIT>' * <NUM_LIT><EOL>self.write_record(summary_record, summaries)<EOL>self.write_record(name_record, names)<EOL>self.bward = summary_record<EOL>self.free = (free_record - <NUM_LIT:1>) * <NUM_LIT> // <NUM_LIT:8> + <NUM_LIT:1><EOL><DEDENT>start_word = self.free<EOL>f.seek((start_word - <NUM_LIT:1>) * <NUM_LIT:8>)<EOL>array = numpy_array(array)  <EOL>f.write(array.view())<EOL>end_word = f.tell() // <NUM_LIT:8><EOL>self.free = end_word + <NUM_LIT:1><EOL>self.write_file_record()<EOL>values = values[:self.nd + self.ni - <NUM_LIT:2>] + (start_word, end_word)<EOL>base = <NUM_LIT> * (summary_record - <NUM_LIT:1>)<EOL>offset = int(n_summaries) * self.summary_step<EOL>f.seek(base + scs.size + offset)<EOL>f.write(self.summary_struct.pack(*values))<EOL>f.seek(base + <NUM_LIT> + offset)<EOL>f.write(name[:self.summary_length].ljust(self.summary_step, b'<STR_LIT:U+0020>'))<EOL>

Add a new array to the DAF file.

        The summary will be initialized with the `name` and `values`,
        and will have its start word and end word fields set to point to
        where the `array` of floats has been appended to the file.


return os.path.join(self.dirpath, filename)<EOL>

[DEPRECATED] Compute the path to a particular file in the ephemeris.


s = self.sets.get(name)<EOL>if s is None:<EOL><INDENT>self.sets[name] = s = np.load(self.path('<STR_LIT>' % name))<EOL><DEDENT>return s<EOL>

[DEPRECATED] Load the polynomial series for `name` and return it.


def position(self, name, tdb, tdb2=<NUM_LIT:0.0>):

bundle = self.compute_bundle(name, tdb, tdb2)<EOL>return self.position_from_bundle(bundle)<EOL>

[DEPRECATED] Compute the position of `name` at time ``tdb [+ tdb2]``.

        The position is returned as a NumPy array ``[x y z]``.

        The barycentric dynamical time `tdb` argument should be a float.
        If there are many dates you want computed, then make `tdb` an
        array, which is more efficient than calling this method multiple
        times; the return value will be a two-dimensional array giving a
        row of values for each coordinate.

        For extra precision, the time can be split into two floats; a
        popular choice is to use `tdb` for the integer or half-integer
        date, and `tdb2` to hold the remaining fraction.

        Consult the `names` attribute of this ephemeris for the values
        of `name` it supports, such as ``'mars'`` or ``'earthmoon'``.


def position_and_velocity(self, name, tdb, tdb2=<NUM_LIT:0.0>):

bundle = self.compute_bundle(name, tdb, tdb2)<EOL>position = self.position_from_bundle(bundle)<EOL>velocity = self.velocity_from_bundle(bundle)<EOL>return position, velocity<EOL>

[DEPRECATED] Compute the position and velocity of `name` at ``tdb [+ tdb2]``.

        The position and velocity are returned in a 2-tuple::

            ([x y z], [xdot ydot zdot])

        The barycentric dynamical time `tdb` argument should be a float.
        If there are many dates you want computed, then make `tdb` an
        array, which is more efficient than calling this method multiple
        times; the return values will be two-dimensional arrays giving a
        row of values for each coordinate.

        For extra precision, the time can be split into two floats; a
        popular choice is to use `tdb` for the integer or half-integer
        date, and `tdb2` to hold the remaining fraction.

        Consult the `names` attribute of this ephemeris for the values
        of `name` it supports, such as ``'mars'`` or ``'earthmoon'``.


bundle = self.compute_bundle(name, tdb, <NUM_LIT:0.0>)<EOL>position = self.position_from_bundle(bundle)<EOL>velocity = self.velocity_from_bundle(bundle)<EOL>return np.concatenate((position, velocity))<EOL>

[DEPRECATED] Legacy routine that concatenates position and velocity vectors.

        This routine is deprecated.  Use the methods `position()` and
        `position_and_velocity()` instead.  This method follows the same
        calling convention, but incurs extra copy operations in order to
        return a single NumPy array::

            [x y z xdot ydot zdot]


def compute_bundle(self, name, tdb, tdb2=<NUM_LIT:0.0>):

input_was_scalar = getattr(tdb, '<STR_LIT>', ()) == ()<EOL>if input_was_scalar:<EOL><INDENT>tdb = np.array((tdb,))<EOL><DEDENT>coefficient_sets = self.load(name)<EOL>number_of_sets, axis_count, coefficient_count = coefficient_sets.shape<EOL>jalpha, jomega = self.jalpha, self.jomega<EOL>days_per_set = (jomega - jalpha) / number_of_sets<EOL>index, offset = divmod((tdb - jalpha) + tdb2, days_per_set)<EOL>index = index.astype(int)<EOL>if (index < <NUM_LIT:0>).any() or (number_of_sets < index).any():<EOL><INDENT>raise DateError('<STR_LIT>'<EOL>% (self.name, jalpha, jomega))<EOL><DEDENT>omegas = (index == number_of_sets)<EOL>index[omegas] -= <NUM_LIT:1><EOL>offset[omegas] += days_per_set<EOL>coefficients = np.rollaxis(coefficient_sets[index], <NUM_LIT:1>)<EOL>T = np.empty((coefficient_count, len(index)))<EOL>T[<NUM_LIT:0>] = <NUM_LIT:1.0><EOL>T[<NUM_LIT:1>] = t1 = <NUM_LIT> * offset / days_per_set - <NUM_LIT:1.0><EOL>twot1 = t1 + t1<EOL>for i in range(<NUM_LIT:2>, coefficient_count):<EOL><INDENT>T[i] = twot1 * T[i-<NUM_LIT:1>] - T[i-<NUM_LIT:2>]<EOL><DEDENT>bundle = coefficients, days_per_set, T, twot1<EOL>return bundle<EOL>

[DEPRECATED] Return a tuple of coefficients and parameters for `tdb`.

        The return value is a tuple that bundles together the
        coefficients and other Chebyshev intermediate values that are
        needed for the computation of either the position or velocity.
        The bundle can then be passed to either `position_from_bundle()`
        or `velocity_from_bundle()` to finish the computation.  See the
        package-level documentation for details; most users will simply
        call `position()` or `position_and_velocity()` instead.

        The barycentric dynamical time `tdb` argument should be a float.
        If there are many dates you want computed, then make `tdb` an
        array, which is more efficient than calling this method multiple
        times; the return values will be arrays providing a value for
        each time in `tdb`.

        For extra precision, the time can be split into two floats; a
        popular choice is to use `tdb` for the integer or half-integer
        date, and `tdb2` to hold the remaining fraction.

        Consult the `names` attribute of this ephemeris for the values
        of `name` it supports, such as ``'mars'`` or ``'earthmoon'``.


coefficients, days_per_set, T, twot1 = bundle<EOL>return (T.T * coefficients).sum(axis=<NUM_LIT:2>)<EOL>

[DEPRECATED] Return position, given the `coefficient_bundle()` return value.


coefficients, days_per_set, T, twot1 = bundle<EOL>coefficient_count = coefficients.shape[<NUM_LIT:2>]<EOL>dT = np.empty_like(T)<EOL>dT[<NUM_LIT:0>] = <NUM_LIT:0.0><EOL>dT[<NUM_LIT:1>] = <NUM_LIT:1.0><EOL>dT[<NUM_LIT:2>] = twot1 + twot1<EOL>for i in range(<NUM_LIT:3>, coefficient_count):<EOL><INDENT>dT[i] = twot1 * dT[i-<NUM_LIT:1>] - dT[i-<NUM_LIT:2>] + T[i-<NUM_LIT:1>] + T[i-<NUM_LIT:1>]<EOL><DEDENT>dT *= <NUM_LIT><EOL>dT /= days_per_set<EOL>return (dT.T * coefficients).sum(axis=<NUM_LIT:2>)<EOL>

[DEPRECATED] Return velocity, given the `coefficient_bundle()` return value.


def julian_day(year, month=<NUM_LIT:1>, day=<NUM_LIT:1>):

janfeb = month < <NUM_LIT:3><EOL>return (day<EOL>+ <NUM_LIT> * (year + <NUM_LIT> - janfeb) // <NUM_LIT:4><EOL>+ <NUM_LIT> * (month - <NUM_LIT:2> + janfeb * <NUM_LIT:12>) // <NUM_LIT:12><EOL>- <NUM_LIT:3> * ((year + <NUM_LIT> - janfeb) // <NUM_LIT:100>) // <NUM_LIT:4><EOL>- <NUM_LIT>)<EOL>

Given a proleptic Gregorian calendar date, return a Julian day int.


return s.replace('<STR_LIT:D>', '<STR_LIT:e>')<EOL>

Convert a string in 0.1D+01 FORTRAN notation into 0.1e+10.


<EOL>if os.path.exists("<STR_LIT>"):<EOL><INDENT>return os.path.abspath("<STR_LIT>")<EOL><DEDENT>if os.path.exists("<STR_LIT>"):<EOL><INDENT>return os.path.abspath("<STR_LIT>")<EOL><DEDENT>if os.path.isfile("<STR_LIT>"):<EOL><INDENT>curdir = os.path.abspath(os.getcwd())<EOL>while os.path.isfile(os.path.join(curdir, "<STR_LIT>")):<EOL><INDENT>curdir = os.path.abspath(os.path.join(curdir, "<STR_LIT:..>"))<EOL>if os.path.isfile(os.path.join(curdir, "<STR_LIT>")):<EOL><INDENT>return os.path.join(curdir, "<STR_LIT>")<EOL><DEDENT>if os.path.isfile(os.path.join(curdir, "<STR_LIT>")):<EOL><INDENT>return os.path.join(curdir, "<STR_LIT>")<EOL><DEDENT><DEDENT><DEDENT>if "<STR_LIT>" in os.environ and os.path.exists(os.environ["<STR_LIT>"]):<EOL><INDENT>pylintrc = os.environ["<STR_LIT>"]<EOL><DEDENT>else:<EOL><INDENT>user_home = os.path.expanduser("<STR_LIT>")<EOL>if user_home in ("<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>pylintrc = "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>pylintrc = os.path.join(user_home, "<STR_LIT>")<EOL>if not os.path.isfile(pylintrc):<EOL><INDENT>pylintrc = os.path.join(user_home, "<STR_LIT>", "<STR_LIT>")<EOL><DEDENT><DEDENT><DEDENT>if not os.path.isfile(pylintrc):<EOL><INDENT>if os.path.isfile("<STR_LIT>"):<EOL><INDENT>pylintrc = "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>pylintrc = None<EOL><DEDENT><DEDENT>return pylintrc<EOL>

search the pylint rc file and return its path if it find it, else None


def _validate(value, optdict, name="<STR_LIT>"):

try:<EOL><INDENT>_type = optdict["<STR_LIT:type>"]<EOL><DEDENT>except KeyError:<EOL><INDENT>return value<EOL><DEDENT>return _call_validator(_type, optdict, name, value)<EOL>

return a validated value for an option according to its type

    optional argument name is only used for error message formatting


if self.parser is None or not self.default_tag:<EOL><INDENT>return option.help<EOL><DEDENT>optname = option._long_opts[<NUM_LIT:0>][<NUM_LIT:2>:]<EOL>try:<EOL><INDENT>provider = self.parser.options_manager._all_options[optname]<EOL><DEDENT>except KeyError:<EOL><INDENT>value = None<EOL><DEDENT>else:<EOL><INDENT>optdict = provider.get_option_def(optname)<EOL>optname = provider.option_attrname(optname, optdict)<EOL>value = getattr(provider.config, optname, optdict)<EOL>value = utils._format_option_value(optdict, value)<EOL><DEDENT>if value is optparse.NO_DEFAULT or not value:<EOL><INDENT>value = self.NO_DEFAULT_VALUE<EOL><DEDENT>return option.help.replace(self.default_tag, str(value))<EOL>

Patch OptionParser.expand_default with custom behaviour

    This will handle defaults to avoid overriding values in the
    configuration file.


if opt not in self._long_opt:<EOL><INDENT>raise optparse.BadOptionError(opt)<EOL><DEDENT>return opt<EOL>


def register_options_provider(self, provider, own_group=True):

assert provider.priority <= <NUM_LIT:0>, "<STR_LIT>"<EOL>for i in range(len(self.options_providers)):<EOL><INDENT>if provider.priority > self.options_providers[i].priority:<EOL><INDENT>self.options_providers.insert(i, provider)<EOL>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.options_providers.append(provider)<EOL><DEDENT>non_group_spec_options = [<EOL>option for option in provider.options if "<STR_LIT>" not in option[<NUM_LIT:1>]<EOL>]<EOL>groups = getattr(provider, "<STR_LIT>", ())<EOL>if own_group and non_group_spec_options:<EOL><INDENT>self.add_option_group(<EOL>provider.name.upper(),<EOL>provider.__doc__,<EOL>non_group_spec_options,<EOL>provider,<EOL>)<EOL><DEDENT>else:<EOL><INDENT>for opt, optdict in non_group_spec_options:<EOL><INDENT>self.add_optik_option(provider, self.cmdline_parser, opt, optdict)<EOL><DEDENT><DEDENT>for gname, gdoc in groups:<EOL><INDENT>gname = gname.upper()<EOL>goptions = [<EOL>option<EOL>for option in provider.options<EOL>if option[<NUM_LIT:1>].get("<STR_LIT>", "<STR_LIT>").upper() == gname<EOL>]<EOL>self.add_option_group(gname, gdoc, goptions, provider)<EOL><DEDENT>


def optik_option(self, provider, opt, optdict):

optdict = copy.copy(optdict)<EOL>if "<STR_LIT:action>" in optdict:<EOL><INDENT>self._nocallback_options[provider] = opt<EOL><DEDENT>else:<EOL><INDENT>optdict["<STR_LIT:action>"] = "<STR_LIT>"<EOL>optdict["<STR_LIT>"] = self.cb_set_provider_option<EOL><DEDENT>if "<STR_LIT:default>" in optdict:<EOL><INDENT>if (<EOL>"<STR_LIT>" in optdict<EOL>and optdict.get("<STR_LIT:default>") is not None<EOL>and optdict["<STR_LIT:action>"] not in ("<STR_LIT:store_true>", "<STR_LIT>")<EOL>):<EOL><INDENT>optdict["<STR_LIT>"] += "<STR_LIT>"<EOL><DEDENT>del optdict["<STR_LIT:default>"]<EOL><DEDENT>args = ["<STR_LIT>" + str(opt)]<EOL>if "<STR_LIT>" in optdict:<EOL><INDENT>self._short_options[optdict["<STR_LIT>"]] = opt<EOL>args.append("<STR_LIT:->" + optdict["<STR_LIT>"])<EOL>del optdict["<STR_LIT>"]<EOL><DEDENT>for key in list(optdict.keys()):<EOL><INDENT>if key not in self._optik_option_attrs:<EOL><INDENT>optdict.pop(key)<EOL><DEDENT><DEDENT>return args, optdict<EOL>

get our personal option definition and return a suitable form for
        use with optik/optparse


def cb_set_provider_option(self, option, opt, value, parser):

if opt.startswith("<STR_LIT>"):<EOL><INDENT>opt = opt[<NUM_LIT:2>:]<EOL><DEDENT>else:<EOL><INDENT>opt = self._short_options[opt[<NUM_LIT:1>:]]<EOL><DEDENT>if value is None:<EOL><INDENT>value = <NUM_LIT:1><EOL><DEDENT>self.global_set_option(opt, value)<EOL>


def global_set_option(self, opt, value):

self._all_options[opt].set_option(opt, value)<EOL>

set option on the correct option provider


def generate_config(self, stream=None, skipsections=(), encoding=None):

options_by_section = {}<EOL>sections = []<EOL>for provider in self.options_providers:<EOL><INDENT>for section, options in provider.options_by_section():<EOL><INDENT>if section is None:<EOL><INDENT>section = provider.name<EOL><DEDENT>if section in skipsections:<EOL><INDENT>continue<EOL><DEDENT>options = [<EOL>(n, d, v)<EOL>for (n, d, v) in options<EOL>if d.get("<STR_LIT:type>") is not None and not d.get("<STR_LIT>")<EOL>]<EOL>if not options:<EOL><INDENT>continue<EOL><DEDENT>if section not in sections:<EOL><INDENT>sections.append(section)<EOL><DEDENT>alloptions = options_by_section.setdefault(section, [])<EOL>alloptions += options<EOL><DEDENT><DEDENT>stream = stream or sys.stdout<EOL>printed = False<EOL>for section in sections:<EOL><INDENT>if printed:<EOL><INDENT>print("<STR_LIT:\n>", file=stream)<EOL><DEDENT>utils.format_section(<EOL>stream, section.upper(), sorted(options_by_section[section])<EOL>)<EOL>printed = True<EOL><DEDENT>

write a configuration file according to the current configuration
        into the given stream or stdout


for provider in self.options_providers:<EOL><INDENT>provider.load_defaults()<EOL><DEDENT>

initialize configuration using default values


def read_config_file(self, config_file=None, verbose=None):

helplevel = <NUM_LIT:1><EOL>while helplevel <= self._maxlevel:<EOL><INDENT>opt = "<STR_LIT:->".join(["<STR_LIT>"] * helplevel) + "<STR_LIT>"<EOL>if opt in self._all_options:<EOL><INDENT>break  <EOL><DEDENT>def helpfunc(option, opt, val, p, level=helplevel):<EOL><INDENT>print(self.help(level))<EOL>sys.exit(<NUM_LIT:0>)<EOL><DEDENT>helpmsg = "<STR_LIT>" % "<STR_LIT:U+0020>".join(["<STR_LIT>"] * helplevel)<EOL>optdict = {"<STR_LIT:action>": "<STR_LIT>", "<STR_LIT>": helpfunc, "<STR_LIT>": helpmsg}<EOL>provider = self.options_providers[<NUM_LIT:0>]<EOL>self.add_optik_option(provider, self.cmdline_parser, opt, optdict)<EOL>provider.options += ((opt, optdict),)<EOL>helplevel += <NUM_LIT:1><EOL><DEDENT>if config_file is None:<EOL><INDENT>config_file = self.config_file<EOL><DEDENT>if config_file is not None:<EOL><INDENT>config_file = os.path.expanduser(config_file)<EOL>if not os.path.exists(config_file):<EOL><INDENT>raise IOError("<STR_LIT>".format(config_file))<EOL><DEDENT><DEDENT>use_config_file = config_file and os.path.exists(config_file)<EOL>if use_config_file:<EOL><INDENT>parser = self.cfgfile_parser<EOL>with io.open(config_file, "<STR_LIT:r>", encoding="<STR_LIT>") as fp:<EOL><INDENT>parser.read_file(fp)<EOL><DEDENT>for sect, values in list(parser._sections.items()):<EOL><INDENT>if not sect.isupper() and values:<EOL><INDENT>parser._sections[sect.upper()] = values<EOL><DEDENT><DEDENT><DEDENT>if not verbose:<EOL><INDENT>return<EOL><DEDENT>if use_config_file:<EOL><INDENT>msg = "<STR_LIT>".format(os.path.abspath(config_file))<EOL><DEDENT>else:<EOL><INDENT>msg = "<STR_LIT>"<EOL><DEDENT>print(msg, file=sys.stderr)<EOL>

read the configuration file but do not load it (i.e. dispatching
        values to each options provider)


parser = self.cfgfile_parser<EOL>for section in parser.sections():<EOL><INDENT>for option, value in parser.items(section):<EOL><INDENT>try:<EOL><INDENT>self.global_set_option(option, value)<EOL><DEDENT>except (KeyError, optparse.OptionError):<EOL><INDENT>continue<EOL><DEDENT><DEDENT><DEDENT>

dispatch values previously read from a configuration file to each
        options provider)


return self.load_configuration_from_config(kwargs)<EOL>

override configuration according to given parameters


with _patch_optparse():<EOL><INDENT>if args is None:<EOL><INDENT>args = sys.argv[<NUM_LIT:1>:]<EOL><DEDENT>else:<EOL><INDENT>args = list(args)<EOL><DEDENT>(options, args) = self.cmdline_parser.parse_args(args=args)<EOL>for provider in self._nocallback_options:<EOL><INDENT>config = provider.config<EOL>for attr in config.__dict__.keys():<EOL><INDENT>value = getattr(options, attr, None)<EOL>if value is None:<EOL><INDENT>continue<EOL><DEDENT>setattr(config, attr, value)<EOL><DEDENT><DEDENT>return args<EOL><DEDENT>

Override configuration according to command line parameters

        return additional arguments


def add_help_section(self, title, description, level=<NUM_LIT:0>):

group = optparse.OptionGroup(<EOL>self.cmdline_parser, title=title.capitalize(), description=description<EOL>)<EOL>group.level = level<EOL>self._maxlevel = max(self._maxlevel, level)<EOL>self.cmdline_parser.add_option_group(group)<EOL>

add a dummy option section for help purpose


self.cmdline_parser.formatter.output_level = level<EOL>with _patch_optparse():<EOL><INDENT>return self.cmdline_parser.format_help()<EOL><DEDENT>

return the usage string for available options


for opt, optdict in self.options:<EOL><INDENT>action = optdict.get("<STR_LIT:action>")<EOL>if action != "<STR_LIT>":<EOL><INDENT>if optdict is None:<EOL><INDENT>optdict = self.get_option_def(opt)<EOL><DEDENT>default = optdict.get("<STR_LIT:default>")<EOL>self.set_option(opt, default, action, optdict)<EOL><DEDENT><DEDENT>

initialize the provider using default values


def option_attrname(self, opt, optdict=None):

if optdict is None:<EOL><INDENT>optdict = self.get_option_def(opt)<EOL><DEDENT>return optdict.get("<STR_LIT>", opt.replace("<STR_LIT:->", "<STR_LIT:_>"))<EOL>

get the config attribute corresponding to opt


return getattr(self.config, self.option_attrname(opt), None)<EOL>

get the current value for the given option


def set_option(self, optname, value, action=None, optdict=None):

if optdict is None:<EOL><INDENT>optdict = self.get_option_def(optname)<EOL><DEDENT>if value is not None:<EOL><INDENT>value = _validate(value, optdict, optname)<EOL><DEDENT>if action is None:<EOL><INDENT>action = optdict.get("<STR_LIT:action>", "<STR_LIT:store>")<EOL><DEDENT>if action == "<STR_LIT:store>":<EOL><INDENT>setattr(self.config, self.option_attrname(optname, optdict), value)<EOL><DEDENT>elif action in ("<STR_LIT:store_true>", "<STR_LIT:count>"):<EOL><INDENT>setattr(self.config, self.option_attrname(optname, optdict), <NUM_LIT:0>)<EOL><DEDENT>elif action == "<STR_LIT>":<EOL><INDENT>setattr(self.config, self.option_attrname(optname, optdict), <NUM_LIT:1>)<EOL><DEDENT>elif action == "<STR_LIT>":<EOL><INDENT>optname = self.option_attrname(optname, optdict)<EOL>_list = getattr(self.config, optname, None)<EOL>if _list is None:<EOL><INDENT>if isinstance(value, (list, tuple)):<EOL><INDENT>_list = value<EOL><DEDENT>elif value is not None:<EOL><INDENT>_list = []<EOL>_list.append(value)<EOL><DEDENT>setattr(self.config, optname, _list)<EOL><DEDENT>elif isinstance(_list, tuple):<EOL><INDENT>setattr(self.config, optname, _list + (value,))<EOL><DEDENT>else:<EOL><INDENT>_list.append(value)<EOL><DEDENT><DEDENT>elif action == "<STR_LIT>":<EOL><INDENT>optdict["<STR_LIT>"](None, optname, value, None)<EOL><DEDENT>else:<EOL><INDENT>raise UnsupportedAction(action)<EOL><DEDENT>

method called to set an option (registered in the options list)


assert self.options<EOL>for option in self.options:<EOL><INDENT>if option[<NUM_LIT:0>] == opt:<EOL><INDENT>return option[<NUM_LIT:1>]<EOL><DEDENT><DEDENT>raise optparse.OptionError(<EOL>"<STR_LIT>" % (opt, self.name), opt<EOL>)<EOL>

return the dictionary defining an option given its name


sections = {}<EOL>for optname, optdict in self.options:<EOL><INDENT>sections.setdefault(optdict.get("<STR_LIT>"), []).append(<EOL>(optname, optdict, self.option_value(optname))<EOL>)<EOL><DEDENT>if None in sections:<EOL><INDENT>yield None, sections.pop(None)<EOL><DEDENT>for section, options in sorted(sections.items()):<EOL><INDENT>yield section.upper(), options<EOL><DEDENT>

return an iterator on options grouped by section

        (section, [list of (optname, optdict, optvalue)])


def _rest_format_section(stream, section, options, doc=None):

if section:<EOL><INDENT>print("<STR_LIT>" % (section, "<STR_LIT:'>" * len(section)), file=stream)<EOL><DEDENT>if doc:<EOL><INDENT>print(normalize_text(doc, line_len=<NUM_LIT>, indent="<STR_LIT>"), file=stream)<EOL>print(file=stream)<EOL><DEDENT>for optname, optdict, value in options:<EOL><INDENT>help_opt = optdict.get("<STR_LIT>")<EOL>print("<STR_LIT>" % optname, file=stream)<EOL>if help_opt:<EOL><INDENT>help_opt = normalize_text(help_opt, line_len=<NUM_LIT>, indent="<STR_LIT:U+0020>")<EOL>print(help_opt, file=stream)<EOL><DEDENT>if value:<EOL><INDENT>value = str(_format_option_value(optdict, value))<EOL>print(file=stream)<EOL>print("<STR_LIT>" % value.replace("<STR_LIT>", "<STR_LIT>"), file=stream)<EOL><DEDENT><DEDENT>

format an options section using as ReST formatted output


def _register_by_id_managed_msg(self, msgid, line, is_disabled=True):

try:<EOL><INDENT>message_definitions = self.msgs_store.get_message_definitions(msgid)<EOL>for message_definition in message_definitions:<EOL><INDENT>if msgid == message_definition.msgid:<EOL><INDENT>MessagesHandlerMixIn.__by_id_managed_msgs.append(<EOL>(<EOL>self.current_name,<EOL>message_definition.msgid,<EOL>message_definition.symbol,<EOL>line,<EOL>is_disabled,<EOL>)<EOL>)<EOL><DEDENT><DEDENT><DEDENT>except UnknownMessageError:<EOL><INDENT>pass<EOL><DEDENT>

If the msgid is a numeric one, then register it to inform the user
        it could furnish instead a symbolic msgid.


def disable(self, msgid, scope="<STR_LIT>", line=None, ignore_unknown=False):

self._set_msg_status(<EOL>msgid, enable=False, scope=scope, line=line, ignore_unknown=ignore_unknown<EOL>)<EOL>self._register_by_id_managed_msg(msgid, line)<EOL>


def enable(self, msgid, scope="<STR_LIT>", line=None, ignore_unknown=False):

self._set_msg_status(<EOL>msgid, enable=True, scope=scope, line=line, ignore_unknown=ignore_unknown<EOL>)<EOL>self._register_by_id_managed_msg(msgid, line, is_disabled=False)<EOL>


try:<EOL><INDENT>return [md.symbol for md in self.msgs_store.get_message_definitions(msgid)]<EOL><DEDENT>except UnknownMessageError:<EOL><INDENT>return msgid<EOL><DEDENT>

Get the message symbol of the given message id

        Return the original message id if the message does not
        exist.


def get_message_state_scope(self, msgid, line=None, confidence=UNDEFINED):

if self.config.confidence and confidence.name not in self.config.confidence:<EOL><INDENT>return MSG_STATE_CONFIDENCE<EOL><DEDENT>try:<EOL><INDENT>if line in self.file_state._module_msgs_state[msgid]:<EOL><INDENT>return MSG_STATE_SCOPE_MODULE<EOL><DEDENT><DEDENT>except (KeyError, TypeError):<EOL><INDENT>return MSG_STATE_SCOPE_CONFIG<EOL><DEDENT>return None<EOL>

Returns the scope at which a message was enabled/disabled.