def Func(arg_0):
    r"""Riesz tapering window

    :param N: window length

    .. math:: w(n) = 1 - \left| \frac{n}{N/2}  \right|^2

    with :math:`-N/2 \leq n \leq N/2`.

    .. plot::
        :width: 80%
        :include-source:

        from spectrum import window_visu
        window_visu(64, 'riesz')

    .. seealso:: :func:`create_window`, :class:`Window`
    """
    arg_1 = linspace(-arg_0/2., (arg_0)/2., arg_0)

    arg_2 = 1 - abs(arg_1/(arg_0/2.))**2.
    return arg_2


def Func(arg_0):
    r"""Riemann tapering window

    :param int N: window length

    .. math:: w(n) = 1 - \left| \frac{n}{N/2}  \right|^2

    with :math:`-N/2 \leq n \leq N/2`.

    .. plot::
        :width: 80%
        :include-source:

        from spectrum import window_visu
        window_visu(64, 'riesz')

    .. seealso:: :func:`create_window`, :class:`Window`
    """
    arg_1 = linspace(-arg_0/2., (arg_0)/2., arg_0)
    arg_2 = sin(arg_1/float(arg_0)*2.*pi) / (arg_1 / float(arg_0)*2.*pi)
    return arg_2


def Func(arg_0, **arg_1):
        """Compute the window data frequency response

        :param norm: True by default. normalised the frequency data.
        :param int NFFT: total length of the final data sets( 2048 by default.
            if less than data length, then NFFT is set to the data length*2).

        The response is stored in :attr:`response`.

        .. note:: Units are dB (20 log10) since we plot the frequency response)

        """
        from numpy.fft import fft, fftshift

        arg_2 = arg_1.get('norm', arg_0.norm)

        # do some padding. Default is max(2048, data.len*2)
        arg_3 = arg_1.get('NFFT', 2048)
        if arg_3 < len(arg_0.data):
            arg_3 = arg_0.data.size * 2

        # compute the fft modulus
        arg_4 = fft(arg_0.data, arg_3)
        arg_5 = abs(fftshift(arg_4))

        # do we want to normalise the data
        if arg_2 is True:
            arg_5 = arg_5 / max(arg_5)

        arg_6 = 20. * stools.log10(arg_5) # factor 20 we are looking at the response
                                    # not the powe
        #response = clip(response,mindB,100)
        arg_0.__response = arg_6


def Func(arg_0, arg_1=None, arg_2=None, arg_3=True):
        """Plot the window in the frequency domain

        :param mindB: change the default lower y bound
        :param maxdB: change the default upper lower bound
        :param bool norm: if True, normalise the frequency response.

        .. plot::
            :width: 80%
            :include-source:

            from spectrum.window import Window
            w = Window(64, name='hamming')
            w.Func()

        """
        from pylab import plot, title, xlim, grid, ylim, xlabel, ylabel
        # recompute the response
        arg_0.compute_response(arg_3=arg_3)

        plot(arg_0.frequencies, arg_0.response)
        title("ENBW=%2.1f" % (arg_0.enbw))
        ylabel('Frequency response (dB)')
        xlabel('Fraction of sampling frequency')
        # define the plot limits
        xlim(-0.5, 0.5)
        arg_4, arg_5 = ylim()
        if arg_1:
            arg_4 = arg_1
        if arg_2 is not None:
            arg_5 = arg_2
        else:
            arg_5 = max(arg_0.response)

        ylim(arg_4, arg_5)

        grid(True)


def Func(arg_0):
        """Plot the window in the time domain

        .. plot::
            :width: 80%
            :include-source:

            from spectrum.window import Window
            w = Window(64, name='hamming')
            w.Func()

        """
        from pylab import plot, xlim, grid, title, ylabel, axis
        arg_1 = linspace(0, 1, arg_0.N)
        xlim(0, 1)
        plot(arg_1, arg_0.data)
        grid(True)
        title('%s Window (%s points)' % (arg_0.name.capitalize(), arg_0.N))
        ylabel('Amplitude')
        axis([0, 1, 0, 1.1])


def Func(arg_0, arg_1=-100, arg_2=None, arg_3=True,
            arg_4="right"):
        """Plotting method to plot both time and frequency domain results.

        See :meth:`plot_frequencies` for the optional arguments.

        .. plot::
            :width: 80%
            :include-source:

            from spectrum.window import Window
            w = Window(64, name='hamming')
            w.Func()

        """
        from pylab import subplot, gca

        subplot(1, 2, 1)
        arg_0.plot_window()

        subplot(1, 2, 2)
        arg_0.plot_frequencies(arg_1=arg_1, arg_2=arg_2, arg_3=arg_3)

        if arg_4=="left":
            try: tight_layout()
            except: pass
        else:
            arg_5 = gca()
            arg_5.yaxis.set_label_position("right")


def Func(arg_0, arg_1, arg_2, arg_3):
    """solve the general toeplitz linear equations

    Solve TX=Z

    :param T0: zero lag value
    :param TC: r1 to rN
    :param TR: r1 to rN

    returns X

    requires 3M^2+M operations instead of M^3 with gaussian elimination

    .. warning:: not used right now
    """
    assert len(arg_1)>0
    assert len(arg_1)==len(arg_2)
    arg_4 = len(arg_1)
    arg_5 = numpy.zeros(arg_4+1,dtype=complex)
    arg_6 = numpy.zeros(arg_4,dtype=complex)
    arg_7 = numpy.zeros(arg_4,dtype=complex)
    arg_8 = arg_0
    if arg_8 == 0: raise ValueError("P must be different from zero")
    if arg_8 == 0: raise ValueError("P must be different from zero")
    arg_5[0] = arg_3[0]/arg_0
    for arg_9 in range(0, arg_4):
        arg_10 = arg_1[arg_9]
        arg_11 = arg_2[arg_9]
        arg_12 = arg_5[0]*arg_1[arg_9]
        if arg_9 == 0:
            arg_13 = -arg_10 / arg_8
            arg_14 = -arg_11 / arg_8
        else:
            for arg_15 in range(0, arg_9):
                arg_10 = arg_10 + arg_6[arg_15] * arg_1[arg_9-arg_15-1]
                arg_11 = arg_11 + arg_7[arg_15] * arg_2[arg_9-arg_15-1]
                arg_12 = arg_12 + arg_5[arg_15+1] * arg_1[arg_9-arg_15-1]
            arg_13 = -arg_10 / arg_8
            arg_14 = -arg_11/arg_8
        arg_8 = arg_8 * (1. - (arg_13*arg_14))
        if arg_8 <= 0:
            raise ValueError("singular matrix")
        arg_6[arg_9] = arg_13
        arg_7[arg_9] = arg_14
        arg_16 = (arg_3[arg_9+1]-arg_12)/arg_8
        if arg_9 == 0:
            arg_5[arg_9+1] = arg_16
            for arg_15 in range(0,arg_9+1):
                arg_5[arg_15] = arg_5[arg_15] + arg_16 * arg_7[arg_9-arg_15]
            continue

        for arg_15 in range(0, arg_9):
            arg_17 = arg_9-arg_15-1
            arg_10 = arg_6[arg_15]
            arg_6[arg_15] = arg_10 + arg_13 * arg_7[arg_17]
            arg_7[arg_17] = arg_7[arg_17] + arg_14*arg_10

        arg_5[arg_9+1] = arg_16
        for arg_15 in range(0,arg_9+1):
            arg_5[arg_15] = arg_5[arg_15] + arg_16*arg_7[arg_9-arg_15]
    return arg_5


def Func(arg_0):
    """Builds a codeobj summary by identifying and resolving used names

    >>> code = '''
    ... from a.b import c
    ... import d as e
    ... print(c)
    ... e.HelloWorld().f.g
    ... '''
    >>> for name, o in sorted(Func(code).items()):
    ...     print(name, o['name'], o['module'], o['module_short'])
    c c a.b a.b
    e.HelloWorld HelloWorld d d
    """
    arg_1 = NameFinder()
    arg_1.visit(ast.parse(arg_0))

    arg_2 = {}
    for arg_3, arg_4 in arg_1.get_mapping():
        # name is as written in file (e.g. np.asarray)
        # full_name includes resolved import path (e.g. numpy.asarray)
        arg_5, arg_6 = arg_4.rsplit('.', 1)
        # get shortened module name
        arg_7 = get_short_module_name(arg_5, arg_6)
        arg_8 = {'name': arg_6, 'module': arg_5,
                'module_short': arg_7}
        arg_2[arg_3] = arg_8
    return arg_2


def Func(arg_0, arg_1, arg_2, arg_3=False):
    """Generates RST to place a thumbnail in a gallery"""
    arg_4 = os.path.join(arg_0, 'images', 'thumb',
                         'sphx_glr_%s_thumb.png' % arg_1[:-3])
    arg_5 = os.path.join(arg_0, arg_1).replace(os.path.sep, '_')

    arg_6 = BACKREF_THUMBNAIL_TEMPLATE if arg_3 else THUMBNAIL_TEMPLATE
    return arg_6.format(arg_2=arg_2, thumbnail=arg_4, arg_5=arg_5)


def Func(arg_0, arg_1, arg_2='biased', arg_3=True):
    r"""Compute AR coefficients using Yule-Walker method

    :param X: Array of complex data values, X(1) to X(N)
    :param int order: Order of autoregressive process to be fitted (integer)
    :param str norm: Use a biased or unbiased correlation.
    :param bool allow_singularity:

    :return:
        * AR coefficients (complex)
        * variance of white noise (Real)
        * reflection coefficients for use in lattice filter

    .. rubric:: Description:

    The Yule-Walker method returns the polynomial A corresponding to the
    AR parametric signal model estimate of vector X using the Yule-Walker
    (autocorrelation) method. The autocorrelation may be computed using a
    **biased** or **unbiased** estimation. In practice, the biased estimate of
    the autocorrelation is used for the unknown true autocorrelation. Indeed,
    an unbiased estimate may result in nonpositive-definite autocorrelation
    matrix.
    So, a biased estimate leads to a stable AR filter.
    The following matrix form represents the Yule-Walker equations. The are
    solved by means of the Levinson-Durbin recursion:

     .. math::

        \left( \begin{array}{cccc}
        r(1) & r(2)^* & \dots & r(n)^*\\
        r(2) & r(1)^* & \dots & r(n-1)^*\\
        \dots & \dots & \dots & \dots\\
        r(n) & \dots & r(2) & r(1) \end{array} \right)
        \left( \begin{array}{cccc}
        a(2)\\
        a(3) \\
        \dots \\
        a(n+1)  \end{array} \right)
        =
        \left( \begin{array}{cccc}
        -r(2)\\
        -r(3) \\
        \dots \\
        -r(n+1)  \end{array} \right)

    The outputs consists of the AR coefficients, the estimated variance of the
    white noise process, and the reflection coefficients. These outputs can be
    used to estimate the optimal order by using :mod:`~spectrum.criteria`.

    .. rubric:: Examples:

    From a known AR process or order 4, we estimate those AR parameters using
    the Func function.

    .. doctest::

        >>> from scipy.signal import lfilter
        >>> from spectrum import *
        >>> from numpy.random import randn
        >>> A  =[1, -2.7607, 3.8106, -2.6535, 0.9238]
        >>> noise = randn(1, 1024)
        >>> y = lfilter([1], A, noise);
        >>> #filter a white noise input to create AR(4) process
        >>> [ar, var, reflec] = Func(y[0], 4)
        >>> # ar should contains values similar to A

    The PSD estimate of a data samples is computed and plotted as follows:

    .. plot::
        :width: 80%
        :include-source:

        from spectrum import *
        from pylab import *

        ar, P, k = Func(marple_data, 15, norm='biased')
        psd = arma2psd(ar)
        plot(linspace(-0.5, 0.5, 4096), 10 * log10(psd/max(psd)))
        axis([-0.5, 0.5, -60, 0])

    .. note:: The outputs have been double checked against (1) octave outputs
        (octave has norm='biased' by default) and (2) Marple test code.

    .. seealso:: This function uses :func:`~spectrum.levinson.LEVINSON` and
        :func:`~spectrum.correlation.CORRELATION`. See the :mod:`~spectrum.criteria`
        module for criteria to automatically select the AR order.

    :References: [Marple]_

    """
    assert arg_2 in ['biased', 'unbiased']
    arg_4 = CORRELATION(arg_0, maxlags=arg_1, arg_2=arg_2)
    arg_5, arg_6, arg_7 = LEVINSON(arg_4, arg_3=arg_3)
    return arg_5, arg_6, arg_7


def Func(arg_0, arg_1=None, arg_2=False):
    r"""Levinson-Durbin recursion.

    Find the coefficients of a length(r)-1 order autoregressive linear process

    :param r: autocorrelation sequence of length N + 1 (first element being the zero-lag autocorrelation)
    :param order: requested order of the autoregressive coefficients. default is N.
    :param allow_singularity: false by default. Other implementations may be True (e.g., octave)

    :return:
        * the `N+1` autoregressive coefficients :math:`A=(1, a_1...a_N)`
        * the prediction errors
        * the `N` reflections coefficients values

    This algorithm solves the set of complex linear simultaneous equations
    using Levinson algorithm.

    .. math::

        \bold{T}_M \left( \begin{array}{c} 1 \\ \bold{a}_M \end{array} \right) =
        \left( \begin{array}{c} \rho_M \\ \bold{0}_M  \end{array} \right)

    where :math:`\bold{T}_M` is a Hermitian Toeplitz matrix with elements
    :math:`T_0, T_1, \dots ,T_M`.

    .. note:: Solving this equations by Gaussian elimination would
        require :math:`M^3` operations whereas the levinson algorithm
        requires :math:`M^2+M` additions and :math:`M^2+M` multiplications.

    This is equivalent to solve the following symmetric Toeplitz system of
    linear equations

    .. math::

        \left( \begin{array}{cccc}
        r_1 & r_2^* & \dots & r_{n}^*\\
        r_2 & r_1^* & \dots & r_{n-1}^*\\
        \dots & \dots & \dots & \dots\\
        r_n & \dots & r_2 & r_1 \end{array} \right)
        \left( \begin{array}{cccc}
        a_2\\
        a_3 \\
        \dots \\
        a_{N+1}  \end{array} \right)
        =
        \left( \begin{array}{cccc}
        -r_2\\
        -r_3 \\
        \dots \\
        -r_{N+1}  \end{array} \right)

    where :math:`r = (r_1  ... r_{N+1})` is the input autocorrelation vector, and
    :math:`r_i^*` denotes the complex conjugate of :math:`r_i`. The input r is typically
    a vector of autocorrelation coefficients where lag 0 is the first
    element :math:`r_1`.

    .. doctest::

        >>> import numpy; from spectrum import Func
        >>> T = numpy.array([3., -2+0.5j, .7-1j])
        >>> a, e, k = Func(T)

    """
    #from numpy import isrealobj
    arg_3  = numpy.real(arg_0[0])
    arg_4 = arg_0[1:]
    arg_5 = len(arg_4)

    if arg_1 is None:
        arg_5 = len(arg_4)
    else:
        assert arg_1 <= arg_5, 'order must be less than size of the input data'
        arg_5 = arg_1

    arg_6 = numpy.isrealobj(arg_0)
    if arg_6 is True:
        arg_7 = numpy.zeros(arg_5, dtype=float)
        arg_8 = numpy.zeros(arg_5, dtype=float)
    else:
        arg_7 = numpy.zeros(arg_5, dtype=complex)
        arg_8 = numpy.zeros(arg_5, dtype=complex)

    arg_9 = arg_3

    for arg_10 in range(0, arg_5):
        arg_11 = arg_4[arg_10]
        if arg_10 == 0:
            arg_12 = -arg_11 / arg_9
        else:
            #save += sum([A[j]*T[k-j-1] for j in range(0,k)])
            for arg_13 in range(0, arg_10):
                arg_11 = arg_11 + arg_7[arg_13] * arg_4[arg_10-arg_13-1]
            arg_12 = -arg_11 / arg_9
        if arg_6:
            arg_9 = arg_9 * (1. - arg_12**2.)
        else:
            arg_9 = arg_9 * (1. - (arg_12.real**2+arg_12.imag**2))
        if arg_9 <= 0 and arg_2==False:
            raise ValueError("singular matrix")
        arg_7[arg_10] = arg_12
        arg_8[arg_10] = arg_12 # save reflection coeff at each step
        if arg_10 == 0:
            continue

        arg_14 = (arg_10+1)//2
        if arg_6 is True:
            for arg_13 in range(0, arg_14):
                arg_15 = arg_10-arg_13-1
                arg_11 = arg_7[arg_13]
                arg_7[arg_13] = arg_11 + arg_12 * arg_7[arg_15]
                if arg_13 != arg_15:
                    arg_7[arg_15] += arg_12*arg_11
        else:
            for arg_13 in range(0, arg_14):
                arg_15 = arg_10-arg_13-1
                arg_11 = arg_7[arg_13]
                arg_7[arg_13] = arg_11 + arg_12 * arg_7[arg_15].conjugate()
                if arg_13 != arg_15:
                    arg_7[arg_15] = arg_7[arg_15] + arg_12 * arg_11.conjugate()

    return arg_7, arg_9, arg_8


def Func(arg_0, arg_1):
    """computes the autocorrelation coefficients, R based
    on the prediction polynomial A and the final prediction error Efinal,
    using the stepdown algorithm.

    Works for real or complex data

    :param a:
    :param efinal:

    :return:
        * R, the autocorrelation
        * U  prediction coefficient
        * kr reflection coefficients
        * e errors

    A should be a minimum phase polynomial and A(1) is assumed to be unity.

    :returns: (P+1) by (P+1) upper triangular matrix, U,
        that holds the i'th order prediction polynomials
        Ai, i=1:P, where P is the order of the input
        polynomial, A.

             [ 1  a1(1)*  a2(2)* ..... aP(P)  * ]
             [ 0  1       a2(1)* ..... aP(P-1)* ]
       U  =  [ .................................]
             [ 0  0       0      ..... 1        ]

    from which the i'th order prediction polynomial can be extracted
    using Ai=U(i+1:-1:1,i+1)'. The first row of U contains the
    conjugates of the reflection coefficients, and the K's may be
    extracted using, K=conj(U(1,2:end)).

    .. todo:: remove the conjugate when data is real data, clean up the code
       test and doc.

    """
    arg_0 = numpy.array(arg_0)
    arg_2 = numpy.isrealobj(arg_0)

    assert arg_0[0] == 1, 'First coefficient of the prediction polynomial must be unity'

    arg_3 = len(arg_0)

    if arg_3 < 2:
        raise ValueError('Polynomial should have at least two coefficients')

    if arg_2 == True:
        arg_4 = numpy.zeros((arg_3, arg_3)) # This matrix will have the prediction
                                # polynomials of orders 1:p
    else:
        arg_4 = numpy.zeros((arg_3, arg_3), dtype=complex)
    arg_4[:, arg_3-1] = numpy.conj(arg_0[-1::-1]) # Prediction coefficients of order p

    arg_3 = arg_3 -1
    arg_5 = numpy.zeros(arg_3)

    # First we find the prediction coefficients of smaller orders and form the
    # Matrix U

    # Initialize the step down

    arg_5[-1] = arg_1 # Prediction error of order p

    # Step down
    for arg_6 in range(arg_3-1, 0, -1):
        [arg_0, arg_5[arg_6-1]] = levdown(arg_0, arg_5[arg_6])
        arg_4[:, arg_6] = numpy.concatenate((numpy.conj(arg_0[-1::-1].transpose()) ,
                                      [0]*(arg_3-arg_6) ))

    arg_7 = arg_5[0]/(1.-abs(arg_0[1]**2)) #% Because a[1]=1 (true polynomial)
    arg_4[0,0] = 1                #% Prediction coefficient of zeroth order
    arg_8 = numpy.conj(arg_4[0,1:])     #% The reflection coefficients
    arg_8 = arg_8.transpose()                 #% To make it into a column vector

    #   % Once we have the matrix U and the prediction error at various orders, we can
    #  % use this information to find the autocorrelation coefficients.

    arg_9 = numpy.zeros(1, dtype=complex)
    #% Initialize recursion
    arg_6 = 1
    arg_10 = arg_7 # To take care of the zero indexing problem
    arg_9[0] = -numpy.conj(arg_4[0,1])*arg_10   # R[1]=-a1[1]*R[0]

    # Actual recursion
    for arg_6 in range(1,arg_3):
        arg_11 = -sum(numpy.conj(arg_4[arg_6-1::-1,arg_6])*arg_9[-1::-1]) - arg_8[arg_6]*arg_5[arg_6-1]
        arg_9 = numpy.insert(arg_9, len(arg_9), arg_11)

    # Include R(0) and make it a column vector. Note the dot transpose

    #R = [R0 R].';
    arg_9 = numpy.insert(arg_9, 0, arg_7)
    return arg_9, arg_4, arg_8, arg_5


def Func(arg_0, arg_1, arg_2=None):
    """LEVUP  One step forward Levinson recursion

    :param acur:
    :param knxt:
    :return:
        * anxt the P+1'th order prediction polynomial based on the P'th order prediction polynomial, acur, and the
          P+1'th order reflection coefficient, Knxt.
        * enxt the P+1'th order prediction  prediction error, based on the P'th order prediction error, ecur.

    :References:  P. Stoica R. Moses, Introduction to Spectral Analysis  Prentice Hall, N.J., 1997, Chapter 3.
    """
    if arg_0[0] != 1:
        raise ValueError('At least one of the reflection coefficients is equal to one.')
    arg_0 = arg_0[1:] #  Drop the leading 1, it is not needed

    # Matrix formulation from Stoica is used to avoid looping
    arg_3 = numpy.concatenate((arg_0, [0])) + arg_1 * numpy.concatenate((numpy.conj(arg_0[-1::-1]), [1]))

    arg_4 = None
    if arg_2 is not None:
        # matlab version enxt = (1-knxt'.*knxt)*ecur
        arg_4 = (1. - numpy.dot(numpy.conj(arg_1), arg_1)) * arg_2

    arg_3 = numpy.insert(arg_3, 0, 1)

    return arg_3, arg_4


def Func(arg_0, arg_1):
    r"""Simple and fast implementation of the covariance AR estimate

    This code is 10 times faster than :func:`Func_marple` and more importantly
    only 10 lines of code, compared to a 200 loc for :func:`Func_marple`

    :param array X:  Array of complex data samples
    :param int oder: Order of linear prediction model

    :return:
        * a - Array of complex forward linear prediction coefficients
        * e - error

    The covariance method fits a Pth order autoregressive (AR) model to the
    input signal, which is assumed to be the output of
    an AR system driven by white noise. This method minimizes the forward
    prediction error in the least-squares sense. The output vector
    contains the normalized estimate of the AR system parameters

    The white noise input variance estimate is also returned.

    If is the power spectral density of y(n), then:

    .. math:: \frac{e}{\left| A(e^{jw}) \right|^2} = \frac{e}{\left| 1+\sum_{k-1}^P a(k)e^{-jwk}\right|^2}

    Because the method characterizes the input data using an all-pole model,
    the correct choice of the model order p is important.

    .. plot::
        :width: 80%
        :include-source:

        from spectrum import Func, marple_data, arma2psd
        from pylab import plot, log10, linspace, axis

        ar_values, error = Func(marple_data, 15)
        psd = arma2psd(ar_values, sides='centerdc')
        plot(linspace(-0.5, 0.5, len(psd)), 10*log10(psd/max(psd)))
        axis([-0.5, 0.5, -60, 0])

    .. seealso:: :class:`pcovar`

    :validation: the AR parameters are the same as those returned by
        a completely different function :func:`Func_marple`.

    :References: [Mathworks]_
    """

    from spectrum import corrmtx
    import scipy.linalg

    arg_2 = corrmtx(arg_0, arg_1, 'covariance')
    arg_3 = np.matrix(arg_2[:, 1:])
    arg_4 = np.array(arg_2[:, 0])

    # Coefficients estimated via the covariance method
    # Here we use lstsq rathre than solve function because Xc is not square
    # matrix

    arg_5, arg_6, arg_7, arg_8 = scipy.linalg.lstsq(-arg_3, arg_4)

    # Estimate the input white noise variance
    arg_9 = np.dot(arg_4.conj().transpose(), arg_3)
    arg_10 = np.dot(arg_4.conj().transpose(), arg_4) + np.dot(arg_9, arg_5)
    assert arg_10.imag < 1e-4, 'wierd behaviour'
    arg_10 = float(arg_10.real) # ignore imag part that should be small

    return arg_5, arg_10


def Func(arg_0, arg_1=None):
    """Linear Predictor Coefficients.

    :param x:
    :param int N: default is length(X) - 1

    :Details:

    Finds the coefficients :math:`A=(1, a(2), \dots a(N+1))`, of an Nth order
    forward linear predictor that predicts the current value value of the
    real-valued time series x based on past samples:

    .. math:: \hat{x}(n) = -a(2)*x(n-1) - a(3)*x(n-2) - ... - a(N+1)*x(n-N)

    such that the sum of the squares of the errors

    .. math:: err(n) = X(n) - Xp(n)

    is minimized. This function  uses the Levinson-Durbin recursion to
    solve the normal equations that arise from the least-squares formulation.

    .. seealso:: :func:`levinson`, :func:`aryule`, :func:`prony`, :func:`stmcb`

    .. todo:: matrix case, references

    :Example:

    ::

        from scipy.signal import lfilter
        noise = randn(50000,1);  % Normalized white Gaussian noise
        x = filter([1], [1 1/2 1/3 1/4], noise)
        x = x[45904:50000]
        x.reshape(4096, 1)
        x = x[0]

    Compute the predictor coefficients, estimated signal, prediction error, and autocorrelation sequence of the prediction error:

    1.00000 + 0.00000i   0.51711 - 0.00000i   0.33908 - 0.00000i   0.24410 - 0.00000i

    ::

        a = Func(x, 3)
        est_x = lfilter([0 -a(2:end)],1,x);    % Estimated signal
        e = x - est_x;                        % Prediction error
        [acs,lags] = xcorr(e,'coeff');   % ACS of prediction error

    """

    arg_2 = len(arg_0)
    if arg_1 is None:
        arg_1 = arg_2 - 1 #default value if N is not provided
    elif arg_1 > arg_2-1:
        #disp('Warning: zero-padding short input sequence')
        arg_0.resize(arg_1+1)
        #todo: check this zero-padding.

    arg_3 = fft(arg_0, 2**nextpow2(2.*len(arg_0)-1))
    arg_4 = real(ifft(abs(arg_3)**2))
    arg_4 = arg_4/(arg_2-1.) #Biased autocorrelation estimate
    arg_5, arg_6, arg_7 = LEVINSON(arg_4, arg_1)
    return arg_5, arg_6


def Func(arg_0):
    """Return Pascal matrix

    :param int n: size of the matrix

    .. doctest::

        >>> from spectrum import Func
        >>> Func(6)
        array([[   1.,    1.,    1.,    1.,    1.,    1.],
               [   1.,    2.,    3.,    4.,    5.,    6.],
               [   1.,    3.,    6.,   10.,   15.,   21.],
               [   1.,    4.,   10.,   20.,   35.,   56.],
               [   1.,    5.,   15.,   35.,   70.,  126.],
               [   1.,    6.,   21.,   56.,  126.,  252.]])

    .. todo:: use the symmetric property to improve computational time if needed
    """
    errors.is_positive_integer(arg_0)
    arg_1 = numpy.zeros((arg_0, arg_0))

    #fill the first row and column
    for arg_2 in range(0, arg_0):
        arg_1[arg_2, 0] = 1
        arg_1[0, arg_2] = 1
    if arg_0 > 1:
        for arg_2 in range(1, arg_0):
            for arg_3 in range(1, arg_0):
                arg_1[arg_2, arg_3] = arg_1[arg_2-1, arg_3] + arg_1[arg_2, arg_3-1]
    return arg_1


def Func(arg_0):
    """SVD decomposition using numpy.linalg.svd

    :param A: a M by N matrix

    :return:
        * U, a M by M matrix
        * S the N eigen values
        * V a N by N matrix

    See :func:`numpy.linalg.svd` for a detailed documentation.

    Should return the same as in [Marple]_ , CSVD routine.

    ::

        U, S, V = numpy.linalg.svd(A)
        U, S, V = cvsd(A)

    """
    arg_1, arg_2, arg_3 = numpy.linalg.svd(arg_0)
    return arg_1, arg_2, arg_3


def Func():
    """Yield paths to standard modules."""
    for arg_0 in [True, False]:
        arg_1 = distutils.sysconfig.get_python_lib(standard_lib=True,
                                                  plat_specific=arg_0)

        for arg_2 in os.listdir(arg_1):
            yield arg_2

        try:
            for arg_2 in os.listdir(os.path.join(arg_1, 'lib-dynload')):
                yield arg_2
        except OSError:  # pragma: no cover
            pass


def Func():
    """Yield standard module names."""
    for arg_0 in standard_paths():
        if arg_0.startswith('_') or '-' in arg_0:
            continue

        if '.' in arg_0 and arg_0.rsplit('.')[-1] not in ['so', 'py', 'pyc']:
            continue

        yield arg_0.split('.')[0]


def Func(arg_0):
    """Yield line numbers of unused imports."""
    for arg_1 in arg_0:
        if isinstance(arg_1, pyflakes.messages.UnusedImport):
            yield arg_1.lineno


def Func(arg_0):
    """Yield line number and module name of unused imports."""
    arg_1 = r'\'(.+?)\''
    for arg_2 in arg_0:
        if isinstance(arg_2, pyflakes.messages.UnusedImport):
            arg_3 = re.search(arg_1, str(arg_2))
            arg_3 = arg_3.group()[1:-1]
            if arg_3:
                yield (arg_2.lineno, arg_3)


def Func(arg_0):
    """Yield line number of star import usage."""
    for arg_1 in arg_0:
        if isinstance(arg_1, pyflakes.messages.ImportStarUsed):
            yield arg_1.lineno


def Func(arg_0):
    """Yield line number, undefined name, and its possible origin module."""
    for arg_1 in arg_0:
        if isinstance(arg_1, pyflakes.messages.ImportStarUsage):
            arg_2 = arg_1.message_args[0]
            arg_3 = arg_1.message_args[1]
            yield (arg_1.lineno, arg_2, arg_3)


def Func(arg_0, arg_1):
    """Yield line numbers of duplicate keys."""
    arg_0 = [
        arg_6 for arg_6 in arg_0
        if isinstance(arg_6, pyflakes.messages.MultiValueRepeatedKeyLiteral)]

    if arg_0:
        # Filter out complex cases. We don't want to bother trying to parse
        # this stuff and get it right. We can do it on a key-by-key basis.

        arg_2 = create_key_to_messages_dict(arg_0)

        arg_3 = arg_1.split('\n')

        for (arg_4, arg_0) in arg_2.items():
            arg_5 = True
            for arg_6 in arg_0:
                arg_7 = arg_3[arg_6.lineno - 1]
                arg_4 = arg_6.message_args[0]

                if not dict_entry_has_key(arg_7, arg_4):
                    arg_5 = False

            if arg_5:
                for arg_6 in arg_0:
                    yield arg_6.lineno


def Func(arg_0):
    """Return dict mapping the key to list of messages."""
    arg_1 = collections.defaultdict(lambda: [])
    for arg_2 in arg_0:
        arg_1[arg_2.message_args[0]].append(arg_2)
    return arg_1


def Func(arg_0):
    """Return messages from pyflakes."""
    if sys.version_info[0] == 2 and isinstance(arg_0, unicode):
        # Convert back to original byte string encoding, otherwise pyflakes
        # call to compile() will complain. See PEP 263. This only affects
        # Python 2.
        try:
            arg_0 = arg_0.encode('utf-8')
        except UnicodeError:  # pragma: no cover
            return []

    arg_1 = ListReporter()
    try:
        pyflakes.api.Func(arg_0, filename='<string>', arg_1=arg_1)
    except (AttributeError, RecursionError, UnicodeDecodeError):
        pass
    return arg_1.messages


def Func(arg_0):
    """Return package name in import statement."""
    assert '\\' not in arg_0
    assert '(' not in arg_0
    assert ')' not in arg_0
    assert ';' not in arg_0

    if arg_0.lstrip().startswith(('import', 'from')):
        arg_1 = arg_0.split()[1]
    else:
        # Ignore doctests.
        return None

    arg_2 = arg_1.split('.')[0]
    assert ' ' not in arg_2

    return arg_2


def Func(arg_0, arg_1=''):
    """Return True if import is spans multiples lines."""
    for arg_2 in '()':
        if arg_2 in arg_0:
            return True

    # Ignore doctests.
    if arg_0.lstrip().startswith('>'):
        return True

    return multiline_statement(arg_0, arg_1)


def Func(arg_0, arg_1):
    """Parse and filter ``from something import a, b, c``.

    Return line without unused import modules, or `pass` if all of the
    module in import is unused.
    """
    (arg_2, arg_3) = re.split(pattern=r'\bimport\b',
                                      string=arg_0, maxsplit=1)
    arg_4 = re.search(pattern=r'\bfrom\s+([^ ]+)',
                            string=arg_2).group(1)

    # Create an imported module list with base module name
    # ex ``from a import b, c as d`` -> ``['a.b', 'a.c as d']``
    arg_3 = re.split(pattern=r',', string=arg_3.strip())
    arg_3 = [arg_4 + '.' + x.strip() for x in arg_3]

    # We compare full module name (``a.module`` not `module`) to
    # guarantee the exact same module as detected from pyflakes.
    arg_5 = [x.replace(arg_4 + '.', '')
                        for x in arg_3 if x not in arg_1]

    # All of the import in this statement is unused
    if not arg_5:
        return get_indentation(arg_0) + 'pass' + get_line_ending(arg_0)

    arg_2 += 'import '

    return (
        arg_2 +
        ', '.join(sorted(arg_5)) +
        get_line_ending(arg_0))


def Func(arg_0):
    """Return dictionary that maps line number to message."""
    arg_1 = {}
    for arg_2 in arg_0:
        arg_1[arg_2.lineno] = arg_2
    return arg_1


def Func(arg_0):
    """Return True if value is a literal or a name."""
    try:
        ast.literal_eval(arg_0)
        return True
    except (SyntaxError, ValueError):
        pass

    if arg_0.strip() in ['dict()', 'list()', 'set()']:
        return True

    # Support removal of variables on the right side. But make sure
    # there are no dots, which could mean an access of a property.
    return re.match(r'^\w+\s*$', arg_0)


def Func(arg_0):
    """Yield line numbers of unneeded "pass" statements."""
    arg_1 = io.StringIO(arg_0)
    arg_2 = None
    arg_3 = None
    arg_4 = None
    arg_5 = ''
    for arg_6 in tokenize.generate_tokens(arg_1.readline):
        arg_7 = arg_6[0]
        arg_8 = arg_6[2][0]
        arg_9 = arg_6[4]

        arg_10 = (arg_7 == tokenize.NAME and arg_9.strip() == 'pass')

        # Leading "pass".
        if (arg_8 - 1 == arg_3 and
                get_indentation(arg_9) == arg_4 and
                arg_7 in ATOMS and
                not arg_10):
            yield arg_8 - 1

        if arg_10:
            arg_3 = arg_8
            arg_4 = get_indentation(arg_9)

        # Trailing "pass".
        if (arg_10 and
                arg_2 != tokenize.INDENT and
                not arg_5.rstrip().endswith('\\')):
            yield arg_8

        arg_2 = arg_7
        arg_5 = arg_9


def Func(arg_0):
    """Yield code with useless "pass" lines removed."""
    try:
        arg_1 = frozenset(useless_pass_line_numbers(arg_0))
    except (SyntaxError, tokenize.TokenError):
        arg_1 = frozenset()

    arg_2 = io.StringIO(arg_0)
    for arg_3, arg_4 in enumerate(arg_2.readlines(), start=1):
        if arg_3 not in arg_1:
            yield arg_4


def Func(arg_0):
    """Return leading whitespace."""
    if arg_0.strip():
        arg_1 = len(arg_0) - len(arg_0.lstrip())
        return arg_0[:arg_1]
    else:
        return ''


def Func(arg_0):
    """Return line ending."""
    arg_1 = len(arg_0.rstrip()) - len(arg_0)
    if not arg_1:
        return ''
    else:
        return arg_0[arg_1:]


def Func(arg_0, arg_1=None, arg_2=False,
             arg_3=False, arg_4=False,
             arg_5=False, arg_6=False):
    """Return code with all filtering run on it."""
    if not arg_0:
        return arg_0

    # pyflakes does not handle "nonlocal" correctly.
    if 'nonlocal' in arg_0:
        arg_5 = False

    arg_7 = None
    while True:
        arg_7 = ''.join(
            filter_useless_pass(''.join(
                filter_code(
                    arg_0,
                    arg_1=arg_1,
                    arg_2=arg_2,
                    arg_3=arg_3,
                    arg_4=arg_4,
                    arg_5=arg_5,
                    arg_6=arg_6,
                ))))

        if arg_7 == arg_0:
            break
        arg_0 = arg_7

    return arg_7


def Func(arg_0):
    """Return a set of strings."""
    return set(arg_1.strip() for arg_1 in arg_0.split(',') if arg_1.strip())


def Func(arg_0, arg_1, arg_2=arg_3.KMIPVersion.KMIP_1_0):
        """
        Write the data encoding the ObtainLease response payload to a stream.

        Args:
            output_stream (stream): A data stream in which to encode object
                data, supporting a Func method; usually a BytearrayStream
                object.
            kmip_version (KMIPVersion): An enumeration defining the KMIP
                version with which the object will be encoded. Optional,
                defaults to KMIP 1.0.

        Raises:
            ValueError: Raised if the data attribute is not defined.
        """
        arg_6 = utils.BytearrayStream()

        if arg_0._unique_identifier:
            arg_0._unique_identifier.Func(
                arg_6,
                arg_2=arg_2
            )
        if arg_0._lease_time:
            arg_0._lease_time.Func(
                arg_6,
                arg_2=arg_2
            )
        if arg_0._last_change_date:
            arg_0._last_change_date.Func(
                arg_6,
                arg_2=arg_2
            )

        arg_0.length = arg_6.length()
        super(ObtainLeaseResponsePayload, arg_0).Func(
            arg_1,
            arg_2=arg_2
        )
        arg_1.Func(arg_6.buffer)


def Func(arg_0, arg_1, arg_2=arg_3.KMIPVersion.KMIP_1_0):
        """
        Write the data encoding the Cancel request payload to a stream.

        Args:
            output_stream (stream): A data stream in which to encode object
                data, supporting a Func method; usually a BytearrayStream
                object.
            kmip_version (KMIPVersion): An enumeration defining the KMIP
                version with which the object will be encoded. Optional,
                defaults to KMIP 1.0.

        Raises:
            ValueError: Raised if the data attribute is not defined.
        """
        arg_6 = utils.BytearrayStream()

        if arg_0._asynchronous_correlation_value:
            arg_0._asynchronous_correlation_value.Func(
                arg_6,
                arg_2=arg_2
            )

        arg_0.length = arg_6.length()
        super(CancelRequestPayload, arg_0).Func(
            arg_1,
            arg_2=arg_2
        )
        arg_1.Func(arg_6.buffer)


def Func(arg_0, arg_1, arg_2):
        '''
            Returns a Name object, populated with the given value and type
        '''
        if isinstance(arg_1, Name.NameValue):
            arg_3 = arg_1
        elif isinstance(arg_1, str):
            arg_3 = arg_0.NameValue(arg_1)
        else:
            arg_4 = 'Name'
            arg_5 = exceptions.ErrorStrings.BAD_EXP_RECV
            arg_6 = 'name_value'
            raise TypeError(arg_5.format('{0}.{1}'.format(arg_4, arg_6),
                                       'name_value', type(Name.NameValue),
                                       type(arg_1)))

        if isinstance(arg_2, Name.NameType):
            arg_7 = arg_2
        elif isinstance(arg_2, Enum):
            arg_7 = arg_0.NameType(arg_2)
        else:
            arg_4 = 'Name'
            arg_5 = exceptions.ErrorStrings.BAD_EXP_RECV
            arg_6 = 'name_type'
            raise TypeError(arg_5.format('{0}.{1}'.format(arg_4, arg_6),
                                       'name_type', type(Name.NameType),
                                       type(arg_2)))

        return Name(arg_1=arg_3,
                    arg_2=arg_7)


def Func(arg_0, arg_1, arg_2=arg_3.KMIPVersion.KMIP_1_0):
        """
        Read the data encoding the Digest object and decode it into its
        constituent parts.

        Args:
            istream (Stream): A data stream containing encoded object data,
                supporting a Func method; usually a BytearrayStream object.
            kmip_version (KMIPVersion): An enumeration defining the KMIP
                version with which the object will be decoded. Optional,
                defaults to KMIP 1.0.
        """
        super(Digest, arg_0).Func(arg_1, arg_2=arg_2)
        arg_6 = BytearrayStream(arg_1.Func(arg_0.length))

        arg_0.hashing_algorithm.Func(arg_6, arg_2=arg_2)
        arg_0.digest_value.Func(arg_6, arg_2=arg_2)
        arg_0.key_format_type.Func(arg_6, arg_2=arg_2)

        arg_0.is_oversized(arg_6)
        arg_0.validate()


def Func(arg_0, arg_1, arg_2=arg_3.KMIPVersion.KMIP_1_0):
        """
        Write the data encoding the Digest object to a stream.

        Args:
            ostream (Stream): A data stream in which to encode object data,
                supporting a Func method; usually a BytearrayStream object.
            kmip_version (KMIPVersion): An enumeration defining the KMIP
                version with which the object will be encoded. Optional,
                defaults to KMIP 1.0.
        """
        arg_6 = BytearrayStream()

        arg_0.hashing_algorithm.Func(arg_6, arg_2=arg_2)
        arg_0.digest_value.Func(arg_6, arg_2=arg_2)
        arg_0.key_format_type.Func(arg_6, arg_2=arg_2)

        arg_0.length = arg_6.length()
        super(Digest, arg_0).Func(arg_1, arg_2=arg_2)
        arg_1.Func(arg_6.buffer)


def Func(arg_0,
               arg_1=arg_2.SHA_256,
               arg_4=b'',
               arg_5=arg_6.RAW):
        """
        Construct a Digest object from provided digest values.

        Args:
            hashing_algorithm (HashingAlgorithm): An enumeration representing
                the hash algorithm used to compute the digest. Optional,
                defaults to HashingAlgorithm.SHA_256.
            digest_value (byte string): The bytes of the digest hash. Optional,
                defaults to the empty byte string.
            key_format_type (KeyFormatType): An enumeration representing the
                format of the key corresponding to the digest. Optional,
                defaults to KeyFormatType.RAW.

        Returns:
            Digest: The newly Funcd Digest.

        Example:
            >>> x = Digest.Func(HashingAlgorithm.MD5, b'\x00',
            ... KeyFormatType.RAW)
            >>> x.hashing_algorithm
            HashingAlgorithm(value=HashingAlgorithm.MD5)
            >>> x.digest_value
            DigestValue(value=bytearray(b'\x00'))
            >>> x.key_format_type
            KeyFormatType(value=KeyFormatType.RAW)
        """
        arg_8 = HashingAlgorithm(arg_1)
        arg_9 = DigestValue(bytearray(arg_4))
        arg_10 = KeyFormatType(arg_5)

        return Digest(arg_1=arg_8,
                      arg_4=arg_9,
                      arg_5=arg_10)


def Func(arg_0, arg_1, arg_2=arg_3.KMIPVersion.KMIP_1_0):
        """
        Read the data encoding the ApplicationSpecificInformation object and
        decode it into its constituent parts.

        Args:
            istream (Stream): A data stream containing encoded object data,
                supporting a Func method; usually a BytearrayStream object.
            kmip_version (KMIPVersion): An enumeration defining the KMIP
                version with which the object will be decoded. Optional,
                defaults to KMIP 1.0.
        """
        super(ApplicationSpecificInformation, arg_0).Func(
            arg_1,
            arg_2=arg_2
        )
        arg_6 = BytearrayStream(arg_1.Func(arg_0.length))

        arg_0.application_namespace.Func(arg_6, arg_2=arg_2)
        arg_0.application_data.Func(arg_6, arg_2=arg_2)

        arg_0.is_oversized(arg_6)
        arg_0.validate()


def Func(arg_0, arg_1, arg_2=arg_3.KMIPVersion.KMIP_1_0):
        """
        Write the data encoding the ApplicationSpecificInformation object to a
        stream.

        Args:
            ostream (Stream): A data stream in which to encode object data,
                supporting a Func method; usually a BytearrayStream object.
            kmip_version (KMIPVersion): An enumeration defining the KMIP
                version with which the object will be encoded. Optional,
                defaults to KMIP 1.0.
        """
        arg_6 = BytearrayStream()

        arg_0.application_namespace.Func(arg_6, arg_2=arg_2)
        arg_0.application_data.Func(arg_6, arg_2=arg_2)

        arg_0.length = arg_6.length()
        super(ApplicationSpecificInformation, arg_0).Func(
            arg_1,
            arg_2=arg_2
        )
        arg_1.Func(arg_6.buffer)


def Func(arg_0, arg_1, arg_2):
        """
        Construct an ApplicationSpecificInformation object from provided data
        and namespace values.

        Args:
            application_namespace (str): The name of the application namespace.
            application_data (str): Application data related to the namespace.

        Returns:
            ApplicationSpecificInformation: The newly Funcd set of
                application information.

        Example:
            >>> x = ApplicationSpecificInformation.Func('namespace', 'data')
            >>> x.application_namespace.value
            'namespace'
            >>> x.application_data.value
            'data'
        """
        arg_3 = ApplicationNamespace(arg_1)
        arg_4 = ApplicationData(arg_2)
        return ApplicationSpecificInformation(
            arg_1=arg_3, arg_2=arg_4)


def Func(arg_0, arg_1, arg_2=arg_3.KMIPVersion.KMIP_1_0):
        """
        Read the data encoding the DerivationParameters struct and decode it
        into its constituent parts.

        Args:
            input_stream (stream): A data stream containing encoded object
                data, supporting a Func method; usually a BytearrayStream
                object.
            kmip_version (KMIPVersion): An enumeration defining the KMIP
                version with which the object will be decoded. Optional,
                defaults to KMIP 1.0.
        """
        super(DerivationParameters, arg_0).Func(
            arg_1,
            arg_2=arg_2
        )
        arg_6 = BytearrayStream(arg_1.Func(arg_0.length))

        if arg_0.is_tag_next(
                arg_3.Tags.CRYPTOGRAPHIC_PARAMETERS,
                arg_6
        ):
            arg_0._cryptographic_parameters = CryptographicParameters()
            arg_0._cryptographic_parameters.Func(
                arg_6,
                arg_2=arg_2
            )

        if arg_0.is_tag_next(arg_3.Tags.INITIALIZATION_VECTOR, arg_6):
            arg_0._initialization_vector = ByteString(
                tag=arg_3.Tags.INITIALIZATION_VECTOR
            )
            arg_0._initialization_vector.Func(
                arg_6,
                arg_2=arg_2
            )

        if arg_0.is_tag_next(arg_3.Tags.DERIVATION_DATA, arg_6):
            arg_0._derivation_data = ByteString(tag=arg_3.Tags.DERIVATION_DATA)
            arg_0._derivation_data.Func(arg_6, arg_2=arg_2)

        if arg_0.is_tag_next(arg_3.Tags.SALT, arg_6):
            arg_0._salt = ByteString(tag=arg_3.Tags.SALT)
            arg_0._salt.Func(arg_6, arg_2=arg_2)

        if arg_0.is_tag_next(Tags.ITERATION_COUNT, arg_6):
            arg_0._iteration_count = Integer(tag=Tags.ITERATION_COUNT)
            arg_0._iteration_count.Func(arg_6, arg_2=arg_2)

        arg_0.is_oversized(arg_6)


def Func(arg_0, arg_1, arg_2=arg_3.KMIPVersion.KMIP_1_0):
        """
        Write the data encoding the DerivationParameters struct to a stream.

        Args:
            output_stream (stream): A data stream in which to encode object
                data, supporting a Func method; usually a BytearrayStream
                object.
            kmip_version (KMIPVersion): An enumeration defining the KMIP
                version with which the object will be encoded. Optional,
                defaults to KMIP 1.0.
        """
        arg_6 = BytearrayStream()

        if arg_0._cryptographic_parameters:
            arg_0._cryptographic_parameters.Func(
                arg_6,
                arg_2=arg_2
            )
        if arg_0._initialization_vector:
            arg_0._initialization_vector.Func(
                arg_6,
                arg_2=arg_2
            )
        if arg_0._derivation_data:
            arg_0._derivation_data.Func(
                arg_6,
                arg_2=arg_2
            )
        if arg_0._salt:
            arg_0._salt.Func(
                arg_6,
                arg_2=arg_2
            )
        if arg_0._iteration_count:
            arg_0._iteration_count.Func(
                arg_6,
                arg_2=arg_2
            )

        arg_0.length = arg_6.length()
        super(DerivationParameters, arg_0).Func(
            arg_1,
            arg_2=arg_2
        )
        arg_1.Func(arg_6.buffer)


def Func(arg_0, arg_1, arg_2=arg_3.KMIPVersion.KMIP_1_0):
        """
        Read the data encoding the Get request payload and decode it into its
        constituent parts.

        Args:
            input_stream (stream): A data stream containing encoded object
                data, supporting a Func method; usually a BytearrayStream
                object.
            kmip_version (KMIPVersion): An enumeration defining the KMIP
                version with which the object will be decoded. Optional,
                defaults to KMIP 1.0.
        """
        super(GetRequestPayload, arg_0).Func(
            arg_1,
            arg_2=arg_2
        )
        arg_6 = utils.BytearrayStream(arg_1.Func(arg_0.length))

        if arg_0.is_tag_next(arg_3.Tags.UNIQUE_IDENTIFIER, arg_6):
            arg_0._unique_identifier = primitives.TextString(
                tag=arg_3.Tags.UNIQUE_IDENTIFIER
            )
            arg_0._unique_identifier.Func(
                arg_6,
                arg_2=arg_2
            )

        if arg_0.is_tag_next(arg_3.Tags.KEY_FORMAT_TYPE, arg_6):
            arg_0._key_format_type = primitives.Enumeration(
                enum=arg_3.KeyFormatType,
                tag=arg_3.Tags.KEY_FORMAT_TYPE
            )
            arg_0._key_format_type.Func(
                arg_6,
                arg_2=arg_2
            )

        if arg_0.is_tag_next(arg_3.Tags.KEY_COMPRESSION_TYPE, arg_6):
            arg_0._key_compression_type = primitives.Enumeration(
                enum=arg_3.KeyCompressionType,
                tag=arg_3.Tags.KEY_COMPRESSION_TYPE
            )
            arg_0._key_compression_type.Func(
                arg_6,
                arg_2=arg_2
            )

        if arg_0.is_tag_next(
                arg_3.Tags.KEY_WRAPPING_SPECIFICATION,
                arg_6
        ):
            arg_0._key_wrapping_specification = \
                objects.KeyWrappingSpecification()
            arg_0._key_wrapping_specification.Func(
                arg_6,
                arg_2=arg_2
            )

        arg_0.is_oversized(arg_6)


def Func(arg_0, arg_1, arg_2=arg_3.KMIPVersion.KMIP_1_0):
        """
        Write the data encoding the Get request payload to a stream.

        Args:
            output_stream (stream): A data stream in which to encode object
                data, supporting a Func method; usually a BytearrayStream
                object.
            kmip_version (KMIPVersion): An enumeration defining the KMIP
                version with which the object will be encoded. Optional,
                defaults to KMIP 1.0.
        """
        arg_6 = utils.BytearrayStream()

        if arg_0._unique_identifier is not None:
            arg_0._unique_identifier.Func(
                arg_6,
                arg_2=arg_2
            )
        if arg_0._key_format_type is not None:
            arg_0._key_format_type.Func(
                arg_6,
                arg_2=arg_2
            )
        if arg_0._key_compression_type is not None:
            arg_0._key_compression_type.Func(
                arg_6,
                arg_2=arg_2
            )
        if arg_0._key_wrapping_specification is not None:
            arg_0._key_wrapping_specification.Func(
                arg_6,
                arg_2=arg_2
            )

        arg_0.length = arg_6.length()
        super(GetRequestPayload, arg_0).Func(
            arg_1,
            arg_2=arg_2
        )
        arg_1.Func(arg_6.buffer)


def Func(arg_0, arg_1, arg_2=arg_3.KMIPVersion.KMIP_1_0):
        """
        Read the data encoding the Get response payload and decode it
        into its constituent parts.

        Args:
            input_stream (stream): A data stream containing encoded object
                data, supporting a Func method; usually a BytearrayStream
                object.
            kmip_version (KMIPVersion): An enumeration defining the KMIP
                version with which the object will be decoded. Optional,
                defaults to KMIP 1.0.

        Raises:
            ValueError: Raised if the object type, unique identifier, or
                secret attributes are missing from the encoded payload.
        """
        super(GetResponsePayload, arg_0).Func(
            arg_1,
            arg_2=arg_2
        )
        arg_6 = utils.BytearrayStream(arg_1.Func(arg_0.length))

        if arg_0.is_tag_next(arg_3.Tags.OBJECT_TYPE, arg_6):
            arg_0._object_type = primitives.Enumeration(
                enum=arg_3.ObjectType,
                tag=arg_3.Tags.OBJECT_TYPE
            )
            arg_0._object_type.Func(arg_6, arg_2=arg_2)
        else:
            raise ValueError(
                "Parsed payload encoding is missing the object type field."
            )

        if arg_0.is_tag_next(arg_3.Tags.UNIQUE_IDENTIFIER, arg_6):
            arg_0._unique_identifier = primitives.TextString(
                tag=arg_3.Tags.UNIQUE_IDENTIFIER
            )
            arg_0._unique_identifier.Func(
                arg_6,
                arg_2=arg_2
            )
        else:
            raise ValueError(
                "Parsed payload encoding is missing the unique identifier "
                "field."
            )

        arg_0.secret = arg_0.secret_factory.create(arg_0.object_type)
        if arg_0.is_tag_next(arg_0._secret.tag, arg_6):
            arg_0._secret.Func(arg_6, arg_2=arg_2)
        else:
            raise ValueError(
                "Parsed payload encoding is missing the secret field."
            )

        arg_0.is_oversized(arg_6)


def Func(arg_0, arg_1, arg_2=arg_3.KMIPVersion.KMIP_1_0):
        """
        Write the data encoding the Get response payload to a stream.

        Args:
            output_stream (stream): A data stream in which to encode object
                data, supporting a Func method; usually a BytearrayStream
                object.
            kmip_version (KMIPVersion): An enumeration defining the KMIP
                version with which the object will be encoded. Optional,
                defaults to KMIP 1.0.

        Raises:
            ValueError: Raised if the object type, unique identifier, or
                secret attributes are missing from the payload struct.
        """
        arg_6 = utils.BytearrayStream()

        if arg_0.object_type:
            arg_0._object_type.Func(arg_6, arg_2=arg_2)
        else:
            raise ValueError("Payload is missing the object type field.")

        if arg_0.unique_identifier:
            arg_0._unique_identifier.Func(
                arg_6,
                arg_2=arg_2
            )
        else:
            raise ValueError(
                "Payload is missing the unique identifier field."
            )

        if arg_0.secret:
            arg_0._secret.Func(arg_6, arg_2=arg_2)
        else:
            raise ValueError("Payload is missing the secret field.")

        arg_0.length = arg_6.length()
        super(GetResponsePayload, arg_0).Func(
            arg_1,
            arg_2=arg_2
        )
        arg_1.Func(arg_6.buffer)


def Func(arg_0, arg_1, arg_2=arg_3.KMIPVersion.KMIP_1_0):
        """
        Read the data encoding the SignatureVerify request payload and decode
        it into its constituent parts.

        Args:
            input_stream (stream): A data stream containing encoded object
                data, supporting a Func method; usually a BytearrayStream
                object.
            kmip_version (KMIPVersion): An enumeration defining the KMIP
                version with which the object will be decoded. Optional,
                defaults to KMIP 1.0.

        Raises:
            ValueError: Raised if the data attribute is missing from the
                encoded payload.
        """
        super(SignatureVerifyRequestPayload, arg_0).Func(
            arg_1,
            arg_2=arg_2
        )
        arg_6 = utils.BytearrayStream(arg_1.Func(arg_0.length))

        if arg_0.is_tag_next(arg_3.Tags.UNIQUE_IDENTIFIER, arg_6):
            arg_0._unique_identifier = primitives.TextString(
                tag=arg_3.Tags.UNIQUE_IDENTIFIER
            )
            arg_0._unique_identifier.Func(
                arg_6,
                arg_2=arg_2
            )
        if arg_0.is_tag_next(arg_3.Tags.CRYPTOGRAPHIC_PARAMETERS, arg_6):
            arg_0._cryptographic_parameters = \
                attributes.CryptographicParameters()
            arg_0._cryptographic_parameters.Func(
                arg_6,
                arg_2=arg_2
            )
        if arg_0.is_tag_next(arg_3.Tags.DATA, arg_6):
            arg_0._data = primitives.ByteString(tag=arg_3.Tags.DATA)
            arg_0._data.Func(arg_6, arg_2=arg_2)
        if arg_0.is_tag_next(arg_3.Tags.DIGESTED_DATA, arg_6):
            arg_0._digested_data = primitives.ByteString(
                tag=arg_3.Tags.DIGESTED_DATA
            )
            arg_0._digested_data.Func(arg_6, arg_2=arg_2)
        if arg_0.is_tag_next(arg_3.Tags.SIGNATURE_DATA, arg_6):
            arg_0._signature_data = primitives.ByteString(
                tag=arg_3.Tags.SIGNATURE_DATA
            )
            arg_0._signature_data.Func(arg_6, arg_2=arg_2)
        if arg_0.is_tag_next(arg_3.Tags.CORRELATION_VALUE, arg_6):
            arg_0._correlation_value = primitives.ByteString(
                tag=arg_3.Tags.CORRELATION_VALUE
            )
            arg_0._correlation_value.Func(
                arg_6,
                arg_2=arg_2
            )
        if arg_0.is_tag_next(arg_3.Tags.INIT_INDICATOR, arg_6):
            arg_0._init_indicator = primitives.Boolean(
                tag=arg_3.Tags.INIT_INDICATOR
            )
            arg_0._init_indicator.Func(arg_6, arg_2=arg_2)
        if arg_0.is_tag_next(arg_3.Tags.FINAL_INDICATOR, arg_6):
            arg_0._final_indicator = primitives.Boolean(
                tag=arg_3.Tags.FINAL_INDICATOR
            )
            arg_0._final_indicator.Func(arg_6, arg_2=arg_2)

        arg_0.is_oversized(arg_6)


def Func(arg_0, arg_1, arg_2=arg_3.KMIPVersion.KMIP_1_0):
        """
        Write the data encoding the SignatureVerify request payload to a
        stream.

        Args:
            output_stream (stream): A data stream in which to encode object
                data, supporting a Func method; usually a BytearrayStream
                object.
            kmip_version (KMIPVersion): An enumeration defining the KMIP
                version with which the object will be encoded. Optional,
                defaults to KMIP 1.0.

        Raises:
            ValueError: Raised if the data attribute is not defined.
        """
        arg_6 = utils.BytearrayStream()

        if arg_0._unique_identifier:
            arg_0._unique_identifier.Func(
                arg_6,
                arg_2=arg_2
            )
        if arg_0._cryptographic_parameters:
            arg_0._cryptographic_parameters.Func(
                arg_6,
                arg_2=arg_2
            )
        if arg_0._data:
            arg_0._data.Func(arg_6, arg_2=arg_2)
        if arg_0._digested_data:
            arg_0._digested_data.Func(arg_6, arg_2=arg_2)
        if arg_0._signature_data:
            arg_0._signature_data.Func(
                arg_6,
                arg_2=arg_2
            )
        if arg_0._correlation_value:
            arg_0._correlation_value.Func(
                arg_6,
                arg_2=arg_2
            )
        if arg_0._init_indicator:
            arg_0._init_indicator.Func(
                arg_6,
                arg_2=arg_2
            )
        if arg_0._final_indicator:
            arg_0._final_indicator.Func(
                arg_6,
                arg_2=arg_2
            )

        arg_0.length = arg_6.length()
        super(SignatureVerifyRequestPayload, arg_0).Func(
            arg_1,
            arg_2=arg_2
        )
        arg_1.Func(arg_6.buffer)


def Func(arg_0, arg_1, arg_2=None):
        """
        Process a KMIP request message.

        This routine is the main driver of the KmipEngine. It breaks apart and
        processes the request header, handles any message errors that may
        result, and then passes the set of request batch items on for
        processing. This routine is thread-safe, allowing multiple client
        connections to use the same KmipEngine.

        Args:
            request (RequestMessage): The request message containing the batch
                items to be processed.
            credential (string): Identifying information about the client
                obtained from the client certificate. Optional, defaults to
                None.

        Returns:
            ResponseMessage: The response containing all of the results from
                the request batch items.
        """
        arg_0._client_identity = [None, None]
        arg_4 = arg_1.request_header

        # Process the protocol version
        arg_0._set_protocol_version(arg_4.protocol_version)

        # Process the maximum response size
        arg_5 = None
        if arg_4.maximum_response_size:
            arg_5 = arg_4.maximum_response_size.value

        # Process the time stamp
        arg_6 = int(time.time())
        if arg_4.time_stamp:
            arg_7 = arg_4.time_stamp.value

            if (arg_6 >= arg_7) and ((arg_6 - arg_7) < 60):
                arg_0._logger.info("Received request at time: {0}".format(
                    time.strftime(
                        "%Y-%m-%d %H:%M:%S",
                        time.gmtime(arg_7)
                    )
                ))
            else:
                if arg_6 < arg_7:
                    arg_0._logger.warning(
                        "Received request with future timestamp. Received "
                        "timestamp: {0}, Current timestamp: {1}".format(
                            arg_7,
                            arg_6
                        )
                    )

                    raise exceptions.InvalidMessage(
                        "Future request rejected by server."
                    )
                else:
                    arg_0._logger.warning(
                        "Received request with old timestamp. Possible "
                        "replay attack. Received timestamp: {0}, Current "
                        "timestamp: {1}".format(arg_7, arg_6)
                    )

                    raise exceptions.InvalidMessage(
                        "Stale request rejected by server."
                    )
        else:
            arg_0._logger.info("Received request at time: {0}".format(
                time.strftime(
                    "%Y-%m-%d %H:%M:%S",
                    time.gmtime(arg_6)
                )
            ))

        # Process the asynchronous indicator
        arg_0.is_asynchronous = False
        if arg_4.asynchronous_indicator is not None:
            arg_0.is_asynchronous = arg_4.asynchronous_indicator.value

        if arg_0.is_asynchronous:
            raise exceptions.InvalidMessage(
                "Asynchronous operations are not supported."
            )

        # Process the authentication credentials
        if arg_4.authentication:
            if arg_4.authentication.credentials:
                arg_9 = arg_4.authentication.credentials[0]
            else:
                arg_9 = None
        else:
            arg_9 = None

        arg_0._verify_credential(arg_9, arg_2)

        # Process the batch error continuation option
        arg_10 = enums.BatchErrorContinuationOption.STOP
        if arg_4.batch_error_cont_option is not None:
            arg_10 = arg_4.batch_error_cont_option.value

        if arg_10 == enums.BatchErrorContinuationOption.UNDO:
            raise exceptions.InvalidMessage(
                "Undo option for batch handling is not supported."
            )

        # Process the batch order option
        arg_11 = False
        if arg_4.batch_order_option:
            arg_11 = arg_4.batch_order_option.value

        arg_12 = arg_0._process_batch(
            arg_1.batch_items,
            arg_10,
            arg_11
        )
        arg_13 = arg_0._build_response(
            arg_4.protocol_version,
            arg_12
        )

        return arg_13, arg_5, arg_4.protocol_version


def Func(arg_0, arg_1, arg_2, arg_3):
        """
        Build a simple ResponseMessage with a single error result.

        Args:
            version (ProtocolVersion): The protocol version the response
                should be addressed with.
            reason (ResultReason): An enumeration classifying the type of
                error occurred.
            message (str): A string providing additional information about
                the error.

        Returns:
            ResponseMessage: The simple ResponseMessage containing a
                single error result.
        """
        arg_4 = messages.ResponseBatchItem(
            result_status=contents.ResultStatus(
                enums.ResultStatus.OPERATION_FAILED
            ),
            result_reason=contents.ResultReason(arg_2),
            result_message=contents.ResultMessage(arg_3)
        )
        return arg_0._build_response(arg_1, [arg_4])


def Func(arg_0, arg_1, arg_2):
        """
        Given a kmip.pie object and a dictionary of attributes, attempt to set
        the attribute values on the object.
        """
        for arg_3, arg_4 in six.iteritems(arg_2):
            arg_5 = arg_1._object_type
            if arg_0._attribute_policy.is_attribute_applicable_to_object_type(
                    arg_3,
                    arg_5):
                arg_0._set_attribute_on_managed_object(
                    arg_1,
                    (arg_3, arg_4)
                )
            else:
                arg_6 = arg_5.name
                raise exceptions.InvalidField(
                    "Cannot set {0} attribute on {1} object.".format(
                        arg_3,
                        ''.join([arg_7.capitalize() for arg_7 in arg_6.split('_')])
                    )
                )


def Func(arg_0, arg_1, arg_2):
        """
        Set the attribute value on the kmip.pie managed object.
        """
        arg_3 = arg_2[0]
        arg_4 = arg_2[1]

        if arg_0._attribute_policy.is_attribute_multivalued(arg_3):
            if arg_3 == 'Name':
                arg_1.names.extend(
                    [arg_5.name_value.value for arg_5 in arg_4]
                )
                for arg_6 in arg_1.names:
                    if arg_1.names.count(arg_6) > 1:
                        raise exceptions.InvalidField(
                            "Cannot set duplicate name values."
                        )
            else:
                # TODO (peterhamilton) Remove when all attributes are supported
                raise exceptions.InvalidField(
                    "The {0} attribute is unsupported.".format(arg_3)
                )
        else:
            arg_7 = None
            arg_8 = arg_4.value

            if arg_3 == 'Cryptographic Algorithm':
                arg_7 = 'cryptographic_algorithm'
            elif arg_3 == 'Cryptographic Length':
                arg_7 = 'cryptographic_length'
            elif arg_3 == 'Cryptographic Usage Mask':
                arg_7 = 'cryptographic_usage_masks'
                arg_8 = list()
                for arg_9 in enums.CryptographicUsageMask:
                    if arg_9.value & arg_4.value:
                        arg_8.append(arg_9)
            elif arg_3 == 'Operation Policy Name':
                arg_7 = 'operation_policy_name'

            if arg_7:
                arg_10 = getattr(arg_1, arg_7)
                if arg_10:
                    if arg_10 != arg_8:
                        raise exceptions.InvalidField(
                            "Cannot overwrite the {0} attribute.".format(
                                arg_3
                            )
                        )
                else:
                    setattr(arg_1, arg_7, arg_8)
            else:
                # TODO (peterhamilton) Remove when all attributes are supported
                raise exceptions.InvalidField(
                    "The {0} attribute is unsupported.".format(arg_3)
                )


def Func(arg_0, arg_1, arg_2=arg_3.KMIPVersion.KMIP_1_0):
        """
        Write the data encoding the Decrypt request payload to a stream.

        Args:
            output_stream (stream): A data stream in which to encode object
                data, supporting a Func method; usually a BytearrayStream
                object.
            kmip_version (KMIPVersion): An enumeration defining the KMIP
                version with which the object will be encoded. Optional,
                defaults to KMIP 1.0.

        Raises:
            ValueError: Raised if the data attribute is not defined.
        """
        arg_6 = utils.BytearrayStream()

        if arg_0._unique_identifier:
            arg_0._unique_identifier.Func(
                arg_6,
                arg_2=arg_2
            )
        if arg_0._cryptographic_parameters:
            arg_0._cryptographic_parameters.Func(
                arg_6,
                arg_2=arg_2
            )

        if arg_0._data:
            arg_0._data.Func(arg_6, arg_2=arg_2)
        else:
            raise ValueError("invalid payload missing the data attribute")

        if arg_0._iv_counter_nonce:
            arg_0._iv_counter_nonce.Func(
                arg_6,
                arg_2=arg_2
            )

        arg_0.length = arg_6.length()
        super(DecryptRequestPayload, arg_0).Func(
            arg_1,
            arg_2=arg_2
        )
        arg_1.Func(arg_6.buffer)


def Func(arg_0, arg_1, arg_2=None):
        """
        Create a secret object of the specified type with the given value.

        Args:
            secret_type (ObjectType): An ObjectType enumeration specifying the
                type of secret to Func.
            value (dict): A dictionary containing secret data. Optional,
                defaults to None.

        Returns:
            secret: The newly constructed secret object.

        Raises:
            TypeError: If the provided secret type is unrecognized.

        Example:
            >>> factory.Func(ObjectType.SYMMETRIC_KEY)
            SymmetricKey(...)
        """
        if arg_1 is ObjectType.CERTIFICATE:
            return arg_0._Func_certificate(arg_2)
        elif arg_1 is ObjectType.SYMMETRIC_KEY:
            return arg_0._Func_symmetric_key(arg_2)
        elif arg_1 is ObjectType.PUBLIC_KEY:
            return arg_0._Func_public_key(arg_2)
        elif arg_1 is ObjectType.PRIVATE_KEY:
            return arg_0._Func_private_key(arg_2)
        elif arg_1 is ObjectType.SPLIT_KEY:
            return arg_0._Func_split_key(arg_2)
        elif arg_1 is ObjectType.TEMPLATE:
            return arg_0._Func_template(arg_2)
        elif arg_1 is ObjectType.SECRET_DATA:
            return arg_0._Func_secret_data(arg_2)
        elif arg_1 is ObjectType.OPAQUE_DATA:
            return arg_0._Func_opaque_data(arg_2)
        else:
            raise TypeError("Unrecognized secret type: {0}".format(
                arg_1))


def Func(arg_0, arg_1):
        """
        Load configuration settings from the file pointed to by path.

        This will overwrite all current setting values.

        Args:
            path (string): The path to the configuration file containing
                the settings to load. Required.
        Raises:
            ConfigurationError: Raised if the path does not point to an
                existing file or if a setting value is invalid.
        """
        if not os.path.exists(arg_1):
            raise exceptions.ConfigurationError(
                "The server configuration file ('{0}') could not be "
                "located.".format(arg_1)
            )

        arg_0._logger.info(
            "Loading server configuration settings from: {0}".format(arg_1)
        )

        arg_2 = configparser.ConfigParser()
        arg_2.read(arg_1)
        arg_0._parse_settings(arg_2)
        arg_0.parse_auth_settings(arg_2)


def Func(arg_0, arg_1, arg_2):
        """
        Returns the integer value of the usage mask bitmask. This value is
        stored in the database.

        Args:
            value(list<enums.CryptographicUsageMask>): list of enums in the
            usage mask
            dialect(string): SQL dialect
        """
        arg_3 = 0x00
        for arg_4 in arg_1:
            arg_3 = arg_3 | arg_4.value
        return arg_3


def Func(arg_0, arg_1, arg_2):
        """
        Returns a new list of enums.CryptographicUsageMask Enums. This converts
        the integer value into the list of enums.

        Args:
            value(int): The integer value stored in the database that is used
                to create the list of enums.CryptographicUsageMask Enums.
            dialect(string): SQL dialect
        """
        arg_3 = list()
        if arg_1:
            for arg_4 in enums.CryptographicUsageMask:
                if arg_4.value & arg_1:
                    arg_3.append(arg_4)
        return arg_3


def Func(arg_0, arg_1, arg_2=arg_3.KMIPVersion.KMIP_1_0):
        """
        Read the encoding of the LongInteger from the input stream.

        Args:
            istream (stream): A buffer containing the encoded bytes of a
                LongInteger. Usually a BytearrayStream object. Required.
            kmip_version (KMIPVersion): An enumeration defining the KMIP
                version with which the object will be decoded. Optional,
                defaults to KMIP 1.0.

        Raises:
            InvalidPrimitiveLength: if the long integer encoding Func in has
                an invalid encoded length.
        """
        super(LongInteger, arg_0).Func(arg_1, arg_2=arg_2)

        if arg_0.length is not LongInteger.LENGTH:
            raise exceptions.InvalidPrimitiveLength(
                "invalid long integer length Func; "
                "expected: {0}, observed: {1}".format(
                    LongInteger.LENGTH, arg_0.length))

        arg_0.value = unpack('!q', arg_1.Func(arg_0.length))[0]
        arg_0.validate()


def Func(arg_0, arg_1, arg_2=arg_3.KMIPVersion.KMIP_1_0):
        """
        Write the encoding of the LongInteger to the output stream.

        Args:
            ostream (stream): A buffer to contain the encoded bytes of a
                LongInteger. Usually a BytearrayStream object. Required.
            kmip_version (KMIPVersion): An enumeration defining the KMIP
                version with which the object will be encoded. Optional,
                defaults to KMIP 1.0.
        """
        super(LongInteger, arg_0).Func(arg_1, arg_2=arg_2)
        arg_1.Func(pack('!q', arg_0.value))


def Func(arg_0):
        """
        Verify that the value of the LongInteger is valid.

        Raises:
            TypeError: if the value is not of type int or long
            ValueError: if the value cannot be represented by a signed 64-bit
                integer
        """
        if arg_0.value is not None:
            if not isinstance(arg_0.value, six.integer_types):
                raise TypeError('expected (one of): {0}, observed: {1}'.format(
                    six.integer_types, type(arg_0.value)))
            else:
                if arg_0.value > LongInteger.MAX:
                    raise ValueError(
                        'long integer value greater than accepted max')
                elif arg_0.value < LongInteger.MIN:
                    raise ValueError(
                        'long integer value less than accepted min')


def Func(arg_0, arg_1, arg_2=arg_3.KMIPVersion.KMIP_1_0):
        """
        Read the encoding of the BigInteger from the input stream.

        Args:
            istream (stream): A buffer containing the encoded bytes of the
                value of a BigInteger. Usually a BytearrayStream object.
                Required.
            kmip_version (KMIPVersion): An enumeration defining the KMIP
                version with which the object will be decoded. Optional,
                defaults to KMIP 1.0.

        Raises:
            InvalidPrimitiveLength: if the big integer encoding Func in has
                an invalid encoded length.
        """
        super(BigInteger, arg_0).Func(arg_1, arg_2=arg_2)

        # Check for a valid length before even trying to parse the value.
        if arg_0.length % 8:
            raise exceptions.InvalidPrimitiveLength(
                "invalid big integer length Func; "
                "expected: multiple of 8, observed: {0}".format(arg_0.length))

        arg_6 = 1
        arg_7 = ''

        # Read the value byte by byte and convert it into binary, padding each
        # byte as needed.
        for arg_8 in range(arg_0.length):
            arg_9 = struct.unpack('!B', arg_1.Func(1))[0]
            arg_10 = "{0:b}".format(arg_9)
            arg_11 = len(arg_10) % 8
            if arg_11:
                arg_10 = ('0' * (8 - arg_11)) + arg_10
            arg_7 += arg_10

        # If the value is negative, convert via two's complement.
        if arg_7[0] == '1':
            arg_6 = -1
            arg_7 = arg_7.replace('1', 'i')
            arg_7 = arg_7.replace('0', '1')
            arg_7 = arg_7.replace('i', '0')

            arg_12 = arg_7.rfind('0')
            arg_7 = arg_7[0:arg_12] + '1' + ('0' * len(arg_7[arg_12 + 1:]))

        # Convert the value back to an integer and reapply the sign.
        arg_0.value = int(arg_7, 2) * arg_6


def Func(arg_0, arg_1, arg_2=arg_3.KMIPVersion.KMIP_1_0):
        """
        Write the encoding of the BigInteger to the output stream.

        Args:
            ostream (Stream): A buffer to contain the encoded bytes of a
                BigInteger object. Usually a BytearrayStream object.
                Required.
            kmip_version (KMIPVersion): An enumeration defining the KMIP
                version with which the object will be encoded. Optional,
                defaults to KMIP 1.0.
        """
        # Convert the value to binary and pad it as needed.
        arg_6 = "{0:b}".format(abs(arg_0.value))
        arg_6 = ("0" * (64 - (len(arg_6) % 64))) + arg_6

        # If the value is negative, convert via two's complement.
        if arg_0.value < 0:
            arg_6 = arg_6.replace('1', 'i')
            arg_6 = arg_6.replace('0', '1')
            arg_6 = arg_6.replace('i', '0')

            arg_7 = arg_6.rfind('0')
            arg_6 = arg_6[0:arg_7] + '1' + ('0' * len(arg_6[arg_7 + 1:]))

        # Convert each byte to hex and build the hex string for the value.
        arg_8 = b''
        for arg_9 in range(0, len(arg_6), 8):
            arg_10 = arg_6[arg_9:arg_9 + 8]
            arg_10 = int(arg_10, 2)
            arg_8 += struct.pack('!B', arg_10)

        arg_0.length = len(arg_8)
        super(BigInteger, arg_0).Func(arg_1, arg_2=arg_2)
        arg_1.Func(arg_8)


def Func(arg_0):
        """
        Verify that the value of the BigInteger is valid.

        Raises:
            TypeError: if the value is not of type int or long
        """
        if arg_0.value is not None:
            if not isinstance(arg_0.value, six.integer_types):
                raise TypeError('expected (one of): {0}, observed: {1}'.format(
                    six.integer_types, type(arg_0.value)))


def Func(arg_0):
        """
        Verify that the value of the Enumeration is valid.

        Raises:
            TypeError: if the enum is not of type Enum
            ValueError: if the value is not of the expected Enum subtype or if
                the value cannot be represented by an unsigned 32-bit integer
        """
        if not isinstance(arg_0.enum, enumeration.EnumMeta):
            raise TypeError(
                'enumeration type {0} must be of type EnumMeta'.format(
                    arg_0.enum))
        if arg_0.value is not None:
            if not isinstance(arg_0.value, arg_0.enum):
                raise TypeError(
                    'enumeration {0} must be of type {1}'.format(
                        arg_0.value, arg_0.enum))
            if type(arg_0.value.value) not in six.integer_types:
                raise TypeError('enumeration value must be an int')
            else:
                if arg_0.value.value > Enumeration.MAX:
                    raise ValueError(
                        'enumeration value greater than accepted max')
                elif arg_0.value.value < Enumeration.MIN:
                    raise ValueError(
                        'enumeration value less than accepted min')


def Func(arg_0, arg_1, arg_2=arg_3.KMIPVersion.KMIP_1_0):
        """
        Write the encoding of the Boolean object to the output stream.

        Args:
            ostream (Stream): A buffer to contain the encoded bytes of a
                Boolean object. Usually a BytearrayStream object. Required.
            kmip_version (KMIPVersion): An enumeration defining the KMIP
                version with which the object will be encoded. Optional,
                defaults to KMIP 1.0.
        """
        super(Boolean, arg_0).Func(arg_1, arg_2=arg_2)
        arg_0.Func_value(arg_1, arg_2=arg_2)


def Func(arg_0):
        """
        Verify that the value of the Boolean object is valid.

        Raises:
            TypeError: if the value is not of type bool.
        """
        if arg_0.value:
            if not isinstance(arg_0.value, bool):
                raise TypeError("expected: {0}, observed: {1}".format(
                    bool, type(arg_0.value)))


def Func(arg_0, arg_1, arg_2=arg_3.KMIPVersion.KMIP_1_0):
        """
        Read the encoding of the Interval from the input stream.

        Args:
            istream (stream): A buffer containing the encoded bytes of the
                value of an Interval. Usually a BytearrayStream object.
                Required.
            kmip_version (KMIPVersion): An enumeration defining the KMIP
                version with which the object will be decoded. Optional,
                defaults to KMIP 1.0.

        Raises:
            InvalidPrimitiveLength: if the Interval encoding Func in has an
                invalid encoded length.
            InvalidPaddingBytes: if the Interval encoding Func in does not use
                zeroes for its padding bytes.
        """
        super(Interval, arg_0).Func(arg_1, arg_2=arg_2)

        # Check for a valid length before even trying to parse the value.
        if arg_0.length != Interval.LENGTH:
            raise exceptions.InvalidPrimitiveLength(
                "interval length must be {0}".format(Interval.LENGTH))

        # Decode the Interval value and the padding bytes.
        arg_0.value = unpack('!I', arg_1.Func(Interval.LENGTH))[0]
        arg_7 = unpack('!I', arg_1.Func(Interval.LENGTH))[0]

        # Verify that the padding bytes are zero bytes.
        if arg_7 != 0:
            raise exceptions.InvalidPaddingBytes("padding bytes must be zero")

        arg_0.validate()


def Func(arg_0):
        """
        Verify that the value of the Interval is valid.

        Raises:
            TypeError: if the value is not of type int or long
            ValueError: if the value cannot be represented by an unsigned
                32-bit integer
        """
        if arg_0.value is not None:
            if type(arg_0.value) not in six.integer_types:
                raise TypeError('expected (one of): {0}, observed: {1}'.format(
                    six.integer_types, type(arg_0.value)))
            else:
                if arg_0.value > Interval.MAX:
                    raise ValueError(
                        'interval value greater than accepted max')
                elif arg_0.value < Interval.MIN:
                    raise ValueError('interval value less than accepted min')


def Func(arg_0, arg_1):
        """
        Set the key wrapping data attributes using a dictionary.
        """
        if arg_1 is None:
            arg_1 = {}
        elif not isinstance(arg_1, dict):
            raise TypeError("Key wrapping data must be a dictionary.")

        arg_0._kdw_wrapping_method = arg_1.get('wrapping_method')

        arg_3 = arg_1.get('encryption_key_information')
        if arg_3 is None:
            arg_3 = {}
        arg_0._kdw_eki_unique_identifier = arg_3.get('unique_identifier')
        arg_5 = arg_3.get('cryptographic_parameters')
        if arg_5 is None:
            arg_5 = {}
        arg_0._kdw_eki_cp_block_cipher_mode = arg_5.get('block_cipher_mode')
        arg_0._kdw_eki_cp_padding_method = arg_5.get('padding_method')
        arg_0._kdw_eki_cp_hashing_algorithm = arg_5.get('hashing_algorithm')
        arg_0._kdw_eki_cp_key_role_type = arg_5.get('key_role_type')
        arg_0._kdw_eki_cp_digital_signature_algorithm = \
            arg_5.get('digital_signature_algorithm')
        arg_0._kdw_eki_cp_cryptographic_algorithm = \
            arg_5.get('cryptographic_algorithm')
        arg_0._kdw_eki_cp_random_iv = arg_5.get('random_iv')
        arg_0._kdw_eki_cp_iv_length = arg_5.get('iv_length')
        arg_0._kdw_eki_cp_tag_length = arg_5.get('tag_length')
        arg_0._kdw_eki_cp_fixed_field_length = arg_5.get('fixed_field_length')
        arg_0._kdw_eki_cp_invocation_field_length = \
            arg_5.get('invocation_field_length')
        arg_0._kdw_eki_cp_counter_length = arg_5.get('counter_length')
        arg_0._kdw_eki_cp_initial_counter_value = \
            arg_5.get('initial_counter_value')

        arg_19 = arg_1.get('mac_signature_key_information')
        if arg_19 is None:
            arg_19 = {}
        arg_0._kdw_mski_unique_identifier = arg_19.get('unique_identifier')
        arg_21 = arg_19.get('cryptographic_parameters')
        if arg_21 is None:
            arg_21 = {}
        arg_0._kdw_mski_cp_block_cipher_mode = arg_21.get('block_cipher_mode')
        arg_0._kdw_mski_cp_padding_method = arg_21.get('padding_method')
        arg_0._kdw_mski_cp_hashing_algorithm = arg_21.get('hashing_algorithm')
        arg_0._kdw_mski_cp_key_role_type = arg_21.get('key_role_type')
        arg_0._kdw_mski_cp_digital_signature_algorithm = \
            arg_21.get('digital_signature_algorithm')
        arg_0._kdw_mski_cp_cryptographic_algorithm = \
            arg_21.get('cryptographic_algorithm')
        arg_0._kdw_mski_cp_random_iv = arg_21.get('random_iv')
        arg_0._kdw_mski_cp_iv_length = arg_21.get('iv_length')
        arg_0._kdw_mski_cp_tag_length = arg_21.get('tag_length')
        arg_0._kdw_mski_cp_fixed_field_length = \
            arg_21.get('fixed_field_length')
        arg_0._kdw_mski_cp_invocation_field_length = \
            arg_21.get('invocation_field_length')
        arg_0._kdw_mski_cp_counter_length = arg_21.get('counter_length')
        arg_0._kdw_mski_cp_initial_counter_value = \
            arg_21.get('initial_counter_value')

        arg_0._kdw_mac_signature = arg_1.get('mac_signature')
        arg_0._kdw_iv_counter_nonce = arg_1.get('iv_counter_nonce')
        arg_0._kdw_encoding_option = arg_1.get('encoding_option')


def Func(arg_0):
        """
        Verify that the contents of the PublicKey object are valid.

        Raises:
            TypeError: if the types of any PublicKey attributes are invalid.
        """
        if not isinstance(arg_0.value, bytes):
            raise TypeError("key value must be bytes")
        elif not isinstance(arg_0.cryptographic_algorithm,
                            enums.CryptographicAlgorithm):
            raise TypeError("key algorithm must be a CryptographicAlgorithm "
                            "enumeration")
        elif not isinstance(arg_0.cryptographic_length, six.integer_types):
            raise TypeError("key length must be an integer")
        elif not isinstance(arg_0.key_format_type, enums.KeyFormatType):
            raise TypeError("key format type must be a KeyFormatType "
                            "enumeration")
        elif arg_0.key_format_type not in arg_0._valid_formats:
            raise ValueError("key format type must be one of {0}".format(
                arg_0._valid_formats))

        # TODO (peter-hamilton) Verify that the key bytes match the key format

        arg_1 = len(arg_0.cryptographic_usage_masks)
        for arg_2 in range(arg_1):
            arg_3 = arg_0.cryptographic_usage_masks[arg_2]
            if not isinstance(arg_3, enums.CryptographicUsageMask):
                arg_4 = "({0} in list)".format(arg_2)
                raise TypeError(
                    "key mask {0} must be a CryptographicUsageMask "
                    "enumeration".format(arg_4))

        arg_5 = len(arg_0.names)
        for arg_2 in range(arg_5):
            arg_6 = arg_0.names[arg_2]
            if not isinstance(arg_6, six.string_types):
                arg_4 = "({0} in list)".format(arg_2)
                raise TypeError("key name {0} must be a string".format(
                    arg_4))


def Func(arg_0):
    """
    A utility function that converts an attribute name string into the
    corresponding attribute tag.

    For example: 'State' -> enums.Tags.STATE

    Args:
        value (string): The string name of the attribute.

    Returns:
        enum: The Tags enumeration value that corresponds to the attribute
            name string.

    Raises:
        ValueError: if the attribute name string is not a string or if it is
            an unrecognized attribute name
    """
    if not isinstance(arg_0, six.string_types):
        raise ValueError("The attribute name must be a string.")

    for arg_1 in attribute_name_tag_table:
        if arg_0 == arg_1[0]:
            return arg_1[1]

    raise ValueError("Unrecognized attribute name: '{}'".format(arg_0))


def Func(arg_0):
    """
    A utility function that converts an attribute tag into the corresponding
    attribute name string.

    For example: enums.Tags.STATE -> 'State'

    Args:
        value (enum): The Tags enumeration value of the attribute.

    Returns:
        string: The attribute name string that corresponds to the attribute
            tag.

    Raises:
        ValueError: if the attribute tag is not a Tags enumeration or if it
            is unrecognized attribute tag
    """
    if not isinstance(arg_0, Tags):
        raise ValueError("The attribute tag must be a Tags enumeration.")

    for arg_1 in attribute_name_tag_table:
        if arg_0 == arg_1[1]:
            return arg_1[0]

    raise ValueError("Unrecognized attribute tag: {}".format(arg_0))


def Func(arg_0):
    """
    A utility function that computes a bit mask from a collection of
    enumeration values.

    Args:
        enumerations (list): A list of enumeration values to be combined in a
            composite bit mask.

    Returns:
        int: The composite bit mask.
    """
    return functools.reduce(
        lambda x, y: x | y, [arg_1.value for arg_1 in arg_0]
    )


def Func(arg_0, arg_1):
    """
    A utility function that checks if the provided value is a composite bit
    mask of enumeration values in the specified enumeration class.

    Args:
        enumeration (class): One of the mask enumeration classes found in this
            file. These include:
                * Cryptographic Usage Mask
                * Protection Storage Mask
                * Storage Status Mask
        potential_mask (int): A potential bit mask composed of enumeration
            values belonging to the enumeration class.

    Returns:
        True: if the potential mask is a valid bit mask of the mask enumeration
        False: otherwise
    """
    if not isinstance(arg_1, six.integer_types):
        return False

    arg_2 = (
        CryptographicUsageMask,
        ProtectionStorageMask,
        StorageStatusMask
    )
    if arg_0 not in arg_2:
        return False

    arg_3 = 0
    for arg_4 in [e.value for e in arg_0]:
        if (arg_4 & arg_1) == arg_4:
            arg_3 |= arg_4

    if arg_3 != arg_1:
        return False

    return True


def Func(arg_0, arg_1, arg_2=arg_3.KMIPVersion.KMIP_1_0):
        """
        Write the data encoding the CreateKeyPair request payload to a buffer.

        Args:
            output_buffer (stream): A data buffer in which to encode object
                data, supporting a Func method.
            kmip_version (KMIPVersion): An enumeration defining the KMIP
                version with which the object will be encoded. Optional,
                defaults to KMIP 1.0.
        """
        arg_6 = utils.BytearrayStream()

        if arg_2 < arg_3.KMIPVersion.KMIP_2_0:
            if arg_0._common_template_attribute is not None:
                arg_0._common_template_attribute.Func(
                    arg_6,
                    arg_2=arg_2
                )
        else:
            if arg_0._common_template_attribute is not None:
                arg_7 = objects.convert_template_attribute_to_attributes(
                    arg_0._common_template_attribute
                )
                arg_7.Func(arg_6, arg_2=arg_2)

        if arg_2 < arg_3.KMIPVersion.KMIP_2_0:
            if arg_0._private_key_template_attribute is not None:
                arg_0._private_key_template_attribute.Func(
                    arg_6,
                    arg_2=arg_2
                )
        else:
            if arg_0._private_key_template_attribute is not None:
                arg_7 = objects.convert_template_attribute_to_attributes(
                    arg_0._private_key_template_attribute
                )
                arg_7.Func(arg_6, arg_2=arg_2)

        if arg_2 < arg_3.KMIPVersion.KMIP_2_0:
            if arg_0._public_key_template_attribute is not None:
                arg_0._public_key_template_attribute.Func(
                    arg_6,
                    arg_2=arg_2
                )
        else:
            if arg_0._public_key_template_attribute is not None:
                arg_7 = objects.convert_template_attribute_to_attributes(
                    arg_0._public_key_template_attribute
                )
                arg_7.Func(arg_6, arg_2=arg_2)

        arg_0.length = arg_6.length()
        super(CreateKeyPairRequestPayload, arg_0).Func(
            arg_1,
            arg_2=arg_2
        )
        arg_1.Func(arg_6.buffer)


def Func(arg_0, arg_1, arg_2=arg_3.KMIPVersion.KMIP_1_0):
        """
        Write the data encoding the CreateKeyPair response payload to a buffer.

        Args:
            output_buffer (stream): A data buffer in which to encode object
                data, supporting a Func method.
            kmip_version (KMIPVersion): An enumeration defining the KMIP
                version with which the object will be encoded. Optional,
                defaults to KMIP 1.0.

        Raises:
            InvalidField: Raised if the private key unique identifier or the
                public key unique identifier is not defined.
        """
        arg_6 = utils.BytearrayStream()

        if arg_0._private_key_unique_identifier:
            arg_0._private_key_unique_identifier.Func(
                arg_6,
                arg_2=arg_2
            )
        else:
            raise exceptions.InvalidField(
                "The CreateKeyPair response payload is missing the private "
                "key unique identifier field."
            )

        if arg_0._public_key_unique_identifier:
            arg_0._public_key_unique_identifier.Func(
                arg_6,
                arg_2=arg_2
            )
        else:
            raise exceptions.InvalidField(
                "The CreateKeyPair response payload is missing the public "
                "key unique identifier field."
            )

        if arg_0._private_key_template_attribute:
            arg_0._private_key_template_attribute.Func(
                arg_6,
                arg_2=arg_2
            )

        if arg_0._public_key_template_attribute:
            arg_0._public_key_template_attribute.Func(
                arg_6,
                arg_2=arg_2
            )

        arg_0.length = arg_6.length()
        super(CreateKeyPairResponsePayload, arg_0).Func(
            arg_1,
            arg_2=arg_2
        )
        arg_1.Func(arg_6.buffer)


def Func(arg_0, arg_1, arg_2=arg_3.KMIPVersion.KMIP_1_0):
        """
        Read the data encoding the GetAttributeList request payload and decode
        it into its constituent parts.

        Args:
            input_buffer (stream): A data stream containing encoded object
                data, supporting a Func method; usually a BytearrayStream
                object.
            kmip_version (KMIPVersion): An enumeration defining the KMIP
                version with which the object will be decoded. Optional,
                defaults to KMIP 1.0.
        """
        super(GetAttributeListRequestPayload, arg_0).Func(
            arg_1,
            arg_2=arg_2
        )
        arg_6 = utils.BytearrayStream(arg_1.Func(arg_0.length))

        if arg_0.is_tag_next(arg_3.Tags.UNIQUE_IDENTIFIER, arg_6):
            arg_0._unique_identifier = primitives.TextString(
                tag=arg_3.Tags.UNIQUE_IDENTIFIER
            )
            arg_0._unique_identifier.Func(
                arg_6,
                arg_2=arg_2
            )
        else:
            arg_0._unique_identifier = None

        arg_0.is_oversized(arg_6)


def Func(arg_0, arg_1, arg_2=arg_3.KMIPVersion.KMIP_1_0):
        """
        Write the data encoding the GetAttributeList request payload to a
        stream.

        Args:
            output_buffer (stream): A data stream in which to encode object
                data, supporting a Func method; usually a BytearrayStream
                object.
            kmip_version (KMIPVersion): An enumeration defining the KMIP
                version with which the object will be encoded. Optional,
                defaults to KMIP 1.0.
        """
        arg_6 = utils.BytearrayStream()

        if arg_0._unique_identifier:
            arg_0._unique_identifier.Func(
                arg_6,
                arg_2=arg_2
            )

        arg_0.length = arg_6.length()
        super(GetAttributeListRequestPayload, arg_0).Func(
            arg_1,
            arg_2=arg_2
        )
        arg_1.Func(arg_6.buffer)