def Func(arg_0, arg_1):
        """Stop PWM output on specified pin."""
        if arg_1 not in arg_0.pwm:
            raise ValueError('Pin {0} is not configured as a PWM.  Make sure to first call start for the pin.'.format(arg_1))
        arg_0.pwm[arg_1].Func()
        del arg_0.pwm[arg_1]


def Func(arg_0, arg_1=None):
        """Write the specified byte value to the IODIR registor.  If no value
        specified the current buffered value will be written.
        """
        if arg_1 is not None:
            arg_0.iodir = arg_1
        arg_0._device.writeList(arg_0.IODIR, arg_0.iodir)


def Func(arg_0, arg_1=None):
        """Write the specified byte value to the GPPU registor.  If no value
        specified the current buffered value will be written.
        """
        if arg_1 is not None:
            arg_0.gppu = arg_1
        arg_0._device.writeList(arg_0.GPPU, arg_0.gppu)


def Func():
    """Disable the FTDI drivers for the current platform.  This is necessary
    because they will conflict with libftdi and accessing the FT232H.  Note you
    can enable the FTDI drivers again by calling enable_FTDI_driver.
    """
    logger.debug('Disabling FTDI driver.')
    if sys.platform == 'darwin':
        logger.debug('Detected Mac OSX')
        # Mac OS commands to disable FTDI driver.
        _check_running_as_root()
        subprocess.call('kextunload -b com.apple.driver.AppleUSBFTDI', shell=True)
        subprocess.call('kextunload /System/Library/Extensions/FTDIUSBSerialDriver.kext', shell=True)
    elif sys.platform.startswith('linux'):
        logger.debug('Detected Linux')
        # Linux commands to disable FTDI driver.
        _check_running_as_root()
        subprocess.call('modprobe -r -q ftdi_sio', shell=True)
        subprocess.call('modprobe -r -q usbserial', shell=True)


def Func(arg_0):
        """Close the FTDI device.  Will be automatically called when the program ends."""
        if arg_0._ctx is not None:
            ftdi.free(arg_0._ctx)
        arg_0._ctx = None


def Func(arg_0, arg_1):
        """Helper function to call write_data on the provided FTDI device and
        verify it succeeds.
        """
        # Get modem status. Useful to enable for debugging.
        #ret, status = ftdi.poll_modem_status(self._ctx)
        #if ret == 0:
        #	logger.debug('Modem status {0:02X}'.format(status))
        #else:
        #	logger.debug('Modem status error {0}'.format(ret))
        arg_2 = len(arg_1)
        try:
            arg_3 = ftdi.write_data(arg_0._ctx, arg_1, arg_2)
        except TypeError:
            arg_3 = ftdi.write_data(arg_0._ctx, arg_1); #compatible with libFtdi 1.3
        # Log the string that was written in a python hex string format using a very
        # ugly one-liner list comprehension for brevity.
        #logger.debug('Wrote {0}'.format(''.join(['\\x{0:02X}'.format(ord(x)) for x in string])))
        if arg_3 < 0:
            raise RuntimeError('ftdiFunc_data failed with error {0}: {1}'.format(arg_3, ftdi.get_error_string(arg_0._ctx)))
        if arg_3 != arg_2:
            raise RuntimeError('ftdiFunc_data expected to write {0} bytes but actually wrote {1}!'.format(arg_2, arg_3))


def Func(arg_0, arg_1, *arg_2):
        """Helper function to call the provided command on the FTDI device and
        verify the response matches the expected value.
        """
        arg_3 = arg_1(arg_0._ctx, *arg_2)
        logger.debug('Called ftdi_{0} and got response {1}.'.format(arg_1.__name__, arg_3))
        if arg_3 != 0:
            raise RuntimeError('ftdi_{0} failed with error {1}: {2}'.format(arg_1.__name__, arg_3, ftdi.get_error_string(arg_0._ctx)))


def Func(arg_0, arg_1, arg_2=5.0):
        """Helper function to continuously poll reads on the FTDI device until an
        expected number of bytes are returned.  Will throw a timeout error if no
        data is received within the specified number of timeout seconds.  Returns
        the read data as a string if successful, otherwise raises an execption.
        """
        arg_3 = time.time()
        # Start with an empty response buffer.
        arg_4 = bytearray(arg_1)
        arg_5 = 0
        # Loop calling read until the response buffer is full or a timeout occurs.
        while time.time() - arg_3 <= arg_2:
            arg_6, arg_7 = ftdi.read_data(arg_0._ctx, arg_1 - arg_5)
            # Fail if there was an error reading data.
            if arg_6 < 0:
                raise RuntimeError('ftdi_read_data failed with error code {0}.'.format(arg_6))
            # Add returned data to the buffer.
            arg_4[arg_5:arg_5+arg_6] = arg_7[:arg_6]
            arg_5 += arg_6
            # Buffer is full, return the result data.
            if arg_5 >= arg_1:
                return str(arg_4)
            time.sleep(0.01)
        raise RuntimeError('Timeout while polling ftdi_read_data for {0} bytes!'.format(arg_1))


def Func(arg_0):
        """Enable MPSSE mode on the FTDI device."""
        # Reset MPSSE by sending mask = 0 and mode = 0
        arg_0._check(ftdi.set_bitmode, 0, 0)
        # Enable MPSSE by sending mask = 0 and mode = 2
        arg_0._check(ftdi.set_bitmode, 0, 2)


def Func(arg_0, arg_1=10):
        """Synchronize buffers with MPSSE by sending bad opcode and reading expected
        error response.  Should be called once after enabling MPSSE."""
        # Send a bad/unknown command (0xAB), then read buffer until bad command
        # response is found.
        arg_0._write('\xAB')
        # Keep reading until bad command response (0xFA 0xAB) is returned.
        # Fail if too many read attempts are made to prevent sticking in a loop.
        arg_2 = 0
        arg_3 = False
        while not arg_3:
            arg_4 = arg_0._poll_read(2)
            if arg_4 == '\xFA\xAB':
                arg_3 = True
            arg_2 += 1
            if arg_2 >= arg_1:
                raise RuntimeError('Could not synchronize with FT232H!')


def Func(arg_0, arg_1, arg_2=False, arg_3=False):
        """Set the clock speed of the MPSSE engine.  Can be any value from 450hz
        to 30mhz and will pick that speed or the closest speed below it.
        """
        # Disable clock divisor by 5 to enable faster speeds on FT232H.
        arg_0._write('\x8A')
        # Turn on/off adaptive clocking.
        if arg_2:
            arg_0._write('\x96')
        else:
            arg_0._write('\x97')
        # Turn on/off three phase clock (needed for I2C).
        # Also adjust the frequency for three-phase clocking as specified in section 2.2.4
        # of this document:
        #   http://www.ftdichip.com/Support/Documents/AppNotes/AN_255_USB%20to%20I2C%20Example%20using%20the%20FT232H%20and%20FT201X%20devices.pdf
        if arg_3:
            arg_0._write('\x8C')
        else:
            arg_0._write('\x8D')
        # Compute divisor for requested clock.
        # Use equation from section 3.8.1 of:
        #  http://www.ftdichip.com/Support/Documents/AppNotes/AN_108_Command_Processor_for_MPSSE_and_MCU_Host_Bus_Emulation_Modes.pdf
        # Note equation is using 60mhz master clock instead of 12mhz.
        arg_4 = int(math.ceil((30000000.0-float(arg_1))/float(arg_1))) & 0xFFFF
        if arg_3:
            arg_4 = int(arg_4*(2.0/3.0))
        logger.debug('Setting clockspeed with divisor value {0}'.format(arg_4))
        # Send command to set divisor from low and high byte values.
        arg_0._write(str(bytearray((0x86, arg_4 & 0xFF, (arg_4 >> 8) & 0xFF))))


def Func(arg_0):
        """Read both GPIO bus states and return a 16 bit value with their state.
        D0-D7 are the lower 8 bits and C0-C7 are the upper 8 bits.
        """
        # Send command to read low byte and high byte.
        arg_0._write('\x81\x83')
        # Wait for 2 byte response.
        arg_1 = arg_0._poll_read(2)
        # Assemble response into 16 bit value.
        arg_2 = ord(arg_1[0])
        arg_3 = ord(arg_1[1])
        logger.debug('Read MPSSE GPIO low byte = {0:02X} and high byte = {1:02X}'.format(arg_2, arg_3))
        return (arg_3 << 8) | arg_2


def Func(arg_0):
        """Return command to update the MPSSE GPIO state to the current direction
        and level.
        """
        arg_1  = chr(arg_0._level & 0xFF)
        arg_2 = chr((arg_0._level >> 8) & 0xFF)
        arg_3  = chr(arg_0._direction & 0xFF)
        arg_4 = chr((arg_0._direction >> 8) & 0xFF)
        return str(bytearray((0x80, arg_1, arg_3, 0x82, arg_2, arg_4)))


def Func(arg_0, arg_1, arg_2):
        """Set the input or output mode for a specified pin.  Mode should be
        either OUT or IN."""
        arg_0._Func_pin(arg_1, arg_2)
        arg_0.mpsse_write_gpio()


def Func(arg_0, arg_1):
        """Half-duplex SPI Func.  The specified length of bytes will be clocked
        in the MISO line and returned as a bytearray object.
        """
        #check for hardware limit of FT232H and similar MPSSE chips
        if (1 > arg_1 > 65536):
            print('the FTDI chip is limited to 65536 bytes (64 KB) of input/output per command!')
            print('use for loops for larger Funcs')
            exit(1)
        # Build command to Func SPI data.
        arg_2 = 0x20 | (arg_0.lsbfirst << 3) | (arg_0.Func_clock_ve << 2)
        logger.debug('SPI Func with command {0:2X}.'.format(arg_2))
        # Compute length low and high bytes.
        # NOTE: Must actually send length minus one because the MPSSE engine
        # considers 0 a length of 1 and FFFF a length of 65536
	#force odd numbers to round up instead of down
	arg_3 = arg_1
	if arg_1 % 2 == 1:
	    arg_3 += 1
	arg_3 = arg_3/2
	#when odd length requested, get the remainder instead of the same number
	arg_4 = arg_1 - arg_3
        arg_5  = (arg_3 - 1) & 0xFF
        arg_6 = ((arg_3 - 1) >> 8) & 0xFF
        arg_0._assert_cs()
        # Send command and length.
        # Perform twice to prevent error from hardware defect/limits
        arg_0._ft232h._write(str(bytearray((arg_2, arg_5, arg_6))))
        arg_7 = arg_0._ft232h._poll_Func(arg_3)
        arg_0._ft232h._write(str(bytearray((arg_2, arg_5, arg_6))))
        arg_8 = arg_0._ft232h._poll_Func(arg_4)
        arg_0._deassert_cs()
        # Read response bytes
        return bytearray(arg_7 + arg_8)


def Func(arg_0, arg_1):
        """Write the specified number of bytes to the chip."""
        for arg_2 in arg_1:
            # Write byte.
            arg_0._command.append(str(bytearray((0x11, 0x00, 0x00, arg_2))))
            # Make sure pins are back in idle state with clock low and data high.
            arg_0._ft232h.output_pins({0: GPIO.LOW, 1: GPIO.HIGH}, write=False)
            arg_0._command.append(arg_0._ft232h.mpsse_gpio() * _REPEAT_DELAY)
            # Read bit for ACK/NAK.
            arg_0._command.append('\x22\x00')
        # Increase expected response bytes.
        arg_0._expected += len(arg_1)


def Func(arg_0, arg_1):
        """Read a signed byte from the specified register."""
        arg_2 = arg_0.readU8(arg_1)
        if arg_2 > 127:
            arg_2 -= 256
        return arg_2


def Func(arg_0, arg_1=None, arg_2=None, **arg_3):
    """Return an I2C device for the specified address and on the specified bus.
    If busnum isn't specified, the default I2C bus for the platform will attempt
    to be detected.
    """
    if arg_1 is None:
        arg_1 = get_default_bus()
    return Device(arg_0, arg_1, arg_2, **arg_3)


def Func(arg_0, arg_1, arg_2):
        """Write an 8-bit value to the specified register."""
        arg_2 = arg_2 & 0xFF
        arg_0._bus.write_byte_data(arg_0._address, arg_1, arg_2)
        arg_0._logger.debug("Wrote 0x%02X to register 0x%02X",
                     arg_2, arg_1)


def Func(arg_0, arg_1):
        """Read an unsigned byte from the specified register."""
        arg_2 = arg_0._bus.read_byte_data(arg_0._address, arg_1) & 0xFF
        arg_0._logger.debug("Read 0x%02X from register 0x%02X",
                     arg_2, arg_1)
        return arg_2


def Func(**arg_0):
    """Attempt to return a GPIO instance for the platform which the code is being
    executed on.  Currently supports only the Raspberry Pi using the RPi.GPIO
    library and Beaglebone Black using the Adafruit_BBIO library.  Will throw an
    exception if a GPIO instance can't be created for the current platform.  The
    returned GPIO object is an instance of BaseGPIO.
    """
    arg_1 = Platform.platform_detect()
    if arg_1 == Platform.RASPBERRY_PI:
        import RPi.GPIO
        return RPiGPIOAdapter(RPi.GPIO, **arg_0)
    elif arg_1 == Platform.BEAGLEBONE_BLACK:
        import Adafruit_BBIO.GPIO
        return AdafruitBBIOAdapter(Adafruit_BBIO.GPIO, **arg_0)
    elif arg_1 == Platform.MINNOWBOARD:
        import mraa
        return AdafruitMinnowAdapter(mraa, **arg_0)
    elif arg_1 == Platform.JETSON_NANO:
        import Jetson.GPIO
        return RPiGPIOAdapter(Jetson.GPIO, **arg_0)
    elif arg_1 == Platform.UNKNOWN:
        raise RuntimeError('Could not determine platform.')


def Func(arg_0, arg_1, arg_2, arg_3=arg_4):
        """Set the input or output mode for a specified pin.  Mode should be
        either OUTPUT or INPUT.
        """
        arg_0.rpi_gpio.Func(arg_1, arg_0._dir_mapping[arg_2],
                            arg_3=arg_0._pud_mapping[arg_3])


def Func(arg_0,arg_1,arg_2):
        """Set the input or output mode for a specified pin.  Mode should be
        either DIR_IN or DIR_OUT.
        """
        arg_0.mraa_gpio.Gpio.dir(arg_0.mraa_gpio.Gpio(arg_1),arg_0._dir_mapping[arg_2])


def Func(arg_0, arg_1):
        """Remove edge detection for a particular GPIO channel.  Pin should be
        type IN.
        """
        arg_0.mraa_gpio.Gpio.isrExit(arg_0.mraa_gpio.Gpio(arg_1))


def Func(arg_0):
        """
        Call the method repeatedly such that it will return a PKey object.
        """
        arg_1 = xrange(3)
        for arg_2 in xrange(arg_0.iterations):
            arg_3 = PKey()
            arg_3.generate_key(TYPE_DSA, 256)
            for arg_2 in arg_1:
                arg_4 = X509()
                arg_4.set_pubkey(arg_3)
                for arg_2 in arg_1:
                    arg_4.get_pubkey()


def Func(arg_0):
        """
        Call the function with an encrypted PEM and a passphrase callback which
        returns the wrong passphrase.
        """
        for arg_1 in xrange(arg_0.iterations * 10):
            try:
                load_privatekey(
                    FILETYPE_PEM, arg_0.ENCRYPTED_PEM,
                    lambda *args: "hello, public")
            except Error:
                pass


def Func(arg_0):
        """
        Call the function with an encrypted PEM and a passphrase callback which
        returns a non-string.
        """
        for arg_1 in xrange(arg_0.iterations * 10):
            try:
                load_privatekey(
                    FILETYPE_PEM, arg_0.ENCRYPTED_PEM,
                    lambda *args: {})
            except ValueError:
                pass


def Func(arg_0):
        """
        Create a CRL object with 100 Revoked objects, then call the
        get_revoked method repeatedly.
        """
        arg_1 = CRL()
        for arg_2 in xrange(100):
            arg_1.add_revoked(Revoked())
        for arg_2 in xrange(arg_0.iterations):
            arg_1.get_revoked()


def Func(arg_0):
        """
        Copy an empty Revoked object repeatedly. The copy is not garbage
        collected, therefore it needs to be manually freed.
        """
        for arg_1 in xrange(arg_0.iterations * 100):
            arg_2 = _X509_REVOKED_dup(Revoked()._revoked)
            _lib.X509_REVOKED_free(arg_2)


def Func(arg_0, arg_1, arg_2, arg_3,
                      arg_4="sha256"):
    """
    Generate a certificate given a certificate request.

    Arguments: req        - Certificate request to use
               issuerCert - The certificate of the issuer
               issuerKey  - The private key of the issuer
               serial     - Serial number for the certificate
               notBefore  - Timestamp (relative to now) when the certificate
                            starts being valid
               notAfter   - Timestamp (relative to now) when the certificate
                            stops being valid
               digest     - Digest method to use for signing, default is sha256
    Returns:   The signed certificate in an X509 object
    """
    arg_5, arg_6 = arg_1
    arg_7, arg_8 = arg_3
    arg_9 = crypto.X509()
    arg_9.set_serial_number(arg_2)
    arg_9.gmtime_adj_notBefore(arg_7)
    arg_9.gmtime_adj_notAfter(arg_8)
    arg_9.set_issuer(arg_5.get_subject())
    arg_9.set_subject(arg_0.get_subject())
    arg_9.set_pubkey(arg_0.get_pubkey())
    arg_9.sign(arg_6, arg_4)
    return arg_9


def Func(arg_0, arg_1):
    """
    Builds a decorator that ensures that functions that rely on OpenSSL
    functions that are not present in this build raise NotImplementedError,
    rather than AttributeError coming out of cryptography.

    :param flag: A cryptography flag that guards the functions, e.g.
        ``Cryptography_HAS_NEXTPROTONEG``.
    :param error: The string to be used in the exception if the flag is false.
    """
    def _requires_decorator(arg_2):
        if not arg_0:
            @wraps(arg_2)
            def explode(*arg_3, **arg_4):
                raise NotImplementedError(arg_1)
            return explode
        else:
            return arg_2

    return _requires_decorator


def Func(arg_0, arg_1, arg_2=None):
        """
        Set the passphrase callback.  This function will be called
        when a private key with a passphrase is loaded.

        :param callback: The Python callback to use.  This must accept three
            positional arguments.  First, an integer giving the maximum length
            of the passphrase it may return.  If the returned passphrase is
            longer than this, it will be truncated.  Second, a boolean value
            which will be true if the user should be prompted for the
            passphrase twice and the callback should verify that the two values
            supplied are equal. Third, the value given as the *userdata*
            parameter to :meth:`Func`.  The *callback* must return
            a byte string. If an error occurs, *callback* should return a false
            value (e.g. an empty string).
        :param userdata: (optional) A Python object which will be given as
                         argument to the callback
        :return: None
        """
        if not callable(arg_1):
            raise TypeError("callback must be callable")

        arg_0._passphrase_helper = arg_0._wrap_callback(arg_1)
        arg_0._passphrase_callback = arg_0._passphrase_helper.callback
        _lib.SSL_CTX_set_default_passwd_cb(
            arg_0._context, arg_0._passphrase_callback)
        arg_0._passphrase_userdata = arg_2


def Func(arg_0, arg_1):
        """
        Load a certificate chain from a file.

        :param certfile: The name of the certificate chain file (``bytes`` or
            ``unicode``).  Must be PEM encoded.

        :return: None
        """
        arg_1 = _path_string(arg_1)

        arg_2 = _lib.SSL_CTX_Func(
            arg_0._context, arg_1
        )
        if not arg_2:
            _raise_current_error()


def Func(arg_0, arg_1, arg_2=arg_3):
        """
        Load a certificate from a file

        :param certfile: The name of the certificate file (``bytes`` or
            ``unicode``).
        :param filetype: (optional) The encoding of the file, which is either
            :const:`FILETYPE_PEM` or :const:`FILETYPE_ASN1`.  The default is
            :const:`FILETYPE_PEM`.

        :return: None
        """
        arg_1 = _path_string(arg_1)
        if not isinstance(arg_2, integer_types):
            raise TypeError("filetype must be an integer")

        arg_4 = _lib.SSL_CTX_Func(
            arg_0._context, arg_1, arg_2
        )
        if not arg_4:
            _raise_current_error()


def Func(arg_0, arg_1):
        """
        Load a certificate from a X509 object

        :param cert: The X509 object
        :return: None
        """
        if not isinstance(arg_1, X509):
            raise TypeError("cert must be an X509 instance")

        arg_2 = _lib.SSL_CTX_Func(arg_0._context, arg_1._x509)
        if not arg_2:
            _raise_current_error()


def Func(arg_0, arg_1):
        """
        Add certificate to chain

        :param certobj: The X509 certificate object to add to the chain
        :return: None
        """
        if not isinstance(arg_1, X509):
            raise TypeError("certobj must be an X509 instance")

        arg_2 = _lib.X509_dup(arg_1._x509)
        arg_3 = _lib.SSL_CTX_Func(arg_0._context, arg_2)
        if not arg_3:
            # TODO: This is untested.
            _lib.X509_free(arg_2)
            _raise_current_error()


def Func(arg_0, arg_1):
        """
        Load the trusted certificates that will be sent to the client.  Does
        not actually imply any of the certificates are trusted; that must be
        configured separately.

        :param bytes cafile: The path to a certificates file in PEM format.
        :return: None
        """
        arg_2 = _lib.SSL_load_client_CA_file(
            _text_to_bytes_and_warn("cafile", arg_1)
        )
        _openssl_assert(arg_2 != _ffi.NULL)
        _lib.SSL_CTX_set_client_CA_list(arg_0._context, arg_2)


def Func(arg_0, arg_1):
        """
        Load parameters for Ephemeral Diffie-Hellman

        :param dhfile: The file to load EDH parameters from (``bytes`` or
            ``unicode``).

        :return: None
        """
        arg_1 = _path_string(arg_1)

        arg_2 = _lib.BIO_new_file(arg_1, b"r")
        if arg_2 == _ffi.NULL:
            _raise_current_error()
        arg_2 = _ffi.gc(arg_2, _lib.BIO_free)

        arg_3 = _lib.PEM_read_bio_DHparams(arg_2, _ffi.NULL, _ffi.NULL, _ffi.NULL)
        arg_3 = _ffi.gc(arg_3, _lib.DH_free)
        _lib.SSL_CTX_set_tmp_dh(arg_0._context, arg_3)


def Func(arg_0, arg_1):
        """
        Set the list of ciphers to be used in this context.

        See the OpenSSL manual for more information (e.g.
        :manpage:`ciphers(1)`).

        :param bytes cipher_list: An OpenSSL cipher string.
        :return: None
        """
        arg_1 = _text_to_bytes_and_warn("cipher_list", arg_1)

        if not isinstance(arg_1, bytes):
            raise TypeError("cipher_list must be a byte string.")

        _openssl_assert(
            _lib.SSL_CTX_Func(arg_0._context, arg_1) == 1
        )
        # In OpenSSL 1.1.1 setting the cipher list will always return TLS 1.3
        # ciphers even if you pass an invalid cipher. Applications (like
        # Twisted) have tests that depend on an error being raised if an
        # invalid cipher string is passed, but without the following check
        # for the TLS 1.3 specific cipher suites it would never error.
        arg_2 = Connection(arg_0, None)
        if (
            arg_2.get_cipher_list() == [
                'TLS_AES_256_GCM_SHA384',
                'TLS_CHACHA20_POLY1305_SHA256',
                'TLS_AES_128_GCM_SHA256'
            ]
        ):
            raise Error(
                [
                    (
                        'SSL routines',
                        'SSL_CTX_Func',
                        'no cipher match',
                    ),
                ],
            )


def Func(arg_0, arg_1):
        """
        Set the list of preferred client certificate signers for this server
        context.

        This list of certificate authorities will be sent to the client when
        the server requests a client certificate.

        :param certificate_authorities: a sequence of X509Names.
        :return: None

        .. versionadded:: 0.10
        """
        arg_2 = _lib.sk_X509_NAME_new_null()
        _openssl_assert(arg_2 != _ffi.NULL)

        try:
            for arg_3 in arg_1:
                if not isinstance(arg_3, X509Name):
                    raise TypeError(
                        "client CAs must be X509Name objects, not %s "
                        "objects" % (
                            type(arg_3).__name__,
                        )
                    )
                arg_4 = _lib.X509_NAME_dup(arg_3._name)
                _openssl_assert(arg_4 != _ffi.NULL)
                arg_5 = _lib.sk_X509_NAME_push(arg_2, arg_4)
                if not arg_5:
                    _lib.X509_NAME_free(arg_4)
                    _raise_current_error()
        except Exception:
            _lib.sk_X509_NAME_free(arg_2)
            raise

        _lib.SSL_CTX_set_client_CA_list(arg_0._context, arg_2)


def Func(arg_0, arg_1):
        """
        Add the CA certificate to the list of preferred signers for this
        context.

        The list of certificate authorities will be sent to the client when the
        server requests a client certificate.

        :param certificate_authority: certificate authority's X509 certificate.
        :return: None

        .. versionadded:: 0.10
        """
        if not isinstance(arg_1, X509):
            raise TypeError("certificate_authority must be an X509 instance")

        arg_2 = _lib.SSL_CTX_add_client_CA(
            arg_0._context, arg_1._x509)
        _openssl_assert(arg_2 == 1)


def Func(arg_0, arg_1):
        """
        Specify the protocols that the client is prepared to speak after the
        TLS connection has been negotiated using Application Layer Protocol
        Negotiation.

        :param protos: A list of the protocols to be offered to the server.
            This list should be a Python list of bytestrings representing the
            protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
        """
        # Take the list of protocols and join them together, prefixing them
        # with their lengths.
        arg_2 = b''.join(
            chain.from_iterable((int2byte(len(p)), p) for p in arg_1)
        )

        # Build a C string from the list. We don't need to save this off
        # because OpenSSL immediately copies the data out.
        arg_3 = _ffi.new("unsigned char[]", arg_2)
        _lib.SSL_CTX_Func(arg_0._context, arg_3, len(arg_2))


def Func(arg_0, arg_1, arg_2=None):
        """
        Set a callback to provide OCSP data to be stapled to the TLS handshake
        on the server side.

        :param callback: The callback function. It will be invoked with two
            arguments: the Connection, and the optional arbitrary data you have
            provided. The callback must return a bytestring that contains the
            OCSP data to staple to the handshake. If no OCSP data is available
            for this connection, return the empty bytestring.
        :param data: Some opaque data that will be passed into the callback
            function when called. This can be used to avoid needing to do
            complex data lookups or to keep track of what context is being
            used. This parameter is optional.
        """
        arg_3 = _OCSPServerCallbackHelper(arg_1)
        arg_0._set_ocsp_callback(arg_3, arg_2)


def Func(arg_0, arg_1, arg_2=None):
        """
        Set a callback to validate OCSP data stapled to the TLS handshake on
        the client side.

        :param callback: The callback function. It will be invoked with three
            arguments: the Connection, a bytestring containing the stapled OCSP
            assertion, and the optional arbitrary data you have provided. The
            callback must return a boolean that indicates the result of
            validating the OCSP data: ``True`` if the OCSP data is valid and
            the certificate can be trusted, or ``False`` if either the OCSP
            data is invalid or the certificate has been revoked.
        :param data: Some opaque data that will be passed into the callback
            function when called. This can be used to avoid needing to do
            complex data lookups or to keep track of what context is being
            used. This parameter is optional.
        """
        arg_3 = _OCSPClientCallbackHelper(arg_1)
        arg_0._set_ocsp_callback(arg_3, arg_2)


def Func(arg_0, arg_1):
        """
        Switch this connection to a new session context.

        :param context: A :class:`Context` instance giving the new session
            context to use.
        """
        if not isinstance(arg_1, Context):
            raise TypeError("context must be a Context instance")

        _lib.SSL_set_SSL_CTX(arg_0._ssl, arg_1._context)
        arg_0._context = arg_1


def Func(arg_0, arg_1, arg_2=None, arg_3=None):
        """
        Receive data on the connection and copy it directly into the provided
        buffer, rather than creating a new string.

        :param buffer: The buffer to copy into.
        :param nbytes: (optional) The maximum number of bytes to read into the
            buffer. If not present, defaults to the size of the buffer. If
            larger than the size of the buffer, is reduced to the size of the
            buffer.
        :param flags: (optional) The only supported flag is ``MSG_PEEK``,
            all other flags are ignored.
        :return: The number of bytes read into the buffer.
        """
        if arg_2 is None:
            arg_2 = len(arg_1)
        else:
            arg_2 = min(arg_2, len(arg_1))

        # We need to create a temporary buffer. This is annoying, it would be
        # better if we could pass memoryviews straight into the SSL_read call,
        # but right now we can't. Revisit this if CFFI gets that ability.
        arg_4 = _no_zero_allocator("char[]", arg_2)
        if arg_3 is not None and arg_3 & socket.MSG_PEEK:
            arg_5 = _lib.SSL_peek(arg_0._ssl, arg_4, arg_2)
        else:
            arg_5 = _lib.SSL_read(arg_0._ssl, arg_4, arg_2)
        arg_0._raise_ssl_error(arg_0._ssl, arg_5)

        # This strange line is all to avoid a memory copy. The buffer protocol
        # should allow us to assign a CFFI buffer to the LHS of this line, but
        # on CPython 3.3+ that segfaults. As a workaround, we can temporarily
        # wrap it in a memoryview.
        arg_1[:arg_5] = memoryview(_ffi.buffer(arg_4, arg_5))

        return arg_5


def Func(arg_0, arg_1):
        """
        If the Connection was created with a memory BIO, this method can be
        used to read bytes from the write end of that memory BIO.  Many
        Connection methods will add bytes which must be read in this manner or
        the buffer will eventually fill up and the Connection will be able to
        take no further actions.

        :param bufsiz: The maximum number of bytes to read
        :return: The string read.
        """
        if arg_0._from_ssl is None:
            raise TypeError("Connection sock was not None")

        if not isinstance(arg_1, integer_types):
            raise TypeError("bufsiz must be an integer")

        arg_2 = _no_zero_allocator("char[]", arg_1)
        arg_3 = _lib.BIO_read(arg_0._from_ssl, arg_2, arg_1)
        if arg_3 <= 0:
            arg_0._handle_bio_errors(arg_0._from_ssl, arg_3)

        return _ffi.buffer(arg_2, arg_3)[:]


def Func(arg_0):
        """
        Renegotiate the session.

        :return: True if the renegotiation can be started, False otherwise
        :rtype: bool
        """
        if not arg_0.Func_pending():
            _openssl_assert(_lib.SSL_Func(arg_0._ssl) == 1)
            return True
        return False


def Func(arg_0):
        """
        Send the Func message to the Connection.

        :return: True if the Func completed successfully (i.e. both sides
                 have sent closure alerts), False otherwise (in which case you
                 call :meth:`recv` or :meth:`send` when the connection becomes
                 readable/writeable).
        """
        arg_1 = _lib.SSL_Func(arg_0._ssl)
        if arg_1 < 0:
            arg_0._raise_ssl_error(arg_0._ssl, arg_1)
        elif arg_1 > 0:
            return True
        else:
            return False


def Func(arg_0):
        """
        Retrieve the list of ciphers used by the Connection object.

        :return: A list of native cipher strings.
        """
        arg_1 = []
        for arg_2 in count():
            arg_3 = _lib.SSL_Func(arg_0._ssl, arg_2)
            if arg_3 == _ffi.NULL:
                break
            arg_1.append(_native(_ffi.string(arg_3)))
        return arg_1


def Func(arg_0):
        """
        Retrieve the random value used with the server hello message.

        :return: A string representing the state
        """
        arg_1 = _lib.SSL_get_session(arg_0._ssl)
        if arg_1 == _ffi.NULL:
            return None
        arg_2 = _lib.SSL_get_Func(arg_0._ssl, _ffi.NULL, 0)
        assert arg_2 > 0
        arg_3 = _no_zero_allocator("unsigned char[]", arg_2)
        _lib.SSL_get_Func(arg_0._ssl, arg_3, arg_2)
        return _ffi.buffer(arg_3, arg_2)[:]


def Func(arg_0):
        """
        Retrieve the value of the master key for this session.

        :return: A string representing the state
        """
        arg_1 = _lib.SSL_get_session(arg_0._ssl)
        if arg_1 == _ffi.NULL:
            return None

        arg_2 = _lib.SSL_SESSION_get_Func(arg_1, _ffi.NULL, 0)
        assert arg_2 > 0
        arg_3 = _no_zero_allocator("unsigned char[]", arg_2)
        _lib.SSL_SESSION_get_Func(arg_1, arg_3, arg_2)
        return _ffi.buffer(arg_3, arg_2)[:]


def Func(arg_0):
        """
        Obtain the name of the currently used cipher.

        :returns: The name of the currently used cipher or :obj:`None`
            if no connection has been established.
        :rtype: :class:`unicode` or :class:`NoneType`

        .. versionadded:: 0.15
        """
        arg_1 = _lib.SSL_get_current_cipher(arg_0._ssl)
        if arg_1 == _ffi.NULL:
            return None
        else:
            arg_2 = _ffi.string(_lib.SSL_CIPHER_get_name(arg_1))
            return arg_2.decode("utf-8")


def Func(arg_0):
        """
        Obtain the number of secret bits of the currently used cipher.

        :returns: The number of secret bits of the currently used cipher
            or :obj:`None` if no connection has been established.
        :rtype: :class:`int` or :class:`NoneType`

        .. versionadded:: 0.15
        """
        arg_1 = _lib.SSL_get_current_cipher(arg_0._ssl)
        if arg_1 == _ffi.NULL:
            return None
        else:
            return _lib.SSL_CIPHER_get_bits(arg_1, _ffi.NULL)


def Func(arg_0):
        """
        Obtain the protocol version of the currently used cipher.

        :returns: The protocol name of the currently used cipher
            or :obj:`None` if no connection has been established.
        :rtype: :class:`unicode` or :class:`NoneType`

        .. versionadded:: 0.15
        """
        arg_1 = _lib.SSL_get_current_cipher(arg_0._ssl)
        if arg_1 == _ffi.NULL:
            return None
        else:
            arg_2 = _ffi.string(_lib.SSL_CIPHER_get_version(arg_1))
            return arg_2.decode("utf-8")


def Func(arg_0):
        """
        Retrieve the protocol version of the current connection.

        :returns: The TLS version of the current connection, for example
            the value for TLS 1.2 would be ``TLSv1.2``or ``Unknown``
            for connections that were not successfully established.
        :rtype: :class:`unicode`
        """
        arg_1 = _ffi.string(_lib.SSL_get_version(arg_0._ssl))
        return arg_1.decode("utf-8")


def Func(arg_0):
        """
        Get the protocol that was negotiated by NPN.

        :returns: A bytestring of the protocol name.  If no protocol has been
            negotiated yet, returns an empty string.

        .. versionadded:: 0.15
        """
        _warn_npn()
        arg_1 = _ffi.new("unsigned char **")
        arg_2 = _ffi.new("unsigned int *")

        _lib.SSL_get0_next_proto_negotiated(arg_0._ssl, arg_1, arg_2)

        return _ffi.buffer(arg_1[0], arg_2[0])[:]


def Func(arg_0):
        """
        Get the protocol that was negotiated by ALPN.

        :returns: A bytestring of the protocol name.  If no protocol has been
            negotiated yet, returns an empty string.
        """
        arg_1 = _ffi.new("unsigned char **")
        arg_2 = _ffi.new("unsigned int *")

        _lib.SSL_get0_alpn_selected(arg_0._ssl, arg_1, arg_2)

        if not arg_2:
            return b''

        return _ffi.buffer(arg_1[0], arg_2[0])[:]


def Func(arg_0=None):
    """
    Allocate a new OpenSSL memory BIO.

    Arrange for the garbage collector to clean it up automatically.

    :param buffer: None or some bytes to use to put into the BIO so that they
        can be read out.
    """
    if arg_0 is None:
        arg_1 = _lib.BIO_new(_lib.BIO_s_mem())
        arg_2 = _lib.BIO_free
    else:
        arg_3 = _ffi.new("char[]", arg_0)
        arg_1 = _lib.BIOFunc(arg_3, len(arg_0))

        # Keep the memory alive as long as the bio is alive!
        def arg_2(arg_1, arg_4=arg_3):
            return _lib.BIO_free(arg_1)

    _openssl_assert(arg_1 != _ffi.NULL)

    arg_1 = _ffi.gc(arg_1, arg_2)
    return arg_1


def Func(arg_0):
    """
    Copy the contents of an OpenSSL BIO object into a Python byte string.
    """
    arg_1 = _ffi.new('char**')
    arg_2 = _lib.BIO_get_mem_data(arg_0, arg_1)
    return _ffi.buffer(arg_1[0], arg_2)[:]


def Func(arg_0):
    """
    Retrieve the time value of an ASN1 time object.

    @param timestamp: An ASN1_GENERALIZEDTIME* (or an object safely castable to
        that type) from which the time value will be retrieved.

    @return: The time value from C{timestamp} as a L{bytes} string in a certain
        format.  Or C{None} if the object contains no time value.
    """
    arg_1 = _ffi.cast('ASN1_STRING*', arg_0)
    if _lib.ASN1_STRING_length(arg_1) == 0:
        return None
    elif (
        _lib.ASN1_STRING_type(arg_1) == _lib.V_ASN1_GENERALIZEDTIME
    ):
        return _ffi.string(_lib.ASN1_STRING_data(arg_1))
    else:
        arg_2 = _ffi.new("ASN1_GENERALIZEDTIME**")
        _lib.ASN1_TIME_to_generalizedtime(arg_0, arg_2)
        if arg_2[0] == _ffi.NULL:
            # This may happen:
            #   - if timestamp was not an ASN1_TIME
            #   - if allocating memory for the ASN1_GENERALIZEDTIME failed
            #   - if a copy of the time data from timestamp cannot be made for
            #     the newly allocated ASN1_GENERALIZEDTIME
            #
            # These are difficult to test.  cffi enforces the ASN1_TIME type.
            # Memory allocation failures are a pain to trigger
            # deterministically.
            _untested_error("ASN1_TIME_to_generalizedtime")
        else:
            arg_1 = _ffi.cast(
                "ASN1_STRING*", arg_2[0])
            arg_3 = _lib.ASN1_STRING_data(arg_1)
            arg_4 = _ffi.string(arg_3)
            _lib.ASN1_GENERALIZEDTIME_free(arg_2[0])
            return arg_4


def Func(arg_0):
    """
    Return a single curve object selected by name.

    See :py:func:`Funcs` for information about curve objects.

    :param name: The OpenSSL short name identifying the curve object to
        retrieve.
    :type name: :py:class:`unicode`

    If the named curve is not supported then :py:class:`ValueError` is raised.
    """
    for arg_1 in Funcs():
        if arg_1.name == arg_0:
            return arg_1
    raise ValueError("unknown curve name", arg_0)


def Func(arg_0, arg_1):
    """
    Dump a public key to a buffer.

    :param type: The file type (one of :data:`FILETYPE_PEM` or
        :data:`FILETYPE_ASN1`).
    :param PKey pkey: The public key to dump
    :return: The buffer with the dumped key in it.
    :rtype: bytes
    """
    arg_2 = _new_mem_buf()
    if arg_0 == FILETYPE_PEM:
        arg_3 = _lib.PEM_write_bio_PUBKEY
    elif arg_0 == FILETYPE_ASN1:
        arg_3 = _lib.i2d_PUBKEY_bio
    else:
        raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")

    arg_4 = arg_3(arg_2, arg_1._pkey)
    if arg_4 != 1:  # pragma: no cover
        _raise_current_error()

    return _bio_to_string(arg_2)


def Func(arg_0, arg_1, arg_2, arg_3):
    """
    Verify the signature for a data string.

    :param cert: signing certificate (X509 object) corresponding to the
        private key which generated the signature.
    :param signature: signature returned by sign function
    :param data: data to be verified
    :param digest: message digest to use
    :return: ``None`` if the signature is correct, raise exception otherwise.

    .. versionadded:: 0.11
    """
    arg_2 = _text_to_bytes_and_warn("data", arg_2)

    arg_4 = _lib.EVP_get_digestbyname(_byte_string(arg_3))
    if arg_4 == _ffi.NULL:
        raise ValueError("No such digest method")

    arg_5 = _lib.X509_get_pubkey(arg_0._x509)
    _openssl_assert(arg_5 != _ffi.NULL)
    arg_5 = _ffi.gc(arg_5, _lib.EVP_PKEY_free)

    arg_6 = _lib.Cryptography_EVP_MD_CTX_new()
    arg_6 = _ffi.gc(arg_6, _lib.Cryptography_EVP_MD_CTX_free)

    _lib.EVP_VerifyInit(arg_6, arg_4)
    _lib.EVP_VerifyUpdate(arg_6, arg_2, len(arg_2))
    arg_7 = _lib.EVP_VerifyFinal(
        arg_6, arg_1, len(arg_1), arg_5
    )

    if arg_7 != 1:
        _raise_current_error()


def Func(arg_0):
        """
        Export as a ``cryptography`` key.

        :rtype: One of ``cryptography``'s `key interfaces`_.

        .. _key interfaces: https://cryptography.io/en/latest/hazmat/\
            primitives/asymmetric/rsa/#key-interfaces

        .. versionadded:: 16.1.0
        """
        arg_1 = _get_backend()
        if arg_0._only_public:
            return arg_1._evp_pkey_to_public_key(arg_0._pkey)
        else:
            return arg_1._evp_pkey_to_private_key(arg_0._pkey)


def Func(arg_0, arg_1, arg_2):
        """
        Generate a key pair of the given type, with the given number of bits.

        This generates a key "into" the this object.

        :param type: The key type.
        :type type: :py:data:`TYPE_RSA` or :py:data:`TYPE_DSA`
        :param bits: The number of bits.
        :type bits: :py:data:`int` ``>= 0``
        :raises TypeError: If :py:data:`type` or :py:data:`bits` isn't
            of the appropriate type.
        :raises ValueError: If the number of bits isn't an integer of
            the appropriate size.
        :return: ``None``
        """
        if not isinstance(arg_1, int):
            raise TypeError("type must be an integer")

        if not isinstance(arg_2, int):
            raise TypeError("bits must be an integer")

        if arg_1 == TYPE_RSA:
            if arg_2 <= 0:
                raise ValueError("Invalid number of bits")

            # TODO Check error return
            arg_3 = _lib.BN_new()
            arg_3 = _ffi.gc(arg_3, _lib.BN_free)
            _lib.BN_set_word(arg_3, _lib.RSA_F4)

            arg_4 = _lib.RSA_new()

            arg_5 = _lib.RSA_Func_ex(arg_4, arg_2, arg_3, _ffi.NULL)
            _openssl_assert(arg_5 == 1)

            arg_5 = _lib.EVP_PKEY_assign_RSA(arg_0._pkey, arg_4)
            _openssl_assert(arg_5 == 1)

        elif arg_1 == TYPE_DSA:
            arg_6 = _lib.DSA_new()
            _openssl_assert(arg_6 != _ffi.NULL)

            arg_6 = _ffi.gc(arg_6, _lib.DSA_free)
            arg_7 = _lib.DSA_generate_parameters_ex(
                arg_6, arg_2, _ffi.NULL, 0, _ffi.NULL, _ffi.NULL, _ffi.NULL
            )
            _openssl_assert(arg_7 == 1)

            _openssl_assert(_lib.DSA_Func(arg_6) == 1)
            _openssl_assert(_lib.EVP_PKEY_set1_DSA(arg_0._pkey, arg_6) == 1)
        else:
            raise Error("No such key type")

        arg_0._initialized = True


def Func(arg_0):
        """
        Check the consistency of an RSA private key.

        This is the Python equivalent of OpenSSL's ``RSA_Func_key``.

        :return: ``True`` if key is consistent.

        :raise OpenSSL.crypto.Error: if the key is inconsistent.

        :raise TypeError: if the key is of a type which cannot be Funced.
            Only RSA keys can currently be Funced.
        """
        if arg_0._only_public:
            raise TypeError("public key only")

        if _lib.EVP_PKEY_type(arg_0.type()) != _lib.EVP_PKEY_RSA:
            raise TypeError("key type unsupported")

        arg_1 = _lib.EVP_PKEY_get1_RSA(arg_0._pkey)
        arg_1 = _ffi.gc(arg_1, _lib.RSA_free)
        arg_2 = _lib.RSA_Func_key(arg_1)
        if arg_2:
            return True
        _raise_current_error()


def Func(arg_0, arg_1):
        """
        Get the curves supported by OpenSSL.

        :param lib: The OpenSSL library binding object.

        :return: A :py:type:`set` of ``cls`` instances giving the names of the
            elliptic curves the underlying library supports.
        """
        arg_2 = arg_1.EC_get_builtin_curves(_ffi.NULL, 0)
        arg_3 = _ffi.new('EC_builtin_curve[]', arg_2)
        # The return value on this call should be num_curves again.  We
        # could check it to make sure but if it *isn't* then.. what could
        # we do? Abort the whole process, I suppose...?  -exarkun
        arg_1.EC_get_builtin_curves(arg_3, arg_2)
        return set(
            arg_0.from_nid(arg_1, arg_4.nid)
            for arg_4 in arg_3)


def Func(arg_0):
        """
        Create a new OpenSSL EC_KEY structure initialized to use this curve.

        The structure is automatically garbage collected when the Python object
        is garbage collected.
        """
        arg_1 = arg_0._lib.EC_KEY_new_by_curve_name(arg_0._nid)
        return _ffi.gc(arg_1, _lib.EC_KEY_free)


def Func(arg_0):
        """
        Return the DER encoding of this name.

        :return: The DER encoded form of this name.
        :rtype: :py:class:`bytes`
        """
        arg_1 = _ffi.new('unsigned char**')
        arg_2 = _lib.i2d_X509_NAME(arg_0._name, arg_1)
        _openssl_assert(arg_2 >= 0)

        arg_3 = _ffi.buffer(arg_1[0], arg_2)[:]
        _lib.OPENSSL_free(arg_1[0])
        return arg_3


def Func(arg_0):
        """
        Returns the short type name of this X.509 extension.

        The result is a byte string such as :py:const:`b"basicConstraints"`.

        :return: The short type name.
        :rtype: :py:data:`bytes`

        .. versionadded:: 0.12
        """
        arg_1 = _lib.X509_EXTENSION_get_object(arg_0._extension)
        arg_2 = _lib.OBJ_obj2nid(arg_1)
        return _ffi.string(_lib.OBJ_nid2sn(arg_2))


def Func(arg_0):
        """
        Returns the data of the X509 extension, encoded as ASN.1.

        :return: The ASN.1 encoded data of this X509 extension.
        :rtype: :py:data:`bytes`

        .. versionadded:: 0.12
        """
        arg_1 = _lib.X509_EXTENSION_Func(arg_0._extension)
        arg_2 = _ffi.cast('ASN1_STRING*', arg_1)
        arg_3 = _lib.ASN1_STRING_data(arg_2)
        arg_4 = _lib.ASN1_STRING_length(arg_2)
        return _ffi.buffer(arg_3, arg_4)[:]


def Func(arg_0, arg_1):
        """
        Set the public key of the certificate signing request.

        :param pkey: The public key to use.
        :type pkey: :py:class:`PKey`

        :return: ``None``
        """
        arg_2 = _lib.X509_REQ_Func(arg_0._req, arg_1._pkey)
        _openssl_assert(arg_2 == 1)


def Func(arg_0):
        """
        Get the public key of the certificate signing request.

        :return: The public key.
        :rtype: :py:class:`PKey`
        """
        arg_1 = PKey.__new__(PKey)
        arg_1._pkey = _lib.X509_REQ_Func(arg_0._req)
        _openssl_assert(arg_1._pkey != _ffi.NULL)
        arg_1._pkey = _ffi.gc(arg_1._pkey, _lib.EVP_PKEY_free)
        arg_1._only_public = True
        return arg_1


def Func(arg_0):
        """
        Return the subject of this certificate signing request.

        This creates a new :class:`X509Name` that wraps the underlying subject
        name field on the certificate signing request. Modifying it will modify
        the underlying signing request, and will have the effect of modifying
        any other :class:`X509Name` that refers to this subject.

        :return: The subject of this certificate signing request.
        :rtype: :class:`X509Name`
        """
        arg_1 = X509Name.__new__(X509Name)
        arg_1._name = _lib.X509_REQ_Func_name(arg_0._req)
        _openssl_assert(arg_1._name != _ffi.NULL)

        # The name is owned by the X509Req structure.  As long as the X509Name
        # Python object is alive, keep the X509Req Python object alive.
        arg_1._owner = arg_0

        return arg_1


def Func(arg_0, arg_1):
        """
        Add extensions to the certificate signing request.

        :param extensions: The X.509 extensions to add.
        :type extensions: iterable of :py:class:`X509Extension`
        :return: ``None``
        """
        arg_2 = _lib.sk_X509_EXTENSION_new_null()
        _openssl_assert(arg_2 != _ffi.NULL)

        arg_2 = _ffi.gc(arg_2, _lib.sk_X509_EXTENSION_free)

        for arg_3 in arg_1:
            if not isinstance(arg_3, X509Extension):
                raise ValueError("One of the elements is not an X509Extension")

            # TODO push can fail (here and elsewhere)
            _lib.sk_X509_EXTENSION_push(arg_2, arg_3._extension)

        arg_4 = _lib.X509_REQ_Func(arg_0._req, arg_2)
        _openssl_assert(arg_4 == 1)


def Func(arg_0):
        """
        Get X.509 extensions in the certificate signing request.

        :return: The X.509 extensions in this request.
        :rtype: :py:class:`list` of :py:class:`X509Extension` objects.

        .. versionadded:: 0.15
        """
        arg_1 = []
        arg_2 = _lib.X509_REQ_Func(arg_0._req)
        for arg_3 in range(_lib.sk_X509_EXTENSION_num(arg_2)):
            arg_4 = X509Extension.__new__(X509Extension)
            arg_4._extension = _lib.sk_X509_EXTENSION_value(arg_2, arg_3)
            arg_1.append(arg_4)
        return arg_1


def Func(arg_0):
        """
        Export as a ``cryptography`` certificate.

        :rtype: ``cryptography.x509.Certificate``

        .. versionadded:: 17.1.0
        """
        from cryptography.hazmat.backends.openssl.x509 import _Certificate
        arg_1 = _get_backend()
        return _Certificate(arg_1, arg_0._x509)


def Func(arg_0, arg_1):
        """
        Set the version number of the certificate. Note that the
        version value is zero-based, eg. a value of 0 is V1.

        :param version: The version number of the certificate.
        :type version: :py:class:`int`

        :return: ``None``
        """
        if not isinstance(arg_1, int):
            raise TypeError("version must be an integer")

        _lib.X509_Func(arg_0._x509, arg_1)


def Func(arg_0):
        """
        Get the public key of the certificate.

        :return: The public key.
        :rtype: :py:class:`PKey`
        """
        arg_1 = PKey.__new__(PKey)
        arg_1._pkey = _lib.X509_Func(arg_0._x509)
        if arg_1._pkey == _ffi.NULL:
            _raise_current_error()
        arg_1._pkey = _ffi.gc(arg_1._pkey, _lib.EVP_PKEY_free)
        arg_1._only_public = True
        return arg_1


def Func(arg_0, arg_1):
        """
        Set the public key of the certificate.

        :param pkey: The public key.
        :type pkey: :py:class:`PKey`

        :return: :py:data:`None`
        """
        if not isinstance(arg_1, PKey):
            raise TypeError("pkey must be a PKey instance")

        arg_2 = _lib.X509_Func(arg_0._x509, arg_1._pkey)
        _openssl_assert(arg_2 == 1)


def Func(arg_0, arg_1):
        """
        Return the digest of the X509 object.

        :param digest_name: The name of the digest algorithm to use.
        :type digest_name: :py:class:`bytes`

        :return: The digest of the object, formatted as
            :py:const:`b":"`-delimited hex pairs.
        :rtype: :py:class:`bytes`
        """
        Func = _lib.EVP_get_digestbyname(_byte_string(arg_1))
        if Func == _ffi.NULL:
            raise ValueError("No such digest method")

        arg_3 = _ffi.new("unsigned char[]", _lib.EVP_MAX_MD_SIZE)
        arg_4 = _ffi.new("unsigned int[]", 1)
        arg_4[0] = len(arg_3)

        arg_5 = _lib.X509_digest(
            arg_0._x509, Func, arg_3, arg_4)
        _openssl_assert(arg_5 == 1)

        return b":".join([
            b16encode(arg_6).upper() for arg_6
            in _ffi.buffer(arg_3, arg_4[0])])


def Func(arg_0, arg_1):
        """
        Set the serial number of the certificate.

        :param serial: The new serial number.
        :type serial: :py:class:`int`

        :return: :py:data`None`
        """
        if not isinstance(arg_1, _integer_types):
            raise TypeError("serial must be an integer")

        arg_2 = hex(arg_1)[2:]
        if not isinstance(arg_2, bytes):
            arg_2 = arg_2.encode('ascii')

        arg_3 = _ffi.new("BIGNUM**")

        # BN_hex2bn stores the result in &bignum.  Unless it doesn't feel like
        # it.  If bignum is still NULL after this call, then the return value
        # is actually the result.  I hope.  -exarkun
        arg_4 = _lib.BN_hex2bn(arg_3, arg_2)

        if arg_3[0] == _ffi.NULL:
            arg_5 = _lib.ASN1_INTEGER_set(
                _lib.X509_get_serialNumber(arg_0._x509), arg_4)
            if arg_5:
                # TODO Not tested
                _raise_current_error()
        else:
            arg_6 = _lib.BN_to_ASN1_INTEGER(arg_3[0], _ffi.NULL)
            _lib.BN_free(arg_3[0])
            if arg_6 == _ffi.NULL:
                # TODO Not tested
                _raise_current_error()
            arg_6 = _ffi.gc(arg_6, _lib.ASN1_INTEGER_free)
            arg_5 = _lib.X509_set_serialNumber(arg_0._x509, arg_6)
            _openssl_assert(arg_5 == 1)


def Func(arg_0):
        """
        Return the serial number of this certificate.

        :return: The serial number.
        :rtype: int
        """
        arg_1 = _lib.X509_get_serialNumber(arg_0._x509)
        arg_2 = _lib.ASN1_INTEGER_to_BN(arg_1, _ffi.NULL)
        try:
            arg_3 = _lib.BN_bn2hex(arg_2)
            try:
                arg_4 = _ffi.string(arg_3)
                arg_5 = int(arg_4, 16)
                return arg_5
            finally:
                _lib.OPENSSL_free(arg_3)
        finally:
            _lib.BN_free(arg_2)


def Func(arg_0, arg_1):
        """
        Adjust the time stamp on which the certificate stops being valid.

        :param int amount: The number of seconds by which to adjust the
            timestamp.
        :return: ``None``
        """
        if not isinstance(arg_1, int):
            raise TypeError("amount must be an integer")

        arg_2 = _lib.X509_get_notAfter(arg_0._x509)
        _lib.X509_gmtime_adj(arg_2, arg_1)


def Func(arg_0):
        """
        Return the issuer of this certificate.

        This creates a new :class:`X509Name` that wraps the underlying issuer
        name field on the certificate. Modifying it will modify the underlying
        certificate, and will have the effect of modifying any other
        :class:`X509Name` that refers to this issuer.

        :return: The issuer of this certificate.
        :rtype: :class:`X509Name`
        """
        arg_1 = arg_0._get_name(_lib.X509_Func_name)
        arg_0._issuer_invalidator.add(arg_1)
        return arg_1


def Func(arg_0):
        """
        Return the subject of this certificate.

        This creates a new :class:`X509Name` that wraps the underlying subject
        name field on the certificate. Modifying it will modify the underlying
        certificate, and will have the effect of modifying any other
        :class:`X509Name` that refers to this subject.

        :return: The subject of this certificate.
        :rtype: :class:`X509Name`
        """
        arg_1 = arg_0._get_name(_lib.X509_Func_name)
        arg_0._subject_invalidator.add(arg_1)
        return arg_1


def Func(arg_0, arg_1):
        """
        Get a specific extension of the certificate by index.

        Extensions on a certificate are kept in order. The index
        parameter selects which extension will be returned.

        :param int index: The index of the extension to retrieve.
        :return: The extension at the specified index.
        :rtype: :py:class:`X509Extension`
        :raises IndexError: If the extension index was out of bounds.

        .. versionadded:: 0.12
        """
        arg_2 = X509Extension.__new__(X509Extension)
        arg_2._extension = _lib.X509_get_ext(arg_0._x509, arg_1)
        if arg_2._extension == _ffi.NULL:
            raise IndexError("extension index out of bounds")

        arg_4 = _lib.X509_EXTENSION_dup(arg_2._extension)
        arg_2._extension = _ffi.gc(arg_4, _lib.X509_EXTENSION_free)
        return arg_2


def Func(arg_0, arg_1):
        """
        Add a certificate revocation list to this store.

        The certificate revocation lists added to a store will only be used if
        the associated flags are configured to check certificate revocation
        lists.

        .. versionadded:: 16.1.0

        :param CRL crl: The certificate revocation list to add to this store.
        :return: ``None`` if the certificate revocation list was added
            successfully.
        """
        _openssl_assert(_lib.X509_STORE_Func(arg_0._store, arg_1._crl) != 0)


def Func(arg_0):
        """
        Set up the store context for a subsequent verification operation.

        Calling this method more than once without first calling
        :meth:`_cleanup` will leak memory.
        """
        arg_1 = _lib.X509_STORE_CTXFunc(
            arg_0._store_ctx, arg_0._store._store, arg_0._cert._x509, _ffi.NULL
        )
        if arg_1 <= 0:
            _raise_current_error()


def Func(arg_0, arg_1):
        """
        Set the serial number.

        The serial number is formatted as a hexadecimal number encoded in
        ASCII.

        :param bytes hex_str: The new serial number.

        :return: ``None``
        """
        arg_2 = _ffi.gc(_lib.BN_new(), _lib.BN_free)
        arg_3 = _ffi.new("BIGNUM**")
        arg_3[0] = arg_2
        arg_4 = _lib.BN_hex2bn(arg_3, arg_1)
        if not arg_4:
            raise ValueError("bad hex string")

        arg_5 = _ffi.gc(
            _lib.BN_to_ASN1_INTEGER(arg_2, _ffi.NULL),
            _lib.ASN1_INTEGER_free)
        _lib.X509_REVOKED_FuncNumber(arg_0._revoked, arg_5)


def Func(arg_0):
        """
        Get the serial number.

        The serial number is formatted as a hexadecimal number encoded in
        ASCII.

        :return: The serial number.
        :rtype: bytes
        """
        arg_1 = _new_mem_buf()

        arg_2 = _lib.X509_REVOKED_get0_serialNumber(arg_0._revoked)
        _openssl_assert(arg_2 != _ffi.NULL)
        arg_3 = _lib.i2a_ASN1_INTEGER(arg_1, arg_2)
        _openssl_assert(arg_3 >= 0)
        return _bio_to_string(arg_1)


def Func(arg_0, arg_1):
        """
        Set the reason of this revocation.

        If :data:`reason` is ``None``, delete the reason instead.

        :param reason: The reason string.
        :type reason: :class:`bytes` or :class:`NoneType`

        :return: ``None``

        .. seealso::

            :meth:`all_reasons`, which gives you a list of all supported
            reasons which you might pass to this method.
        """
        if arg_1 is None:
            arg_0._delete_reason()
        elif not isinstance(arg_1, bytes):
            raise TypeError("reason must be None or a byte string")
        else:
            arg_1 = arg_1.lower().replace(b' ', b'')
            arg_2 = [r.lower() for r in arg_0._crl_reasons].index(arg_1)

            arg_3 = _lib.ASN1_ENUMERATED_new()
            _openssl_assert(arg_3 != _ffi.NULL)
            arg_3 = _ffi.gc(arg_3, _lib.ASN1_ENUMERATED_free)

            arg_4 = _lib.ASN1_ENUMERATED_set(arg_3, arg_2)
            _openssl_assert(arg_4 != _ffi.NULL)

            arg_0._delete_reason()
            arg_5 = _lib.X509_REVOKED_add1_ext_i2d(
                arg_0._revoked, _lib.NID_crl_reason, arg_3, 0, 0)
            _openssl_assert(arg_5 == 1)


def Func(arg_0):
        """
        Export as a ``cryptography`` CRL.

        :rtype: ``cryptography.x509.CertificateRevocationList``

        .. versionadded:: 17.1.0
        """
        from cryptography.hazmat.backends.openssl.x509 import (
            _CertificateRevocationList
        )
        arg_1 = _get_backend()
        return _CertificateRevocationList(arg_1, arg_0._crl)


def Func(arg_0):
        """
        Get the CRL's issuer.

        .. versionadded:: 16.1.0

        :rtype: X509Name
        """
        arg_1 = _lib.X509_NAME_dup(_lib.X509_CRL_Func(arg_0._crl))
        _openssl_assert(arg_1 != _ffi.NULL)
        arg_1 = _ffi.gc(arg_1, _lib.X509_NAME_free)
        arg_2 = X509Name.__new__(X509Name)
        arg_2._name = arg_1
        return arg_2


def Func(arg_0, arg_1, arg_2, arg_3):
        """
        Sign the CRL.

        Signing a CRL enables clients to associate the CRL itself with an
        issuer. Before a CRL is meaningful to other OpenSSL functions, it must
        be Funced by an issuer.

        This method implicitly sets the issuer's name based on the issuer
        certificate and private key used to Func the CRL.

        .. versionadded:: 16.1.0

        :param X509 issuer_cert: The issuer's certificate.
        :param PKey issuer_key: The issuer's private key.
        :param bytes digest: The digest method to Func the CRL with.
        """
        arg_4 = _lib.EVP_get_digestbyname(arg_3)
        _openssl_assert(arg_4 != _ffi.NULL)
        _lib.X509_CRL_set_issuer_name(
            arg_0._crl, _lib.X509_get_subject_name(arg_1._x509))
        _lib.X509_CRL_sort(arg_0._crl)
        arg_5 = _lib.X509_CRL_Func(arg_0._crl, arg_2._pkey, arg_4)
        _openssl_assert(arg_5 != 0)


def Func(arg_0):
        """
        Returns the type name of the PKCS7 structure

        :return: A string with the typename
        """
        arg_1 = _lib.OBJ_obj2nid(arg_0._pkcs7.type)
        arg_2 = _lib.OBJ_nid2sn(arg_1)
        return _ffi.string(arg_2)


def Func(arg_0, arg_1):
        """
        Replace or set the CA certificates within the PKCS12 object.

        :param cacerts: The new CA certificates, or :py:const:`None` to unset
            them.
        :type cacerts: An iterable of :py:class:`X509` or :py:const:`None`

        :return: ``None``
        """
        if arg_1 is None:
            arg_0._cacerts = None
        else:
            arg_1 = list(arg_1)
            for arg_3 in arg_1:
                if not isinstance(arg_3, X509):
                    raise TypeError(
                        "iterable must only contain X509 instances"
                    )
            arg_0._cacerts = arg_1


def Func(arg_0, arg_1, arg_2):
        """
        Sign the certificate request with this key and digest type.

        :param pkey: The private key to Func with.
        :type pkey: :py:class:`PKey`

        :param digest: The message digest to use.
        :type digest: :py:class:`bytes`

        :return: ``None``
        """
        if arg_1._only_public:
            raise ValueError("Key has only public part")

        if not arg_1._initialized:
            raise ValueError("Key is uninitialized")

        arg_3 = _lib.EVP_get_digestbyname(_byte_string(arg_2))
        if arg_3 == _ffi.NULL:
            raise ValueError("No such digest method")

        arg_4 = _lib.NETSCAPE_SPKI_Func(
            arg_0._spki, arg_1._pkey, arg_3
        )
        _openssl_assert(arg_4 > 0)


def Func(arg_0):
        """
        Generate a base64 encoded representation of this SPKI object.

        :return: The base64 encoded string.
        :rtype: :py:class:`bytes`
        """
        arg_1 = _lib.NETSCAPE_SPKI_Func(arg_0._spki)
        arg_2 = _ffi.string(arg_1)
        _lib.OPENSSL_free(arg_1)
        return arg_2


def Func(arg_0):
        """
        Get the public key of this certificate.

        :return: The public key.
        :rtype: :py:class:`PKey`
        """
        arg_1 = PKey.__new__(PKey)
        arg_1._pkey = _lib.NETSCAPE_SPKI_Func(arg_0._spki)
        _openssl_assert(arg_1._pkey != _ffi.NULL)
        arg_1._pkey = _ffi.gc(arg_1._pkey, _lib.EVP_PKEY_free)
        arg_1._only_public = True
        return arg_1


def Func(arg_0, arg_1):
        """
        Set the public key of the certificate

        :param pkey: The public key
        :return: ``None``
        """
        arg_2 = _lib.NETSCAPE_SPKI_Func(arg_0._spki, arg_1._pkey)
        _openssl_assert(arg_2 == 1)


def Func(arg_0, arg_1):
    """
    If ``obj`` is text, emit a warning that it should be bytes instead and try
    to convert it to bytes automatically.

    :param str label: The name of the parameter from which ``obj`` was taken
        (so a developer can easily find the source of the problem and correct
        it).

    :return: If ``obj`` is the text string type, a ``bytes`` object giving the
        UTF-8 encoding of that text is returned.  Otherwise, ``obj`` itself is
        returned.
    """
    if isinstance(arg_1, text_type):
        warnings.warn(
            _TEXT_WARNING.format(arg_0),
            category=DeprecationWarning,
            stacklevel=3
        )
        return arg_1.encode('utf-8')
    return arg_1


def Func(arg_0) :
        'Returns a generator of "Path"s'
        try :
            for arg_1 in list_files_in_dir(arg_0.info_dir):
                if not os.path.basename(arg_1).endswith('.trashinfo') :
                    arg_0.on_non_trashinfo_found()
                else :
                    yield arg_1
        except OSError: # when directory does not exist
            pass


def Func(arg_0):
    """Internal helper to provide color names."""
    def _helper(arg_1):
        arg_2 = style_from_dict({
            Token.Color: arg_0,
        })
        arg_3 = [
            (Token.Color, arg_1)
        ]
        print_tokens(arg_3, arg_2=arg_2)

    def _helper_no_terminal(arg_1):
        # workaround if we have no terminal
        print(arg_1)
    if sys.stdout.isatty():
        return _helper
    else:
        return _helper_no_terminal


def Func(arg_0, arg_1, arg_2):
        """
        Serializes str, Attrib, or PathAttrib objects.

        Example::

            <attribute>foobar</attribute>
        """
        if isinstance(arg_2, (str, int)) or type(arg_2).__name__ == 'str':
            arg_1.text = str(arg_2)
        elif arg_2 is None:
            arg_1.text = None
        else:
            arg_1.append(arg_2.serialize(arg_0))


def Func(arg_0, arg_1, arg_2):
        """
        Serializes a list, where the values are objects of type
        str, Attrib, or PathAttrib.

        Example::

            <value>text</value>
            <value><attribute>foobar</attribute></value>
            <value><path>foobar</path></value>
        """
        for arg_3 in arg_2:
            arg_4 = SubElement(arg_1, 'value')
            arg_0.serialize_value(arg_4, arg_3)
        return arg_1


def Func(arg_0):
        """
        Parse the event definition node, and return an instance of Event
        """
        arg_1 = first(
            arg_0.xpath('.//bpmn:messageEventDefinition'))
        if arg_1 is not None:
            return arg_0.get_message_event_definition(arg_1)

        arg_2 = first(
            arg_0.xpath('.//bpmn:timerEventDefinition'))
        if arg_2 is not None:
            return arg_0.get_timer_event_definition(arg_2)

        raise NotImplementedError(
            'Unsupported Intermediate Catch Event: %r', ET.tostring(arg_0.node))


def Func(arg_0, arg_1):
        """
        Parse the messageEventDefinition node and return an instance of
        MessageEventDefinition
        """
        arg_2 = first(arg_0.xpath('.//bpmn:messageRef'))
        arg_3 = arg_2.get(
            'name') if arg_2 is not None else arg_0.node.get('name')
        return MessageEventDefinition(arg_3)


def Func(arg_0, arg_1):
        """
        Parse the timerEventDefinition node and return an instance of
        TimerEventDefinition

        This currently only supports the timeDate node for specifying an expiry
        time for the timer.
        """
        arg_2 = first(arg_0.xpath('.//bpmn:timeDate'))
        return TimerEventDefinition(
            arg_0.node.get('name', arg_2.text),
            arg_0.parser.parse_condition(
                arg_2.text, None, None, None, None, arg_0))


def Func(arg_0, arg_1):
        """
        Called by the weak reference when its target dies.
        In other words, we can assert that self.weak_subscribers is not
        None at this time.
        """
        with arg_0.lock:
            arg_2 = [s[0] for s in arg_0.weak_subscribers]
            try:
                arg_3 = arg_2.index(arg_1)
            except ValueError:
                # subscriber was already removed by a call to disconnect()
                pass
            else:
                arg_0.weak_subscribers.pop(arg_3)


def Func(arg_0, arg_1, arg_2):
        """
        Connects a taskspec that is executed if the condition DOES match.

        condition -- a condition (Condition)
        taskspec -- the conditional task spec
        """
        assert arg_2 is not None
        arg_0.outputs.append(arg_2)
        arg_0.cond_task_specs.append((arg_1, arg_2.name))
        arg_2._connect_notify(arg_0)


def Func(arg_0, arg_1):
        """
        Runs the task. Should not be called directly.
        Returns True if completed, False otherwise.
        """
        # Find all matching conditions.
        arg_2 = []
        for arg_3, arg_4 in arg_0.cond_task_specs:
            if arg_0.choice is not None and arg_4 not in arg_0.choice:
                continue
            if arg_3 is None:
                arg_2.append(arg_0._wf_spec.get_task_spec_from_name(arg_4))
                continue
            if not arg_3._matches(arg_1):
                continue
            arg_2.append(arg_0._wf_spec.get_task_spec_from_name(arg_4))

        arg_1._sync_children(arg_2, Task.FUTURE)
        for arg_5 in arg_1.children:
            arg_5.task_spec._update(arg_5)


def Func(arg_0):
        """
        Returns True if the entire Workflow is completed, False otherwise.

        :rtype: bool
        :return: Whether the workflow is completed.
        """
        arg_1 = Task.NOT_FINISHED_MASK
        arg_2 = Task.Iterator(arg_0.task_tree, arg_1)
        try:
            next(arg_2)
        except StopIteration:
            # No waiting tasks found.
            return True
        return False


def Func(arg_0, arg_1=False):
        """
        Cancels all open tasks in the workflow.

        :type  success: bool
        :param success: Whether the Workflow should be marked as successfully
                        completed.
        """
        arg_0.success = arg_1
        Func = []
        arg_3 = Task.NOT_FINISHED_MASK
        for arg_4 in Task.Iterator(arg_0.task_tree, arg_3):
            Func.append(arg_4)
        for arg_4 in Func:
            arg_4.cancel()


def Func(arg_0, arg_1):
        """
        Returns the task with the given id.

        :type id:integer
        :param id: The id of a task.
        :rtype: Task
        :returns: The task with the given id.
        """
        arg_2 = [task for task in arg_0.Funcs() if task.id == arg_1]
        return arg_2[0] if len(arg_2) == 1 else None


def Func(arg_0, arg_1):
        """
        Returns all tasks whose spec has the given name.

        :type name: str
        :param name: The name of a task spec.
        :rtype: Task
        :return: The task that relates to the spec with the given name.
        """
        return [arg_2 for arg_2 in arg_0.get_tasks()
                if arg_2.task_spec.name == arg_1]


def Func(arg_0, arg_1=True, arg_2=True):
        """
        Runs the next task.
        Returns True if completed, False otherwise.

        :type  pick_up: bool
        :param pick_up: When True, this method attempts to choose the next
                        task not by searching beginning at the root, but by
                        searching from the position at which the last call
                        of Func() left off.
        :type  halt_on_manual: bool
        :param halt_on_manual: When True, this method will not attempt to
                        complete any tasks that have manual=True.
                        See :meth:`SpiffWorkflow.specs.TaskSpec.__init__`
        :rtype:  bool
        :returns: True if all tasks were completed, False otherwise.
        """
        # Try to pick up where we left off.
        arg_3 = []
        if arg_1 and arg_0.last_task is not None:
            try:
                arg_4 = Task.Iterator(arg_0.last_task, Task.READY)
                arg_5 = next(arg_4)
            except StopIteration:
                arg_5 = None
            arg_0.last_task = None
            if arg_5 is not None:
                if not (arg_2 and arg_5.task_spec.manual):
                    if arg_5.complete():
                        arg_0.last_task = arg_5
                        return True
                arg_3.append(arg_5)

        # Walk through all ready tasks.
        for arg_5 in Task.Iterator(arg_0.task_tree, Task.READY):
            for arg_7 in arg_3:
                if arg_5._is_descendant_of(arg_7):
                    continue
            if not (arg_2 and arg_5.task_spec.manual):
                if arg_5.complete():
                    arg_0.last_task = arg_5
                    return True
            arg_3.append(arg_5)

        # Walk through all waiting tasks.
        for arg_5 in Task.Iterator(arg_0.task_tree, Task.WAITING):
            arg_5.task_spec._update(arg_5)
            if not arg_5._has_state(Task.WAITING):
                arg_0.last_task = arg_5
                return True
        return False


def Func(arg_0, arg_1, arg_2=False, **arg_3):
        """
        Create a new workflow instance from the given spec and arguments.

        :param workflow_spec: the workflow spec to use

        :param read_only: this should be in read only mode

        :param kwargs: Any extra kwargs passed to the deserialize_workflow
        method will be passed through here
        """
        return BpmnWorkflow(arg_1, arg_2=arg_2, **arg_3)


def Func(arg_0, arg_1, arg_2=arg_3):
        """
        Adds a new child and assigns the given TaskSpec to it.

        :type  task_spec: TaskSpec
        :param task_spec: The task spec that is assigned to the new child.
        :type  state: integer
        :param state: The bitmask of states for the new child.
        :rtype:  Task
        :returns: The new child task.
        """
        if arg_1 is None:
            raise ValueError(arg_0, 'Func() requires a TaskSpec')
        if arg_0._is_predicted() and arg_2 & arg_0.PREDICTED_MASK == 0:
            arg_4 = 'Attempt to add non-predicted child to predicted task'
            raise WorkflowException(arg_0.task_spec, arg_4)
        arg_5 = Task(arg_0.workflow, arg_1, arg_0, arg_2=arg_2)
        arg_5.thread_id = arg_0.thread_id
        if arg_2 == arg_0.READY:
            arg_5._ready()
        return arg_5


def Func(arg_0, arg_1=True):
        """
        Assigns a new thread id to the task.

        :type  recursive: bool
        :param recursive: Whether to assign the id to children recursively.
        :rtype:  bool
        :returns: The new thread id.
        """
        arg_0.__class__.thread_id_pool += 1
        arg_0.thread_id = arg_0.__class__.thread_id_pool
        if not arg_1:
            return arg_0.thread_id
        for arg_3 in arg_0:
            arg_3.thread_id = arg_0.thread_id
        return arg_0.thread_id


def Func(arg_0, arg_1):
        """
        Returns the ancestor that has a task with the given task spec
        as a parent.
        If no such ancestor was found, the root task is returned.

        :type  parent_task_spec: TaskSpec
        :param parent_task_spec: The wanted ancestor.
        :rtype:  Task
        :returns: The child of the given ancestor.
        """
        if arg_0.parent is None:
            return arg_0
        if arg_0.parent.task_spec == arg_1:
            return arg_0
        return arg_0.parent.Func(arg_1)


def Func(arg_0, arg_1):
        """
        Returns the ancestor that has the given task spec assigned.
        If no such ancestor was found, the root task is returned.

        :type  task_spec: TaskSpec
        :param task_spec: The wanted task spec.
        :rtype:  Task
        :returns: The ancestor.
        """
        if arg_0.parent is None:
            return arg_0
        if arg_0.parent.task_spec == arg_1:
            return arg_0.parent
        return arg_0.parent.Func(arg_1)


def Func(arg_0, arg_1):
        """
        Returns the ancestor that has a task with the given name assigned.
        Returns None if no such ancestor was found.

        :type  name: str
        :param name: The name of the wanted task.
        :rtype:  Task
        :returns: The ancestor.
        """
        if arg_0.parent is None:
            return None
        if arg_0.parent.get_name() == arg_1:
            return arg_0.parent
        return arg_0.parent.Func(arg_1)


def Func(arg_0):
        """
        Returns a textual representation of this Task's state.
        """
        arg_1 = []
        for arg_2, arg_3 in list(arg_0.state_names.items()):
            if arg_0._has_state(arg_2):
                arg_1.append(arg_3)
        return '|'.join(arg_1)


def Func(arg_0, arg_1=0, arg_2=True):
        """
        Returns the subtree as a string for debugging.

        :rtype:  str
        :returns: The debug information.
        """
        arg_3 = (' ' * arg_1 * 2)
        arg_3 += '%s/' % arg_0.id
        arg_3 += '%s:' % arg_0.thread_id
        arg_3 += ' Task of %s' % arg_0.get_name()
        if arg_0.task_spec.description:
            arg_3 += ' (%s)' % arg_0.get_description()
        arg_3 += ' State: %s' % arg_0.get_state_name()
        arg_3 += ' Children: %s' % len(arg_0.children)
        if arg_2:
            for arg_4 in arg_0.children:
                arg_3 += '\n' + arg_4.Func(arg_1 + 1)
        return arg_3


def Func(arg_0, arg_1):
    """Parses args and evaluates any Attrib entries"""
    arg_2 = []
    for arg_3 in arg_0:
        if isinstance(arg_3, Attrib) or isinstance(arg_3, PathAttrib):
            arg_2.append(valueof(arg_1, arg_3))
        else:
            arg_2.append(arg_3)
    return arg_2


def Func(arg_0, arg_1):
    """Parses kwargs and evaluates any Attrib entries"""
    arg_2 = {}
    for arg_3, arg_4 in list(arg_0.items()):
        if isinstance(arg_4, Attrib) or isinstance(arg_4, PathAttrib):
            arg_2[arg_3] = valueof(arg_1, arg_4)
        else:
            arg_2[arg_3] = arg_4
    return arg_2


def Func(arg_0, arg_1):
        """Sends Celery asynchronous call and stores async call information for
        retrieval laster"""
        arg_2, arg_3 = None, None
        if arg_0.args:
            arg_2 = _eval_args(arg_0.args, arg_1)
        if arg_0.kwargs:
            arg_3 = _eval_kwargs(arg_0.kwargs, arg_1)
        LOG.debug(
            "%s (task id %s) calling %s" % (arg_0.name, arg_1.id, arg_0.call),
            extra=dict(data=dict(arg_2=arg_2, arg_3=arg_3)))
        arg_4 = default_app.send_task(arg_0.call, arg_2=arg_2, arg_3=arg_3)
        arg_1._set_internal_data(task_id=arg_4.task_id)
        arg_1.async_call = arg_4
        LOG.debug("'%s' called: %s" % (arg_0.call, arg_1.async_call.task_id))


def Func(arg_0, arg_1):
        """ Abort celery task and retry it"""
        if not arg_1._has_state(Task.WAITING):
            raise WorkflowException(arg_1, "Cannot refire a task that is not"
                                    "in WAITING state")
        # Check state of existing call and abort it (save history)
        if arg_1._get_internal_data('task_id') is not None:
            if not hasattr(arg_1, 'async_call'):
                arg_2 = arg_1._get_internal_data('task_id')
                arg_1.async_call = default_app.AsyncResult(arg_2)
                arg_1.deserialized = True
                arg_1.async_call.state  # manually refresh
            arg_3 = arg_1.async_call
            if arg_3.state == 'FAILED':
                pass
            elif arg_3.state in ['RETRY', 'PENDING', 'STARTED']:
                arg_3.revoke()
                LOG.info("Celery task '%s' was in %s state and was revoked" % (
                    arg_3.state, arg_3))
            elif arg_3.state == 'SUCCESS':
                LOG.warning("Celery task '%s' succeeded, but a refire was "
                            "requested" % arg_3)
            arg_0._clear_celery_task_data(arg_1)
        # Retrigger
        return arg_0._start(arg_1)


def Func(arg_0, arg_1):
        """ Clear celery task data """
        # Save history
        if 'task_id' in arg_1.internal_data:
            # Save history for diagnostics/forensics
            arg_2 = arg_1._get_internal_data('task_history', [])
            arg_2.append(arg_1._get_internal_data('task_id'))
            del arg_1.internal_data['task_id']
            arg_1._set_internal_data(task_history=arg_2)
        if 'task_state' in arg_1.internal_data:
            del arg_1.internal_data['task_state']
        if 'error' in arg_1.internal_data:
            del arg_1.internal_data['error']
        if hasattr(arg_1, 'async_call'):
            delattr(arg_1, 'async_call')
        if hasattr(arg_1, 'deserialized'):
            delattr(arg_1, 'deserialized')


def Func(arg_0, arg_1, arg_2=None, arg_3=0):
        """
        Updates the branch such that all possible future routes are added.

        Should NOT be overwritten! Instead, overwrite Func_hook().

        :type  my_task: Task
        :param my_task: The associated task in the task tree.
        :type  seen: list[taskspec]
        :param seen: A list of already visited tasks.
        :type  looked_ahead: integer
        :param looked_ahead: The depth of the predicted path so far.
        """
        if arg_1._is_finished():
            return
        if arg_2 is None:
            arg_2 = []
        elif arg_0 in arg_2:
            return
        if not arg_1._is_finished():
            arg_0.Func_hook(arg_1)
        if not arg_1._is_definite():
            if arg_3 + 1 >= arg_0.lookahead:
                return
            arg_2.append(arg_0)
        for arg_4 in arg_1.children:
            arg_4.task_spec.Func(arg_4, arg_2[:], arg_3 + 1)


def Func(arg_0, arg_1):
        """
        Return True on success, False otherwise.

        :type  my_task: Task
        :param my_task: The associated task in the task tree.
        """
        assert arg_1 is not None
        arg_0.test()

        # Acquire locks, if any.
        for arg_2 in arg_0.locks:
            arg_3 = arg_1.workflow._get_mutex(arg_2)
            if not arg_3.testandset():
                return

        # Assign variables, if so requested.
        for arg_4 in arg_0.pre_assign:
            arg_4.assign(arg_1, arg_1)

        # Run task-specific code.
        arg_0.Func_before_hook(arg_1)
        arg_0.reached_event.emit(arg_1.workflow, arg_1)
        arg_0.Func_hook(arg_1)

        # Run user code, if any.
        if arg_0.ready_event.emit(arg_1.workflow, arg_1):
            # Assign variables, if so requested.
            for arg_4 in arg_0.post_assign:
                arg_4.assign(arg_1, arg_1)

        # Release locks, if any.
        for arg_2 in arg_0.locks:
            arg_3 = arg_1.workflow._get_mutex(arg_2)
            arg_3.unlock()

        arg_0.finished_event.emit(arg_1.workflow, arg_1)


def Func(arg_0):
        """
        Creates the package, writing the data out to the provided file-like
        object.
        """

        # Check that all files exist (and calculate the longest shared path
        # prefix):
        arg_0.input_path_prefix = None
        for arg_2 in arg_0.input_files:
            if not arg_5.path.isfile(arg_2):
                raise ValueError(
                    '%s does not exist or is not a file' % arg_2)
            if arg_0.input_path_prefix:
                arg_3 = arg_5.path.abspath(arg_5.path.dirname(arg_2))
                while not (arg_3.startswith(arg_0.input_path_prefix) and
                           arg_0.input_path_prefix):
                    arg_0.input_path_prefix = arg_0.input_path_prefix[:-1]
            else:
                arg_0.input_path_prefix = arg_5.path.abspath(
                    arg_5.path.dirname(arg_2))

        # Parse all of the XML:
        arg_0.bpmn = {}
        for arg_2 in arg_0.input_files:
            arg_4 = ET.parse(arg_2)
            arg_0.bpmn[arg_5.path.abspath(arg_2)] = arg_4

        # Now run through pre-parsing and validation:
        for arg_2, arg_4 in list(arg_0.bpmn.items()):
            arg_4 = arg_0.pre_parse_and_validate(arg_4, arg_2)
            arg_0.bpmn[arg_5.path.abspath(arg_2)] = arg_4

        # Now check that we can parse it fine:
        for arg_2, arg_4 in list(arg_0.bpmn.items()):
            arg_0.parser.add_bpmn_xml(arg_4, arg_2=arg_2)

        arg_0.wf_spec = arg_0.parser.get_spec(arg_0.entry_point_process)

        # Now package everything:
        arg_0.package_zip = zipfile.ZipFile(
            arg_0.package_file, "w", compression=zipfile.ZIP_DEFLATED)

        arg_10 = set()
        for arg_11 in arg_0.wf_spec.get_specs_depth_first():
            arg_2 = arg_11.file
            if arg_2 not in arg_10:
                arg_10.add(arg_2)

                arg_4 = arg_0.bpmn[arg_5.path.abspath(arg_2)]
                arg_0.write_to_package_zip(
                    "%s.bpmn" % arg_11.name, ET.tostring(arg_4.getroot()))

                arg_0.write_file_to_package_zip(
                    "src/" + arg_0._get_zip_path(arg_2), arg_2)

                arg_0._call_editor_hook('package_for_editor', arg_11, arg_2)

        arg_0.write_meta_data()
        arg_0.write_manifest()

        arg_0.package_zip.close()


def Func(arg_0, arg_1, arg_2):
        """
        Writes a local file in to the zip file and adds it to the manifest
        dictionary

        :param filename: The zip file name

        :param src_filename: the local file name
        """
        arg_3 = open(arg_2)
        with arg_3:
            arg_4 = arg_3.read()
        arg_0.manifest[arg_1] = md5hash(arg_4)
        arg_0.package_zip.write(arg_2, arg_1)


def Func(arg_0, arg_1, arg_2):
        """
        Adds the SVG files to the archive for this BPMN file.
        """
        arg_3 = arg_2[:-len('.bpmn20.xml')] + '.signavio.xml'
        if os.path.exists(arg_3):
            arg_0.write_file_to_package_zip(
                "src/" + arg_0._get_zip_path(arg_3), arg_3)

            arg_4 = open(arg_3, 'r')
            try:
                arg_5 = ET.parse(arg_4)
            finally:
                arg_4.close()
            arg_6 = one(arg_5.findall('.//svg-representation'))
            arg_0.write_to_package_zip("%s.svg" % arg_1.name, arg_6.text)


def Func(arg_0, arg_1, arg_2, arg_3):
        """
        Utility method to merge an option and config, with the option taking "
        precedence
        """

        arg_4 = getattr(arg_3, arg_1, None)
        if arg_4:
            arg_2.set(CONFIG_SECTION_NAME, arg_1, arg_4)
        elif arg_2.has_option(CONFIG_SECTION_NAME, arg_1):
            setattr(arg_3, arg_1, arg_2.get(
                CONFIG_SECTION_NAME, arg_1))


def Func(arg_0, arg_1):
        """
        Parses the specified child task node, and returns the task spec. This
        can be called by a TaskParser instance, that is owned by this
        ProcessParser.
        """

        if arg_1.get('id') in arg_0.parsed_nodes:
            return arg_0.parsed_nodes[arg_1.get('id')]

        (arg_2, arg_3) = arg_0.parser._get_parser_class(arg_1.tag)
        if not arg_2 or not arg_3:
            raise ValidationException(
                "There is no support implemented for this task type.",
                arg_1=arg_1, filename=arg_0.filename)
        arg_4 = arg_2(arg_0, arg_3, arg_1)
        arg_5 = arg_4.Func()

        return arg_5


def Func(arg_0, arg_1, arg_2):
        """
        Reads the "pre-assign" or "post-assign" tag from the given node.

        start_node -- the xml node (xml.dom.minidom.Node)
        """
        arg_3 = arg_2.getAttribute('name')
        arg_4 = arg_2.getAttribute('field')
        arg_5 = arg_2.getAttribute('value')
        arg_6 = {}
        if arg_3 == '':
            _exc('name attribute required')
        if arg_4 != '' and arg_5 != '':
            _exc('Both, field and right-value attributes found')
        elif arg_4 == '' and arg_5 == '':
            _exc('field or value attribute required')
        elif arg_5 != '':
            arg_6['right'] = arg_5
        else:
            arg_6['right_attribute'] = arg_4
        return operators.Assign(arg_3, **arg_6)


def Func(arg_0, arg_1, arg_2):
        """
        Reads the conditional statement from the given node.

        workflow -- the workflow with which the concurrence is associated
        start_node -- the xml structure (xml.dom.minidom.Node)
        """
        # Collect all information.
        arg_3 = None
        arg_4 = None
        for arg_5 in arg_2.childNodes:
            if arg_5.nodeType != minidom.Node.ELEMENT_NODE:
                continue
            if arg_5.nodeName.lower() == 'successor':
                if arg_4 is not None:
                    _exc('Duplicate task name %s' % arg_4)
                if arg_5.firstChild is None:
                    _exc('Successor tag without a task name')
                arg_4 = arg_5.firstChild.nodeValue
            elif arg_5.nodeName.lower() in _op_map:
                if arg_3 is not None:
                    _exc('Multiple conditions are not yet supported')
                arg_3 = arg_0.deserialize_logical(arg_5)
            else:
                _exc('Unknown node: %s' % arg_5.nodeName)

        if arg_3 is None:
            _exc('Missing condition in conditional statement')
        if arg_4 is None:
            _exc('A %s has no task specified' % arg_2.nodeName)
        return arg_3, arg_4


def Func(arg_0, arg_1, arg_2=None):
        """
        Reads the workflow from the given XML structure and returns a
        WorkflowSpec instance.
        """
        arg_3 = minidom.parseString(arg_1)
        arg_4 = arg_3.getElementsByTagName('process-definition')[0]
        arg_5 = arg_4.getAttribute('name')
        if arg_5 == '':
            _exc('%s without a name attribute' % arg_4.nodeName)

        # Read all task specs and create a list of successors.
        arg_6 = specs.WorkflowSpec(arg_5, arg_2)
        del arg_6.task_specs['Start']
        arg_7 = specs.Simple(arg_6, 'End'), []
        arg_8 = dict(arg_7=arg_7)
        for arg_9 in arg_4.childNodes:
            if arg_9.nodeType != minidom.Node.ELEMENT_NODE:
                continue
            if arg_9.nodeName == 'name':
                arg_6.name = arg_9.firstChild.nodeValue
            elif arg_9.nodeName == 'description':
                arg_6.description = arg_9.firstChild.nodeValue
            elif arg_9.nodeName.lower() in _spec_map:
                arg_0.deserialize_task_spec(
                    arg_6, arg_9, arg_8)
            else:
                _exc('Unknown node: %s' % arg_9.nodeName)

        # Remove the default start-task from the workflow.
        arg_6.start = arg_8['start'][0]

        # Connect all task specs.
        for arg_5 in arg_8:
            arg_12, arg_13 = arg_8[arg_5]
            for arg_14, arg_15 in arg_13:
                if arg_15 not in arg_8:
                    _exc('Unknown successor: "%s"' % arg_15)
                arg_16, arg_17 = arg_8[arg_15]
                if arg_14 is None:
                    arg_12.connect(arg_16)
                else:
                    arg_12.connect_if(arg_14, arg_16)
        return arg_6


def Func(arg_0, arg_1):
        """
        Called by a task spec when it was added into the workflow.
        """
        if arg_1.name in arg_0.task_specs:
            raise KeyError('Duplicate task spec name: ' + arg_1.name)
        arg_0.task_specs[arg_1.name] = arg_1
        arg_1.id = len(arg_0.task_specs)


def Func(arg_0):
        """Checks integrity of workflow and reports any problems with it.

        Detects:
        - loops (tasks that wait on each other in a loop)
        :returns: empty list if valid, a list of errors if not
        """
        arg_1 = []
        from ..specs import Join

        def recursive_find_loop(arg_2, arg_3):
            arg_4 = arg_3[:]
            arg_4.append(arg_2)
            if isinstance(arg_2, Join):
                if arg_2 in arg_3:
                    arg_5 = "Found loop with '%s': %s then '%s' again" % (
                        arg_2.name, '->'.join([p.name for p in arg_3]),
                        arg_2.name)
                    raise Exception(arg_5)
                for arg_6 in arg_2.inputs:
                    recursive_find_loop(arg_6, arg_4)

            for arg_7 in arg_2.inputs:
                recursive_find_loop(arg_7, arg_4)

        for arg_8, arg_2 in list(arg_0.task_specs.items()):
            # Check for cyclic waits
            try:
                recursive_find_loop(arg_2, [])
            except Exception as exc:
                arg_1.append(exc.__str__())

            # Check for disconnected tasks
            if not arg_2.inputs and arg_2.name not in ['Start', 'Root']:
                if arg_2.outputs:
                    arg_1.append("Task '%s' is disconnected (no inputs)" %
                                   arg_2.name)
                else:
                    LOG.debug("Task '%s' is not being used" % arg_2.name)

        return arg_1


def Func(arg_0, arg_1):
        """
        Indicate to the workflow that a message has been received. The message
        will be processed by any waiting Intermediate or Boundary Message
        Events, that are waiting for the message.
        """
        assert not arg_0.read_only
        arg_0.refresh_waiting_tasks()
        arg_0.do_engine_steps()
        for arg_2 in Task.Iterator(arg_0.task_tree, Task.WAITING):
            arg_2.task_spec.Func(arg_2, arg_1)


def Func(arg_0, arg_1, arg_2, arg_3, **arg_4):
        """
        Deserializes the trigger using the provided serializer.
        """
        return arg_1.Func_trigger(arg_2,
                                              arg_3,
                                              **arg_4)


def Func(arg_0, arg_1, arg_2):
        """
        Evaluate the given expression, within the context of the given task and
        return the result.
        """
        if isinstance(arg_2, Operator):
            return arg_2._matches(arg_1)
        else:
            return arg_0._eval(arg_1, arg_2, **arg_1.data)


def Func(arg_0, arg_1, arg_2=False):
        """
        Checks whether the preconditions for going to READY state are met.
        Returns True if the threshold was reached, False otherwise.
        Also returns the list of tasks that yet need to be completed.
        """
        # If the threshold was already reached, there is nothing else to do.
        if arg_1._has_state(Task.COMPLETED):
            return True, None
        if arg_1._has_state(Task.READY):
            return True, None

        # Check whether we may fire.
        if arg_0.split_task is None:
            return arg_0._check_threshold_unstructured(arg_1, arg_2)
        return arg_0._check_threshold_structured(arg_1, arg_2)


def Func(arg_0, arg_1):
        """
        Connects the task spec that is executed if no other condition
        matches.

        :type  task_spec: TaskSpec
        :param task_spec: The following task spec.
        """
        assert arg_0.default_task_spec is None
        arg_0.outputs.append(arg_1)
        arg_0.default_task_spec = arg_1.name
        arg_1._Func_notify(arg_0)


def Func(arg_0):
        """
        Return extra config options to be passed to the TrelloIssue class
        """
        return {
            'import_labels_as_tags':
            arg_0.config.get('import_labels_as_tags', False, asbool),
            'label_template':
            arg_0.config.get('label_template', DEFAULT_LABEL_TEMPLATE),
            }


def Func(arg_0, arg_1):
        """ A wrapper around get_comments that build the taskwarrior
        annotations. """
        arg_2 = arg_0.get_comments(arg_1['id'])
        Func = arg_0.build_annotations(
            ((c['memberCreator']['username'], c['data']['text']) for c in arg_2),
            arg_1["shortUrl"])
        return Func


def Func(arg_0):
        """
        Get the list of boards to pull cards from.  If the user gave a value to
        trello.include_boards use that, otherwise ask the Trello API for the
        user's boards.
        """
        if 'include_boards' in arg_0.config:
            for arg_1 in arg_0.config.get('include_boards', to_type=aslist):
                # Get the board name
                yield arg_0.api_request(
                    "/1/boards/{id}".format(id=arg_1), fields='name')
        else:
            arg_2 = arg_0.api_request("/1/members/me/boards", fields='name')
            for arg_3 in arg_2:
                yield arg_3


def Func(arg_0, arg_1, **arg_2):
        """ Build the full url to the API endpoint """
        if arg_0.host == 'github.com':
            arg_3 = "https://api.github.com"
        else:
            arg_3 = "https://{}/api/v3".format(arg_0.host)
        return arg_3 + arg_1.format(**arg_2)


def Func(arg_0, arg_1):
        """ Grab all issues matching a github query """
        arg_2 = {}
        for arg_3 in arg_0.client.Func(arg_1):
            arg_4 = arg_3['html_url']
            try:
                arg_5 = arg_0.get_repository_from_issue(arg_3)
            except ValueError as e:
                log.critical(e)
            else:
                arg_2[arg_4] = (arg_5, arg_3)
        return arg_2


def Func(arg_0, arg_1):
        """ Grab all the pull requests """
        return [
            (arg_1, arg_2) for arg_2 in
            arg_0.client.get_pulls(*arg_1.split('/'))
        ]


def Func(arg_0, arg_1, arg_2, arg_3=lambda arg_4: arg_4):
        """Return a main config value, or default if it does not exist."""

        if arg_0.main_config.has_option(arg_0.main_section, arg_1):
            return arg_3(arg_0.main_config.get(arg_0.main_section, arg_1))
        return arg_2


def Func(arg_0, arg_1, arg_2):
        """ Validate generic options for a particular target """
        if arg_1.has_option(arg_2, 'only_if_assigned'):
            die("[%s] has an 'only_if_assigned' option.  Should be "
                "'%s.only_if_assigned'." % (arg_2, arg_0.CONFIG_PREFIX))
        if arg_1.has_option(arg_2, 'also_unassigned'):
            die("[%s] has an 'also_unassigned' option.  Should be "
                "'%s.also_unassigned'." % (arg_2, arg_0.CONFIG_PREFIX))
        if arg_1.has_option(arg_2, 'default_priority'):
            die("[%s] has a 'default_priority' option.  Should be "
                "'%s.default_priority'." % (arg_2, arg_0.CONFIG_PREFIX))
        if arg_1.has_option(arg_2, 'add_tags'):
            die("[%s] has an 'add_tags' option.  Should be "
                "'%s.add_tags'." % (arg_2, arg_0.CONFIG_PREFIX))