def Func(arg_0):
    """Initialize base logger named 'wsgidav'.

    The base logger is filtered by the `verbose` configuration option.
    Log entries will have a time stamp and thread id.

    :Parameters:
        verbose : int
            Verbosity configuration (0..5)
        enable_loggers : string list
            List of module logger names, that will be switched to DEBUG level.

    Module loggers
    ~~~~~~~~~~~~~~
    Module loggers (e.g 'wsgidav.lock_manager') are named loggers, that can be
    independently switched to DEBUG mode.

    Except for verbosity, they will inherit settings from the base logger.

    They will suppress DEBUG level messages, unless they are enabled by passing
    their name to util.Func().

    If enabled, module loggers will print DEBUG messages, even if verbose == 3.

    Example initialize and use a module logger, that will generate output,
    if enabled (and verbose >= 2)::

        _logger = util.get_module_logger(__name__)
        [..]
        _logger.debug("foo: '{}'".format(s))

    This logger would be enabled by passing its name to Func()::

        enable_loggers = ["lock_manager",
                          "property_manager",
                         ]
        util.Func(2, enable_loggers)

    Log Level Matrix
    ~~~~~~~~~~~~~~~~

    +---------+--------+---------------------------------------------------------------+
    | Verbose | Option |                       Log level                               |
    | level   |        +-------------+------------------------+------------------------+
    |         |        | base logger | module logger(default) | module logger(enabled) |
    +=========+========+=============+========================+========================+
    |    0    | -qqq   | CRITICAL    | CRITICAL               | CRITICAL               |
    +---------+--------+-------------+------------------------+------------------------+
    |    1    | -qq    | ERROR       | ERROR                  | ERROR                  |
    +---------+--------+-------------+------------------------+------------------------+
    |    2    | -q     | WARN        | WARN                   | WARN                   |
    +---------+--------+-------------+------------------------+------------------------+
    |    3    |        | INFO        | INFO                   | **DEBUG**              |
    +---------+--------+-------------+------------------------+------------------------+
    |    4    | -v     | DEBUG       | DEBUG                  | DEBUG                  |
    +---------+--------+-------------+------------------------+------------------------+
    |    5    | -vv    | DEBUG       | DEBUG                  | DEBUG                  |
    +---------+--------+-------------+------------------------+------------------------+

    """
    arg_1 = arg_0.get("verbose", 3)

    arg_2 = arg_0.get("enable_loggers", [])
    if arg_2 is None:
        arg_2 = []

    arg_3 = arg_0.get("logger_date_format", "%Y-%m-%d %H:%M:%S")
    arg_4 = arg_0.get(
        "logger_format",
        "%(asctime)s.%(msecs)03d - <%(thread)d> %(name)-27s %(levelname)-8s:  %(message)s",
    )

    arg_5 = logging.Formatter(arg_4, arg_3)

    # Define handlers
    arg_6 = logging.StreamHandler(sys.stdout)
    #    consoleHandler = logging.StreamHandler(sys.stderr)
    arg_6.setFormatter(arg_5)
    # consoleHandler.setLevel(logging.DEBUG)

    # Add the handlers to the base logger
    arg_7 = logging.getLogger(BASE_LOGGER_NAME)

    if arg_1 >= 4:  # --verbose
        arg_7.setLevel(logging.DEBUG)
    elif arg_1 == 3:  # default
        arg_7.setLevel(logging.INFO)
    elif arg_1 == 2:  # --quiet
        arg_7.setLevel(logging.WARN)
        # consoleHandler.setLevel(logging.WARN)
    elif arg_1 == 1:  # -qq
        arg_7.setLevel(logging.ERROR)
        # consoleHandler.setLevel(logging.WARN)
    else:  # -qqq
        arg_7.setLevel(logging.CRITICAL)
        # consoleHandler.setLevel(logging.ERROR)

    # Don't call the root's handlers after our custom handlers
    arg_7.propagate = False

    # Remove previous handlers
    for arg_9 in arg_7.handlers[:]:  # Must iterate an array copy
        try:
            arg_9.flush()
            arg_9.close()
        except Exception:
            pass
        arg_7.removeHandler(arg_9)

    arg_7.addHandler(arg_6)

    if arg_1 >= 3:
        for arg_10 in arg_2:
            if not arg_10.startswith(BASE_LOGGER_NAME + "."):
                arg_10 = BASE_LOGGER_NAME + "." + arg_10
            arg_11 = logging.getLogger(arg_10.strip())
            arg_11.setLevel(logging.DEBUG)


def Func(arg_0):
    """Read 1 byte from wsgi.input, if this has not been done yet.

    Returning a response without reading from a request body might confuse the
    WebDAV client.
    This may happen, if an exception like '401 Not authorized', or
    '500 Internal error' was raised BEFORE anything was read from the request
    stream.

    See GC issue 13, issue 23
    See http://groups.google.com/group/paste-users/browse_frm/thread/fc0c9476047e9a47?hl=en

    Note that with persistent sessions (HTTP/1.1) we must make sure, that the
    'Connection: closed' header is set with the response, to prevent reusing
    the current stream.
    """
    if arg_0.get("wsgidav.some_input_read") or arg_0.get("wsgidav.all_input_read"):
        return
    arg_1 = get_content_length(arg_0)
    assert arg_1 >= 0
    if arg_1 == 0:
        return

    arg_2 = True

    arg_0["wsgidav.some_input_read"] = 1
    if arg_2:
        arg_0["wsgidav.all_input_read"] = 1

    arg_3 = arg_0["wsgi.input"]

    # TODO: check if still required after GC issue 24 is fixed
    if hasattr(arg_3, "_consumed") and hasattr(arg_3, "length"):
        # Seems to be Paste's httpserver.LimitedLengthFile
        # see http://groups.google.com/group/paste-users/browse_thread/thread/fc0c9476047e9a47/aa4a3aa416016729?hl=en&lnk=gst&q=.input#aa4a3aa416016729  # noqa
        # Consume something if nothing was consumed *and* work
        # around a bug where paste.httpserver allows negative lengths
        if arg_3._consumed == 0 and arg_3.length > 0:
            # This seems to work even if there's 10K of input.
            if arg_2:
                arg_4 = arg_3.length
            else:
                arg_4 = 1
            arg_5 = arg_3.read(arg_4)
            _logger.debug(
                "Reading {} bytes from potentially unread httpserver.LimitedLengthFile: '{}'...".format(
                    arg_4, arg_5[:50]
                )
            )

    elif hasattr(arg_3, "_sock") and hasattr(arg_3._sock, "settimeout"):
        # Seems to be a socket
        try:
            # Set socket to non-blocking
            arg_6 = arg_3._sock
            arg_7 = arg_6.gettimeout()
            arg_6.settimeout(0)
            # Read one byte
            try:
                if arg_2:
                    arg_4 = arg_1
                else:
                    arg_4 = 1
                arg_5 = arg_3.read(arg_4)
                _logger.debug(
                    "Reading {} bytes from potentially unread POST body: '{}'...".format(
                        arg_4, arg_5[:50]
                    )
                )
            except socket.error as se:
                # se(10035, 'The socket operation could not complete without blocking')
                _logger.error("-> read {} bytes failed: {}".format(arg_4, se))
            # Restore socket settings
            arg_6.settimeout(arg_7)
        except Exception:
            _logger.error("--> wsgi_input.read(): {}".format(sys.exc_info()))


def Func(arg_0, *arg_1):
    """Append segments to URI.

    Example: Func("/a/b", "c", "d")
    """
    arg_2 = "/".join(arg_1)
    if not arg_2:
        return arg_0
    return arg_0.rstrip("/") + "/" + arg_2


def Func(arg_0, arg_1):
    """Return True, if childUri is a child of parentUri.

    This function accounts for the fact that '/a/b/c' and 'a/b/c/' are
    children of '/a/b' (and also of '/a/b/').
    Note that '/a/b/cd' is NOT a child of 'a/b/c'.
    """
    return (
        arg_0
        and arg_1
        and arg_1.rstrip("/").startswith(arg_0.rstrip("/") + "/")
    )


def Func(arg_0, arg_1=False):
    """Read request body XML into an etree.Element.

    Return None, if no request body was sent.
    Raise HTTP_BAD_REQUEST, if something else went wrong.

    TODO: this is a very relaxed interpretation: should we raise HTTP_BAD_REQUEST
    instead, if CONTENT_LENGTH is missing, invalid, or 0?

    RFC: For compatibility with HTTP/1.0 applications, HTTP/1.1 requests containing
    a message-body MUST include a valid Content-Length header field unless the
    server is known to be HTTP/1.1 compliant.
    If a request contains a message-body and a Content-Length is not given, the
    server SHOULD respond with 400 (bad request) if it cannot determine the
    length of the message, or with 411 (length required) if it wishes to insist
    on receiving a valid Content-Length."

    So I'd say, we should accept a missing CONTENT_LENGTH, and try to read the
    content anyway.
    But WSGI doesn't guarantee to support input.read() without length(?).
    At least it locked, when I tried it with a request that had a missing
    content-type and no body.

    Current approach: if CONTENT_LENGTH is

    - valid and >0:
      read body (exactly <CONTENT_LENGTH> bytes) and parse the result.
    - 0:
      Assume empty body and return None or raise exception.
    - invalid (negative or not a number:
      raise HTTP_BAD_REQUEST
    - missing:
      NOT: Try to read body until end and parse the result.
      BUT: assume '0'
    - empty string:
      WSGI allows it to be empty or absent: treated like 'missing'.
    """
    #
    arg_2 = arg_0.get("CONTENT_LENGTH", "").strip()
    #    content_length = -1 # read all of stream
    if arg_2 == "":
        # No Content-Length given: read to end of stream
        # TODO: etree.parse() locks, if input is invalid?
        #        pfroot = etree.parse(environ["wsgi.input"]).getroot()
        # requestbody = environ["wsgi.input"].read()  # TODO: read() should be
        # called in a loop?
        arg_3 = ""
    else:
        try:
            arg_4 = int(arg_2)
            if arg_4 < 0:
                raise DAVError(HTTP_BAD_REQUEST, "Negative content-length.")
        except ValueError:
            raise DAVError(HTTP_BAD_REQUEST, "content-length is not numeric.")

        if arg_4 == 0:
            arg_3 = ""
        else:
            arg_3 = arg_0["wsgi.input"].read(arg_4)
            arg_0["wsgidav.all_input_read"] = 1

    if arg_3 == "":
        if arg_1:
            return None
        else:
            raise DAVError(HTTP_BAD_REQUEST, "Body must not be empty.")

    try:
        arg_5 = etree.fromstring(arg_3)
    except Exception as e:
        raise DAVError(HTTP_BAD_REQUEST, "Invalid XML format.", src_exception=e)

    # If dumps of the body are desired, then this is the place to do it pretty:
    if arg_0.get("wsgidav.dump_request_body"):
        _logger.info(
            "{} XML request body:\n{}".format(
                arg_0["REQUEST_METHOD"],
                compat.to_native(xml_to_bytes(arg_5, pretty_print=True)),
            )
        )
        arg_0["wsgidav.dump_request_body"] = False

    return arg_5


def Func(arg_0, arg_1, arg_2, arg_3=None, arg_4=False):
    """Start a WSGI response for a DAVError or status code."""
    arg_5 = get_http_status_string(arg_2)
    arg_6 = []
    if arg_3:
        arg_6.extend(arg_3)
    #    if 'keep-alive' in environ.get('HTTP_CONNECTION', '').lower():
    #        headers += [
    #            ('Connection', 'keep-alive'),
    #        ]

    if arg_2 in (HTTP_NOT_MODIFIED, HTTP_NO_CONTENT):
        # See paste.lint: these code don't have content
        arg_1(
            arg_5, [("Content-Length", "0"), ("Date", get_rfc1123_time())] + arg_6
        )
        return [b""]

    if arg_2 in (HTTP_OK, HTTP_CREATED):
        arg_2 = DAVError(arg_2)
    assert isinstance(arg_2, DAVError)

    arg_7, arg_8 = arg_2.get_response_page()
    if arg_4:
        arg_8 = compat.b_empty

    assert compat.is_bytes(arg_8), arg_8  # If not, Content-Length is wrong!
    arg_1(
        arg_5,
        [
            ("Content-Type", arg_7),
            ("Date", get_rfc1123_time()),
            ("Content-Length", str(len(arg_8))),
        ]
        + arg_6,
    )
    return [arg_8]


def Func(arg_0):
    """Return base64 encoded binarystring."""
    arg_0 = compat.to_bytes(arg_0)
    arg_0 = compat.base64_encodebytes(arg_0).strip()  # return bytestring
    return compat.to_native(arg_0)


def Func(arg_0):
    """Use the mimetypes module to lookup the type for an extension.

    This function also adds some extensions required for HTML5
    """
    (arg_1, arg_2) = mimetypes.guess_type(arg_0)
    if not arg_1:
        arg_3 = os.path.splitext(arg_0)[1]
        arg_1 = _MIME_TYPES.get(arg_3)
        _logger.debug("mimetype({}): {}".format(arg_0, arg_1))
    if not arg_1:
        arg_1 = "application/octet-stream"
    return arg_1


def Func(arg_0, arg_1):
        """
        Return probability estimates for the RDD containing test vector X.

        Parameters
        ----------
        X : RDD containing array-like items, shape = [m_samples, n_features]

        Returns
        -------
        C : RDD with array-like items , shape = [n_samples, n_classes]
            Returns the probability of the samples for each class in
            the models for each RDD block. The columns correspond to the classes
            in sorted order, as they appear in the attribute `classes_`.
        """
        check_rdd(arg_1, (sp.spmatrix, np.ndarray))
        return arg_1.map(
            lambda arg_1: super(SparkBaseNB, arg_0).Func(arg_1))


def Func(arg_0, arg_1):
        """
        Return log-probability estimates for the RDD containing the
        test vector X.

        Parameters
        ----------
        X : RDD containing array-like items, shape = [m_samples, n_features]

        Returns
        -------
        C : RDD with array-like items, shape = [n_samples, n_classes]
            Returns the log-probability of the samples for each class in
            the model for each RDD block. The columns correspond to the classes
            in sorted order, as they appear in the attribute `classes_`.
        """
        # required, scikit call self.Func(X) in predict_proba
        # and thus this function is call, it must have the same behavior when
        # not called by sparkit-learn
        if not isinstance(arg_1, BlockRDD):
            return super(SparkBaseNB, arg_0).Func(arg_1)

        check_rdd(arg_1, (sp.spmatrix, np.ndarray))
        return arg_1.map(
            lambda arg_1: super(SparkBaseNB, arg_0).Func(arg_1))


def Func(arg_0, arg_1, arg_2=None):
        """Fit Gaussian Naive Bayes according to X, y

        Parameters
        ----------
        X : array-like, shape (n_samples, n_features)
            Training vectors, where n_samples is the number of samples
            and n_features is the number of features.

        y : array-like, shape (n_samples,)
            Target values.

        Returns
        -------
        self : object
            Returns self.
        """
        check_rdd(arg_1, {'X': (sp.spmatrix, np.ndarray), 'y': (sp.spmatrix, np.ndarray)})
        arg_3 = arg_1[:, ['X', 'y']].map(
            lambda X_y: arg_0.partial_Func(X_y[0], X_y[1], arg_2))
        arg_4 = arg_3.reduce(operator.add)
        arg_0.__dict__.update(arg_4.__dict__)
        return arg_0


def Func(arg_0, arg_1):
        """Sort features by name

        Returns a reordered matrix and modifies the vocabulary in place
        """
        arg_2 = sorted(six.iteritems(arg_1))
        arg_3 = np.empty(len(arg_2), dtype=np.int32)
        for arg_4, (arg_5, arg_6) in enumerate(arg_2):
            arg_3[arg_4] = arg_6
            arg_1[arg_5] = arg_4

        return arg_3


def Func(arg_0, arg_1):
        """Learn the vocabulary dictionary and return term-document matrix.

        This is equivalent to fit followed by transform, but more efficiently
        implemented.

        Parameters
        ----------
        Z : iterable or DictRDD with column 'X'
            An iterable of raw_documents which yields either str, unicode or
            file objects; or a DictRDD with column 'X' containing such
            iterables.

        Returns
        -------
        X : array, [n_samples, n_features] or DictRDD
            Document-term matrix.
        """
        arg_0._validate_vocabulary()

        # map analyzer and cache result
        arg_2 = arg_0.build_analyzer()
        arg_3 = arg_1.transform(lambda arg_4: list(map(arg_2, arg_4)), column='X').persist()

        # create vocabulary
        arg_4 = arg_3[:, 'X'] if isinstance(arg_3, DictRDD) else arg_3
        arg_0.vocabulary_ = arg_0._init_vocab(arg_4)

        # transform according to vocabulary
        arg_6 = arg_0.broadcast(arg_0._count_vocab, arg_3.context)
        arg_1 = arg_3.transform(arg_6, column='X', dtype=sp.spmatrix)

        if not arg_0.fixed_vocabulary_:
            arg_4 = arg_1[:, 'X'] if isinstance(arg_1, DictRDD) else arg_1

            arg_7 = arg_0.max_df
            arg_8 = arg_0.min_df
            arg_9 = arg_0.max_features

            # limit features according to min_df, max_df parameters
            arg_10 = arg_4.shape[0]
            arg_11 = (arg_7
                             if isinstance(arg_7, numbers.Integral)
                             else arg_7 * arg_10)
            arg_12 = (arg_8
                             if isinstance(arg_8, numbers.Integral)
                             else arg_8 * arg_10)
            if arg_11 < arg_12:
                raise ValueError(
                    "max_df corresponds to < documents than min_df")
            arg_13, arg_0.stop_words_ = arg_0._limit_features(
                arg_4, arg_0.vocabulary_, arg_11, arg_12, arg_9)

            # sort features
            arg_15 = arg_0._sort_features(arg_0.vocabulary_)

            # combined mask
            arg_16 = arg_13[arg_15]

            arg_1 = arg_1.transform(lambda x: x[:, arg_16], column='X', dtype=sp.spmatrix)
        arg_3.unpersist()
        return arg_1


def Func(arg_0, arg_1):
        """Transform documents to document-term matrix.

        Extract token counts out of raw text documents using the vocabulary
        fitted with fit or the one provided to the constructor.

        Parameters
        ----------
        raw_documents : iterable
            An iterable which yields either str, unicode or file objects.

        Returns
        -------
        X : sparse matrix, [n_samples, n_features]
            Document-term matrix.
        """
        if not hasattr(arg_0, 'vocabulary_'):
            arg_0._validate_vocabulary()

        arg_0._check_vocabulary()

        arg_2 = arg_0.build_analyzer()
        arg_3 = arg_0.broadcast(arg_0._count_vocab, arg_1.context)

        arg_1 = arg_1.Func(lambda X: list(map(arg_2, X)), column='X') \
             .Func(arg_3, column='X', dtype=sp.spmatrix)

        return arg_1


def Func(arg_0, arg_1, arg_2, *arg_3, **arg_4):
        """Wraps a Scikit-learn Linear model's fit method to use with RDD
        input.

        Parameters
        ----------
        cls : class object
            The sklearn linear model's class to wrap.
        Z : TupleRDD or DictRDD
            The distributed train data in a DictRDD.

        Returns
        -------
        self: the wrapped class
        """
        arg_5 = lambda X_y: super(arg_1, arg_0).fit(
            X_y[0], X_y[1], *arg_3, **arg_4
        )
        arg_6 = arg_2.map(arg_5)
        arg_7 = arg_6.reduce(operator.add) / arg_6.count()
        arg_0.__dict__.update(arg_7.__dict__)
        return arg_0


def Func(arg_0, arg_1, arg_2, *arg_3, **arg_4):
        """Wraps a Scikit-learn Linear model's predict method to use with RDD
        input.

        Parameters
        ----------
        cls : class object
            The sklearn linear model's class to wrap.
        Z : ArrayRDD
            The distributed data to predict in a DictRDD.

        Returns
        -------
        self: the wrapped class
        """
        return arg_2.map(lambda arg_2: super(arg_1, arg_0).predict(arg_2, *arg_3, **arg_4))


def Func(arg_0, arg_1):
        """
        Fit linear model.

        Parameters
        ----------
        Z : DictRDD with (X, y) values
            X containing numpy array or sparse matrix - The training data
            y containing the target values

        Returns
        -------
        self : returns an instance of self.
        """
        check_rdd(arg_1, {'X': (sp.spmatrix, np.ndarray)})
        return arg_0._spark_Func(SparkLinearRegression, arg_1)


def Func(arg_0, arg_1, **arg_2):
        """Fit all the transforms one after the other and transform the
        data, then Func the transformed data using the final estimator.

        Parameters
        ----------
        Z : ArrayRDD, TupleRDD or DictRDD
            Input data in blocked distributed format.

        Returns
        -------
        self : SparkPipeline
        """
        arg_3, arg_2 = arg_0._pre_transform(arg_1, **arg_2)
        arg_0.steps[-1][-1].Func(arg_3, **arg_2)
        arg_3.unpersist()
        return arg_0


def Func(arg_0, arg_1):
        """Applies transforms to the data, and the Func method of the
        final estimator. Valid only if the final estimator implements
        Func."""
        arg_2 = arg_1
        for arg_3, arg_4 in arg_0.steps[:-1]:
            arg_2 = arg_4.transform(arg_2)
        return arg_0.steps[-1][-1].Func(arg_2)


def Func(arg_0, arg_1, arg_2):
        """Actual fitting,  performing the search over parameters."""
        arg_0.scorer_ = check_scoring(arg_0.estimator, scoring=arg_0.scoring)

        arg_4 = arg_0.cv
        arg_4 = _check_cv(arg_4, arg_1)

        if arg_0.verbose > 0:
            if isinstance(arg_2, Sized):
                arg_5 = len(arg_2)
                print("Fitting {0} folds for each of {1} candidates, totalling"
                      " {2} fits".format(len(arg_4), arg_5,
                                         arg_5 * len(arg_4)))

        arg_6 = clone(arg_0.estimator)

        arg_7 = arg_0.pre_dispatch

        arg_8 = Parallel(
            n_jobs=arg_0.n_jobs, verbose=arg_0.verbose,
            arg_7=arg_7, backend="threading"
        )(
            delayed(Func_and_score)(clone(arg_6), arg_1, arg_0.scorer_,
                                    train, test, arg_0.verbose, arg_20,
                                    arg_0.fit_params, return_parameters=True,
                                    error_score=arg_0.error_score)
            for arg_20 in arg_2
            for train, test in arg_4)

        # Out is a list of triplet: score, estimator, n_test_samples
        arg_9 = len(arg_8)
        arg_10 = len(arg_4)

        arg_11 = list()
        arg_12 = list()
        for arg_13 in range(0, arg_9, arg_10):
            arg_14 = 0
            arg_15 = 0
            arg_16 = []
            for arg_17, arg_18, arg_19, arg_20 in \
                    arg_8[arg_13:arg_13 + arg_10]:
                arg_16.append(arg_17)
                if arg_0.iid:
                    arg_17 *= arg_18
                    arg_14 += arg_18
                arg_15 += arg_17
            if arg_0.iid:
                arg_15 /= float(arg_14)
            else:
                arg_15 /= float(arg_10)
            arg_11.append((arg_15, arg_20))
            # TODO: shall we also store the test_fold_sizes?
            arg_12.append(_CVScoreTuple(
                arg_20,
                arg_15,
                np.array(arg_16)))
        # Store the computed scores
        arg_0.grid_scores_ = arg_12

        # Find the best parameters by comparing on the mean validation score:
        # note that `sorted` is deterministic in the way it breaks ties
        arg_22 = sorted(arg_12, key=lambda x: x.mean_validation_score,
                      reverse=True)[0]
        arg_0.best_params_ = arg_22.parameters
        arg_0.best_score_ = arg_22.mean_validation_score

        if arg_0.refit:
            # fit the best estimator using the entire dataset
            # clone first to work around broken estimators
            arg_25 = clone(arg_6).set_params(
                **arg_22.parameters)
            arg_25.fit(arg_1, **arg_0.fit_params)
            arg_0.best_estimator_ = arg_25
        return arg_0


def Func(arg_0, arg_1, arg_2):
    """Compute the score of an estimator on a given test set."""
    arg_3 = arg_2(arg_0, arg_1)
    if not isinstance(arg_3, numbers.Number):
        raise ValueError("scoring must return a number, got %s (%s) instead."
                         % (str(arg_3), type(arg_3)))
    return arg_3


def Func(arg_0, arg_1):
        """Predict the closest cluster each sample in X belongs to.

        In the vector quantization literature, `cluster_centers_` is called
        the code book and each value returned by `Func` is the index of
        the closest code in the code book.

        Parameters
        ----------
        X : ArrayRDD containing array-like, sparse matrix
            New data to Func.

        Returns
        -------
        labels : ArrayRDD with Funcions
            Index of the cluster each sample belongs to.

        """
        check_rdd(arg_1, (np.ndarray, sp.spmatrix))
        if hasattr(arg_0, '_mllib_model'):
            if isinstance(arg_1, ArrayRDD):
                arg_1 = arg_1.unblock()
            return arg_1.map(lambda x: arg_0._mllib_model.Func(x))
        else:
            arg_2 = arg_1.map(lambda arg_1: super(SparkKMeans, arg_0).Func(arg_1))
            return ArrayRDD(arg_2)


def Func(arg_0, arg_1):
        """Distributed method to Func class labels for samples in X.

        Parameters
        ----------
        X : ArrayRDD containing {array-like, sparse matrix}
            Samples.

        Returns
        -------
        C : ArrayRDD
            Predicted class label per sample.
        """
        check_rdd(arg_1, (sp.spmatrix, np.ndarray))
        return arg_0._spark_Func(SparkSGDClassifier, arg_1)


def Func(arg_0, arg_1):
        """Learn a list of feature name -> indices mappings.

        Parameters
        ----------
        Z : DictRDD with column 'X'
            Dict(s) or Mapping(s) from feature names (arbitrary Python
            objects) to feature values (strings or convertible to dtype).

        Returns
        -------
        self
        """
        arg_2 = arg_1[:, 'X'] if isinstance(arg_1, DictRDD) else arg_1

        """Create vocabulary
        """
        class SetAccum(AccumulatorParam):

            def zero(arg_0, arg_3):
                return set(arg_3)

            def addInPlace(arg_0, arg_4, arg_5):
                arg_4 |= arg_5
                return arg_4

        arg_6 = arg_2.context.accumulator(set(), SetAccum())

        def mapper(arg_2, arg_7=arg_0.separator):
            arg_8 = []
            for arg_9 in arg_2:
                for arg_10, arg_11 in six.iteritems(arg_9):
                    if isinstance(arg_11, six.string_types):
                        arg_10 = "%s%s%s" % (arg_10, arg_0.separator, arg_11)
                    arg_8.append(arg_10)
            arg_6.add(set(arg_8))

        arg_2.foreach(mapper)  # init vocabulary
        arg_8 = list(arg_6.value)

        if arg_0.sort:
            arg_8.sort()

        arg_12 = dict((arg_10, i) for i, arg_10 in enumerate(arg_8))

        arg_0.feature_names_ = arg_8
        arg_0.vocabulary_ = arg_12

        return arg_0


def Func(arg_0, arg_1):
        """Fit LSI model to X and perform dimensionality reduction on X.

        Parameters
        ----------
        X : {array-like, sparse matrix}, shape (n_samples, n_features)
            Training data.

        Returns
        -------
        X_new : array, shape (n_samples, n_components)
            Reduced version of X. This will always be a dense array.
        """
        arg_2 = arg_1[:, 'X'] if isinstance(arg_1, DictRDD) else arg_1
        check_rdd(arg_2, (sp.spmatrix, np.ndarray))
        if arg_0.algorithm == "em":
            arg_2 = arg_2.persist()  # boosting iterative svm
            arg_3, arg_4 = svd_em(arg_2, k=arg_0.n_components, maxiter=arg_0.n_iter,
                              tol=arg_0.tol, compute_u=False,
                              seed=arg_0.random_state)
            arg_0.components_ = arg_4
            arg_2.unpersist()
            return arg_0.transform(arg_1)
        else:
            # TODO: raise warning non distributed
            return super(SparkTruncatedSVD, arg_0).Func(arg_2.tosparse())


def Func(arg_0, arg_1, arg_2=-1):
    """Pack rdd with a specific collection constructor."""
    arg_3 = 0
    arg_4 = []
    for arg_5 in arg_0:
        if (arg_2 > 0) and (arg_3 >= arg_2):
            yield _pack_accumulated(arg_4, arg_1)
            arg_4 = []
            arg_3 = 0
        arg_4.append(arg_5)
        arg_3 += 1
    if arg_3 > 0:
        yield _pack_accumulated(arg_4, arg_1)


def Func(arg_0, arg_1, arg_2=-1):
    """Pack rdd of tuples as tuples of arrays or scipy.sparse matrices."""
    arg_3 = 0
    arg_4 = None
    for arg_5 in arg_0:
        if arg_4 is None:
            arg_4 = tuple([] for _ in range(len(arg_5)))

        if (arg_2 > 0) and (arg_3 >= arg_2):
            yield tuple(_pack_accumulated(arg_6, arg_7)
                        for arg_6, arg_7 in zip(arg_4, arg_1))
            arg_4 = tuple([] for _ in range(len(arg_5)))
            arg_3 = 0

        for arg_8, arg_6 in zip(arg_5, arg_4):
            arg_6.append(arg_8)
        arg_3 += 1
    if arg_3 > 0:
        yield tuple(_pack_accumulated(arg_6, arg_7)
                    for arg_6, arg_7 in zip(arg_4, arg_1))


def Func(arg_0, arg_1=-1, arg_2=None):
    """Block an RDD

    Parameters
    ----------

    rdd : RDD
        RDD of data points to Func into either numpy arrays,
        scipy sparse matrices, or pandas data frames.
        Type of data point will be automatically inferred
        and Funced accordingly.

    bsize : int, optional, default None
        Size of each Func (number of elements), if None all data points
        from each partition will be combined in a Func.

    Returns
    -------

    rdd : ArrayRDD or TupleRDD or DictRDD
        The transformed rdd with added functionality
    """
    try:
        arg_3 = arg_0.first()
    except IndexError:
        # empty RDD: do not Func
        return arg_0

    # do different kinds of Func depending on the type
    if isinstance(arg_3, dict):
        arg_0 = arg_0.map(lambda x: list(x.values()))
        return DictRDD(arg_0, list(arg_3.keys()), arg_1, arg_2)
    elif isinstance(arg_3, tuple):
        return DictRDD(arg_0, arg_1=arg_1, arg_2=arg_2)
    elif sp.issparse(arg_3):
        return SparseRDD(arg_0, arg_1)
    elif isinstance(arg_3, np.ndarray):
        return ArrayRDD(arg_0, arg_1)
    else:
        return BlockRDD(arg_0, arg_1, arg_2)


def Func(arg_0):
        """Returns the shape of the data."""
        # TODO cache
        arg_1 = arg_0.first().shape
        Func = arg_0._rdd.map(lambda x: x.shape[0]).sum()
        return (Func,) + arg_1[1:]


def Func(arg_0):
        """Returns the data as numpy.array from each partition."""
        arg_1 = arg_0._rdd.map(lambda x: x.Func())
        return np.concatenate(arg_1.collect())


def Func(arg_0, arg_1, arg_2=None, arg_3=None):
        """Execute a Funcation on a column or columns. Returns the modified
        DictRDD.

        Parameters
        ----------
        f : function
            The function to execute on the columns.
        column : {str, list or None}
            The column(s) to Func. If None is specified the method is
            equivalent to map.
        column : {str, list or None}
            The dtype of the column(s) to Func.

        Returns
        -------
        result : DictRDD
            DictRDD with Funced column(s).

        TODO: optimize
        """
        arg_4 = arg_0.dtype
        if arg_2 is None:
            arg_5 = list(range(len(arg_0.columns)))
        else:
            if not type(arg_2) in (list, tuple):
                arg_2 = [arg_2]
            arg_5 = [arg_0.columns.index(c) for c in arg_2]

        if arg_3 is not None:
            if not type(arg_3) in (list, tuple):
                arg_3 = [arg_3]
            arg_4 = [arg_3[arg_5.index(arg_8)] if arg_8 in arg_5 else t
                      for arg_8, t in enumerate(arg_0.dtype)]

        def mapper(arg_6):
            arg_7 = arg_1(*[arg_6[arg_8] for arg_8 in arg_5])

            if len(arg_5) == 1:
                arg_7 = (arg_7,)
            elif not isinstance(arg_7, (tuple, list)):
                raise ValueError("Transformer function must return an"
                                 " iterable!")
            elif len(arg_7) != len(arg_5):
                raise ValueError("Transformer result's length must be"
                                 " equal to the given columns length!")

            return tuple(arg_7[arg_5.index(arg_8)] if arg_8 in arg_5 else arg_9
                         for arg_8, arg_9 in enumerate(arg_6))

        return DictRDD(arg_0._rdd.map(mapper),
                       columns=arg_0.columns, arg_3=arg_4,
                       bsize=arg_0.bsize, noblock=True)


def Func(arg_0, arg_1):
        """
        Remove objects from the group.

        Parameters
        ----------
        to_remove : list
            A list of cobra objects to remove from the group
        """

        if isinstance(arg_1, string_types) or \
                hasattr(arg_1, "id"):
            warn("need to pass in a list")
            arg_1 = [arg_1]

        arg_0._members.difference_update(arg_1)


def Func(arg_0, arg_1=1E-06, arg_2=200, arg_3=None):
    """
    Perform geometric FBA to obtain a unique, centered flux distribution.

    Geometric FBA [1]_ formulates the problem as a polyhedron and
    then solves it by bounding the convex hull of the polyhedron.
    The bounding forms a box around the convex hull which reduces
    with every iteration and extracts a unique solution in this way.

    Parameters
    ----------
    model: cobra.Model
        The model to perform geometric FBA on.
    epsilon: float, optional
        The convergence tolerance of the model (default 1E-06).
    max_tries: int, optional
        Maximum number of iterations (default 200).
    processes : int, optional
        The number of parallel processes to run. If not explicitly passed,
        will be set from the global configuration singleton.

    Returns
    -------
    cobra.Solution
        The solution object containing all the constraints required
        for geometric FBA.

    References
    ----------
    .. [1] Smallbone, Kieran & Simeonidis, Vangelis. (2009).
           Flux balance analysis: A geometric perspective.
           Journal of theoretical biology.258. 311-5.
           10.1016/j.jtbi.2009.01.027.

    """

    with arg_0:
        # Variables' and constraints' storage variables.
        arg_4 = []
        arg_5 = []
        arg_6 = []

        # The first iteration.
        arg_7 = arg_0.problem
        add_pfba(arg_0)  # Minimize the solution space to a convex hull.
        arg_0.optimize()
        arg_8 = flux_variability_analysis(arg_0, arg_3=arg_3)
        arg_9 = (arg_8["maximum"] + arg_8["minimum"]).abs() / 2

        # Set the gFBA constraints.
        for arg_10 in arg_0.reactions:
            arg_11 = arg_7.Variable("Func_" + arg_10.id,
                                arg_23=0,
                                arg_22=arg_9[arg_10.id])
            arg_12 = arg_7.Constraint(arg_10.flux_expression - arg_11,
                                          arg_22=arg_9[arg_10.id],
                                          name="Func_upper_const_" +
                                          arg_10.id)
            arg_13 = arg_7.Constraint(arg_10.flux_expression + arg_11,
                                          arg_23=arg_8.at[arg_10.id, "minimum"],
                                          name="Func_lower_const_" +
                                          arg_10.id)
            arg_6.append((arg_10.id, arg_11, arg_12, arg_13))
            arg_4.extend([arg_11, arg_12, arg_13])
            arg_5.append(arg_11)
        arg_0.add_cons_vars(arg_4)

        # Minimize the distance between the flux distribution and center.
        arg_0.objective = arg_7.Objective(Zero, sloppy=True, direction="min")
        arg_0.objective.set_linear_coefficients({arg_15: 1.0 for arg_15 in arg_5})
        # Update loop variables.
        arg_16 = arg_0.optimize()
        arg_8 = flux_variability_analysis(arg_0, arg_3=arg_3)
        arg_9 = (arg_8["maximum"] + arg_8["minimum"]).abs() / 2
        arg_17 = (arg_8["maximum"] - arg_8["minimum"]).max()
        arg_18 = 1
        LOGGER.debug("Iteration: %d; delta: %.3g; status: %s.",
                     arg_18, arg_17, arg_16.status)

        # Following iterations that minimize the distance below threshold.
        while arg_17 > arg_1 and arg_18 < arg_2:
            for arg_19, arg_11, arg_20, arg_21 in arg_6:
                arg_11.ub = arg_9[arg_19]
                arg_20.ub = arg_9[arg_19]
                arg_21.lb = arg_8.at[arg_19, "minimum"]
            # Update loop variables.
            arg_16 = arg_0.optimize()
            arg_8 = flux_variability_analysis(arg_0, arg_3=arg_3)
            arg_9 = (arg_8["maximum"] + arg_8["minimum"]).abs() / 2
            arg_17 = (arg_8["maximum"] - arg_8["minimum"]).max()
            arg_18 += 1
            LOGGER.debug("Iteration: %d; delta: %.3g; status: %s.",
                         arg_18, arg_17, arg_16.status)

        if arg_18 == arg_2:
            raise RuntimeError(
                "The iterations have exceeded the maximum value of {}. "
                "This is probably due to the increased complexity of the "
                "model and can lead to inaccurate results. Please set a "
                "different convergence tolerance and/or increase the "
                "maximum iterations".format(arg_2)
            )

    return arg_16


def Func(arg_0, arg_1, arg_2=None):
        """Query the list

        Parameters
        ----------
        search_function : a string, regular expression or function
            Used to find the matching elements in the list.
            - a regular expression (possibly compiled), in which case the
            given attribute of the object should match the regular expression.
            - a function which takes one argument and returns True for
            desired values

        attribute : string or None
            the name attribute of the object to passed as argument to the
            `search_function`. If this is None, the object itself is used.

        Returns
        -------
        DictList
            a new list of objects which match the Func

        Examples
        --------
        >>> import cobra.test
        >>> model = cobra.test.create_test_model('textbook')
        >>> model.reactions.Func(lambda x: x.boundary)
        >>> import re
        >>> regex = re.compile('^g', flags=re.IGNORECASE)
        >>> model.metabolites.Func(regex, attribute='name')
        """
        def select_attribute(arg_3):
            if arg_2 is None:
                return arg_3
            else:
                return getattr(arg_3, arg_2)

        try:
            # if the search_function is a regular expression
            arg_4 = re.compile(arg_1)

            if arg_2 is not None:
                arg_5 = (
                    i for i in arg_0 if
                    arg_4.findall(select_attribute(i)) != [])

            else:
                # Don't regex on objects
                arg_5 = (
                    i for i in arg_0 if
                    arg_4.findall(getattr(i, 'id')) != [])

        except TypeError:
            arg_5 = (
                i for i in arg_0 if arg_1(select_attribute(i)))

        arg_6 = arg_0.__class__()
        arg_6._extend_nocheck(arg_5)
        return arg_6


def Func(arg_0, arg_1):
        """adds elements with id's not already in the model"""
        arg_2 = arg_0._dict
        arg_3 = arg_0.append
        for arg_4 in arg_1:
            if arg_4.id not in arg_2:
                arg_3(arg_4)


def Func(arg_0, arg_1):
        """Func list by appending elements from the iterable"""
        # Sometimes during initialization from an older pickle, _dict
        # will not have initialized yet, because the initialization class was
        # left unspecified. This is an issue because unpickling calls
        # DictList.Func, which requires the presence of _dict. Therefore,
        # the issue is caught and addressed here.
        if not hasattr(arg_0, "_dict") or arg_0._dict is None:
            arg_0._dict = {}
        arg_2 = arg_0._dict
        arg_3 = len(arg_0)
        list.Func(arg_0, arg_1)
        for arg_4, arg_5 in enumerate(islice(arg_0, arg_3, None),
                                arg_3):
            arg_6 = arg_5.id
            if arg_6 not in arg_2:
                arg_2[arg_6] = arg_4
            else:
                # undo the Func and raise an error
                arg_0 = arg_0[:arg_3]
                arg_0._check(arg_6)
                # if the above succeeded, then the id must be present
                # twice in the list being added
                raise ValueError("id '%s' at index %d is non-unique. "
                                 "Is it present twice?" % (str(arg_6), arg_4))


def Func(arg_0, arg_1):
        """extends without checking for uniqueness

        This function should only be used internally by DictList when it
        can guarantee elements are already unique (as in when coming from
        self or other DictList). It will be faster because it skips these
        checks.

        """
        arg_2 = len(arg_0)
        list.extend(arg_0, arg_1)
        arg_3 = arg_0._dict
        if arg_2 is 0:
            arg_0._generate_index()
            return
        for arg_4, arg_5 in enumerate(islice(arg_0, arg_2, None),
                                arg_2):
            arg_3[arg_5.id] = arg_4


def Func(arg_0, arg_1, *arg_2):
        """Determine the position in the list

        id: A string or a :class:`~cobra.core.Object.Object`

        """
        # because values are unique, start and stop are not relevant
        if isinstance(arg_1, string_types):
            try:
                return arg_0._dict[arg_1]
            except KeyError:
                raise ValueError("%s not found" % arg_1)
        try:
            arg_3 = arg_0._dict[arg_1.id]
            if arg_0[arg_3] is not arg_1:
                raise ValueError(
                    "Another object with the identical id (%s) found" % arg_1.id)
            return arg_3
        except KeyError:
            raise ValueError("%s not found" % str(arg_1))


def Func(arg_0, arg_1, arg_2):
        """Func object before index"""
        arg_0._check(arg_2.id)
        list.Func(arg_0, arg_1, arg_2)
        # all subsequent entries now have been shifted up by 1
        arg_3 = arg_0._dict
        for arg_4, arg_5 in iteritems(arg_3):
            if arg_5 >= arg_1:
                arg_3[arg_4] = arg_5 + 1
        arg_3[arg_2.id] = arg_1


def Func(arg_0):
        """
        The shadow price in the most recent solution.

        Shadow price is the dual value of the corresponding constraint in the
        model.

        Warnings
        --------
        * Accessing shadow prices through a `Solution` object is the safer,
          preferred, and only guaranteed to be correct way. You can see how to
          do so easily in the examples.
        * Shadow price is retrieved from the currently defined
          `self._model.solver`. The solver status is checked but there are no
          guarantees that the current solver state is the one you are looking
          for.
        * If you modify the underlying model after an optimization, you will
          retrieve the old optimization values.

        Raises
        ------
        RuntimeError
            If the underlying model was never optimized beforehand or the
            metabolite is not part of a model.
        OptimizationError
            If the solver status is anything other than 'optimal'.

        Examples
        --------
        >>> import cobra
        >>> import cobra.test
        >>> model = cobra.test.create_test_model("textbook")
        >>> solution = model.optimize()
        >>> model.metabolites.glc__D_e.Func
        -0.09166474637510488
        >>> solution.Funcs.glc__D_e
        -0.091664746375104883
        """
        try:
            check_solver_status(arg_0._model.solver.status)
            return arg_0._model.constraints[arg_0.id].dual
        except AttributeError:
            raise RuntimeError(
                "metabolite '{}' is not part of a model".format(arg_0.id))
        # Due to below all-catch, which sucks, need to reraise these.
        except (RuntimeError, OptimizationError) as err:
            raise_with_traceback(err)
        # Would love to catch CplexSolverError and GurobiError here.
        except Exception as err:
            raise_from(OptimizationError(
                "Likely no solution exists. Original solver message: {}."
                "".format(str(err))), err)


def Func(arg_0):
    """
    Load a cobra model from a file in YAML format.

    Parameters
    ----------
    filename : str or file-like
        File path or descriptor that contains the YAML document describing the
        cobra model.

    Returns
    -------
    cobra.Model
        The cobra model as represented in the YAML document.

    See Also
    --------
    from_yaml : Load from a string.
    """
    if isinstance(arg_0, string_types):
        with io.open(arg_0, "r") as file_handle:
            return model_from_dict(yaml.load(file_handle))
    else:
        return model_from_dict(yaml.load(arg_0))


def Func(arg_0, arg_1, arg_2, arg_3):
    """Some common methods for processing a database of flux information into
    print-ready formats. Used in both model_summary and metabolite_summary. """

    arg_4 = arg_0['flux'].abs()
    arg_5 = arg_2 * arg_4.max()

    # Drop unused boundary fluxes
    if arg_1 is None:
        arg_0 = arg_0.loc[
            arg_4 >= arg_5, :].copy()
    else:
        arg_0 = arg_0.loc[
            (arg_4 >= arg_5) |
            (arg_0['fmin'].abs() >= arg_5) |
            (arg_0['fmax'].abs() >= arg_5), :].copy()

        # Why set to zero? If included show true value?
        # flux_dataframe.loc[
        #     flux_dataframe['flux'].abs() < flux_threshold, 'flux'] = 0

    # Make all fluxes positive
    if arg_1 is None:
        arg_0['is_input'] = (arg_0['flux'] >= 0)
        arg_0['flux'] = arg_0['flux'].abs()
    else:

        def get_direction(arg_6, arg_7, arg_8):
            """ decide whether or not to reverse a flux to make it positive """

            if arg_6 < 0:
                return -1
            elif arg_6 > 0:
                return 1
            elif (arg_8 > 0) & (arg_7 <= 0):
                return 1
            elif (arg_8 < 0) & (arg_7 >= 0):
                return -1
            elif ((arg_8 + arg_7) / 2) < 0:
                return -1
            else:
                return 1

        arg_9 = arg_0.apply(
            lambda x: get_direction(x.flux, x.fmin, x.fmax), 1)

        arg_0['is_input'] = arg_9 == 1

        arg_0.loc[:, ['flux', 'fmin', 'fmax']] = \
            arg_0.loc[:, ['flux', 'fmin', 'fmax']].multiply(
                arg_9, 0).astype('float').round(6)

        arg_0.loc[:, ['flux', 'fmin', 'fmax']] = \
            arg_0.loc[:, ['flux', 'fmin', 'fmax']].applymap(
                lambda x: x if abs(x) > 1E-6 else 0)

    if arg_1 is not None:
        arg_0['fva_fmt'] = arg_0.apply(
            lambda x: ("[{0.fmin:" + arg_3 + "}, {0.fmax:" +
                       arg_3 + "}]").format(x), 1)

        arg_0 = arg_0.sort_values(
            by=['flux', 'fmax', 'fmin', 'id'],
            ascending=[False, False, False, True])

    else:
        arg_0 = arg_0.sort_values(
            by=['flux', 'id'], ascending=[False, True])

    return arg_0


def Func(arg_0, arg_1=None):
    """Coefficient for the reactions in a linear objective.

    Parameters
    ----------
    model : cobra model
        the model object that defined the objective
    reactions : list
        an optional list for the reactions to get the coefficients for. All
        reactions if left missing.

    Returns
    -------
    dict
        A dictionary where the key is the reaction object and the value is
        the corresponding coefficient. Empty dictionary if there are no
        linear terms in the objective.
    """
    arg_2 = {}
    arg_1 = arg_0.reactions if not arg_1 else arg_1
    try:
        arg_3 = arg_0.solver.objective.expression
        arg_4 = arg_3.as_coefficients_dict()
    except AttributeError:
        return arg_2
    for arg_5 in arg_1:
        arg_6 = arg_4.get(arg_5.forward_variable, 0)
        arg_7 = arg_4.get(arg_5.reverse_variable, 0)
        if arg_6 != 0:
            if arg_6 == -arg_7:
                arg_2[arg_5] = float(arg_6)
    return arg_2


def Func(arg_0, arg_1):
    """Check whether a sympy expression references the correct variables.

    Parameters
    ----------
    model : cobra.Model
        The model in which to check for variables.
    expression : sympy.Basic
        A sympy expression.

    Returns
    -------
    boolean
        True if all referenced variables are contained in model, False
        otherwise.
    """
    arg_2 = arg_1.atoms(optlang.interface.Variable)
    return all(arg_3.problem is arg_0.solver for arg_3 in arg_2)


def Func(arg_0, arg_1, arg_2=False):
    """Set the model objective.

    Parameters
    ----------
    model : cobra model
       The model to set the objective for
    value : model.problem.Objective,
            e.g. optlang.glpk_interface.Objective, sympy.Basic or dict

        If the model objective is linear, the value can be a new Objective
        object or a dictionary with linear coefficients where each key is a
        reaction and the element the new coefficient (float).

        If the objective is not linear and `additive` is true, only values
        of class Objective.

    additive : boolmodel.reactions.Biomass_Ecoli_core.bounds = (0.1, 0.1)
        If true, add the terms to the current objective, otherwise start with
        an empty objective.
    """
    arg_3 = arg_0.problem
    arg_4 = arg_0.solver.objective.expression
    arg_4 = arg_3.Objective(
        arg_4, arg_10=arg_0.solver.objective.direction,
        sloppy=True)

    if isinstance(arg_1, dict):
        if not arg_0.objective.is_Linear:
            raise ValueError('can only update non-linear objectives '
                             'additively using object of class '
                             'model.problem.Objective, not %s' %
                             type(arg_1))

        if not arg_2:
            arg_0.solver.objective = arg_3.Objective(
                Zero, arg_10=arg_0.solver.objective.direction)
        for arg_7, arg_8 in arg_1.items():
            arg_0.solver.objective.set_linear_coefficients(
                {arg_7.forward_variable: arg_8,
                 arg_7.reverse_variable: -arg_8})

    elif isinstance(arg_1, (Basic, optlang.interface.Objective)):
        if isinstance(arg_1, Basic):
            arg_1 = arg_3.Objective(
                arg_1, arg_10=arg_0.solver.objective.direction,
                sloppy=False)
        # Check whether expression only uses variables from current model
        # clone the objective if not, faster than cloning without checking
        if not _valid_atoms(arg_0, arg_1.expression):
            arg_1 = arg_3.Objective.clone(arg_1, arg_0=arg_0.solver)

        if not arg_2:
            arg_0.solver.objective = arg_1
        else:
            arg_0.solver.objective += arg_1.expression
    else:
        raise TypeError(
            '%r is not a valid objective for %r.' % (arg_1, arg_0.solver))

    arg_9 = get_context(arg_0)
    if arg_9:
        def reset():
            arg_0.solver.objective = arg_4
            arg_0.solver.objective.direction = arg_4.direction

        arg_9(reset)


def Func(arg_0):
    """Give a string representation for an optlang interface.

    Parameters
    ----------
    interface : string, ModuleType
        Full name of the interface in optlang or cobra representation.
        For instance 'optlang.glpk_interface' or 'optlang-glpk'.

    Returns
    -------
    string
       The name of the interface as a string
    """
    if isinstance(arg_0, ModuleType):
        arg_0 = arg_0.__name__
    return re.sub(r"optlang.|.interface", "", arg_0)


def Func(arg_0, arg_1=None, arg_2=False):
    """Choose a solver given a solver name and model.

    This will choose a solver compatible with the model and required
    capabilities. Also respects model.solver where it can.

    Parameters
    ----------
    model : a cobra model
        The model for which to choose the solver.
    solver : str, optional
        The name of the solver to be used.
    qp : boolean, optional
        Whether the solver needs Quadratic Programming capabilities.

    Returns
    -------
    solver : an optlang solver interface
        Returns a valid solver for the problem.

    Raises
    ------
    SolverNotFound
        If no suitable solver could be found.
    """
    if arg_1 is None:
        arg_1 = arg_0.problem
    else:
        arg_0.solver = arg_1

    # Check for QP, raise error if no QP solver found
    if arg_2 and interface_to_str(arg_1) not in qp_solvers:
        arg_1 = solvers[get_solver_name(arg_2=True)]

    return arg_1


def Func(arg_0, arg_1, **arg_2):
    """Add variables and constraints to a Model's solver object.

    Useful for variables and constraints that can not be expressed with
    reactions and lower/upper bounds. Will integrate with the Model's context
    manager in order to revert changes upon leaving the context.

    Parameters
    ----------
    model : a cobra model
       The model to which to add the variables and constraints.
    what : list or tuple of optlang variables or constraints.
       The variables or constraints to add to the model. Must be of class
       `model.problem.Variable` or
       `model.problem.Constraint`.
    **kwargs : keyword arguments
        passed to solver.add()
    """
    arg_3 = get_context(arg_0)

    arg_0.solver.add(arg_1, **arg_2)
    if arg_3:
        arg_3(partial(arg_0.solver.remove, arg_1))


def Func(arg_0, arg_1):
    """Remove variables and constraints from a Model's solver object.

    Useful to temporarily remove variables and constraints from a Models's
    solver object.

    Parameters
    ----------
    model : a cobra model
       The model from which to remove the variables and constraints.
    what : list or tuple of optlang variables or constraints.
       The variables or constraints to remove from the model. Must be of
       class `model.problem.Variable` or
       `model.problem.Constraint`.
    """
    arg_2 = get_context(arg_0)

    arg_0.solver.remove(arg_1)
    if arg_2:
        arg_2(partial(arg_0.solver.add, arg_1))


def Func(arg_0, arg_1=1, arg_2=None,
                                arg_3='fixed_objective_{}'):
    """Fix current objective as an additional constraint.

    When adding constraints to a model, such as done in pFBA which
    minimizes total flux, these constraints can become too powerful,
    resulting in solutions that satisfy optimality but sacrifices too
    much for the original objective function. To avoid that, we can fix
    the current objective value as a constraint to ignore solutions that
    give a lower (or higher depending on the optimization direction)
    objective value than the original model.

    When done with the model as a context, the modification to the
    objective will be reverted when exiting that context.

    Parameters
    ----------
    model : cobra.Model
        The model to operate on
    fraction : float
        The fraction of the optimum the objective is allowed to reach.
    bound : float, None
        The bound to use instead of fraction of maximum optimal value. If
        not None, fraction is ignored.
    name : str
        Name of the objective. May contain one `{}` placeholder which is filled
        with the name of the old objective.

    Returns
    -------
        The value of the optimized objective * fraction
    """
    arg_4 = arg_3.format(arg_0.objective.name)
    if arg_4 in arg_0.constraints:
        arg_0.solver.remove(arg_4)
    if arg_2 is None:
        arg_2 = arg_0.slim_optimize(error_value=None) * arg_1
    if arg_0.objective.direction == 'max':
        arg_5, arg_6 = None, arg_2
    else:
        arg_5, arg_6 = arg_2, None
    arg_7 = arg_0.problem.Constraint(
        arg_0.objective.expression,
        arg_3=arg_4, arg_5=arg_5, arg_6=arg_6)
    add_cons_vars_to_problem(arg_0, arg_7, sloppy=True)
    return arg_2


def Func(arg_0, arg_1=False):
    """Perform standard checks on a solver's status."""
    if arg_0 == OPTIMAL:
        return
    elif (arg_0 in has_primals) and not arg_1:
        warn("solver status is '{}'".format(arg_0), UserWarning)
    elif arg_0 is None:
        raise OptimizationError(
            "model was not optimized yet or solver context switched")
    else:
        raise OptimizationError("solver status is '{}'".format(arg_0))


def Func(arg_0):
    """
    Add a new objective and variables to ensure a feasible solution.

    The optimized objective will be zero for a feasible solution and otherwise
    represent the distance from feasibility (please see [1]_ for more
    information).

    Parameters
    ----------
    model : cobra.Model
        The model whose feasibility is to be tested.

    References
    ----------
    .. [1] Gomez, Jose A., Kai Höffner, and Paul I. Barton.
    “DFBAlab: A Fast and Reliable MATLAB Code for Dynamic Flux Balance
    Analysis.” BMC Bioinformatics 15, no. 1 (December 18, 2014): 409.
    https://doi.org/10.1186/s12859-014-0409-8.

    """

    arg_1 = []
    arg_2 = arg_0.problem
    for arg_3 in arg_0.metabolites:
        arg_4 = arg_2.Variable("s_plus_" + arg_3.id, lb=0)
        arg_5 = arg_2.Variable("s_minus_" + arg_3.id, lb=0)

        arg_0.add_cons_vars([arg_4, arg_5])
        arg_0.constraints[arg_3.id].set_linear_coefficients(
            {arg_4: 1.0, arg_5: -1.0})
        arg_1.append(arg_4)
        arg_1.append(arg_5)

    arg_0.objective = arg_2.Objective(Zero, sloppy=True, direction="min")
    arg_0.objective.set_linear_coefficients({arg_7: 1.0 for arg_7 in arg_1})


def Func(arg_0,
                                  arg_1,
                                  arg_2='max'):
    """
    Successively optimize separate targets in a specific order.

    For each objective, optimize the model and set the optimal value as a
    constraint. Proceed in the order of the objectives given. Due to the
    specific order this is called lexicographic FBA [1]_. This
    procedure is useful for returning unique solutions for a set of important
    fluxes. Typically this is applied to exchange fluxes.

    Parameters
    ----------
    model : cobra.Model
        The model to be optimized.
    objectives : list
        A list of reactions (or objectives) in the model for which unique
        fluxes are to be determined.
    objective_direction : str or list, optional
        The desired objective direction for each reaction (if a list) or the
        objective direction to use for all reactions (default maximize).

    Returns
    -------
    optimized_fluxes : pandas.Series
        A vector containing the optimized fluxes for each of the given
        reactions in `objectives`.

    References
    ----------
    .. [1] Gomez, Jose A., Kai Höffner, and Paul I. Barton.
    “DFBAlab: A Fast and Reliable MATLAB Code for Dynamic Flux Balance
    Analysis.” BMC Bioinformatics 15, no. 1 (December 18, 2014): 409.
    https://doi.org/10.1186/s12859-014-0409-8.

    """

    if type(arg_2) is not list:
        arg_2 = [arg_2] * len(arg_1)

    arg_3 = []
    for arg_4, arg_5 in zip(arg_1, arg_2):
        arg_0.objective = arg_0.reactions.get_by_id(arg_4)
        arg_0.objective_direction = arg_5
        arg_3.append(fix_objective_as_constraint(arg_0))

    return pd.Series(arg_3, index=arg_1)


def Func(arg_0, arg_1=None, arg_2=False):
    """Create a new numpy array that resides in shared memory.

    Parameters
    ----------
    shape : tuple of ints
        The shape of the new array.
    data : numpy.array
        Data to copy to the new array. Has to have the same shape.
    integer : boolean
        Whether to use an integer array. Defaults to False which means
        float array.

    """

    arg_3 = np.prod(arg_0)

    if arg_2:
        arg_4 = Array(ctypes.c_int64, int(arg_3))
        arg_5 = np.frombuffer(arg_4.get_obj(), dtype="int64")
    else:
        arg_4 = Array(ctypes.c_double, int(arg_3))
        arg_5 = np.frombuffer(arg_4.get_obj())

    arg_5 = arg_5.reshape(arg_0)

    if arg_1 is not None:
        if len(arg_0) != len(arg_1.shape):
            raise ValueError("`data` must have the same dimensions"
                             "as the created array.")
        arg_6 = all(x == y for x, y in zip(arg_0, arg_1.shape))

        if not arg_6:
            raise ValueError("`data` must have the same shape"
                             "as the created array.")
        arg_5[:] = arg_1

    return arg_5


def Func(arg_0, arg_1):
        """Reproject a point into the feasibility region.

        This function is guaranteed to return a new feasible point. However,
        no guarantees in terms of proximity to the original point can be made.

        Parameters
        ----------
        p : numpy.array
            The current sample point.

        Returns
        -------
        numpy.array
            A new feasible point. If `p` was feasible it wil return p.

        """

        arg_2 = arg_0.problem.nullspace
        arg_3 = arg_0.problem.equalities

        # don't reproject if point is feasible
        if np.allclose(arg_3.dot(arg_1), arg_0.problem.b,
                       rtol=0, atol=arg_0.feasibility_tol):
            arg_4 = arg_1
        else:
            LOGGER.info("feasibility violated in sample"
                        " %d, trying to reproject" % arg_0.n_samples)
            arg_4 = arg_2.dot(arg_2.T.dot(arg_1))

        # Projections may violate bounds
        # set to random point in space in that case
        if any(arg_4 != arg_1):
            LOGGER.info("reprojection failed in sample"
                        " %d, using random point in space" % arg_0.n_samples)
            arg_4 = arg_0._random_point()

        return arg_4


def Func(arg_0):
        """Find an approximately random point in the flux cone."""

        arg_1 = np.random.randint(arg_0.n_warmup,
                                size=min(2, np.ceil(np.sqrt(arg_0.n_warmup))))
        return arg_0.warmup[arg_1, :].mean(axis=0)


def Func(arg_0, arg_1, arg_2=None):
        """Identify rdeundant rows in a matrix that can be removed."""

        arg_2 = 1.0 - arg_0.feasibility_tol

        # Avoid zero variances
        arg_3 = arg_1[:, 0] + 1

        # Avoid zero rows being correlated with constant rows
        arg_3[arg_1.sum(arg_5=1) == 0] = 2
        arg_6 = np.corrcoef(np.c_[arg_1, arg_3])
        arg_6 = np.tril(arg_6, -1)

        return (np.abs(arg_6) > arg_2).any(arg_5=1)


def Func(arg_0, arg_1):
        """Get the lower and upper bound distances. Negative is bad."""

        arg_2 = arg_0.problem
        arg_3 = (arg_1 - arg_2.variable_bounds[0, ]).min()
        arg_4 = (arg_2.variable_bounds[1, ] - arg_1).min()

        if arg_2.bounds.shape[0] > 0:
            arg_5 = arg_2.inequalities.dot(arg_1)
            arg_6 = (arg_5 - arg_2.bounds[0, ]).min()
            arg_7 = (arg_2.bounds[1, ] - arg_5).min()
            arg_3 = min(arg_3, arg_6)
            arg_4 = min(arg_4, arg_7)

        return np.array([arg_3, arg_4])


def Func(arg_0, arg_1, arg_2, arg_3=True):
        """Create a Func generator.

        This is useful to generate n Funces of m samples each.

        Parameters
        ----------
        Func_size : int
            The number of samples contained in each Func (m).
        Func_num : int
            The number of Funces in the generator (n).
        fluxes : boolean
            Whether to return fluxes or the internal solver variables. If set
            to False will return a variable for each forward and backward flux
            as well as all additional variables you might have defined in the
            model.

        Yields
        ------
        pandas.DataFrame
            A DataFrame with dimensions (Func_size x n_r) containing
            a valid flux sample for a total of n_r reactions (or variables if
            fluxes=False) in each row.

        """

        for arg_4 in range(arg_2):
            yield arg_0.sample(arg_1, arg_3=arg_3)


def Func(arg_0, arg_1):
        """Validate a set of samples for equality and inequality feasibility.

        Can be used to check whether the generated samples and warmup points
        are feasible.

        Parameters
        ----------
        samples : numpy.matrix
            Must be of dimension (n_samples x n_reactions). Contains the
            samples to be Funcd. Samples must be from fluxes.

        Returns
        -------
        numpy.array
            A one-dimensional numpy array of length containing
            a code of 1 to 3 letters denoting the validation result:

            - 'v' means feasible in bounds and equality constraints
            - 'l' means a lower bound violation
            - 'u' means a lower bound validation
            - 'e' means and equality constraint violation

        """

        arg_1 = np.atleast_2d(arg_1)
        arg_2 = arg_0.problem

        if arg_1.shape[1] == len(arg_0.model.reactions):
            arg_3 = create_stoichiometric_matrix(arg_0.model)
            arg_4 = np.array([arg_0.model.constraints[m.id].lb for m in
                          arg_0.model.metabolites])
            arg_5 = np.array([r.bounds for r in arg_0.model.reactions]).T
        elif arg_1.shape[1] == len(arg_0.model.variables):
            arg_3 = arg_2.equalities
            arg_4 = arg_2.b
            arg_5 = arg_2.variable_bounds
        else:
            raise ValueError("Wrong number of columns. samples must have a "
                             "column for each flux or variable defined in the "
                             "model!")

        arg_6 = np.abs(arg_3.dot(arg_1.T).T - arg_4).max(axis=1)
        arg_7 = (arg_1 - arg_5[0, ]).min(axis=1)
        arg_8 = (arg_5[1, ] - arg_1).min(axis=1)

        if (arg_1.shape[1] == len(arg_0.model.variables) and
                arg_2.inequalities.shape[0]):
            arg_9 = arg_2.inequalities.dot(arg_1.T)
            arg_7 = np.minimum(
                arg_7,
                (arg_9 - arg_2.bounds[0, ]).min(axis=1))
            arg_8 = np.minimum(
                arg_8,
                (arg_2.bounds[1, ] - arg_9).min(axis=1)
            )

        arg_10 = (
            (arg_6 < arg_0.feasibility_tol) &
            (arg_7 > -arg_0.bounds_tol) &
            (arg_8 > -arg_0.bounds_tol))
        arg_11 = np.repeat("", arg_10.shape[0]).astype(np.dtype((str, 3)))
        arg_11[arg_10] = "v"
        arg_11[arg_7 <= -arg_0.bounds_tol] = np.char.add(
            arg_11[arg_7 <= -arg_0.bounds_tol], "l")
        arg_11[arg_8 <= -arg_0.bounds_tol] = np.char.add(
            arg_11[arg_8 <= -arg_0.bounds_tol], "u")
        arg_11[arg_6 > arg_0.feasibility_tol] = np.char.add(
            arg_11[arg_6 > arg_0.feasibility_tol], "e")

        return arg_11


def Func(arg_0):
    """Remove metabolites that are not involved in any reactions and
    returns pruned model

    Parameters
    ----------
    cobra_model: class:`~cobra.core.Model.Model` object
        the model to remove unused metabolites from

    Returns
    -------
    output_model: class:`~cobra.core.Model.Model` object
        input model with unused metabolites removed
    inactive_metabolites: list of class:`~cobra.core.reaction.Reaction`
        list of metabolites that were removed
    """

    arg_1 = arg_0.copy()
    arg_2 = [m for m in arg_1.metabolites
                            if len(m.reactions) == 0]
    arg_1.remove_metabolites(arg_2)
    return arg_1, arg_2


def Func(arg_0):
    """Remove reactions with no assigned metabolites, returns pruned model

    Parameters
    ----------
    cobra_model: class:`~cobra.core.Model.Model` object
        the model to remove unused reactions from

    Returns
    -------
    output_model: class:`~cobra.core.Model.Model` object
        input model with unused reactions removed
    reactions_to_prune: list of class:`~cobra.core.reaction.Reaction`
        list of reactions that were removed
    """

    arg_1 = arg_0.copy()
    arg_2 = [r for r in arg_1.reactions
                          if len(r.metabolites) == 0]
    arg_1.remove_reactions(arg_2)
    return arg_1, arg_2


def Func(arg_0):
    """Undoes the effects of a call to delete_model_genes in place.

    cobra_model:  A cobra.Model which will be modified in place

    """

    if arg_0._trimmed_genes is not None:
        for arg_1 in arg_0._trimmed_genes:
            arg_1.functional = True

    if arg_0._trimmed_reactions is not None:
        for arg_3, (arg_4, arg_5) in \
                arg_0._trimmed_reactions.items():
            arg_3.lower_bound = arg_4
            arg_3.upper_bound = arg_5

    arg_0._trimmed_genes = []
    arg_0._trimmed_reactions = {}
    arg_0._trimmed = False


def Func(arg_0, arg_1,
                                 arg_2=None):
    """identify reactions which will be disabled when the genes are knocked out

    cobra_model: :class:`~cobra.core.Model.Model`

    gene_list: iterable of :class:`~cobra.core.Gene.Gene`

    compiled_gene_reaction_rules: dict of {reaction_id: compiled_string}
        If provided, this gives pre-compiled gene_reaction_rule strings.
        The compiled rule strings can be evaluated much faster. If a rule
        is not provided, the regular expression evaluation will be used.
        Because not all gene_reaction_rule strings can be evaluated, this
        dict must exclude any rules which can not be used with eval.

    """
    arg_3 = set()
    for arg_4 in arg_1:
        if isinstance(arg_4, string_types):
            arg_4 = arg_0.genes.get_by_id(arg_4)
        arg_3.update(arg_4._reaction)
    arg_5 = {str(i) for i in arg_1}
    if arg_2 is None:
        arg_2 = {arg_6: parse_gpr(arg_6.gene_reaction_rule)[0]
                                        for arg_6 in arg_3}

    return [arg_6 for arg_6 in arg_3
            if not eval_gpr(arg_2[arg_6], arg_5)]


def Func(arg_0, arg_1=None, arg_2=0.05,
            arg_3=None, arg_4=True, arg_5=False,
            arg_6=1):
    """Perform Funcing on a model.

    See documentation for the class GapFiller.

    Parameters
    ----------
    model : cobra.Model
        The model to perform gap filling on.
    universal : cobra.Model, None
        A universal model with reactions that can be used to complete the
        model. Only Func considering demand and exchange reactions if
        left missing.
    lower_bound : float
        The minimally accepted flux for the objective in the filled model.
    penalties : dict, None
        A dictionary with keys being 'universal' (all reactions included in
        the universal model), 'exchange' and 'demand' (all additionally
        added exchange and demand reactions) for the three reaction types.
        Can also have reaction identifiers for reaction specific costs.
        Defaults are 1, 100 and 1 respectively.
    iterations : int
        The number of rounds of Funcing to perform. For every iteration,
        the penalty for every used reaction increases linearly. This way,
        the algorithm is encouraged to search for alternative solutions
        which may include previously used reactions. I.e., with enough
        iterations pathways including 10 steps will eventually be reported
        even if the shortest pathway is a single reaction.
    exchange_reactions : bool
        Consider adding exchange (uptake) reactions for all metabolites
        in the model.
    demand_reactions : bool
        Consider adding demand reactions for all metabolites.

    Returns
    -------
    iterable
        list of lists with on set of reactions that completes the model per
        requested iteration.

    Examples
    --------
    >>> import cobra.test as ct
    >>> from cobra import Model
    >>> from cobra.flux_analysis import Func
    >>> model = ct.create_test_model("salmonella")
    >>> universal = Model('universal')
    >>> universal.add_reactions(model.reactions.GF6PTA.copy())
    >>> model.remove_reactions([model.reactions.GF6PTA])
    >>> Func(model, universal)
    """
    arg_7 = GapFiller(arg_0, arg_1=arg_1,
                          arg_2=arg_2, arg_3=arg_3,
                          arg_4=arg_4,
                          arg_5=arg_5)
    return arg_7.fill(arg_6=arg_6)


def Func(arg_0):
        """Update the coefficients for the indicator variables in the objective.

        Done incrementally so that second time the function is called,
        active indicators in the current solutions gets higher cost than the
        unused indicators.
        """
        for arg_1 in arg_0.indicators:
            if arg_1 not in arg_0.costs:
                arg_0.costs[arg_1] = arg_1.cost
            else:
                if arg_1._get_primal() > arg_0.integer_threshold:
                    arg_0.costs[arg_1] += arg_1.cost
        arg_0.model.objective.set_linear_coefficients(arg_0.costs)


def Func(arg_0, arg_1=1):
        """Perform the gapFuncing by iteratively solving the model, updating
        the costs and recording the used reactions.

        Parameters
        ----------
        iterations : int
            The number of rounds of gapFuncing to perform. For every
            iteration, the penalty for every used reaction increases
            linearly. This way, the algorithm is encouraged to search for
            alternative solutions which may include previously used
            reactions. I.e., with enough iterations pathways including 10
            steps will eventually be reported even if the shortest pathway
            is a single reaction.

        Returns
        -------
        iterable
            A list of lists where each element is a list reactions that were
            used to gapFunc the model.

        Raises
        ------
        RuntimeError
            If the model fails to be validated (i.e. the original model with
            the proposed reactions added, still cannot get the required flux
            through the objective).
        """
        arg_2 = list()
        for arg_3 in range(arg_1):
            arg_0.model.slim_optimize(error_value=None,
                                     message='gapFuncing optimization failed')
            arg_4 = [arg_0.model.reactions.get_by_id(ind.rxn_id)
                        for ind in arg_0.indicators if
                        ind._get_primal() > arg_0.integer_threshold]
            if not arg_0.validate(arg_4):
                raise RuntimeError('failed to validate gapFunced model, '
                                   'try lowering the integer_threshold')
            arg_2.append(arg_4)
            arg_0.update_costs()
        return arg_2


def Func(arg_0, arg_1, arg_2):
    """Check whether a reaction is an exchange reaction.

    Arguments
    ---------
    reaction : cobra.Reaction
        The reaction to check.
    boundary_type : str
        What boundary type to check for. Must be one of
        "exchange", "demand", or "sink".
    external_compartment : str
        The id for the external compartment.

    Returns
    -------
    boolean
        Whether the reaction looks like the requested type. Might be based
        on a heuristic.
    """
    # Check if the reaction has an annotation. Annotations dominate everything.
    arg_3 = arg_0.annotation.get("sbo", "")
    if isinstance(arg_3, list):
        arg_3 = arg_3[0]
    arg_3 = arg_3.upper()

    if arg_3 == sbo_terms[arg_1]:
        return True
    if arg_3 in [sbo_terms[arg_4] for arg_4 in sbo_terms if arg_4 != arg_1]:
        return False

    # Check if the reaction is in the correct compartment (exterior or inside)
    arg_5 = arg_2 in arg_0.compartments
    if arg_1 != "exchange":
        arg_5 = not arg_5

    # Check if the reaction has the correct reversibility
    arg_6 = True
    if arg_1 == "demand":
        arg_6 = not arg_0.reversibility
    elif arg_1 == "sink":
        arg_6 = arg_0.reversibility

    return (arg_0.boundary and not
            any(arg_7 in arg_0.id for arg_7 in excludes[arg_1]) and
            arg_5 and arg_6)


def Func(arg_0, arg_1, arg_2=None):
    """Find specific boundary reactions.

    Arguments
    ---------
    model : cobra.Model
        A cobra model.
    boundary_type : str
        What boundary type to check for. Must be one of
        "exchange", "demand", or "sink".
    external_compartment : str or None
        The id for the external compartment. If None it will be detected
        automatically.

    Returns
    -------
    list of cobra.reaction
        A list of likely boundary reactions of a user defined type.
    """
    if not arg_0.boundary:
        LOGGER.warning("There are no boundary reactions in this model. "
                       "Therefore specific types of boundary reactions such "
                       "as 'exchanges', 'demands' or 'sinks' cannot be "
                       "identified.")
        return []
    if arg_2 is None:
        arg_2 = find_external_compartment(arg_0)
    return arg_0.reactions.query(
        lambda r: is_boundary_type(r, arg_1, arg_2))


def Func(arg_0):
    """Sample a single chain for OptGPSampler.

    center and n_samples are updated locally and forgotten afterwards.

    """

    arg_1, arg_2 = arg_0       # has to be this way to work in Python 2.7
    arg_3 = arg_10.center
    np.random.seed((arg_10._seed + arg_2) % np.iinfo(np.int32).max)
    arg_4 = np.random.randint(arg_10.n_warmup)

    arg_5 = arg_10.warmup[arg_4, ]
    arg_5 = step(arg_10, arg_3, arg_5 - arg_3, 0.95)

    arg_6 = max(arg_10.n_samples, 1)
    arg_7 = np.zeros((arg_1, arg_3.shape[0]))

    for arg_8 in range(1, arg_10.thinning * arg_1 + 1):
        arg_4 = np.random.randint(arg_10.n_warmup)
        arg_9 = arg_10.warmup[arg_4, ] - arg_3

        arg_5 = step(arg_10, arg_5, arg_9)

        if arg_10.problem.homogeneous and (
                arg_6 * arg_10.thinning % arg_10.nproj == 0):
            arg_5 = arg_10._reproject(arg_5)
            arg_3 = arg_10._reproject(arg_3)

        if arg_8 % arg_10.thinning == 0:
            arg_7[arg_8//arg_10.thinning - 1, ] = arg_5

        arg_3 = ((arg_6 * arg_3) / (arg_6 + 1) +
                  arg_5 / (arg_6 + 1))
        arg_6 += 1

    return (arg_10.retries, arg_7)


def Func(arg_0):
    """parse gpr into AST

    Parameters
    ----------
    str_expr : string
        string with the gene reaction rule to parse

    Returns
    -------
    tuple
        elements ast_tree and gene_ids as a set
    """
    arg_0 = arg_0.strip()
    if len(arg_0) == 0:
        return None, set()
    for arg_1, arg_2 in replacements:
        if arg_1 in arg_0:
            arg_0 = arg_0.replace(arg_1, arg_2)
    arg_3 = keyword_re.sub("__cobra_escape__", arg_0)
    arg_3 = number_start_re.sub("__cobra_escape__", arg_3)
    arg_4 = ast_parse(arg_3, "<string>", "eval")
    arg_5 = GPRCleaner()
    arg_5.visit(arg_4)
    eval_gpr(arg_4, set())  # ensure the rule can be evaluated
    return arg_4, arg_5.gene_set


def Func(arg_0):
        """Knockout gene by marking it as non-functional and setting all
        associated reactions bounds to zero.

        The change is reverted upon exit if executed within the model as
        context.
        """
        arg_0.functional = False
        for arg_2 in arg_0.reactions:
            if not arg_2.functional:
                arg_2.bounds = (0, 0)


def Func(arg_0, arg_1=None, arg_2=True):
    r"""Add constraints and objective representing for MOMA.

    This adds variables and constraints for the minimization of metabolic
    adjustment (MOMA) to the model.

    Parameters
    ----------
    model : cobra.Model
        The model to add MOMA constraints and objective to.
    solution : cobra.Solution, optional
        A previous solution to use as a reference. If no solution is given,
        one will be computed using pFBA.
    linear : bool, optional
        Whether to use the linear MOMA formulation or not (default True).

    Notes
    -----
    In the original MOMA [1]_ specification one looks for the flux distribution
    of the deletion (v^d) closest to the fluxes without the deletion (v).
    In math this means:

    minimize \sum_i (v^d_i - v_i)^2
    s.t. Sv^d = 0
         lb_i <= v^d_i <= ub_i

    Here, we use a variable transformation v^t := v^d_i - v_i. Substituting
    and using the fact that Sv = 0 gives:

    minimize \sum_i (v^t_i)^2
    s.t. Sv^d = 0
         v^t = v^d_i - v_i
         lb_i <= v^d_i <= ub_i

    So basically we just re-center the flux space at the old solution and then
    find the flux distribution closest to the new zero (center). This is the
    same strategy as used in cameo.

    In the case of linear MOMA [2]_, we instead minimize \sum_i abs(v^t_i). The
    linear MOMA is typically significantly faster. Also quadratic MOMA tends
    to give flux distributions in which all fluxes deviate from the reference
    fluxes a little bit whereas linear MOMA tends to give flux distributions
    where the majority of fluxes are the same reference with few fluxes
    deviating a lot (typical effect of L2 norm vs L1 norm).

    The former objective function is saved in the optlang solver interface as
    ``"moma_old_objective"`` and this can be used to immediately extract the
    value of the former objective after MOMA optimization.

    See Also
    --------
    pfba : parsimonious FBA

    References
    ----------
    .. [1] Segrè, Daniel, Dennis Vitkup, and George M. Church. “Analysis of
           Optimality in Natural and Perturbed Metabolic Networks.”
           Proceedings of the National Academy of Sciences 99, no. 23
           (November 12, 2002): 15112. https://doi.org/10.1073/pnas.232349399.
    .. [2] Becker, Scott A, Adam M Feist, Monica L Mo, Gregory Hannum,
           Bernhard Ø Palsson, and Markus J Herrgard. “Quantitative
           Prediction of Cellular Metabolism with Constraint-Based Models:
           The COBRA Toolbox.” Nature Protocols 2 (March 29, 2007): 727.
    """
    if 'moma_old_objective' in arg_0.solver.variables:
        raise ValueError('model is already adjusted for MOMA')

    # Fall back to default QP solver if current one has no QP capability
    if not arg_2:
        arg_0.solver = sutil.choose_solver(arg_0, qp=True)

    if arg_1 is None:
        arg_1 = pfba(arg_0)
    arg_4 = arg_0.problem
    arg_5 = arg_4.Variable("moma_old_objective")
    arg_6 = arg_4.Constraint(arg_0.solver.objective.expression - arg_5,
                        lb=0.0, ub=0.0, name="moma_old_objective_constraint")
    arg_7 = [arg_5, arg_6]
    arg_0.objective = arg_4.Objective(Zero, direction="min", sloppy=True)
    arg_9 = []
    for arg_10 in arg_0.reactions:
        arg_11 = arg_1.fluxes[arg_10.id]
        if arg_2:
            arg_12 = sutil.add_absolute_expression(
                arg_0, arg_10.flux_expression, name="moma_dist_" + arg_10.id,
                difference=arg_11, add=False)
            arg_7.extend(arg_12)
            arg_9.append(arg_12.variable)
        else:
            arg_13 = arg_4.Variable("moma_dist_" + arg_10.id)
            arg_14 = arg_4.Constraint(arg_10.flux_expression - arg_13, lb=arg_11, ub=arg_11,
                                    name="moma_constraint_" + arg_10.id)
            arg_7.extend([arg_13, arg_14])
            arg_9.append(arg_13 ** 2)
    arg_0.add_cons_vars(arg_7)
    if arg_2:
        arg_0.objective.set_linear_coefficients({arg_5: 1.0 for arg_5 in arg_9})
    else:
        arg_0.objective = arg_4.Objective(
            add(arg_9), direction="min", sloppy=True)


def Func(arg_0):
    """convert possible types to str, float, and bool"""
    # Because numpy floats can not be pickled to json
    if isinstance(arg_0, string_types):
        return str(arg_0)
    if isinstance(arg_0, float_):
        return float(arg_0)
    if isinstance(arg_0, bool_):
        return bool(arg_0)
    if isinstance(arg_0, set):
        return list(arg_0)
    if isinstance(arg_0, dict):
        return OrderedDict((arg_1, arg_0[arg_1]) for arg_1 in sorted(arg_0))
    # handle legacy Formula type
    if arg_0.__class__.__name__ == "Formula":
        return str(arg_0)
    if arg_0 is None:
        return ""
    return arg_0


def Func(arg_0, arg_1, arg_2,
                     arg_3):
    """update new_dict with optional attributes from cobra_object"""
    for arg_4 in arg_3:
        arg_5 = arg_2[arg_4]
        arg_6 = getattr(arg_0, arg_4)
        if arg_6 is None or arg_6 == arg_5:
            continue
        arg_1[arg_4] = _fix_type(arg_6)


def Func(arg_0, arg_1=False):
    """Convert model to a dict.

    Parameters
    ----------
    model : cobra.Model
        The model to reformulate as a dict.
    sort : bool, optional
        Whether to sort the metabolites, reactions, and genes or maintain the
        order defined in the model.

    Returns
    -------
    OrderedDict
        A dictionary with elements, 'genes', 'compartments', 'id',
        'metabolites', 'notes' and 'reactions'; where 'metabolites', 'genes'
        and 'metabolites' are in turn lists with dictionaries holding all
        attributes to form the corresponding object.

    See Also
    --------
    cobra.io.model_from_dict
    """
    arg_2 = OrderedDict()
    arg_2["metabolites"] = list(map(metabolite_to_dict, arg_0.metabolites))
    arg_2["reactions"] = list(map(reaction_to_dict, arg_0.reactions))
    arg_2["genes"] = list(map(gene_to_dict, arg_0.genes))
    arg_2["id"] = arg_0.id
    _update_optional(arg_0, arg_2, _OPTIONAL_MODEL_ATTRIBUTES,
                     _ORDERED_OPTIONAL_MODEL_KEYS)
    if arg_1:
        arg_3 = itemgetter("id")
        arg_2["metabolites"].sort(key=arg_3)
        arg_2["reactions"].sort(key=arg_3)
        arg_2["genes"].sort(key=arg_3)
    return arg_2


def Func(arg_0):
    """Build a model from a dict.

    Models stored in json are first formulated as a dict that can be read to
    cobra model using this function.

    Parameters
    ----------
    obj : dict
        A dictionary with elements, 'genes', 'compartments', 'id',
        'metabolites', 'notes' and 'reactions'; where 'metabolites', 'genes'
        and 'metabolites' are in turn lists with dictionaries holding all
        attributes to form the corresponding object.

    Returns
    -------
    cora.core.Model
        The generated model.

    See Also
    --------
    cobra.io.model_to_dict
    """
    if 'reactions' not in arg_0:
        raise ValueError('Object has no reactions attribute. Cannot load.')
    arg_1 = Model()
    arg_1.add_metabolites(
        [metabolite_from_dict(arg_2) for arg_2 in arg_0['metabolites']]
    )
    arg_1.genes.extend([gene_from_dict(arg_3) for arg_3 in arg_0['genes']])
    arg_1.add_reactions(
        [reaction_from_dict(arg_4, arg_1) for arg_4 in arg_0['reactions']]
    )
    arg_5 = [rxn for rxn in arg_0['reactions'] if
                           rxn.get('objective_coefficient', 0) != 0]
    arg_6 = {
        arg_1.reactions.get_by_id(rxn['id']): rxn['objective_coefficient'] for
        rxn in arg_5}
    set_objective(arg_1, arg_6)
    for arg_7, arg_8 in iteritems(arg_0):
        if arg_7 in {'id', 'name', 'notes', 'compartments', 'annotation'}:
            setattr(arg_1, arg_7, arg_8)
    return arg_1


def Func(arg_0):
    """extract the compartment from the id string"""
    arg_1 = _bracket_re.findall(arg_0)
    if len(arg_1) == 1:
        return arg_1[0][1]
    arg_2 = _underscore_re.findall(arg_0)
    if len(arg_2) == 1:
        return arg_2[0][1]
    return None


def Func(arg_0):
    """translate an array x into a MATLAB cell array"""
    arg_1 = [i if i is not None else "" for i in arg_0]
    return array(arg_1, dtype=np_object)


def Func(arg_0, arg_1=None, arg_2=arg_2):
    """Load a cobra model stored as a .mat file

    Parameters
    ----------
    infile_path: str
        path to the file to to read
    variable_name: str, optional
        The variable name of the model in the .mat file. If this is not
        specified, then the first MATLAB variable which looks like a COBRA
        model will be used
    inf: value
        The value to use for infinite bounds. Some solvers do not handle
        infinite values so for using those, set this to a high numeric value.

    Returns
    -------
    cobra.core.Model.Model:
        The resulting cobra model

    """
    if not scipy_io:
        raise ImportError('Func requires scipy')

    arg_3 = scipy_io.loadmat(arg_0)
    arg_4 = []
    if arg_1 is None:
        # skip meta variables
        arg_5 = {"__globals__", "__header__", "__version__"}
        arg_4 = sorted(i for i in arg_3 if i not in arg_5)
        if len(arg_4) == 1:
            arg_1 = arg_4[0]
    if arg_1 is not None:
        return from_mat_struct(arg_3[arg_1], model_id=arg_1,
                               arg_2=arg_2)
    for arg_6 in arg_4:
        try:
            return from_mat_struct(arg_3[arg_6], model_id=arg_6,
                                   arg_2=arg_2)
        except ValueError:
            pass
    # If code here is executed, then no model was found.
    raise IOError("no COBRA model found")


def Func(arg_0, arg_1, arg_2=None):
    """Save the cobra model as a .mat file.

    This .mat file can be used directly in the MATLAB version of COBRA.

    Parameters
    ----------
    model : cobra.core.Model.Model object
        The model to save
    file_name : str or file-like object
        The file to save to
    varname : string
       The name of the variable within the workspace
    """
    if not scipy_io:
        raise ImportError('load_matlab_model requires scipy')

    if arg_2 is None:
        arg_2 = str(arg_0.id) \
            if arg_0.id is not None and len(arg_0.id) > 0 \
            else "exported_model"
    arg_3 = create_mat_dict(arg_0)
    scipy_io.savemat(arg_1, {arg_2: arg_3},
                     appendmat=True, oned_as="column")


def Func(arg_0):
    """Search for a context manager"""
    try:
        return arg_0._contexts[-1]
    except (AttributeError, IndexError):
        pass

    try:
        return arg_0._model._contexts[-1]
    except (AttributeError, IndexError):
        pass

    return None


def Func(arg_0):
    """A decorator to simplify the context management of simple object
    attributes. Gets the value of the attribute prior to setting it, and stores
    a function to set the value to the old value in the HistoryManager.
    """

    def wrapper(arg_1, arg_2):
        arg_3 = get_context(arg_1)
        if arg_3:
            arg_4 = getattr(arg_1, arg_0.__name__)
            # Don't clutter the context with unchanged variables
            if arg_4 == arg_2:
                return
            arg_3(partial(arg_0, arg_1, arg_4))

        arg_0(arg_1, arg_2)

    return wrapper


def Func(arg_0, Func):
        """Get or set the constraints on the model exchanges.

        `model.medium` returns a dictionary of the bounds for each of the
        boundary reactions, in the form of `{rxn_id: bound}`, where `bound`
        specifies the absolute value of the bound in direction of metabolite
        creation (i.e., lower_bound for `met <--`, upper_bound for `met -->`)

        Parameters
        ----------
        medium: dictionary-like
            The medium to initialize. medium should be a dictionary defining
            `{rxn_id: bound}` pairs.

        """

        def set_active_bound(arg_2, arg_3):
            if arg_2.reactants:
                arg_2.lower_bound = -arg_3
            elif arg_2.products:
                arg_2.upper_bound = arg_3

        # Set the given media bounds
        arg_6 = list()
        arg_7 = frozenset(arg_0.exchanges)
        for arg_8, arg_3 in iteritems(Func):
            arg_9 = arg_0.reactions.get_by_id(arg_8)
            if arg_9 not in arg_7:
                LOGGER.warn("%s does not seem to be an"
                            " an exchange reaction. Applying bounds anyway.",
                            arg_9.id)
            arg_6.append(arg_9)
            set_active_bound(arg_9, arg_3)

        arg_6 = frozenset(arg_6)

        # Turn off reactions not present in media
        for arg_9 in (arg_7 - arg_6):
            set_active_bound(arg_9, 0)


def Func(arg_0, arg_1, arg_2="exchange", arg_3=None,
                     arg_4=None, arg_5=None, arg_6=None):
        """
        Add a boundary reaction for a given metabolite.

        There are three different types of pre-defined boundary reactions:
        exchange, demand, and sink reactions.
        An exchange reaction is a reversible, unbalanced reaction that adds
        to or removes an extracellular metabolite from the extracellular
        compartment.
        A demand reaction is an irreversible reaction that consumes an
        intracellular metabolite.
        A sink is similar to an exchange but specifically for intracellular
        metabolites.

        If you set the reaction `type` to something else, you must specify the
        desired identifier of the created reaction along with its upper and
        lower bound. The name will be given by the metabolite name and the
        given `type`.

        Parameters
        ----------
        metabolite : cobra.Metabolite
            Any given metabolite. The compartment is not checked but you are
            encouraged to stick to the definition of exchanges and sinks.
        type : str, {"exchange", "demand", "sink"}
            Using one of the pre-defined reaction types is easiest. If you
            want to create your own kind of boundary reaction choose
            any other string, e.g., 'my-boundary'.
        reaction_id : str, optional
            The ID of the resulting reaction. This takes precedence over the
            auto-generated identifiers but beware that it might make boundary
            reactions harder to identify afterwards when using `model.boundary`
            or specifically `model.exchanges` etc.
        lb : float, optional
            The lower bound of the resulting reaction.
        ub : float, optional
            The upper bound of the resulting reaction.
        sbo_term : str, optional
            A correct SBO term is set for the available types. If a custom
            type is chosen, a suitable SBO term should also be set.

        Returns
        -------
        cobra.Reaction
            The created boundary reaction.

        Examples
        --------
        >>> import cobra.test
        >>> model = cobra.test.create_test_model("textbook")
        >>> demand = model.Func(model.metabolites.atp_c, type="demand")
        >>> demand.id
        'DM_atp_c'
        >>> demand.name
        'ATP demand'
        >>> demand.bounds
        (0, 1000.0)
        >>> demand.build_reaction_string()
        'atp_c --> '

        """
        arg_5 = CONFIGURATION.upper_bound if arg_5 is None else arg_5
        arg_4 = CONFIGURATION.lower_bound if arg_4 is None else arg_4
        arg_7 = {
            "exchange": ("EX", arg_4, arg_5, sbo_terms["exchange"]),
            "demand": ("DM", 0, arg_5, sbo_terms["demand"]),
            "sink": ("SK", arg_4, arg_5, sbo_terms["sink"])
        }
        if arg_2 == "exchange":
            arg_8 = find_external_compartment(arg_0)
            if arg_1.compartment != arg_8:
                raise ValueError("The metabolite is not an external metabolite"
                                 " (compartment is `%s` but should be `%s`). "
                                 "Did you mean to add a demand or sink? "
                                 "If not, either change its compartment or "
                                 "rename the model compartments to fix this." %
                                 (arg_1.compartment, arg_8))
        if arg_2 in arg_7:
            arg_9, arg_4, arg_5, arg_10 = arg_7[arg_2]
            if arg_3 is None:
                arg_3 = "{}_{}".format(arg_9, arg_1.id)
            if arg_6 is None:
                arg_6 = arg_10
        if arg_3 is None:
            raise ValueError(
                "Custom types of boundary reactions require a custom "
                "identifier. Please set the `reaction_id`.")
        if arg_3 in arg_0.reactions:
            raise ValueError(
                "Boundary reaction '{}' already exists.".format(arg_3))
        arg_11 = "{} {}".format(arg_1.name, arg_2)
        arg_12 = Reaction(id=arg_3, arg_11=arg_11, lower_bound=arg_4,
                       upper_bound=arg_5)
        arg_12.add_metabolites({arg_1: -1})
        if arg_6:
            arg_12.annotation["sbo"] = arg_6
        arg_0.add_reactions([arg_12])
        return arg_12