def split(y, top_db=<NUM_LIT>, ref=np.max, frame_length=<NUM_LIT>, hop_length=<NUM_LIT>):

non_silent = _signal_to_frame_nonsilent(y,<EOL>frame_length=frame_length,<EOL>hop_length=hop_length,<EOL>ref=ref,<EOL>top_db=top_db)<EOL>edges = np.flatnonzero(np.diff(non_silent.astype(int)))<EOL>edges = [edges + <NUM_LIT:1>]<EOL>if non_silent[<NUM_LIT:0>]:<EOL><INDENT>edges.insert(<NUM_LIT:0>, [<NUM_LIT:0>])<EOL><DEDENT>if non_silent[-<NUM_LIT:1>]:<EOL><INDENT>edges.append([len(non_silent)])<EOL><DEDENT>edges = core.frames_to_samples(np.concatenate(edges),<EOL>hop_length=hop_length)<EOL>edges = np.minimum(edges, y.shape[-<NUM_LIT:1>])<EOL>return edges.reshape((-<NUM_LIT:1>, <NUM_LIT:2>))<EOL>

Split an audio signal into non-silent intervals.

    Parameters
    ----------
    y : np.ndarray, shape=(n,) or (2, n)
        An audio signal

    top_db : number > 0
        The threshold (in decibels) below reference to consider as
        silence

    ref : number or callable
        The reference power.  By default, it uses `np.max` and compares
        to the peak power in the signal.

    frame_length : int > 0
        The number of samples per analysis frame

    hop_length : int > 0
        The number of samples between analysis frames

    Returns
    -------
    intervals : np.ndarray, shape=(m, 2)
        `intervals[i] == (start_i, end_i)` are the start and end time
        (in samples) of non-silent interval `i`.


def remix(y, intervals, align_zeros=True):

<EOL>util.valid_audio(y, mono=False)<EOL>y_out = []<EOL>if align_zeros:<EOL><INDENT>y_mono = core.to_mono(y)<EOL>zeros = np.nonzero(core.zero_crossings(y_mono))[-<NUM_LIT:1>]<EOL>zeros = np.append(zeros, [len(y_mono)])<EOL><DEDENT>clip = [slice(None)] * y.ndim<EOL>for interval in intervals:<EOL><INDENT>if align_zeros:<EOL><INDENT>interval = zeros[util.match_events(interval, zeros)]<EOL><DEDENT>clip[-<NUM_LIT:1>] = slice(interval[<NUM_LIT:0>], interval[<NUM_LIT:1>])<EOL>y_out.append(y[tuple(clip)])<EOL><DEDENT>return np.concatenate(y_out, axis=-<NUM_LIT:1>)<EOL>

Remix an audio signal by re-ordering time intervals.

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

    intervals : iterable of tuples (start, end)
        An iterable (list-like or generator) where the `i`th item
        `intervals[i]` indicates the start and end (in samples)
        of a slice of `y`.

    align_zeros : boolean
        If `True`, interval boundaries are mapped to the closest
        zero-crossing in `y`.  If `y` is stereo, zero-crossings
        are computed after converting to mono.

    Returns
    -------
    y_remix : np.ndarray [shape=(d,) or (2, d)]
        `y` remixed in the order specified by `intervals`

    Examples
    --------
    Load in the example track and reverse the beats

    >>> y, sr = librosa.load(librosa.util.example_audio_file())

    Compute beats

    >>> _, beat_frames = librosa.beat.beat_track(y=y, sr=sr,
    ...                                          hop_length=512)

    Convert from frames to sample indices

    >>> beat_samples = librosa.frames_to_samples(beat_frames)

    Generate intervals from consecutive events

    >>> intervals = librosa.util.frame(beat_samples, frame_length=2,
    ...                                hop_length=1).T

    Reverse the beat intervals

    >>> y_out = librosa.effects.remix(y, intervals[::-1])


def path_enhance(R, n, window='<STR_LIT>', max_ratio=<NUM_LIT>, min_ratio=None, n_filters=<NUM_LIT:7>,<EOL>zero_mean=False, clip=True, **kwargs):

if min_ratio is None:<EOL><INDENT>min_ratio = <NUM_LIT:1.>/max_ratio<EOL><DEDENT>elif min_ratio > max_ratio:<EOL><INDENT>raise ParameterError('<STR_LIT>'.format(min_ratio, max_ratio))<EOL><DEDENT>R_smooth = None<EOL>for ratio in np.logspace(np.log2(min_ratio), np.log2(max_ratio), num=n_filters, base=<NUM_LIT:2>):<EOL><INDENT>kernel = diagonal_filter(window, n, slope=ratio, zero_mean=zero_mean)<EOL>if R_smooth is None:<EOL><INDENT>R_smooth = scipy.ndimage.convolve(R, kernel, **kwargs)<EOL><DEDENT>else:<EOL><INDENT>np.maximum(R_smooth, scipy.ndimage.convolve(R, kernel, **kwargs),<EOL>out=R_smooth)<EOL><DEDENT><DEDENT>if clip:<EOL><INDENT>np.clip(R_smooth, <NUM_LIT:0>, None, out=R_smooth)<EOL><DEDENT>return R_smooth<EOL>

Multi-angle path enhancement for self- and cross-similarity matrices.

    This function convolves multiple diagonal smoothing filters with a self-similarity (or
    recurrence) matrix R, and aggregates the result by an element-wise maximum.

    Technically, the output is a matrix R_smooth such that

        `R_smooth[i, j] = max_theta (R * filter_theta)[i, j]`

    where `*` denotes 2-dimensional convolution, and `filter_theta` is a smoothing filter at
    orientation theta.

    This is intended to provide coherent temporal smoothing of self-similarity matrices
    when there are changes in tempo.

    Smoothing filters are generated at evenly spaced orientations between min_ratio and
    max_ratio.

    This function is inspired by the multi-angle path enhancement of [1]_, but differs by
    modeling tempo differences in the space of similarity matrices rather than re-sampling
    the underlying features prior to generating the self-similarity matrix.

    .. [1] Müller, Meinard and Frank Kurth.
            "Enhancing similarity matrices for music audio analysis."
            2006 IEEE International Conference on Acoustics Speech and Signal Processing Proceedings.
            Vol. 5. IEEE, 2006.

    .. note:: if using recurrence_matrix to construct the input similarity matrix, be sure to include the main
              diagonal by setting `self=True`.  Otherwise, the diagonal will be suppressed, and this is likely to
              produce discontinuities which will pollute the smoothing filter response.

    Parameters
    ----------
    R : np.ndarray
        The self- or cross-similarity matrix to be smoothed.
        Note: sparse inputs are not supported.

    n : int > 0
        The length of the smoothing filter

    window : window specification
        The type of smoothing filter to use.  See `filters.get_window` for more information
        on window specification formats.

    max_ratio : float > 0
        The maximum tempo ratio to support

    min_ratio : float > 0
        The minimum tempo ratio to support.
        If not provided, it will default to `1/max_ratio`

    n_filters : int >= 1
        The number of different smoothing filters to use, evenly spaced
        between `min_ratio` and `max_ratio`.

        If `min_ratio = 1/max_ratio` (the default), using an odd number
        of filters will ensure that the main diagonal (ratio=1) is included.

    zero_mean : bool
        By default, the smoothing filters are non-negative and sum to one (i.e. are averaging
        filters).

        If `zero_mean=True`, then the smoothing filters are made to sum to zero by subtracting
        a constant value from the non-diagonal coordinates of the filter.  This is primarily
        useful for suppressing blocks while enhancing diagonals.

    clip : bool
        If True, the smoothed similarity matrix will be thresholded at 0, and will not contain
        negative entries.

    kwargs : additional keyword arguments
        Additional arguments to pass to `scipy.ndimage.convolve`

    Returns
    -------
    R_smooth : np.ndarray, shape=R.shape
        The smoothed self- or cross-similarity matrix

    See Also
    --------
    filters.diagonal_filter
    recurrence_matrix

    Examples
    --------
    Use a 51-frame diagonal smoothing filter to enhance paths in a recurrence matrix

    >>> y, sr = librosa.load(librosa.util.example_audio_file(), duration=30)
    >>> chroma = librosa.feature.chroma_cqt(y=y, sr=sr)
    >>> rec = librosa.segment.recurrence_matrix(chroma, mode='affinity', self=True)
    >>> rec_smooth = librosa.segment.path_enhance(rec, 51, window='hann', n_filters=7)

    Plot the recurrence matrix before and after smoothing

    >>> import matplotlib.pyplot as plt
    >>> plt.figure(figsize=(8, 4))
    >>> plt.subplot(1,2,1)
    >>> librosa.display.specshow(rec, x_axis='time', y_axis='time')
    >>> plt.title('Unfiltered recurrence')
    >>> plt.subplot(1,2,2)
    >>> librosa.display.specshow(rec_smooth, x_axis='time', y_axis='time')
    >>> plt.title('Multi-angle enhanced recurrence')
    >>> plt.tight_layout()


def recurrence_to_lag(rec, pad=True, axis=-<NUM_LIT:1>):

axis = np.abs(axis)<EOL>if rec.ndim != <NUM_LIT:2> or rec.shape[<NUM_LIT:0>] != rec.shape[<NUM_LIT:1>]:<EOL><INDENT>raise ParameterError('<STR_LIT>'<EOL>'<STR_LIT:{}>'.format(rec.shape))<EOL><DEDENT>sparse = scipy.sparse.issparse(rec)<EOL>roll_ax = None<EOL>if sparse:<EOL><INDENT>roll_ax = <NUM_LIT:1> - axis<EOL>lag_format = rec.format<EOL>if axis == <NUM_LIT:0>:<EOL><INDENT>rec = rec.tocsc()<EOL><DEDENT>elif axis in (-<NUM_LIT:1>, <NUM_LIT:1>):<EOL><INDENT>rec = rec.tocsr()<EOL><DEDENT><DEDENT>t = rec.shape[axis]<EOL>if sparse:<EOL><INDENT>if pad:<EOL><INDENT>kron = np.asarray([[<NUM_LIT:1>, <NUM_LIT:0>]]).swapaxes(axis, <NUM_LIT:0>)<EOL>lag = scipy.sparse.kron(kron.astype(rec.dtype), rec, format='<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>lag = scipy.sparse.lil_matrix(rec)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if pad:<EOL><INDENT>padding = [(<NUM_LIT:0>, <NUM_LIT:0>), (<NUM_LIT:0>, <NUM_LIT:0>)]<EOL>padding[(<NUM_LIT:1>-axis)] = (<NUM_LIT:0>, t)<EOL>lag = np.pad(rec, padding, mode='<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>lag = rec.copy()<EOL><DEDENT><DEDENT>idx_slice = [slice(None)] * lag.ndim<EOL>for i in range(<NUM_LIT:1>, t):<EOL><INDENT>idx_slice[axis] = i<EOL>lag[tuple(idx_slice)] = util.roll_sparse(lag[tuple(idx_slice)], -i, axis=roll_ax)<EOL><DEDENT>if sparse:<EOL><INDENT>return lag.asformat(lag_format)<EOL><DEDENT>return np.ascontiguousarray(lag.T).T<EOL>

Convert a recurrence matrix into a lag matrix.

        `lag[i, j] == rec[i+j, j]`

    Parameters
    ----------
    rec : np.ndarray, or scipy.sparse.spmatrix [shape=(n, n)]
        A (binary) recurrence matrix, as returned by `recurrence_matrix`

    pad : bool
        If False, `lag` matrix is square, which is equivalent to
        assuming that the signal repeats itself indefinitely.

        If True, `lag` is padded with `n` zeros, which eliminates
        the assumption of repetition.

    axis : int
        The axis to keep as the `time` axis.
        The alternate axis will be converted to lag coordinates.

    Returns
    -------
    lag : np.ndarray
        The recurrence matrix in (lag, time) (if `axis=1`)
        or (time, lag) (if `axis=0`) coordinates

    Raises
    ------
    ParameterError : if `rec` is non-square

    See Also
    --------
    recurrence_matrix
    lag_to_recurrence

    Examples
    --------
    >>> y, sr = librosa.load(librosa.util.example_audio_file())
    >>> mfccs = librosa.feature.mfcc(y=y, sr=sr)
    >>> recurrence = librosa.segment.recurrence_matrix(mfccs)
    >>> lag_pad = librosa.segment.recurrence_to_lag(recurrence, pad=True)
    >>> lag_nopad = librosa.segment.recurrence_to_lag(recurrence, pad=False)

    >>> import matplotlib.pyplot as plt
    >>> plt.figure(figsize=(8, 4))
    >>> plt.subplot(1, 2, 1)
    >>> librosa.display.specshow(lag_pad, x_axis='time', y_axis='lag')
    >>> plt.title('Lag (zero-padded)')
    >>> plt.subplot(1, 2, 2)
    >>> librosa.display.specshow(lag_nopad, x_axis='time')
    >>> plt.title('Lag (no padding)')
    >>> plt.tight_layout()


def timelag_filter(function, pad=True, index=<NUM_LIT:0>):

def __my_filter(wrapped_f, *args, **kwargs):<EOL><INDENT>'''<STR_LIT>'''<EOL>args = list(args)<EOL>args[index] = recurrence_to_lag(args[index], pad=pad)<EOL>result = wrapped_f(*args, **kwargs)<EOL>return lag_to_recurrence(result)<EOL><DEDENT>return decorator(__my_filter, function)<EOL>

Filtering in the time-lag domain.

    This is primarily useful for adapting image filters to operate on
    `recurrence_to_lag` output.

    Using `timelag_filter` is equivalent to the following sequence of
    operations:

    >>> data_tl = librosa.segment.recurrence_to_lag(data)
    >>> data_filtered_tl = function(data_tl)
    >>> data_filtered = librosa.segment.lag_to_recurrence(data_filtered_tl)

    Parameters
    ----------
    function : callable
        The filtering function to wrap, e.g., `scipy.ndimage.median_filter`

    pad : bool
        Whether to zero-pad the structure feature matrix

    index : int >= 0
        If `function` accepts input data as a positional argument, it should be
        indexed by `index`

    Returns
    -------
    wrapped_function : callable
        A new filter function which applies in time-lag space rather than
        time-time space.

    Examples
    --------

    Apply a 5-bin median filter to the diagonal of a recurrence matrix

    >>> y, sr = librosa.load(librosa.util.example_audio_file())
    >>> chroma = librosa.feature.chroma_cqt(y=y, sr=sr)
    >>> rec = librosa.segment.recurrence_matrix(chroma)
    >>> from scipy.ndimage import median_filter
    >>> diagonal_median = librosa.segment.timelag_filter(median_filter)
    >>> rec_filtered = diagonal_median(rec, size=(1, 3), mode='mirror')

    Or with affinity weights

    >>> rec_aff = librosa.segment.recurrence_matrix(chroma, mode='affinity')
    >>> rec_aff_fil = diagonal_median(rec_aff, size=(1, 3), mode='mirror')

    >>> import matplotlib.pyplot as plt
    >>> plt.figure(figsize=(8,8))
    >>> plt.subplot(2, 2, 1)
    >>> librosa.display.specshow(rec, y_axis='time')
    >>> plt.title('Raw recurrence matrix')
    >>> plt.subplot(2, 2, 2)
    >>> librosa.display.specshow(rec_filtered)
    >>> plt.title('Filtered recurrence matrix')
    >>> plt.subplot(2, 2, 3)
    >>> librosa.display.specshow(rec_aff, x_axis='time', y_axis='time',
    ...                          cmap='magma_r')
    >>> plt.title('Raw affinity matrix')
    >>> plt.subplot(2, 2, 4)
    >>> librosa.display.specshow(rec_aff_fil, x_axis='time',
    ...                          cmap='magma_r')
    >>> plt.title('Filtered affinity matrix')
    >>> plt.tight_layout()


def spectral_rolloff(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>freq=None, roll_percent=<NUM_LIT>):

if not <NUM_LIT:0.0> < roll_percent < <NUM_LIT:1.0>:<EOL><INDENT>raise ParameterError('<STR_LIT>')<EOL><DEDENT>S, n_fft = _spectrogram(y=y, S=S, n_fft=n_fft, hop_length=hop_length,<EOL>win_length=win_length, window=window, center=center,<EOL>pad_mode=pad_mode)<EOL>if not np.isrealobj(S):<EOL><INDENT>raise ParameterError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>elif np.any(S < <NUM_LIT:0>):<EOL><INDENT>raise ParameterError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>if freq is None:<EOL><INDENT>freq = fft_frequencies(sr=sr, n_fft=n_fft)<EOL><DEDENT>if freq.ndim == <NUM_LIT:1>:<EOL><INDENT>freq = freq.reshape((-<NUM_LIT:1>, <NUM_LIT:1>))<EOL><DEDENT>total_energy = np.cumsum(S, axis=<NUM_LIT:0>)<EOL>threshold = roll_percent * total_energy[-<NUM_LIT:1>]<EOL>ind = np.where(total_energy < threshold, np.nan, <NUM_LIT:1>)<EOL>return np.nanmin(ind * freq, axis=<NUM_LIT:0>, keepdims=True)<EOL>

Compute roll-off frequency.

    The roll-off frequency is defined for each frame as the center frequency
    for a spectrogram bin such that at least roll_percent (0.85 by default)
    of the energy of the spectrum in this frame is contained in this bin and
    the bins below. This can be used to, e.g., approximate the maximum (or
    minimum) frequency by setting roll_percent to a value close to 1 (or 0).

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

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

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

    n_fft : int > 0 [scalar]
        FFT window size

    hop_length : int > 0 [scalar]
        hop length for STFT. See `librosa.core.stft` for details.

    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.

    freq : None or np.ndarray [shape=(d,) or shape=(d, t)]
        Center frequencies for spectrogram bins.
        If `None`, then FFT bin center frequencies are used.
        Otherwise, it can be a single array of `d` center frequencies,

        .. note:: `freq` is assumed to be sorted in increasing order

    roll_percent : float [0 < roll_percent < 1]
        Roll-off percentage.

    Returns
    -------
    rolloff : np.ndarray [shape=(1, t)]
        roll-off frequency for each frame

    Examples
    --------
    From time-series input

    >>> y, sr = librosa.load(librosa.util.example_audio_file())
    >>> # Approximate maximum frequencies with roll_percent=0.85 (default)
    >>> rolloff = librosa.feature.spectral_rolloff(y=y, sr=sr)
    >>> rolloff
    array([[ 8376.416,   968.994, ...,  8925.513,  9108.545]])
    >>> # Approximate minimum frequencies with roll_percent=0.1
    >>> rolloff = librosa.feature.spectral_rolloff(y=y, sr=sr, roll_percent=0.1)
    >>> rolloff
    array([[ 75.36621094,  64.59960938,  64.59960938, ...,  75.36621094,
         75.36621094,  64.59960938]])

    From spectrogram input

    >>> S, phase = librosa.magphase(librosa.stft(y))
    >>> librosa.feature.spectral_rolloff(S=S, sr=sr)
    array([[ 8376.416,   968.994, ...,  8925.513,  9108.545]])

    >>> # With a higher roll percentage:
    >>> y, sr = librosa.load(librosa.util.example_audio_file())
    >>> librosa.feature.spectral_rolloff(y=y, sr=sr, roll_percent=0.95)
    array([[ 10012.939,   3003.882, ...,  10034.473,  10077.539]])

    >>> import matplotlib.pyplot as plt
    >>> plt.figure()
    >>> plt.subplot(2, 1, 1)
    >>> plt.semilogy(rolloff.T, label='Roll-off frequency')
    >>> plt.ylabel('Hz')
    >>> plt.xticks([])
    >>> plt.xlim([0, rolloff.shape[-1]])
    >>> plt.legend()
    >>> plt.subplot(2, 1, 2)
    >>> librosa.display.specshow(librosa.amplitude_to_db(S, ref=np.max),
    ...                          y_axis='log', x_axis='time')
    >>> plt.title('log Power spectrogram')
    >>> plt.tight_layout()


def rms(y=None, S=None, frame_length=<NUM_LIT>, hop_length=<NUM_LIT>,<EOL>center=True, pad_mode='<STR_LIT>'):

if y is not None and S is not None:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if y is not None:<EOL><INDENT>y = to_mono(y)<EOL>if center:<EOL><INDENT>y = np.pad(y, int(frame_length // <NUM_LIT:2>), mode=pad_mode)<EOL><DEDENT>x = util.frame(y,<EOL>frame_length=frame_length,<EOL>hop_length=hop_length)<EOL><DEDENT>elif S is not None:<EOL><INDENT>x, _ = _spectrogram(y=y, S=S,<EOL>n_fft=frame_length,<EOL>hop_length=hop_length)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>return np.sqrt(np.mean(np.abs(x)**<NUM_LIT:2>, axis=<NUM_LIT:0>, keepdims=True))<EOL>

Compute root-mean-square (RMS) value for each frame, either from the
    audio samples `y` or from a spectrogram `S`.

    Computing the RMS value from audio samples is faster as it doesn't require
    a STFT calculation. However, using a spectrogram will give a more accurate
    representation of energy over time because its frames can be windowed,
    thus prefer using `S` if it's already available.

    Parameters
    ----------
    y : np.ndarray [shape=(n,)] or None
        (optional) audio time series. Required if `S` is not input.

    S : np.ndarray [shape=(d, t)] or None
        (optional) spectrogram magnitude. Required if `y` is not input.

    frame_length : int > 0 [scalar]
        length of analysis frame (in samples) for energy calculation

    hop_length : int > 0 [scalar]
        hop length for STFT. See `librosa.core.stft` for details.

    center : bool
        If `True` and operating on time-domain input (`y`), pad the signal
        by `frame_length//2` on either side.

        If operating on spectrogram input, this has no effect.

    pad_mode : str
        Padding mode for centered analysis.  See `np.pad` for valid
        values.

    Returns
    -------
    rms : np.ndarray [shape=(1, t)]
        RMS value for each frame

    Examples
    --------
    >>> y, sr = librosa.load(librosa.util.example_audio_file())
    >>> librosa.feature.rms(y=y)
    array([[ 0.   ,  0.056, ...,  0.   ,  0.   ]], dtype=float32)

    Or from spectrogram input

    >>> S, phase = librosa.magphase(librosa.stft(y))
    >>> rms = librosa.feature.rms(S=S)

    >>> import matplotlib.pyplot as plt
    >>> plt.figure()
    >>> plt.subplot(2, 1, 1)
    >>> plt.semilogy(rms.T, label='RMS Energy')
    >>> plt.xticks([])
    >>> plt.xlim([0, rms.shape[-1]])
    >>> plt.legend(loc='best')
    >>> plt.subplot(2, 1, 2)
    >>> librosa.display.specshow(librosa.amplitude_to_db(S, ref=np.max),
    ...                          y_axis='log', x_axis='time')
    >>> plt.title('log Power spectrogram')
    >>> plt.tight_layout()

    Use a STFT window of constant ones and no frame centering to get consistent
    results with the RMS computed from the audio samples `y`

    >>> S = librosa.magphase(librosa.stft(y, window=np.ones, center=False))[0]
    >>> librosa.feature.rms(S=S)


def spectral_bandwidth(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>freq=None, centroid=None, norm=True, p=<NUM_LIT:2>):

S, n_fft = _spectrogram(y=y, S=S, n_fft=n_fft, hop_length=hop_length,<EOL>win_length=win_length, window=window, center=center,<EOL>pad_mode=pad_mode)<EOL>if not np.isrealobj(S):<EOL><INDENT>raise ParameterError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>elif np.any(S < <NUM_LIT:0>):<EOL><INDENT>raise ParameterError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>if centroid is None:<EOL><INDENT>centroid = spectral_centroid(y=y, sr=sr, S=S,<EOL>n_fft=n_fft,<EOL>hop_length=hop_length,<EOL>freq=freq)<EOL><DEDENT>if freq is None:<EOL><INDENT>freq = fft_frequencies(sr=sr, n_fft=n_fft)<EOL><DEDENT>if freq.ndim == <NUM_LIT:1>:<EOL><INDENT>deviation = np.abs(np.subtract.outer(freq, centroid[<NUM_LIT:0>]))<EOL><DEDENT>else:<EOL><INDENT>deviation = np.abs(freq - centroid[<NUM_LIT:0>])<EOL><DEDENT>if norm:<EOL><INDENT>S = util.normalize(S, norm=<NUM_LIT:1>, axis=<NUM_LIT:0>)<EOL><DEDENT>return np.sum(S * deviation**p, axis=<NUM_LIT:0>, keepdims=True)**(<NUM_LIT:1.>/p)<EOL>

Compute p'th-order spectral bandwidth:

        (sum_k S[k] * (freq[k] - centroid)**p)**(1/p)

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

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

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

    n_fft : int > 0 [scalar]
        FFT window size

    hop_length : int > 0 [scalar]
        hop length for STFT. See `librosa.core.stft` for details.

    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.

    freq : None or np.ndarray [shape=(d,) or shape=(d, t)]
        Center frequencies for spectrogram bins.
        If `None`, then FFT bin center frequencies are used.
        Otherwise, it can be a single array of `d` center frequencies,
        or a matrix of center frequencies as constructed by
        `librosa.core.ifgram`

    centroid : None or np.ndarray [shape=(1, t)]
        pre-computed centroid frequencies

    norm : bool
        Normalize per-frame spectral energy (sum to one)

    p : float > 0
        Power to raise deviation from spectral centroid.

    Returns
    -------
    bandwidth : np.ndarray [shape=(1, t)]
        frequency bandwidth for each frame

    Examples
    --------
    From time-series input

    >>> y, sr = librosa.load(librosa.util.example_audio_file())
    >>> spec_bw = librosa.feature.spectral_bandwidth(y=y, sr=sr)
    >>> spec_bw
    array([[ 3379.878,  1429.486, ...,  3235.214,  3080.148]])

    From spectrogram input

    >>> S, phase = librosa.magphase(librosa.stft(y=y))
    >>> librosa.feature.spectral_bandwidth(S=S)
    array([[ 3379.878,  1429.486, ...,  3235.214,  3080.148]])

    Using variable bin center frequencies

    >>> if_gram, D = librosa.ifgram(y)
    >>> librosa.feature.spectral_bandwidth(S=np.abs(D), freq=if_gram)
    array([[ 3380.011,  1429.11 , ...,  3235.22 ,  3080.148]])

    Plot the result

    >>> import matplotlib.pyplot as plt
    >>> plt.figure()
    >>> plt.subplot(2, 1, 1)
    >>> plt.semilogy(spec_bw.T, label='Spectral bandwidth')
    >>> plt.ylabel('Hz')
    >>> plt.xticks([])
    >>> plt.xlim([0, spec_bw.shape[-1]])
    >>> plt.legend()
    >>> plt.subplot(2, 1, 2)
    >>> librosa.display.specshow(librosa.amplitude_to_db(S, ref=np.max),
    ...                          y_axis='log', x_axis='time')
    >>> plt.title('log Power spectrogram')
    >>> 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()


@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>


return slug_re.match(slug)<EOL>

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


raise NotImplementedError<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>


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>


return ImageGallerySerializer(instance).data<EOL>


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

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


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>


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.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.


<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.


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.


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

Updates setting for this integration with the given name.


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


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

Return the number of votes for this answer


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


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


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

Returns the filename without its extension.


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.


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>


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`.


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.


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

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


return self.daf.comments()<EOL>


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.


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.


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.


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.


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'``.


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

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


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.


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


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)])


<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


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


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

get the current value for the given option


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


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 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)


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)


def add_renamed_message(self, old_id, old_symbol, new_symbol):

message_definition = self.get_message_definitions(new_symbol)[<NUM_LIT:0>]<EOL>message_definition.old_names.append((old_id, old_symbol))<EOL>self._register_alternative_name(message_definition, old_id, old_symbol)<EOL>

Register the old ID and symbol for a warning that was renamed.

        This allows users to keep using the old ID/symbol in suppressions.


checker.check_consistency()<EOL>for message in checker.messages:<EOL><INDENT>self.register_message(message)<EOL><DEDENT>

Register all messages from a checker.

        :param BaseChecker checker:


def _register_alternative_name(self, msg, msgid, symbol):

self._check_id_and_symbol_consistency(msgid, symbol)<EOL>self._alternative_names[msgid] = msg<EOL>self._alternative_names[symbol] = msg<EOL>


<EOL>return template.format(**dict(zip(self._fields, self)))<EOL>

Format the message according to the given template.

        The template format is the one of the format method :
        cf. http://docs.python.org/2/library/string.html#formatstrings


if self.minversion is not None and self.minversion > sys.version_info:<EOL><INDENT>return False<EOL><DEDENT>if self.maxversion is not None and self.maxversion <= sys.version_info:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>

return True if message may be emitted using the current interpreter


def py_run(command_options="<STR_LIT>", return_std=False, stdout=None, stderr=None):

<EOL>executable = sys.executable if "<STR_LIT>" in sys.executable else "<STR_LIT>"<EOL>epylint_part = [executable, "<STR_LIT:-c>", "<STR_LIT>"]<EOL>options = shlex.split(command_options, posix=not sys.platform.startswith("<STR_LIT>"))<EOL>cli = epylint_part + options<EOL>if stdout is None:<EOL><INDENT>if return_std:<EOL><INDENT>stdout = PIPE<EOL><DEDENT>else:<EOL><INDENT>stdout = sys.stdout<EOL><DEDENT><DEDENT>if stderr is None:<EOL><INDENT>if return_std:<EOL><INDENT>stderr = PIPE<EOL><DEDENT>else:<EOL><INDENT>stderr = sys.stderr<EOL><DEDENT><DEDENT>process = Popen(<EOL>cli,<EOL>shell=False,<EOL>stdout=stdout,<EOL>stderr=stderr,<EOL>env=_get_env(),<EOL>universal_newlines=True,<EOL>)<EOL>proc_stdout, proc_stderr = process.communicate()<EOL>if return_std:<EOL><INDENT>return StringIO(proc_stdout), StringIO(proc_stderr)<EOL><DEDENT>return None<EOL>

Run pylint from python

    ``command_options`` is a string containing ``pylint`` command line options;
    ``return_std`` (boolean) indicates return of created standard output
    and error (see below);
    ``stdout`` and ``stderr`` are 'file-like' objects in which standard output
    could be written.

    Calling agent is responsible for stdout/err management (creation, close).
    Default standard output and error are those from sys,
    or standalone ones (``subprocess.PIPE``) are used
    if they are not set and ``return_std``.

    If ``return_std`` is set to ``True``, this function returns a 2-uple
    containing standard output and error related to created process,
    as follows: ``(stdout, stderr)``.

    To silently run Pylint on a module, and get its standard output and error:
        >>> (pylint_stdout, pylint_stderr) = py_run( 'module_name.py', True)


<EOL>full_path = osp.abspath(filename)<EOL>parent_path = osp.dirname(full_path)<EOL>child_path = osp.basename(full_path)<EOL>while parent_path != "<STR_LIT:/>" and osp.exists(osp.join(parent_path, "<STR_LIT>")):<EOL><INDENT>child_path = osp.join(osp.basename(parent_path), child_path)<EOL>parent_path = osp.dirname(parent_path)<EOL><DEDENT>run_cmd = "<STR_LIT>"<EOL>cmd = (<EOL>[sys.executable, "<STR_LIT:-c>", run_cmd]<EOL>+ [<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT:n>",<EOL>child_path,<EOL>]<EOL>+ list(options)<EOL>)<EOL>process = Popen(<EOL>cmd, stdout=PIPE, cwd=parent_path, env=_get_env(), universal_newlines=True<EOL>)<EOL>for line in process.stdout:<EOL><INDENT>if line.startswith("<STR_LIT>"):<EOL><INDENT>continue<EOL><DEDENT>parts = line.split("<STR_LIT::>")<EOL>if parts and parts[<NUM_LIT:0>] == child_path:<EOL><INDENT>line = "<STR_LIT::>".join([filename] + parts[<NUM_LIT:1>:])<EOL><DEDENT>print(line, end="<STR_LIT:U+0020>")<EOL><DEDENT>process.wait()<EOL>return process.returncode<EOL>

Pylint the given file.

    When run from emacs we will be in the directory of a file, and passed its
    filename.  If this file is part of a package and is trying to import other
    modules from within its own package or another package rooted in a directory
    below it, pylint will classify it as a failed import.

    To get around this, we traverse down the directory tree to find the root of
    the package this module is in.  We then invoke pylint from this directory.

    Finally, we must correct the filenames in the output generated by pylint so
    Emacs doesn't become confused (it will expect just the original filename,
    while pylint may extend it with extra directories if we've traversed down
    the tree)


self.children.append(child)<EOL>child.parent = self<EOL>


try:<EOL><INDENT>return self.TYPE.replace("<STR_LIT:->", "<STR_LIT:_>")<EOL><DEDENT>except Exception:<EOL><INDENT>return self.__class__.__name__.lower()<EOL><DEDENT>

return the visit name for the mixed class. When calling 'accept', the
method <'visit_' + name returned by this method> will be called on the
visitor


for child in getattr(layout, "<STR_LIT>", ()):<EOL><INDENT>child.accept(self)<EOL><DEDENT>

recurse on the layout children and call their accept method
        (see the Visitor pattern)


self.write(string + os.linesep)<EOL>


<EOL>out = self.out<EOL>try:<EOL><INDENT>for child in layout.children:<EOL><INDENT>stream = StringIO()<EOL>self.out = stream<EOL>child.accept(self)<EOL>yield stream.getvalue()<EOL><DEDENT><DEDENT>finally:<EOL><INDENT>self.out = out<EOL><DEDENT>

trick to compute the formatting of children layout before actually
        writing it

        return an iterator on strings (one for each child element)


self.format_children(layout)<EOL>self.writeln()<EOL>


return list(self._reports)<EOL>

Return a list of reports, sorted in the order
        in which they must be called.


def colorize_ansi(msg, color=None, style=None):

<EOL>if color is None and style is None:<EOL><INDENT>return msg<EOL><DEDENT>escape_code = _get_ansi_code(color, style)<EOL>if escape_code:<EOL><INDENT>return "<STR_LIT>" % (escape_code, msg, ANSI_RESET)<EOL><DEDENT>return msg<EOL>

colorize message by wrapping it with ansi escape codes

    :type msg: str or unicode
    :param msg: the message string to colorize

    :type color: str or None
    :param color:
      the color identifier (see `ANSI_COLORS` for available values)

    :type style: str or None
    :param style:
      style string (see `ANSI_COLORS` for available values). To get
      several style effects at the same time, use a coma as separator.

    :raise KeyError: if an unexistent color or style identifier is given

    :rtype: str or unicode
    :return: the ansi escaped string


try:<EOL><INDENT>return self.color_mapping[msg_id[<NUM_LIT:0>]]<EOL><DEDENT>except KeyError:<EOL><INDENT>return None, None<EOL><DEDENT>

Returns the tuple color, style associated with msg_id as defined
        in self.color_mapping


self.section = <NUM_LIT:0><EOL>if hasattr(layout, "<STR_LIT>"):<EOL><INDENT>layout.children[<NUM_LIT:0>].children[<NUM_LIT:0>].data += "<STR_LIT>" % layout.report_id<EOL><DEDENT>self._display(layout)<EOL>

display results encapsulated in the layout tree


process a module

        the module's content is accessible via astroid.stream


called after visiting project (i.e set of modules)


linter.register_checker(BroadTryClauseChecker(linter))<EOL>

Required method to auto register this checker.


node_doc = utils.docstringify(node.doc, self.config.default_docstring_type)<EOL>self.check_functiondef_params(node, node_doc)<EOL>self.check_functiondef_returns(node, node_doc)<EOL>self.check_functiondef_yields(node, node_doc)<EOL>

Called for function and method definitions (def).

        :param node: Node for a function or method definition in the AST
        :type node: :class:`astroid.scoped_nodes.Function`


def _add_raise_message(self, missing_excs, node):

if node.is_abstract():<EOL><INDENT>try:<EOL><INDENT>missing_excs.remove("<STR_LIT>")<EOL><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>if not missing_excs:<EOL><INDENT>return<EOL><DEDENT>self.add_message(<EOL>"<STR_LIT>", args=("<STR_LIT:U+002CU+0020>".join(sorted(missing_excs)),), node=node<EOL>)<EOL>

Adds a message on :param:`node` for the missing exception type.

:param missing_excs: A list of missing exception types.
:type missing_excs: set(str)

:param node: The node show the message on.
:type node: astroid.node_classes.NodeNG


returns = return_node.value<EOL>if returns is None:<EOL><INDENT>return False<EOL><DEDENT>return not (isinstance(returns, astroid.Const) and returns.value is None)<EOL>

Check if a return node returns a value other than None.

    :param return_node: The return node to check.
    :type return_node: astroid.Return

    :rtype: bool
    :return: True if the return node returns a value other than None,
        False otherwise.


warnings.warn(<EOL>"<STR_LIT>",<EOL>DeprecationWarning,<EOL>)<EOL>linter.register_checker(docparams.DocstringParameterChecker(linter))<EOL>

Required method to auto register this checker.

    :param linter: Main interface object for Pylint plugins
    :type linter: Pylint object


first, second, third = args<EOL>return first, second, third<EOL>

Don't emit unbalanced tuple unpacking if the
    rhs of the assignment is a variable-length argument,
    because we don't know the actual length of the tuple.


if True:<EOL><INDENT>return [<NUM_LIT:1>, <NUM_LIT:2>]<EOL><DEDENT>return [<NUM_LIT:2>, <NUM_LIT:3>, <NUM_LIT:4>]<EOL>


first, second = <NUM_LIT:1>, <NUM_LIT:2><EOL>return first + second<EOL>


(first, second) = <NUM_LIT:1>, <NUM_LIT:2>, <NUM_LIT:3> <EOL>return first + second<EOL>


def function12(value=dict([('<STR_LIT:a>', <NUM_LIT:1>), ('<STR_LIT:b>', <NUM_LIT:2>)])):

return value<EOL>

dictionaries with items should not output item values in error message


return value<EOL>


Expects 0 args, but we are taking in account arguments with defaults.


return self<EOL>


return self, aax<EOL>


raise NotImplementedError<EOL>


return aaa<EOL>

overridden method, though don't use every argument


return aaa + aab + aac<EOL>


return {key: str(value) for key, value in key.items()}<EOL>

Should not raise unused-argument message because key is
used inside comprehension dict


with open("<STR_LIT>") as ctx.obj:  <EOL><INDENT>context.do()  <EOL>context = None<EOL><DEDENT>


var = nomoreknown  <EOL>assert var<EOL>


@decorator(arg=(i * <NUM_LIT:2> for i in range(<NUM_LIT:15>)))<EOL>def func2():

A function with a decorator that contains a genexpr.


bug2 = True<EOL>def on_click(event):<EOL><INDENT>"""<STR_LIT>"""<EOL>if event:<EOL><INDENT>nonlocal bug2<EOL>bug2 = not bug2<EOL><DEDENT><DEDENT>on_click(True)<EOL>


return first_argument<EOL>


return arg + arg<EOL>


return (self, arg)<EOL>


@staticmethod<EOL><INDENT>def static_method_in_class(param1, param2=<NUM_LIT:3>, *args): <DEDENT>

pass<EOL>


def func_in_class(self, param1, param2=<NUM_LIT:2>, *args):

pass<EOL>


return arg1.value + arg2<EOL>


return parameter<EOL>


return TESTSTR[None]<EOL>


return TESTTUPLE[<NUM_LIT:0>]<EOL>


return TESTLIST['<STR_LIT:0>']<EOL>


class ListTest(list):<EOL><INDENT>"""<STR_LIT>"""<EOL>def __getitem__(self, key):<EOL><INDENT>pass<EOL><DEDENT><DEDENT>test = ListTest()<EOL>test[None] = <NUM_LIT:0> <EOL>del test[None] <EOL>test[None][<NUM_LIT:0>] = <NUM_LIT:0> <EOL>test[<NUM_LIT:0>][<NUM_LIT:0>] = <NUM_LIT:0> <EOL>test[<NUM_LIT:0>] = <NUM_LIT:0> <EOL>del test[<NUM_LIT:0>]<EOL>

Get, set, and delete on a subclass of list that overrides __getitem__


class ListTest(list):<EOL><INDENT>"""<STR_LIT>"""<EOL>def __delitem__(self, key):<EOL><INDENT>pass<EOL><DEDENT><DEDENT>test = ListTest()<EOL>test[None][<NUM_LIT:0>] = <NUM_LIT:0> <EOL>test[None] = <NUM_LIT:0>  <EOL>test[<NUM_LIT:0>][<NUM_LIT:0>] = <NUM_LIT:0> <EOL>test[<NUM_LIT:0>] = <NUM_LIT:0> <EOL>del test[None] <EOL>del test[<NUM_LIT:0>]<EOL>

Get, set, and delete on a subclass of list that overrides __delitem__


class TupleTest(tuple):<EOL><INDENT>"""<STR_LIT>"""<EOL>pass<EOL><DEDENT>return TupleTest()[<NUM_LIT:0>]<EOL>

Index of subclass of tuple is an int constant


class ListTest(list):<EOL><INDENT>"""<STR_LIT>"""<EOL>pass<EOL><DEDENT>test = ListTest()<EOL>test[None] = <NUM_LIT:0> <EOL>del test[None] <EOL>test[<NUM_LIT:0>] = <NUM_LIT:0> <EOL>del test[<NUM_LIT:0>]<EOL>


raise ValueError('<STR_LIT>' % (name, value))<EOL>

The arguments have to be written as a tuple for formatting


lala = <NUM_LIT:10><EOL>


raise NotImplementedError()<EOL>


return self<EOL>


return trop<EOL>


super(NewAaaa, self).hop()<EOL>


return true_value if condition else false_value<EOL>


if text:<EOL><INDENT>yield "<STR_LIT>" % text<EOL>yield "<STR_LIT>"<EOL>yield "<STR_LIT>"<EOL>yield "<STR_LIT>"<EOL>yield "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>yield "<STR_LIT>"<EOL>yield "<STR_LIT>"<EOL>yield "<STR_LIT>"<EOL>yield "<STR_LIT>"<EOL>yield "<STR_LIT>"<EOL><DEDENT>


self.var = "<STR_LIT>"<EOL>


return (i for i in range(<NUM_LIT:10>))<EOL>


lst = []<EOL>for i in range(<NUM_LIT:10>):<EOL><INDENT>j = i * i<EOL>lst.append(lambda: j)  <EOL><DEDENT>return lst<EOL>


lst = []<EOL>for i in range(<NUM_LIT:10>):<EOL><INDENT>print(i)<EOL>lst.append(lambda: i)<EOL><DEDENT>


return (lambda: i for i in range(<NUM_LIT:10>))<EOL>

Problematic case.

    If this function is used as

    >>> [x() for x in bad_case5()]

    it behaves 'as expected', i.e. the result is range(10).

    If it's used with

    >>> lst = list(bad_case5())
    >>> [x() for x in lst]

    the result is [9] * 10 again.


import x<EOL>


pass<EOL>


print(value)<EOL>


def inner():<EOL><INDENT>return <NUM_LIT><EOL><DEDENT>return inner()<EOL>


...<EOL>

Test that an Ellipsis as a body does not trigger the error


partial_func = partial(root_function, <NUM_LIT:1>, <NUM_LIT:2>, <NUM_LIT:3>)<EOL>partial_func()<EOL>return root_function(<NUM_LIT:1>, <NUM_LIT:2>, <NUM_LIT:3>)<EOL>

Test we don't emit a FP for https://github.com/PyCQA/pylint/issues/2588


return Sub(), self<EOL>


return TESTLIST['<STR_LIT:0>':'<STR_LIT:1>':]<EOL>


return TESTLIST[<NUM_LIT:0>:<NUM_LIT:0>:<NUM_LIT:0>]<EOL>


class IndexType(object):<EOL><INDENT>"""<STR_LIT>"""<EOL>def __index__(self):<EOL><INDENT>"""<STR_LIT>"""<EOL>return <NUM_LIT:0><EOL><DEDENT><DEDENT>class IndexSubType(IndexType):<EOL><INDENT>"""<STR_LIT>"""<EOL>pass<EOL><DEDENT>return TESTLIST[IndexSubType():None:None]<EOL>

class with __index__ in superclass used as index


class IndexTest(object):<EOL><INDENT>"""<STR_LIT>"""<EOL>def __index__(self):<EOL><INDENT>"""<STR_LIT>"""<EOL>return <NUM_LIT:0><EOL><DEDENT><DEDENT>return TESTLIST[IndexTest():None:None]<EOL>


self._prov.hophop()<EOL>self._prov.hophophop()<EOL>


import socket<EOL>sckt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)<EOL>sckt.connect(('<STR_LIT:127.0.0.1>', <NUM_LIT>))<EOL>sckt.close()<EOL>

Test a regression
    Version used:

    - Pylint 0.10.0
    - Logilab common 0.15.0
    - Logilab astroid 0.15.1

    False E1101 positive, line 23:
    Instance of '_socketobject' has no 'connect' member


print(self._prov.attr)<EOL>print(self._prov.attribute)<EOL>


raise None<EOL>


import decimal<EOL>raise decimal.DivisionByZero(<NUM_LIT:4>)<EOL>

decimal.DivisionByZero is defined in C on Python 3.


raise NewStyleClass<EOL>


'<STR_LIT>'.format(<NUM_LIT>, {'<STR_LIT>': <NUM_LIT>})<EOL>'<STR_LIT>'.format(<NUM_LIT>, {'<STR_LIT>': <NUM_LIT>}, <NUM_LIT>) <EOL>'<STR_LIT>'.format(<NUM_LIT>)<EOL>

Test a regression using mixed manual position arguments
    and attribute access arguments.


return "<STR_LIT>".format(<NUM_LIT:1>)<EOL>

The following string is invalid, avoid crashing.


from collections import namedtuple<EOL>class Crash(namedtuple("<STR_LIT:C>", "<STR_LIT>")):<EOL><INDENT>"""<STR_LIT>"""<EOL>def __str__(self):<EOL><INDENT>return "<STR_LIT>".format(self)<EOL><DEDENT><DEDENT>return Crash<EOL>

Check that using a namedtuple subclass doesn't crash when
trying to infer EmptyNodes (resulted after mocking the
members of namedtuples).


'<STR_LIT>'.format(<NUM_LIT>, <NUM_LIT>)<EOL>'<STR_LIT>'.format(<NUM_LIT:1>, a=[<NUM_LIT:1>, <NUM_LIT:2>])<EOL>'<STR_LIT>'.format(<NUM_LIT>, <NUM_LIT>)<EOL>'<STR_LIT>'.format(<NUM_LIT>) <EOL>'<STR_LIT>'.format(<NUM_LIT>, <NUM_LIT>, <NUM_LIT>) <EOL>'<STR_LIT>'.format(<NUM_LIT:1>) <EOL>'<STR_LIT>'.format(<NUM_LIT:1>, a=<NUM_LIT:2>)<EOL>


__revision__ = <NUM_LIT:1> <EOL>return __revision__<EOL>


pass<EOL>

Second dummy function, don't emit function-redefined message
    because of the dummy name


bool_var = True<EOL>someint = <NUM_LIT:2><EOL>if not not bool_var:  <EOL><INDENT>pass<EOL><DEDENT>if not someint == <NUM_LIT:1>:  <EOL><INDENT>pass<EOL><DEDENT>if not someint != <NUM_LIT:1>:  <EOL><INDENT>pass<EOL><DEDENT>if not someint < <NUM_LIT:1>:  <EOL><INDENT>pass<EOL><DEDENT>if not someint > <NUM_LIT:1>:  <EOL><INDENT>pass<EOL><DEDENT>if not someint <= <NUM_LIT:1>:  <EOL><INDENT>pass<EOL><DEDENT>if not someint >= <NUM_LIT:1>:  <EOL><INDENT>pass<EOL><DEDENT>if not not someint:  <EOL><INDENT>pass<EOL><DEDENT>if not bool_var == True:  <EOL><INDENT>pass<EOL><DEDENT>if not bool_var == False:  <EOL><INDENT>pass<EOL><DEDENT>if not bool_var != True:  <EOL><INDENT>pass<EOL><DEDENT>if not True == True:  <EOL><INDENT>pass<EOL><DEDENT>if not <NUM_LIT:2> in [<NUM_LIT:3>, <NUM_LIT:4>]:  <EOL><INDENT>pass<EOL><DEDENT>if not someint is '<STR_LIT:test>':  <EOL><INDENT>pass<EOL><DEDENT>


def ignored_arguments_function(arga, argu, argi,<EOL>_arge=<NUM_LIT:0>, _argt=<NUM_LIT:1>, _args=None):

arg0 = <NUM_LIT:0><EOL>arg1 = arg0 * <NUM_LIT:1> + arga<EOL>arg2 = arg1 * <NUM_LIT:2> + argu<EOL>arg3 = arg2 * <NUM_LIT:3> + argi<EOL>arg4 = arg3 * <NUM_LIT:4> + _arge<EOL>arg5 = arg4 * <NUM_LIT:5> + _argt<EOL>arg6 = arg5 * <NUM_LIT:6><EOL>arg7 = arg6 * <NUM_LIT:7><EOL>arg8 = arg7 * <NUM_LIT:8><EOL>arg9 = arg8 * <NUM_LIT:9><EOL>arg9 += arg0<EOL>if _args:<EOL><INDENT>arg9 += sum(_args)<EOL><DEDENT>return arg9<EOL>

pylint will ignore _arge, _argt, _args.

    Consequently pylint will only coun 13 arguments.


def too_many_arguments_function(arga, argu, argi, arge, argt, args):

arga = argu<EOL>arga += argi<EOL>arga += arge<EOL>arga += argt<EOL>arga += args<EOL>return arga<EOL>

pylint will complains about too many arguments.


var = range(<NUM_LIT:10>)<EOL>if isinstance(var[<NUM_LIT:1>], (int, float)):<EOL><INDENT>pass<EOL><DEDENT>result = isinstance(var[<NUM_LIT:2>], (int, float))<EOL>if isinstance(var[<NUM_LIT:3>], int) or isinstance(var[<NUM_LIT:3>], float) or isinstance(var[<NUM_LIT:3>], list) and True:  <EOL><INDENT>pass<EOL><DEDENT>result = isinstance(var[<NUM_LIT:4>], int) or isinstance(var[<NUM_LIT:4>], float) or isinstance(var[<NUM_LIT:5>], list) and False  <EOL>result = isinstance(var[<NUM_LIT:5>], int) or True or isinstance(var[<NUM_LIT:5>], float)  <EOL>infered_isinstance = isinstance<EOL>result = infered_isinstance(var[<NUM_LIT:6>], int) or infered_isinstance(var[<NUM_LIT:6>], float) or infered_isinstance(var[<NUM_LIT:6>], list) and False   <EOL>result = isinstance(var[<NUM_LIT:10>], str) or isinstance(var[<NUM_LIT:10>], int) and var[<NUM_LIT:8>] * <NUM_LIT> or isinstance(var[<NUM_LIT:10>], float) and var[<NUM_LIT:5>] * <NUM_LIT> or isinstance(var[<NUM_LIT:10>], list)   <EOL>result = isinstance(var[<NUM_LIT:11>], int) or isinstance(var[<NUM_LIT:11>], int) or isinstance(var[<NUM_LIT:11>], float)   <EOL>result = isinstance(var[<NUM_LIT:20>])<EOL>result = isinstance()<EOL>result = isinstance(var[<NUM_LIT:12>], (int, float)) or isinstance(var[<NUM_LIT:12>], list)  <EOL>result = isinstance(var[<NUM_LIT:5>], int) and var[<NUM_LIT:5>] * <NUM_LIT> or isinstance(var[<NUM_LIT:5>], float) and var[<NUM_LIT:5>] * <NUM_LIT><EOL>result = isinstance(var[<NUM_LIT:7>], int) or not isinstance(var[<NUM_LIT:7>], float)<EOL>result = isinstance(var[<NUM_LIT:6>], int) or isinstance(var[<NUM_LIT:7>], float)<EOL>result = isinstance(var[<NUM_LIT:6>], int) or isinstance(var[<NUM_LIT:7>], int)<EOL>return result<EOL>


return meta("<STR_LIT>", (base, ), {})<EOL>

Create a new type that can be used as a metaclass.


print(some_arg, some_other_arg)<EOL>


Ignored since the method is in the interface.


BAD_LOCAL_VAR = <NUM_LIT:1>  <EOL>print(BAD_LOCAL_VAR)<EOL>


pass<EOL>


Too many branches only if we take
    into consideration the nested functions.


return sorted([(isinstance(c.node, astroid.ClassDef), c.title) for c in classes])<EOL>


result = []<EOL>for rel_type, rels in relations.items():<EOL><INDENT>for rel in rels:<EOL><INDENT>result.append((rel_type, rel.from_object.title, rel.to_object.title))<EOL><DEDENT><DEDENT>result.sort()<EOL>return result<EOL>

extract relation indices from a relation list


return re.sub(<EOL>"<STR_LIT>", "<STR_LIT>", output.replace("<STR_LIT:\\>", "<STR_LIT:/>"), flags=re.MULTILINE<EOL>)<EOL>

Remove version-specific tox parent directories from paths.


print("<STR_LIT>" % {'<STR_LIT>': <NUM_LIT:1>, '<STR_LIT>': <NUM_LIT:2>}) <EOL>print("<STR_LIT:%s>" % (PARG_1, PARG_2)) <EOL>print("<STR_LIT>" % {'<STR_LIT>': <NUM_LIT:1>, '<STR_LIT>': <NUM_LIT:2>}) <EOL>print("<STR_LIT>" % {'<STR_LIT>': <NUM_LIT:1>}) <EOL>print("<STR_LIT>" % {'<STR_LIT>': <NUM_LIT:1>, '<STR_LIT>':<NUM_LIT:2>, '<STR_LIT>':<NUM_LIT:3>}) <EOL>print("<STR_LIT>" % {'<STR_LIT>': <NUM_LIT:1>, <NUM_LIT:2>:<NUM_LIT:3>}) <EOL>print("<STR_LIT>" % (<NUM_LIT:2>, <NUM_LIT:3>)) <EOL>print("<STR_LIT>" % [<NUM_LIT:2>, <NUM_LIT:3>]) <EOL>print("<STR_LIT>" % PARG_1)<EOL>print("<STR_LIT>" % PARG_2)<EOL>print("<STR_LIT>" % <NUM_LIT:1>)<EOL>


print(self, sys)<EOL>


import os as ass<EOL>ass.remove(yooo)<EOL>import re<EOL>re.compile('<STR_LIT>')<EOL>


<EOL>var = <NUM_LIT:0><EOL>


self._thing = value<EOL>


return<EOL>

Function returning None from bare return statement.


yield <NUM_LIT:2><EOL>


raise NotImplementedError<EOL>

use to return something in concrete implementation


for val in seq:<EOL><INDENT>pass<EOL><DEDENT>for val in seq:<EOL><INDENT>yield val<EOL><DEDENT>


self.e1101 = <NUM_LIT:1><EOL>


def __init__(self, host=None, port=<NUM_LIT:0>):

telnetlib.Telnet.__init__(self, host, port)<EOL>

Constructor.
When called without arguments, create an unconnected instance.
With a hostname argument, it connects the instance; a port
number is optional.
Parameter:
- host: IP address of the host
- port: Port number


self.attr = <NUM_LIT:4><EOL>


def readUntilArray(self, matches, _=None):

self.process_rawq()<EOL>maxLength = <NUM_LIT:0><EOL>for match in matches:<EOL><INDENT>if len(match) > maxLength:<EOL><INDENT>maxLength = len(match)<EOL><DEDENT><DEDENT>

Read until a given string is encountered or until timeout.
...


if True:<EOL><INDENT>return <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>yield <NUM_LIT:2><EOL><DEDENT>


if True:<EOL><INDENT>yield <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>return <NUM_LIT:2><EOL><DEDENT>


import sys<EOL>del sys<EOL>


branches = <NUM_LIT:1><EOL>if node.orelse and len(node.orelse) > <NUM_LIT:1>:<EOL><INDENT>branches += <NUM_LIT:1><EOL><DEDENT>self.inc_branch(branches)<EOL>self.stmts += branches<EOL>


def _astroid_wrapper(func, modname):<EOL><INDENT>return func(modname)<EOL><DEDENT>return project_from_files([module], _astroid_wrapper, project_name=name)<EOL>

return an astroid project representation


<EOL>print(self.bla)<EOL>try:<EOL><INDENT>print(self.blip)<EOL><DEDENT>except UndefinedName: <EOL><INDENT>print(self.blip)<EOL><DEDENT>print(self.blip)<EOL>


<EOL>print(self.bla) <EOL>print(self.blop)<EOL>


myint = <NUM_LIT:2><EOL>if myint == <NUM_LIT:5>:<EOL><INDENT>return myint<EOL><DEDENT>elif myint == <NUM_LIT:6>:<EOL><INDENT>return myint<EOL><DEDENT>elif myint == <NUM_LIT:7>:<EOL><INDENT>return myint<EOL><DEDENT>elif myint == <NUM_LIT:8>:<EOL><INDENT>return myint<EOL><DEDENT>elif myint == <NUM_LIT:9>:<EOL><INDENT>return myint<EOL><DEDENT>elif myint == <NUM_LIT:10>:<EOL><INDENT>if myint == <NUM_LIT:8>:<EOL><INDENT>while True:<EOL><INDENT>return True<EOL><DEDENT><DEDENT>elif myint == <NUM_LIT:8>:<EOL><INDENT>with myint:<EOL><INDENT>return <NUM_LIT:8><EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>if myint == <NUM_LIT:2>:<EOL><INDENT>return myint<EOL><DEDENT>return myint<EOL><DEDENT>return myint<EOL>


pass<EOL>


return messages<EOL>


return "<STR_LIT>" % (ex.file, "<STR_LIT:U+002CU+0020>".join(ex.args))<EOL>

function used to replace default __str__ method of exception instances


def set_msg_status(self, msg, line, status):

assert line > <NUM_LIT:0><EOL>try:<EOL><INDENT>self._module_msgs_state[msg.msgid][line] = status<EOL><DEDENT>except KeyError:<EOL><INDENT>self._module_msgs_state[msg.msgid] = {line: status}<EOL><DEDENT>

Set status (enabled/disable) for a given message at a given line


for modname in modnames:<EOL><INDENT>if modname in self._dynamic_plugins:<EOL><INDENT>continue<EOL><DEDENT>self._dynamic_plugins.add(modname)<EOL>module = modutils.load_module_from_name(modname)<EOL>module.register(self)<EOL><DEDENT>

take a list of module names which are pylint plugins and load
        and register them


<EOL>previous_stats = config.load_results(self.file_state.base_name)<EOL>if self.stats["<STR_LIT>"] == <NUM_LIT:0>:<EOL><INDENT>return<EOL><DEDENT>evaluation = self.config.evaluation<EOL>try:<EOL><INDENT>note = eval(evaluation, {}, self.stats)  <EOL><DEDENT>except Exception as ex:<EOL><INDENT>msg = "<STR_LIT>" % ex<EOL><DEDENT>else:<EOL><INDENT>self.stats["<STR_LIT>"] = note<EOL>msg = "<STR_LIT>" % note<EOL>pnote = previous_stats.get("<STR_LIT>")<EOL>if pnote is not None:<EOL><INDENT>msg += "<STR_LIT>" % (pnote, note - pnote)<EOL><DEDENT><DEDENT>if self.config.score:<EOL><INDENT>sect = report_nodes.EvaluationSection(msg)<EOL>self.reporter.display_reports(sect)<EOL><DEDENT>


assert checker.priority <= <NUM_LIT:0>, "<STR_LIT>"<EOL>self._checkers[checker.name].append(checker)<EOL>for r_id, r_title, r_cb in checker.reports:<EOL><INDENT>self.register_report(r_id, r_title, r_cb, checker)<EOL><DEDENT>self.register_options_provider(checker)<EOL>if hasattr(checker, "<STR_LIT>"):<EOL><INDENT>self.msgs_store.register_messages_from_checker(checker)<EOL><DEDENT>checker.load_defaults()<EOL>if not getattr(checker, "<STR_LIT>", True):<EOL><INDENT>self.disable(checker.name)<EOL><DEDENT>

register a new checker

        checker is an object implementing IRawChecker or / and IAstroidChecker


self.disable("<STR_LIT:all>")<EOL>self.enable("<STR_LIT>")<EOL>if self._error_mode:<EOL><INDENT>for msg_id in self._checker_messages("<STR_LIT>"):<EOL><INDENT>if msg_id.startswith("<STR_LIT:E>"):<EOL><INDENT>self.enable(msg_id)<EOL><DEDENT>else:<EOL><INDENT>self.disable(msg_id)<EOL><DEDENT><DEDENT><DEDENT>config_parser = self.cfgfile_parser<EOL>if config_parser.has_option("<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>value = config_parser.get("<STR_LIT>", "<STR_LIT>")<EOL>self.global_set_option("<STR_LIT>", value)<EOL><DEDENT>self._python3_porting_mode = True<EOL>

Disable all other checkers and enable Python 3 warnings.


def report_messages_by_module_stats(sect, stats, _):

if len(stats["<STR_LIT>"]) == <NUM_LIT:1>:<EOL><INDENT>raise exceptions.EmptyReportError()<EOL><DEDENT>by_mod = collections.defaultdict(dict)<EOL>for m_type in ("<STR_LIT>", "<STR_LIT:error>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>total = stats[m_type]<EOL>for module in stats["<STR_LIT>"].keys():<EOL><INDENT>mod_total = stats["<STR_LIT>"][module][m_type]<EOL>if total == <NUM_LIT:0>:<EOL><INDENT>percent = <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>percent = float((mod_total) * <NUM_LIT:100>) / total<EOL><DEDENT>by_mod[module][m_type] = percent<EOL><DEDENT><DEDENT>sorted_result = []<EOL>for module, mod_info in by_mod.items():<EOL><INDENT>sorted_result.append(<EOL>(<EOL>mod_info["<STR_LIT:error>"],<EOL>mod_info["<STR_LIT>"],<EOL>mod_info["<STR_LIT>"],<EOL>mod_info["<STR_LIT>"],<EOL>module,<EOL>)<EOL>)<EOL><DEDENT>sorted_result.sort()<EOL>sorted_result.reverse()<EOL>lines = ["<STR_LIT>", "<STR_LIT:error>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>"]<EOL>for line in sorted_result:<EOL><INDENT>if all(entry == <NUM_LIT:0> for entry in line[:-<NUM_LIT:1>]):<EOL><INDENT>continue<EOL><DEDENT>lines.append(line[-<NUM_LIT:1>])<EOL>for val in line[:-<NUM_LIT:1>]:<EOL><INDENT>lines.append("<STR_LIT>" % val)<EOL><DEDENT><DEDENT>if len(lines) == <NUM_LIT:5>:<EOL><INDENT>raise exceptions.EmptyReportError()<EOL><DEDENT>sect.append(report_nodes.Table(children=lines, cols=<NUM_LIT:5>, rheaders=<NUM_LIT:1>))<EOL>

make errors / warnings by modules report


def cb_generate_config(self, *args, **kwargs):

self.linter.generate_config(skipsections=("<STR_LIT>",))<EOL>sys.exit(<NUM_LIT:0>)<EOL>

optik callback for sample config file generation


self._plugins.extend(utils._splitstrip(value))<EOL>

callback for option preprocessing (i.e. before option parsing)


def check_astroid_module(self, ast_node, walker, rawcheckers, tokencheckers):

try:<EOL><INDENT>tokens = utils.tokenize_module(ast_node)<EOL><DEDENT>except tokenize.TokenError as ex:<EOL><INDENT>self.add_message("<STR_LIT>", line=ex.args[<NUM_LIT:1>][<NUM_LIT:0>], args=ex.args[<NUM_LIT:0>])<EOL>return None<EOL><DEDENT>if not ast_node.pure_python:<EOL><INDENT>self.add_message("<STR_LIT>", args=ast_node.name)<EOL><DEDENT>else:<EOL><INDENT>self.process_tokens(tokens)<EOL>if self._ignore_file:<EOL><INDENT>return False<EOL><DEDENT>self.file_state.collect_block_lines(self.msgs_store, ast_node)<EOL>for checker in rawcheckers:<EOL><INDENT>checker.process_module(ast_node)<EOL><DEDENT>for checker in tokencheckers:<EOL><INDENT>checker.process_tokens(tokens)<EOL><DEDENT><DEDENT>walker.walk(ast_node)<EOL>return True<EOL>

Check a module from its astroid representation.


self.reporter = reporter<EOL>reporter.linter = self<EOL>

set the reporter used to display messages and reports


exec(value)<EOL>

exec arbitrary code to set sys.path for instance


@staticmethod<EOL><INDENT>def should_analyze_file(modname, path, is_argument=False):<DEDENT>

if is_argument:<EOL><INDENT>return True<EOL><DEDENT>return path.endswith("<STR_LIT>")<EOL>

Returns whether or not a module should be checked.

        This implementation returns True for all python source file, indicating
        that all files should be linted.

        Subclasses may override this method to indicate that modules satisfying
        certain conditions should not be linted.

        :param str modname: The name of the module to be checked.
        :param str path: The full path to the source code of the module.
        :param bool is_argument: Whetter the file is an argument to pylint or not.
                                 Files which respect this property are always
                                 checked, since the user requested it explicitly.
        :returns: True if the module should be checked.
        :rtype: bool


orig = list(sys.path)<EOL>changes = []<EOL>for arg in args:<EOL><INDENT>path = _get_python_path(arg)<EOL>if path in changes:<EOL><INDENT>continue<EOL><DEDENT>else:<EOL><INDENT>changes.append(path)<EOL><DEDENT><DEDENT>sys.path[:] = changes + ["<STR_LIT:.>"] + sys.path<EOL>try:<EOL><INDENT>yield<EOL><DEDENT>finally:<EOL><INDENT>sys.path[:] = orig<EOL><DEDENT>

Prepare sys.path for running the linter checks.

    Within this context, each of the given arguments is importable.
    Paths are added to sys.path in corresponding order to the arguments.
    We avoid adding duplicate directories to sys.path.
    `sys.path` is reset to its original value upon exiting this context.


def cb_help_message(self, option, optname, value, parser):

self.linter.msgs_store.help_message(utils._splitstrip(value))<EOL>sys.exit(<NUM_LIT:0>)<EOL>

optik callback for printing some help about a particular message


<EOL>self._logging_names = set()<EOL>logging_mods = self.config.logging_modules<EOL>self._format_style = self.config.logging_format_style<EOL>self._logging_modules = set(logging_mods)<EOL>self._from_imports = {}<EOL>for logging_mod in logging_mods:<EOL><INDENT>parts = logging_mod.rsplit("<STR_LIT:.>", <NUM_LIT:1>)<EOL>if len(parts) > <NUM_LIT:1>:<EOL><INDENT>self._from_imports[parts[<NUM_LIT:0>]] = parts[<NUM_LIT:1>]<EOL><DEDENT><DEDENT>

Clears any state left in this checker from last module checked.


def _check_format_string(self, node, format_arg):

num_args = _count_supplied_tokens(node.args[format_arg + <NUM_LIT:1> :])<EOL>if not num_args:<EOL><INDENT>return<EOL><DEDENT>format_string = node.args[format_arg].value<EOL>if not isinstance(format_string, str):<EOL><INDENT>required_num_args = <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>if self._format_style == "<STR_LIT>":<EOL><INDENT>keyword_args, required_num_args, _, _ = utils.parse_format_string(<EOL>format_string<EOL>)<EOL>if keyword_args:<EOL><INDENT>return<EOL><DEDENT><DEDENT>elif self._format_style == "<STR_LIT>":<EOL><INDENT>keyword_arguments, implicit_pos_args, explicit_pos_args = utils.parse_format_method_string(<EOL>format_string<EOL>)<EOL>keyword_args_cnt = len(<EOL>set(k for k, l in keyword_arguments if not isinstance(k, int))<EOL>)<EOL>required_num_args = (<EOL>keyword_args_cnt + implicit_pos_args + explicit_pos_args<EOL>)<EOL><DEDENT><DEDENT>except utils.UnsupportedFormatCharacter as ex:<EOL><INDENT>char = format_string[ex.index]<EOL>self.add_message(<EOL>"<STR_LIT>",<EOL>node=node,<EOL>args=(char, ord(char), ex.index),<EOL>)<EOL>return<EOL><DEDENT>except utils.IncompleteFormatString:<EOL><INDENT>self.add_message("<STR_LIT>", node=node)<EOL>return<EOL><DEDENT><DEDENT>if num_args > required_num_args:<EOL><INDENT>self.add_message("<STR_LIT>", node=node)<EOL><DEDENT>elif num_args < required_num_args:<EOL><INDENT>self.add_message("<STR_LIT>", node=node)<EOL><DEDENT>

Checks that format string tokens match the supplied arguments.

        Args:
          node (astroid.node_classes.NodeNG): AST node to be checked.
          format_arg (int): Index of the format string in the node arguments.


for module, as_name in node.names:<EOL><INDENT>if module in self._logging_modules:<EOL><INDENT>self._logging_names.add(as_name or module)<EOL><DEDENT><DEDENT>

Checks to see if this module uses Python's built-in logging.


return isinstance(operand, astroid.Const) and operand.name == "<STR_LIT:str>"<EOL>

Return True if the operand in argument is a literal string


def is_method_call(func, types=(), methods=()):

return (<EOL>isinstance(func, astroid.BoundMethod)<EOL>and isinstance(func.bound, astroid.Instance)<EOL>and (func.bound.name in types if types else True)<EOL>and (func.name in methods if methods else True)<EOL>)<EOL>

Determines if a BoundMethod node represents a method call.

    Args:
      func (astroid.BoundMethod): The BoundMethod AST node to check.
      types (Optional[String]): Optional sequence of caller type names to restrict check.
      methods (Optional[String]): Optional sequence of method names to restrict check.

    Returns:
      bool: true if the node represents a method call for the given type and
      method names, False otherwise.


linter.register_checker(EncodingChecker(linter))<EOL>linter.register_checker(ByIdManagedMessagesChecker(linter))<EOL>

required method to auto register this checker


lines = []<EOL>nodes = data.items()<EOL>for i, (mod, (sub, files)) in enumerate(sorted(nodes, key=lambda x: x[<NUM_LIT:0>])):<EOL><INDENT>if not files:<EOL><INDENT>files = "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>files = "<STR_LIT>" % "<STR_LIT:U+002C>".join(sorted(files))<EOL><DEDENT>if indent_str is None:<EOL><INDENT>lines.append("<STR_LIT>" % (mod, files))<EOL>sub_indent_str = "<STR_LIT:U+0020>"<EOL><DEDENT>else:<EOL><INDENT>lines.append(r"<STR_LIT>" % (indent_str, mod, files))<EOL>if i == len(nodes) - <NUM_LIT:1>:<EOL><INDENT>sub_indent_str = "<STR_LIT>" % indent_str<EOL><DEDENT>else:<EOL><INDENT>sub_indent_str = "<STR_LIT>" % indent_str<EOL><DEDENT><DEDENT>if sub:<EOL><INDENT>lines.append(_repr_tree_defs(sub, sub_indent_str))<EOL><DEDENT><DEDENT>return "<STR_LIT:\n>".join(lines)<EOL>

return a string which represents imports as a tree


tree_defs = {}<EOL>for mod, files in mod_files_list:<EOL><INDENT>node = (tree_defs, ())<EOL>for prefix in mod.split("<STR_LIT:.>"):<EOL><INDENT>node = node[<NUM_LIT:0>].setdefault(prefix, [{}, []])<EOL><DEDENT>node[<NUM_LIT:1>] += files<EOL><DEDENT>return tree_defs<EOL>

get a list of 2-uple (module, list_of_files_which_import_this_module),
    it will return a dictionary to represent this as a tree


def _report_dependencies_graph(self, sect, _, _dummy):

dep_info = self.stats["<STR_LIT>"]<EOL>if not dep_info or not (<EOL>self.config.import_graph<EOL>or self.config.ext_import_graph<EOL>or self.config.int_import_graph<EOL>):<EOL><INDENT>raise EmptyReportError()<EOL><DEDENT>filename = self.config.import_graph<EOL>if filename:<EOL><INDENT>_make_graph(filename, dep_info, sect, "<STR_LIT>")<EOL><DEDENT>filename = self.config.ext_import_graph<EOL>if filename:<EOL><INDENT>_make_graph(filename, self._external_dependencies_info(), sect, "<STR_LIT>")<EOL><DEDENT>filename = self.config.int_import_graph<EOL>if filename:<EOL><INDENT>_make_graph(filename, self._internal_dependencies_info(), sect, "<STR_LIT>")<EOL><DEDENT>

write dependencies as a dot (graphviz) file


done = {}<EOL>printer = DotBackend(filename[:-<NUM_LIT:4>], rankdir="<STR_LIT>")<EOL>printer.emit('<STR_LIT>')<EOL>for modname, dependencies in sorted(dep_info.items()):<EOL><INDENT>done[modname] = <NUM_LIT:1><EOL>printer.emit_node(modname)<EOL>for depmodname in dependencies:<EOL><INDENT>if depmodname not in done:<EOL><INDENT>done[depmodname] = <NUM_LIT:1><EOL>printer.emit_node(depmodname)<EOL><DEDENT><DEDENT><DEDENT>for depmodname, dependencies in sorted(dep_info.items()):<EOL><INDENT>for modname in dependencies:<EOL><INDENT>printer.emit_edge(modname, depmodname)<EOL><DEDENT><DEDENT>printer.generate(filename)<EOL>


basename = node.modname<EOL>imported_module = self._get_imported_module(node, basename)<EOL>self._check_import_as_rename(node)<EOL>self._check_misplaced_future(node)<EOL>self._check_deprecated_module(node, basename)<EOL>self._check_preferred_module(node, basename)<EOL>self._check_wildcard_imports(node, imported_module)<EOL>self._check_same_line_imports(node)<EOL>self._check_reimport(node, basename=basename, level=node.level)<EOL>if isinstance(node.parent, astroid.Module):<EOL><INDENT>self._check_position(node)<EOL><DEDENT>if isinstance(node.scope(), astroid.Module):<EOL><INDENT>self._record_import(node, imported_module)<EOL><DEDENT>if imported_module is None:<EOL><INDENT>return<EOL><DEDENT>modnode = node.root()<EOL>self._check_relative_import(modnode, node, imported_module, basename)<EOL>for name, _ in node.names:<EOL><INDENT>if name != "<STR_LIT:*>":<EOL><INDENT>self._add_imported_module(node, "<STR_LIT>" % (imported_module.name, name))<EOL><DEDENT>else:<EOL><INDENT>self._add_imported_module(node, imported_module.name)<EOL><DEDENT><DEDENT>


self._check_reimport(node)<EOL>self._check_import_as_rename(node)<EOL>modnode = node.root()<EOL>names = [name for name, _ in node.names]<EOL>if len(names) >= <NUM_LIT:2>:<EOL><INDENT>self.add_message("<STR_LIT>", args="<STR_LIT:U+002CU+0020>".join(names), node=node)<EOL><DEDENT>for name in names:<EOL><INDENT>self._check_deprecated_module(node, name)<EOL>self._check_preferred_module(node, name)<EOL>imported_module = self._get_imported_module(node, name)<EOL>if isinstance(node.parent, astroid.Module):<EOL><INDENT>self._check_position(node)<EOL><DEDENT>if isinstance(node.scope(), astroid.Module):<EOL><INDENT>self._record_import(node, imported_module)<EOL><DEDENT>if imported_module is None:<EOL><INDENT>continue<EOL><DEDENT>self._check_relative_import(modnode, node, imported_module, name)<EOL>self._add_imported_module(node, imported_module.name)<EOL><DEDENT>

triggered when an import statement is seen


def _check_preferred_module(self, node, mod_path):

if mod_path in self.preferred_modules:<EOL><INDENT>self.add_message(<EOL>"<STR_LIT>",<EOL>node=node,<EOL>args=(self.preferred_modules[mod_path], mod_path),<EOL>)<EOL><DEDENT>

check if the module has a preferred replacement


def _check_relative_import(<EOL>self, modnode, importnode, importedmodnode, importedasname<EOL>):

if not self.linter.is_message_enabled("<STR_LIT>"):<EOL><INDENT>return None<EOL><DEDENT>if importedmodnode.file is None:<EOL><INDENT>return False  <EOL><DEDENT>if modnode is importedmodnode:<EOL><INDENT>return False  <EOL><DEDENT>if modnode.absolute_import_activated() or getattr(importnode, "<STR_LIT>", None):<EOL><INDENT>return False<EOL><DEDENT>if importedmodnode.name != importedasname:<EOL><INDENT>self.add_message(<EOL>"<STR_LIT>",<EOL>args=(importedasname, importedmodnode.name),<EOL>node=importnode,<EOL>)<EOL>return None<EOL><DEDENT>return None<EOL>

check relative import. node is either an Import or From node, modname
        the imported module name.


def _add_imported_module(self, node, importedmodname):

module_file = node.root().file<EOL>context_name = node.root().name<EOL>base = os.path.splitext(os.path.basename(module_file))[<NUM_LIT:0>]<EOL>try:<EOL><INDENT>importedmodname = astroid.modutils.get_module_part(<EOL>importedmodname, module_file<EOL>)<EOL><DEDENT>except ImportError:<EOL><INDENT>pass<EOL><DEDENT>if context_name == importedmodname:<EOL><INDENT>self.add_message("<STR_LIT>", node=node)<EOL><DEDENT>elif not astroid.modutils.is_standard_module(importedmodname):<EOL><INDENT>if base != "<STR_LIT>" and context_name not in self._module_pkg:<EOL><INDENT>self._module_pkg[context_name] = context_name.rsplit("<STR_LIT:.>", <NUM_LIT:1>)[<NUM_LIT:0>]<EOL><DEDENT>importedmodnames = self.stats["<STR_LIT>"].setdefault(<EOL>importedmodname, set()<EOL>)<EOL>if context_name not in importedmodnames:<EOL><INDENT>importedmodnames.add(context_name)<EOL><DEDENT>self.import_graph[context_name].add(importedmodname)<EOL>if not self.linter.is_message_enabled("<STR_LIT>", line=node.lineno):<EOL><INDENT>self._excluded_edges[context_name].add(importedmodname)<EOL><DEDENT><DEDENT>

notify an imported module, used to analyze dependencies


self._to_consume = [NamesConsumer(node, "<STR_LIT>")]<EOL>self._postponed_evaluation_enabled = is_postponed_evaluation_enabled(node)<EOL>for name, stmts in node.locals.items():<EOL><INDENT>if utils.is_builtin(name) and not utils.is_inside_except(stmts[<NUM_LIT:0>]):<EOL><INDENT>if self._should_ignore_redefined_builtin(stmts[<NUM_LIT:0>]) or name == "<STR_LIT>":<EOL><INDENT>continue<EOL><DEDENT>self.add_message("<STR_LIT>", args=name, node=stmts[<NUM_LIT:0>])<EOL><DEDENT><DEDENT>

visit module : update consumption analysis variable
        checks globals doesn't overrides builtins


try:<EOL><INDENT>parent = next(klass.local_attr_ancestors(name))<EOL><DEDENT>except (StopIteration, KeyError):<EOL><INDENT>return None<EOL><DEDENT>try:<EOL><INDENT>meth_node = parent[name]<EOL><DEDENT>except KeyError:<EOL><INDENT>return None<EOL><DEDENT>if isinstance(meth_node, astroid.FunctionDef):<EOL><INDENT>return meth_node<EOL><DEDENT>return None<EOL>


def mark_as_consumed(self, name, new_node):

self.consumed[name] = new_node<EOL>del self.to_consume[name]<EOL>

Mark the name as consumed and delete it from
the to_consume dictionary


def _has_homonym_in_upper_function_scope(self, node, index):

for _consumer in self._to_consume[index - <NUM_LIT:1> :: -<NUM_LIT:1>]:<EOL><INDENT>if _consumer.scope_type == "<STR_LIT>" and node.name in _consumer.to_consume:<EOL><INDENT>return True<EOL><DEDENT><DEDENT>return False<EOL>

Return True if there is a node with the same name in the to_consume dict of an upper scope
and if that scope is a function

:param node: node to check for
:type node: astroid.Node
:param index: index of the current consumer inside self._to_consume
:type index: int
:return: True if there is a node with the same name in the to_consume dict of an upper scope
         and if that scope is a function
:rtype: bool


def _check_unpacking(self, infered, node, targets):

if utils.is_inside_abstract_class(node):<EOL><INDENT>return<EOL><DEDENT>if utils.is_comprehension(node):<EOL><INDENT>return<EOL><DEDENT>if infered is astroid.Uninferable:<EOL><INDENT>return<EOL><DEDENT>if (<EOL>isinstance(infered.parent, astroid.Arguments)<EOL>and isinstance(node.value, astroid.Name)<EOL>and node.value.name == infered.parent.vararg<EOL>):<EOL><INDENT>return<EOL><DEDENT>if isinstance(infered, (astroid.Tuple, astroid.List)):<EOL><INDENT>values = infered.itered()<EOL>if len(targets) != len(values):<EOL><INDENT>if any(isinstance(target, astroid.Starred) for target in targets):<EOL><INDENT>return<EOL><DEDENT>self.add_message(<EOL>"<STR_LIT>",<EOL>node=node,<EOL>args=(<EOL>_get_unpacking_extra_info(node, infered),<EOL>len(targets),<EOL>len(values),<EOL>),<EOL>)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if not utils.is_iterable(infered):<EOL><INDENT>self.add_message(<EOL>"<STR_LIT>",<EOL>node=node,<EOL>args=(_get_unpacking_extra_info(node, infered),),<EOL>)<EOL><DEDENT><DEDENT>

Check for unbalanced tuple unpacking
        and unpacking non sequences.


assert len(self._to_consume) == <NUM_LIT:1><EOL>not_consumed = self._to_consume.pop().to_consume<EOL>if "<STR_LIT>" in node.locals:<EOL><INDENT>self._check_all(node, not_consumed)<EOL><DEDENT>self._check_globals(not_consumed)<EOL>if not self.config.init_import and node.package:<EOL><INDENT>return<EOL><DEDENT>self._check_imports(not_consumed)<EOL>


leave class: update consumption analysis variable


leave setcomp: update consumption analysis variable


if node.type_comment_returns:<EOL><INDENT>self._store_type_annotation_node(node.type_comment_returns)<EOL><DEDENT>if node.type_comment_args:<EOL><INDENT>for argument_annotation in node.type_comment_args:<EOL><INDENT>self._store_type_annotation_node(argument_annotation)<EOL><DEDENT><DEDENT>not_consumed = self._to_consume.pop().to_consume<EOL>if not (<EOL>self.linter.is_message_enabled("<STR_LIT>")<EOL>or self.linter.is_message_enabled("<STR_LIT>")<EOL>or self.linter.is_message_enabled("<STR_LIT>")<EOL>):<EOL><INDENT>return<EOL><DEDENT>if utils.is_error(node):<EOL><INDENT>return<EOL><DEDENT>is_method = node.is_method()<EOL>if is_method and node.is_abstract():<EOL><INDENT>return<EOL><DEDENT>global_names = _flattened_scope_names(node.nodes_of_class(astroid.Global))<EOL>nonlocal_names = _flattened_scope_names(node.nodes_of_class(astroid.Nonlocal))<EOL>for name, stmts in not_consumed.items():<EOL><INDENT>self._check_is_unused(name, node, stmts[<NUM_LIT:0>], global_names, nonlocal_names)<EOL><DEDENT>

leave function: check function's locals are consumed


try:<EOL><INDENT>module = stmt.do_import_module(stmt.modname)<EOL><DEDENT>except astroid.AstroidBuildingException:<EOL><INDENT>return None<EOL><DEDENT>for local_node in module.locals.get(name, []):<EOL><INDENT>if isinstance(local_node, astroid.ImportFrom) and local_node.modname == FUTURE:<EOL><INDENT>return True<EOL><DEDENT><DEDENT>return None<EOL>

Check if the name is a future import from another module.


consumed = []  <EOL>for child_node in node.get_children():<EOL><INDENT>if isinstance(child_node, astroid.ClassDef):<EOL><INDENT>consumed.extend(self._check_classdef_metaclasses(child_node, node))<EOL><DEDENT><DEDENT>for scope_locals, name in consumed:<EOL><INDENT>scope_locals.pop(name, None)<EOL><DEDENT>

Update consumption analysis for metaclasses.


def _check_module_attrs(self, node, module, module_names):

assert isinstance(module, astroid.Module), module<EOL>while module_names:<EOL><INDENT>name = module_names.pop(<NUM_LIT:0>)<EOL>if name == "<STR_LIT>":<EOL><INDENT>module = None<EOL>break<EOL><DEDENT>try:<EOL><INDENT>module = next(module.getattr(name)[<NUM_LIT:0>].infer())<EOL>if module is astroid.Uninferable:<EOL><INDENT>return None<EOL><DEDENT><DEDENT>except astroid.NotFoundError:<EOL><INDENT>if module.name in self._ignored_modules:<EOL><INDENT>return None<EOL><DEDENT>self.add_message(<EOL>"<STR_LIT>", args=(name, module.name), node=node<EOL>)<EOL>return None<EOL><DEDENT>except astroid.InferenceError:<EOL><INDENT>return None<EOL><DEDENT><DEDENT>if module_names:<EOL><INDENT>modname = module.name if module else "<STR_LIT>"<EOL>self.add_message(<EOL>"<STR_LIT>", node=node, args=("<STR_LIT:.>".join(module_names), modname)<EOL>)<EOL>return None<EOL><DEDENT>if isinstance(module, astroid.Module):<EOL><INDENT>return module<EOL><DEDENT>return None<EOL>

check that module_names (list of string) are accessible through the
        given module
        if the latest access name corresponds to a module, return it


more = "<STR_LIT>"<EOL>infered_module = infered.root().name<EOL>if node.root().name == infered_module:<EOL><INDENT>if node.lineno == infered.lineno:<EOL><INDENT>more = "<STR_LIT>" % infered.as_string()<EOL><DEDENT>elif infered.lineno:<EOL><INDENT>more = "<STR_LIT>" % infered.lineno<EOL><DEDENT><DEDENT>elif infered.lineno:<EOL><INDENT>more = "<STR_LIT>" % (infered.lineno, infered_module)<EOL><DEDENT>return more<EOL>

return extra information to add to the message for unpacking-non-sequence
    and unbalanced-tuple-unpacking errors


@check_messages("<STR_LIT>", "<STR_LIT>")<EOL><INDENT>def visit_functiondef(self, node):<DEDENT>

<EOL>if not node.is_method():<EOL><INDENT>return<EOL><DEDENT>klass = node.parent.frame()<EOL>for stmt in node.nodes_of_class(astroid.Call):<EOL><INDENT>if node_frame_class(stmt) != node_frame_class(node):<EOL><INDENT>continue<EOL><DEDENT>expr = stmt.func<EOL>if not isinstance(expr, astroid.Attribute):<EOL><INDENT>continue<EOL><DEDENT>call = expr.expr<EOL>if not (<EOL>isinstance(call, astroid.Call)<EOL>and isinstance(call.func, astroid.Name)<EOL>and call.func.name == "<STR_LIT>"<EOL>):<EOL><INDENT>continue<EOL><DEDENT>if not klass.newstyle and has_known_bases(klass):<EOL><INDENT>continue<EOL><DEDENT>else:<EOL><INDENT>if not call.args:<EOL><INDENT>if sys.version_info[<NUM_LIT:0>] == <NUM_LIT:3>:<EOL><INDENT>continue<EOL><DEDENT>else:<EOL><INDENT>self.add_message("<STR_LIT>", node=call)<EOL>continue<EOL><DEDENT><DEDENT>arg0 = call.args[<NUM_LIT:0>]<EOL>if (<EOL>isinstance(arg0, astroid.Call)<EOL>and isinstance(arg0.func, astroid.Name)<EOL>and arg0.func.name == "<STR_LIT:type>"<EOL>):<EOL><INDENT>self.add_message("<STR_LIT>", node=call, args=("<STR_LIT:type>",))<EOL>continue<EOL><DEDENT>if (<EOL>len(call.args) >= <NUM_LIT:2><EOL>and isinstance(call.args[<NUM_LIT:1>], astroid.Name)<EOL>and call.args[<NUM_LIT:1>].name == "<STR_LIT>"<EOL>and isinstance(arg0, astroid.Attribute)<EOL>and arg0.attrname == "<STR_LIT>"<EOL>):<EOL><INDENT>self.add_message(<EOL>"<STR_LIT>", node=call, args=("<STR_LIT>",)<EOL>)<EOL>continue<EOL><DEDENT>try:<EOL><INDENT>supcls = call.args and next(call.args[<NUM_LIT:0>].infer(), None)<EOL><DEDENT>except astroid.InferenceError:<EOL><INDENT>continue<EOL><DEDENT>if klass is not supcls:<EOL><INDENT>name = None<EOL>if supcls:<EOL><INDENT>name = supcls.name<EOL><DEDENT>elif call.args and hasattr(call.args[<NUM_LIT:0>], "<STR_LIT:name>"):<EOL><INDENT>name = call.args[<NUM_LIT:0>].name<EOL><DEDENT>if name:<EOL><INDENT>self.add_message("<STR_LIT>", node=call, args=(name,))<EOL><DEDENT><DEDENT><DEDENT><DEDENT>


path = []<EOL>for is_attribute, specifier in parts:<EOL><INDENT>if is_attribute:<EOL><INDENT>path.append("<STR_LIT>".format(specifier))<EOL><DEDENT>else:<EOL><INDENT>path.append("<STR_LIT>".format(specifier))<EOL><DEDENT><DEDENT>return str(key) + "<STR_LIT>".join(path)<EOL>

Given a list of format specifiers, returns
    the final access path (e.g. a.b.c[0][1]).