text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Triangular Distribution</title>
<link rel="stylesheet" href="../../../../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.77.1">
<link rel="home" href="../../../../index.html" title="Math Toolkit">
<link rel="up" href="../dists.html" title="Distributions">
<link rel="prev" href="students_t_dist.html" title="Students t Distribution">
<link rel="next" href="uniform_dist.html" title="Uniform Distribution">

Home
Libraries
People
FAQ
More

Triangular
          Distribution

#include <boost/math/distributions/triangular.hpp>

namespace boost{ namespace math{
 template <class RealType = double,
           class Policy   = policies::policy<> >
 class triangular_distribution;

 typedef triangular_distribution<> triangular;

 template <class RealType, class Policy>
 class triangular_distribution
 {
 public:
    typedef RealType value_type;
    typedef Policy   policy_type;

    triangular_distribution(RealType lower = -1, RealType mode = 0) RealType upper = 1); // Constructor.
       : m_lower(lower), m_mode(mode), m_upper(upper) // Default is -1, 0, +1 triangular distribution.
    // Accessor functions.
    RealType lower()const;
    RealType mode()const;
    RealType upper()const;
 }; // class triangular_distribution

}} // namespaces

            The triangular
            distribution is a continuous
            probability
            distribution with a lower limit a, mode
            c, and upper limit b.

            The triangular distribution is often used where the distribution is only
            vaguely known, but, like the uniform
            distribution, upper and limits are 'known', but a 'best guess',
            the mode or center point, is also added. It has been recommended as a
            proxy
            for the beta distribution. The distribution is used in business
            decision making and project planning.

            The triangular
            distribution is a distribution with the probability
            density function:

            f(x) =

                2(x-a)/(b-a) (c-a) for a <= x <= c

                2(b-x)/(b-a)(b-c) for c < x <= b

            Parameter a (lower) can be any finite value. Parameter b (upper) can
            be any finite value > a (lower). Parameter c (mode) a <= c <=
            b. This is the most probable value.

            The random variate
            x must also be finite, and is supported lower <= x <= upper.

            The triangular distribution may be appropriate when an assumption of
            a normal distribution is unjustified because uncertainty is caused by
            rounding and quantization from analog to digital conversion. Upper and
            lower limits are known, and the most probable value lies midway.

            The distribution simplifies when the 'best guess' is either the lower
            or upper limit - a 90 degree angle triangle. The default chosen is the
            001 triangular distribution which expresses an estimate that the lowest
            value is the most likely; for example, you believe that the next-day
            quoted delivery date is most likely (knowing that a quicker delivery
            is impossible - the postman only comes once a day), and that longer delays
            are decreasingly likely, and delivery is assumed to never take more than
            your upper limit.

            The following graph illustrates how the probability
            density function PDF varies with the various parameters:

            and cumulative distribution function

            Member
            Functions

triangular_distribution(RealType lower = 0, RealType mode = 0 RealType upper = 1);

            Constructs a triangular
            distribution with lower lower (a) and upper
            upper (b).

            Requires that the lower, mode
            and upper parameters are all finite, otherwise calls
            domain_error.

RealType lower()const;

            Returns the lower parameter of this distribution
            (default -1).

RealType mode()const;

            Returns the mode parameter of this distribution
            (default 0).

RealType upper()const;

            Returns the upper parameter of this distribution
            (default+1).

            Non-member
            Accessors

            All the usual non-member
            accessor functions that are generic to all distributions are supported:
            Cumulative Distribution Function,
            Probability Density Function, Quantile, Hazard
            Function, Cumulative Hazard Function,
            mean, median,
            mode, variance,
            standard deviation, skewness,
            kurtosis, kurtosis_excess,
            range and support.

            The domain of the random variable is \lowerto \upper, and the supported
            range is lower <= x <= upper.

            Accuracy

            The triangular distribution is implemented with simple arithmetic operators
            and so should have errors within an epsilon or two, except quantiles
            with arguments nearing the extremes of zero and unity.

            Implementation

            In the following table, a is the lower parameter
            of the distribution, c is the mode parameter, b
            is the upper parameter, x is
            the random variate, p is the probability and q
            = 1-p.

<colgroup>
<col>
<col>
</colgroup>

                      Function

                      Implementation Notes

                      pdf

                      Using the relation: pdf = 0 for x < mode, 2(x-a)/(b-a)(c-a)
                      else 2*(b-x)/((b-a)(b-c))

                      cdf

                      Using the relation: cdf = 0 for x < mode (x-a)2/((b-a)(c-a))
                      else 1 - (b-x)2/((b-a)(b-c))

                      cdf complement

                      Using the relation: q = 1 - p

                      quantile

                      let p0 = (c-a)/(b-a) the point of inflection on the cdf, then
                      given probability p and q = 1-p:

                      x = sqrt((b-a)(c-a)p) + a ; for p < p0

                      x = c ; for p == p0

                      x = b - sqrt((b-a)(b-c)q) ; for p > p0

                      (See /boost/math/distributions/triangular.hpp
                      for details.)

                      quantile from the complement

                      As quantile (See /boost/math/distributions/triangular.hpp
                      for details.)

                      mean

                      (a + b + 3) / 3

                      variance

                      (a2+b2+c2 - ab - ac - bc)/18

                      mode

                      c

                      skewness

                      (See /boost/math/distributions/triangular.hpp
                      for details).

                      kurtosis

                      12/5

                      kurtosis excess

                      -3/5

            Some 'known good' test values were obtained from Statlet:
            Calculate and plot probability distributions

            References

                Wikpedia
                triangular distribution

                Weisstein,
                Eric W. "Triangular Distribution." From MathWorld--A Wolfram
                Web Resource.

                Evans, M.; Hastings, N.; and Peacock, B. "Triangular Distribution."
                Ch. 40 in Statistical Distributions, 3rd ed. New York: Wiley, pp.
                187-188, 2000, ISBN - 0471371246]

                Brighton
                Webs Ltd. BW D-Calc 1.0 Distribution Calculator

                The
                Triangular Distribution including its history.

                Gejza
                Wimmer, Viktor Witkovsky and Tomas Duby, Measurement Science Review,
                Volume 2, Section 1, 2002, Proper Rounding Of The Measurement Results
                Under The Assumption Of Triangular Distribution.

Copyright © 2006-2010, 2012 John Maddock, Paul A. Bristow, Hubert Holin, Xiaogang
      Zhang, Bruno Lalande, Johan Råde, Gautam Sewani, Thijs van den Berg and Benjamin
      Sobotta

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
"""
Internal package providing a Python CRUD interface to MLflow experiments and runs.
This is a lower level API than the :py:mod:`mlflow.tracking.fluent` module, and is
exposed in the :py:mod:`mlflow.tracking` module.
"""

import os
from itertools import zip_longest

from mlflow.store.tracking import SEARCH_MAX_RESULTS_DEFAULT
from mlflow.tracking._tracking_service import utils
from mlflow.tracking.metric_value_conversion_utils import convert_metric_value_to_float_if_possible
from mlflow.utils.validation import (
    _validate_run_id,
    _validate_experiment_artifact_location,
    PARAM_VALIDATION_MSG,
)
from mlflow.entities import Param, Metric, RunStatus, RunTag, ViewType, ExperimentTag
from mlflow.exceptions import MlflowException
from mlflow.protos.databricks_pb2 import INVALID_PARAMETER_VALUE, ErrorCode
from mlflow.store.artifact.artifact_repository_registry import get_artifact_repository
from mlflow.utils import chunk_list
from mlflow.utils.mlflow_tags import MLFLOW_USER
from mlflow.utils.string_utils import is_string_type
from mlflow.utils.uri import add_databricks_profile_info_to_artifact_uri
from mlflow.utils.validation import (
    MAX_METRICS_PER_BATCH,
    MAX_PARAMS_TAGS_PER_BATCH,
    MAX_ENTITIES_PER_BATCH,
)
from mlflow.utils.time_utils import get_current_time_millis
from collections import OrderedDict

class TrackingServiceClient:
    """
    Client of an MLflow Tracking Server that creates and manages experiments and runs.
    """

    _artifact_repos_cache = OrderedDict()

    def __init__(self, tracking_uri):
        """
        :param tracking_uri: Address of local or remote tracking server.
        """
        self.tracking_uri = tracking_uri
        # NB: Fetch the tracking store (`self.store`) upon client initialization to ensure that
        # the tracking URI is valid and the store can be properly resolved. We define `store` as a
        # property method to ensure that the client is serializable, even if the store is not
        # self.store  # pylint: disable=pointless-statement
        self.store

    @property
    def store(self):
        return utils._get_store(self.tracking_uri)

    def get_run(self, run_id):
        """
        Fetch the run from backend store. The resulting :py:class:`Run <mlflow.entities.Run>`
        contains a collection of run metadata -- :py:class:`RunInfo <mlflow.entities.RunInfo>`,
        as well as a collection of run parameters, tags, and metrics --
        :py:class:`RunData <mlflow.entities.RunData>`. In the case where multiple metrics with the
        same key are logged for the run, the :py:class:`RunData <mlflow.entities.RunData>` contains
        the most recently logged value at the largest step for each metric.

        :param run_id: Unique identifier for the run.

        :return: A single :py:class:`mlflow.entities.Run` object, if the run exists. Otherwise,
                 raises an exception.
        """
        _validate_run_id(run_id)
        return self.store.get_run(run_id)

    def get_metric_history(self, run_id, key):
        """
        Return a list of metric objects corresponding to all values logged for a given metric.

        :param run_id: Unique identifier for run
        :param key: Metric name within the run

        :return: A list of :py:class:`mlflow.entities.Metric` entities if logged, else empty list
        """
        return self.store.get_metric_history(run_id=run_id, metric_key=key)

    def create_run(self, experiment_id, start_time=None, tags=None, run_name=None):
        """
        Create a :py:class:`mlflow.entities.Run` object that can be associated with
        metrics, parameters, artifacts, etc.
        Unlike :py:func:`mlflow.projects.run`, creates objects but does not run code.
        Unlike :py:func:`mlflow.start_run`, does not change the "active run" used by
        :py:func:`mlflow.log_param`.

        :param experiment_id: The ID of the experiment to create a run in.
        :param start_time: If not provided, use the current timestamp.
        :param tags: A dictionary of key-value pairs that are converted into
                     :py:class:`mlflow.entities.RunTag` objects.
        :param name: The name of this run.
        :return: :py:class:`mlflow.entities.Run` that was created.
        """

        tags = tags if tags else {}

        # Extract user from tags
        # This logic is temporary; the user_id attribute of runs is deprecated and will be removed
        # in a later release.
        user_id = tags.get(MLFLOW_USER, "unknown")

        return self.store.create_run(
            experiment_id=experiment_id,
            user_id=user_id,
            start_time=start_time or get_current_time_millis(),
            tags=[RunTag(key, value) for (key, value) in tags.items()],
            run_name=run_name,
        )

    def search_experiments(
        self,
        view_type=ViewType.ACTIVE_ONLY,
        max_results=SEARCH_MAX_RESULTS_DEFAULT,
        filter_string=None,
        order_by=None,
        page_token=None,
    ):
        """
        Search for experiments that match the specified search query.

        :param view_type: One of enum values ``ACTIVE_ONLY``, ``DELETED_ONLY``, or ``ALL``
                          defined in :py:class:`mlflow.entities.ViewType`.
        :param max_results: Maximum number of experiments desired. Certain server backend may apply
                            its own limit.
        :param filter_string:
            Filter query string (e.g., ``"name = 'my_experiment'"``), defaults to searching for all
            experiments. The following identifiers, comparators, and logical operators are
            supported.

            Identifiers
              - ``name``: Experiment name
              - ``creation_time``: Experiment creation time
              - ``last_update_time``: Experiment last update time
              - ``tags.<tag_key>``: Experiment tag. If ``tag_key`` contains
                spaces, it must be wrapped with backticks (e.g., ``"tags.`extra key`"``).

            Comparators for string attributes and tags
              - ``=``: Equal to
              - ``!=``: Not equal to
              - ``LIKE``: Case-sensitive pattern match
              - ``ILIKE``: Case-insensitive pattern match

            Comparators for numeric attributes
              - ``=``: Equal to
              - ``!=``: Not equal to
              - ``<``: Less than
              - ``<=``: Less than or equal to
              - ``>``: Greater than
              - ``>=``: Greater than or equal to

            Logical operators
              - ``AND``: Combines two sub-queries and returns True if both of them are True.

        :param order_by:
            List of columns to order by. The ``order_by`` column can contain an optional ``DESC`` or
            ``ASC`` value (e.g., ``"name DESC"``). The default ordering is ``ASC``, so ``"name"`` is
            equivalent to ``"name ASC"``. If unspecified, defaults to ``["last_update_time DESC"]``,
            which lists experiments updated most recently first. The following fields are supported:

            - ``experiment_id``: Experiment ID
            - ``name``: Experiment name
            - ``creation_time``: Experiment creation time
            - ``last_update_time``: Experiment last update time

        :param page_token: Token specifying the next page of results. It should be obtained from
                           a ``search_experiments`` call.
        :return: A :py:class:`PagedList <mlflow.store.entities.PagedList>` of
                 :py:class:`Experiment <mlflow.entities.Experiment>` objects. The pagination token
                 for the next page can be obtained via the ``token`` attribute of the object.
        """
        return self.store.search_experiments(
            view_type=view_type,
            max_results=max_results,
            filter_string=filter_string,
            order_by=order_by,
            page_token=page_token,
        )

    def get_experiment(self, experiment_id):
        """
        :param experiment_id: The experiment ID returned from ``create_experiment``.
        :return: :py:class:`mlflow.entities.Experiment`
        """
        return self.store.get_experiment(experiment_id)

    def get_experiment_by_name(self, name):
        """
        :param name: The experiment name.
        :return: :py:class:`mlflow.entities.Experiment`
        """
        return self.store.get_experiment_by_name(name)

    def create_experiment(self, name, artifact_location=None, tags=None):
        """Create an experiment.

        :param name: The experiment name. Must be unique.
        :param artifact_location: The location to store run artifacts.
                                  If not provided, the server picks an appropriate default.
        :param tags: A dictionary of key-value pairs that are converted into
                                  :py:class:`mlflow.entities.ExperimentTag` objects.
        :return: Integer ID of the created experiment.
        """
        _validate_experiment_artifact_location(artifact_location)

        return self.store.create_experiment(
            name=name,
            artifact_location=artifact_location,
            tags=[ExperimentTag(key, value) for (key, value) in tags.items()] if tags else [],
        )

    def delete_experiment(self, experiment_id):
        """
        Delete an experiment from the backend store.

        :param experiment_id: The experiment ID returned from ``create_experiment``.
        """
        self.store.delete_experiment(experiment_id)

    def restore_experiment(self, experiment_id):
        """
        Restore a deleted experiment unless permanently deleted.

        :param experiment_id: The experiment ID returned from ``create_experiment``.
        """
        self.store.restore_experiment(experiment_id)

    def rename_experiment(self, experiment_id, new_name):
        """
        Update an experiment's name. The new name must be unique.

        :param experiment_id: The experiment ID returned from ``create_experiment``.
        """
        self.store.rename_experiment(experiment_id, new_name)

    def log_metric(self, run_id, key, value, timestamp=None, step=None):
        """
        Log a metric against the run ID.

        :param run_id: The run id to which the metric should be logged.
        :param key: Metric name (string). This string may only contain alphanumerics,
                    underscores (_), dashes (-), periods (.), spaces ( ), and slashes (/).
                    All backend stores will support keys up to length 250, but some may
                    support larger keys.
        :param value: Metric value (float) or single-item ndarray / tensor.
                      Note that some special values such
                      as +/- Infinity may be replaced by other values depending on the store. For
                      example, the SQLAlchemy store replaces +/- Inf with max / min float values.
                      All backend stores will support values up to length 5000, but some
                      may support larger values.
        :param timestamp: Time when this metric was calculated. Defaults to the current system time.
        :param step: Training step (iteration) at which was the metric calculated. Defaults to 0.
        """
        timestamp = timestamp if timestamp is not None else get_current_time_millis()
        step = step if step is not None else 0
        metric_value = convert_metric_value_to_float_if_possible(value)
        metric = Metric(key, metric_value, timestamp, step)
        self.store.log_metric(run_id, metric)

    def log_param(self, run_id, key, value):
        """
        Log a parameter (e.g. model hyperparameter) against the run ID. Value is converted to
        a string.
        """
        param = Param(key, str(value))
        try:
            self.store.log_param(run_id, param)
        except MlflowException as e:
            if e.error_code == ErrorCode.Name(INVALID_PARAMETER_VALUE):
                msg = f"{e.message}{PARAM_VALIDATION_MSG}'"
                raise MlflowException(msg, INVALID_PARAMETER_VALUE)
            else:
                raise e

    def set_experiment_tag(self, experiment_id, key, value):
        """
        Set a tag on the experiment with the specified ID. Value is converted to a string.

        :param experiment_id: String ID of the experiment.
        :param key: Name of the tag.
        :param value: Tag value (converted to a string).
        """
        tag = ExperimentTag(key, str(value))
        self.store.set_experiment_tag(experiment_id, tag)

    def set_tag(self, run_id, key, value):
        """
        Set a tag on the run with the specified ID. Value is converted to a string.

        :param run_id: String ID of the run.
        :param key: Tag name (string). This string may only contain alphanumerics, underscores
                    (_), dashes (-), periods (.), spaces ( ), and slashes (/).
                    All backend stores will support keys up to length 250, but some may
                    support larger keys.
        :param value: Tag value (string, but will be string-ified if not).
                      All backend stores will support values up to length 5000, but some
                      may support larger values.
        """
        tag = RunTag(key, str(value))
        self.store.set_tag(run_id, tag)

    def delete_tag(self, run_id, key):
        """
        Delete a tag from a run. This is irreversible.

        :param run_id: String ID of the run
        :param key: Name of the tag
        """
        self.store.delete_tag(run_id, key)

    def update_run(self, run_id, status=None, name=None):
        """
        Update a run with the specified ID to a new status or name.

        :param run_id: The ID of the Run to update.
        :param status: The new status of the run to set, if specified.
                       At least one of ``status`` or ``name`` should be specified.
        :param name: The new name of the run to set, if specified.
                     At least one of ``name`` or ``status`` should be specified.
        """
        # Exit early
        if status is None and name is None:
            return

        run = self.get_run(run_id)
        status = status or run.info.status
        self.store.update_run_info(
            run_id=run_id,
            run_status=RunStatus.from_string(status),
            end_time=run.info.end_time,
            run_name=name,
        )

    def log_batch(self, run_id, metrics=(), params=(), tags=()):
        """
        Log multiple metrics, params, and/or tags.

        :param run_id: String ID of the run
        :param metrics: If provided, List of Metric(key, value, timestamp) instances.
        :param params: If provided, List of Param(key, value) instances.
        :param tags: If provided, List of RunTag(key, value) instances.

        Raises an MlflowException if any errors occur.
        :return: None
        """
        if len(metrics) == 0 and len(params) == 0 and len(tags) == 0:
            return

        param_batches = chunk_list(params, MAX_PARAMS_TAGS_PER_BATCH)
        tag_batches = chunk_list(tags, MAX_PARAMS_TAGS_PER_BATCH)

        for params_batch, tags_batch in zip_longest(param_batches, tag_batches, fillvalue=[]):
            metrics_batch_size = min(
                MAX_ENTITIES_PER_BATCH - len(params_batch) - len(tags_batch),
                MAX_METRICS_PER_BATCH,
            )
            metrics_batch_size = max(metrics_batch_size, 0)
            metrics_batch = metrics[:metrics_batch_size]
            metrics = metrics[metrics_batch_size:]

            self.store.log_batch(
                run_id=run_id, metrics=metrics_batch, params=params_batch, tags=tags_batch
            )

        for metrics_batch in chunk_list(metrics, chunk_size=MAX_METRICS_PER_BATCH):
            self.store.log_batch(run_id=run_id, metrics=metrics_batch, params=[], tags=[])

    def _record_logged_model(self, run_id, mlflow_model):
        from mlflow.models import Model

        if not isinstance(mlflow_model, Model):
            raise TypeError(
                "Argument 'mlflow_model' should be of type mlflow.models.Model but was "
                "{}".format(type(mlflow_model))
            )
        self.store.record_logged_model(run_id, mlflow_model)

    def _get_artifact_repo(self, run_id):
        # Attempt to fetch the artifact repo from a local cache
        cached_repo = TrackingServiceClient._artifact_repos_cache.get(run_id)
        if cached_repo is not None:
            return cached_repo
        else:
            run = self.get_run(run_id)
            artifact_uri = add_databricks_profile_info_to_artifact_uri(
                run.info.artifact_uri, self.tracking_uri
            )
            artifact_repo = get_artifact_repository(artifact_uri)
            # Cache the artifact repo to avoid a future network call, removing the oldest
            # entry in the cache if there are too many elements
            if len(TrackingServiceClient._artifact_repos_cache) > 1024:
                TrackingServiceClient._artifact_repos_cache.popitem(last=False)
            TrackingServiceClient._artifact_repos_cache[run_id] = artifact_repo
            return artifact_repo

    def log_artifact(self, run_id, local_path, artifact_path=None):
        """
        Write a local file or directory to the remote ``artifact_uri``.

        :param local_path: Path to the file or directory to write.
        :param artifact_path: If provided, the directory in ``artifact_uri`` to write to.
        """
        artifact_repo = self._get_artifact_repo(run_id)
        if os.path.isdir(local_path):
            dir_name = os.path.basename(os.path.normpath(local_path))
            path_name = (
                os.path.join(artifact_path, dir_name) if artifact_path is not None else dir_name
            )
            artifact_repo.log_artifacts(local_path, path_name)
        else:
            artifact_repo.log_artifact(local_path, artifact_path)

    def log_artifacts(self, run_id, local_dir, artifact_path=None):
        """
        Write a directory of files to the remote ``artifact_uri``.

        :param local_dir: Path to the directory of files to write.
        :param artifact_path: If provided, the directory in ``artifact_uri`` to write to.
        """
        self._get_artifact_repo(run_id).log_artifacts(local_dir, artifact_path)

    def list_artifacts(self, run_id, path=None):
        """
        List the artifacts for a run.

        :param run_id: The run to list artifacts from.
        :param path: The run's relative artifact path to list from. By default it is set to None
                     or the root artifact path.
        :return: List of :py:class:`mlflow.entities.FileInfo`
        """
        return self._get_artifact_repo(run_id).list_artifacts(path)

    def download_artifacts(self, run_id, path, dst_path=None):
        """
        Download an artifact file or directory from a run to a local directory if applicable,
        and return a local path for it.

        :param run_id: The run to download artifacts from.
        :param path: Relative source path to the desired artifact.
        :param dst_path: Absolute path of the local filesystem destination directory to which to
                         download the specified artifacts. This directory must already exist.
                         If unspecified, the artifacts will either be downloaded to a new
                         uniquely-named directory on the local filesystem or will be returned
                         directly in the case of the LocalArtifactRepository.
        :return: Local path of desired artifact.
        """
        return self._get_artifact_repo(run_id).download_artifacts(path, dst_path)

    def set_terminated(self, run_id, status=None, end_time=None):
        """Set a run's status to terminated.

        :param status: A string value of :py:class:`mlflow.entities.RunStatus`.
                       Defaults to "FINISHED".
        :param end_time: If not provided, defaults to the current time."""
        end_time = end_time if end_time else get_current_time_millis()
        status = status if status else RunStatus.to_string(RunStatus.FINISHED)
        self.store.update_run_info(
            run_id,
            run_status=RunStatus.from_string(status),
            end_time=end_time,
            run_name=None,
        )

    def delete_run(self, run_id):
        """
        Deletes a run with the given ID.
        """
        self.store.delete_run(run_id)

    def restore_run(self, run_id):
        """
        Restores a deleted run with the given ID.
        """
        self.store.restore_run(run_id)

    def search_runs(
        self,
        experiment_ids,
        filter_string="",
        run_view_type=ViewType.ACTIVE_ONLY,
        max_results=SEARCH_MAX_RESULTS_DEFAULT,
        order_by=None,
        page_token=None,
    ):
        """
        Search experiments that fit the search criteria.

        :param experiment_ids: List of experiment IDs, or a single int or string id.
        :param filter_string: Filter query string, defaults to searching all runs.
        :param run_view_type: one of enum values ACTIVE_ONLY, DELETED_ONLY, or ALL runs
                              defined in :py:class:`mlflow.entities.ViewType`.
        :param max_results: Maximum number of runs desired.
        :param order_by: List of columns to order by (e.g., "metrics.rmse"). The ``order_by`` column
                     can contain an optional ``DESC`` or ``ASC`` value. The default is ``ASC``.
                     The default ordering is to sort by ``start_time DESC``, then ``run_id``.
        :param page_token: Token specifying the next page of results. It should be obtained from
            a ``search_runs`` call.

        :return: A :py:class:`PagedList <mlflow.store.entities.PagedList>` of
            :py:class:`Run <mlflow.entities.Run>` objects that satisfy the search expressions.
            If the underlying tracking store supports pagination, the token for the next page may
            be obtained via the ``token`` attribute of the returned object.
        """
        if isinstance(experiment_ids, int) or is_string_type(experiment_ids):
            experiment_ids = [experiment_ids]
        return self.store.search_runs(
            experiment_ids=experiment_ids,
            filter_string=filter_string,
            run_view_type=run_view_type,
            max_results=max_results,
            order_by=order_by,
            page_token=page_token,
        )

redpajama_set_name: RedPajamaGithub


text:
package alikafka

//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

import (
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)

// CreateTopic invokes the alikafka.CreateTopic API synchronously
func (client *Client) CreateTopic(request *CreateTopicRequest) (response *CreateTopicResponse, err error) {
	response = CreateCreateTopicResponse()
	err = client.DoAction(request, response)
	return
}

// CreateTopicWithChan invokes the alikafka.CreateTopic API asynchronously
func (client *Client) CreateTopicWithChan(request *CreateTopicRequest) (<-chan *CreateTopicResponse, <-chan error) {
	responseChan := make(chan *CreateTopicResponse, 1)
	errChan := make(chan error, 1)
	err := client.AddAsyncTask(func() {
		defer close(responseChan)
		defer close(errChan)
		response, err := client.CreateTopic(request)
		if err != nil {
			errChan <- err
		} else {
			responseChan <- response
		}
	})
	if err != nil {
		errChan <- err
		close(responseChan)
		close(errChan)
	}
	return responseChan, errChan
}

// CreateTopicWithCallback invokes the alikafka.CreateTopic API asynchronously
func (client *Client) CreateTopicWithCallback(request *CreateTopicRequest, callback func(response *CreateTopicResponse, err error)) <-chan int {
	result := make(chan int, 1)
	err := client.AddAsyncTask(func() {
		var response *CreateTopicResponse
		var err error
		defer close(result)
		response, err = client.CreateTopic(request)
		callback(response, err)
		result <- 1
	})
	if err != nil {
		defer close(result)
		callback(nil, err)
		result <- 0
	}
	return result
}

// CreateTopicRequest is the request struct for api CreateTopic
type CreateTopicRequest struct {
	*requests.RpcRequest
	Remark            string           `position:"Query" name:"Remark"`
	ReplicationFactor requests.Integer `position:"Query" name:"ReplicationFactor"`
	MinInsyncReplicas requests.Integer `position:"Query" name:"MinInsyncReplicas"`
	InstanceId        string           `position:"Query" name:"InstanceId"`
	Topic             string           `position:"Query" name:"Topic"`
	CompactTopic      requests.Boolean `position:"Query" name:"CompactTopic"`
	PartitionNum      string           `position:"Query" name:"PartitionNum"`
	Config            string           `position:"Query" name:"Config"`
	LocalTopic        requests.Boolean `position:"Query" name:"LocalTopic"`
}

// CreateTopicResponse is the response struct for api CreateTopic
type CreateTopicResponse struct {
	*responses.BaseResponse
	Code      int    `json:"Code" xml:"Code"`
	Message   string `json:"Message" xml:"Message"`
	RequestId string `json:"RequestId" xml:"RequestId"`
	Success   bool   `json:"Success" xml:"Success"`
}

// CreateCreateTopicRequest creates a request to invoke CreateTopic API
func CreateCreateTopicRequest() (request *CreateTopicRequest) {
	request = &CreateTopicRequest{
		RpcRequest: &requests.RpcRequest{},
	}
	request.InitWithApiInfo("alikafka", "2019-09-16", "CreateTopic", "alikafka", "openAPI")
	request.Method = requests.POST
	return
}

// CreateCreateTopicResponse creates a response to parse from CreateTopic response
func CreateCreateTopicResponse() (response *CreateTopicResponse) {
	response = &CreateTopicResponse{
		BaseResponse: &responses.BaseResponse{},
	}
	return
}


text:
<?php

use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;

class AppKernel extends Kernel
{
    /**
     * {@inheritDoc}
     */
    public function __construct($environment, $debug)
    {
        // All date in DB must be in UTC. The setting of the timezone is done in the template.
        date_default_timezone_set( 'UTC' );

        parent::__construct($environment, $debug);
    }

    /**
     * {@inheritDoc}
     */
    public function registerBundles()
    {
        $bundles = array(
            new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
            new Symfony\Bundle\SecurityBundle\SecurityBundle(),
            new Symfony\Bundle\TwigBundle\TwigBundle(),
            new Symfony\Bundle\MonologBundle\MonologBundle(),
            new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
            new Symfony\Bundle\AsseticBundle\AsseticBundle(),
            new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
            new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
        );

        $freeBetBundles = array(
            new Stof\DoctrineExtensionsBundle\StofDoctrineExtensionsBundle(),
            new Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle(),
            new Doctrine\Bundle\MongoDBBundle\DoctrineMongoDBBundle(),
            new FOS\UserBundle\FOSUserBundle(),
            new Knp\Bundle\PaginatorBundle\KnpPaginatorBundle(),
            new Knp\Bundle\MenuBundle\KnpMenuBundle(),
            new Jb\Bundle\ConfigKnpMenuBundle\JbConfigKnpMenuBundle(),
            new \Misd\GuzzleBundle\MisdGuzzleBundle(),
            new FreeBet\Bundle\UIBundle\FreeBetUIBundle(),
            new FreeBet\Bundle\UserBundle\FreeBetUserBundle(),
            new FreeBet\Bundle\GambleBundle\FreeBetGambleBundle(),
            new FreeBet\Bundle\CompetitionBundle\FreeBetCompetitionBundle(),
            new FreeBet\Bundle\StatisticBundle\FreeBetStatisticBundle(),
            new FreeBet\Bundle\SoccerBundle\FreeBetSoccerBundle(),
            new FreeBet\Bundle\SoccerWorldCupBundle\FreeBetSoccerWorldCupBundle(),
            new FreeBet\Bundle\SoccerLeagueBundle\FreeBetSoccerLeagueBundle()
        );

        $bundles = array_merge($bundles, $freeBetBundles);

        if (in_array($this->getEnvironment(), array('dev', 'test'))) {
            $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
            $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
            $bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
            $bundles[] = new Webfactory\Bundle\ExceptionsBundle\WebfactoryExceptionsBundle();
        }

        return $bundles;
    }

    /**
     * Load config for current env
     *
     * @param \Symfony\Component\Config\Loader\LoaderInterface $loader
     */
    public function registerContainerConfiguration(LoaderInterface $loader)
    {
        $loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml');
    }
}


text:
package org.apache.spark.streaming.scheduler.rate

import org.apache.spark.SparkConf
import org.apache.spark.streaming.Duration

/**
 * A component that estimates the rate at which an `InputDStream` should ingest
 * records, based on updates at every batch completion.
 *
 * Please see `org.apache.spark.streaming.scheduler.RateController` for more details.
 */
private[streaming] trait RateEstimator extends Serializable {

  /**
   * Computes the number of records the stream attached to this `RateEstimator`
   * should ingest per second, given an update on the size and completion
   * times of the latest batch.
   *
   * @param time The timestamp of the current batch interval that just finished
   * @param elements The number of records that were processed in this batch
   * @param processingDelay The time in ms that took for the job to complete
   * @param schedulingDelay The time in ms that the job spent in the scheduling queue
   */
  def compute(
      time: Long,
      elements: Long,
      processingDelay: Long,
      schedulingDelay: Long): Option[Double]
}

object RateEstimator {

  /**
   * Return a new `RateEstimator` based on the value of
   * `spark.streaming.backpressure.rateEstimator`.
   *
   * The only known and acceptable estimator right now is `pid`.
   *
   * @return An instance of RateEstimator
   * @throws IllegalArgumentException if the configured RateEstimator is not `pid`.
   */
  def create(conf: SparkConf, batchInterval: Duration): RateEstimator =
    conf.get("spark.streaming.backpressure.rateEstimator", "pid") match {
      case "pid" =>
        val proportional = conf.getDouble("spark.streaming.backpressure.pid.proportional", 1.0)
        val integral = conf.getDouble("spark.streaming.backpressure.pid.integral", 0.2)
        val derived = conf.getDouble("spark.streaming.backpressure.pid.derived", 0.0)
        val minRate = conf.getDouble("spark.streaming.backpressure.pid.minRate", 100)
        new PIDRateEstimator(batchInterval.milliseconds, proportional, integral, derived, minRate)

      case estimator =>
        throw new IllegalArgumentException(s"Unknown rate estimator: $estimator")
    }
}


text:
#pragma once

#ifndef _VERTEX_BUFFER_H
#define _VERTEX_BUFFER_H

/**********************
*   System Includes   *
***********************/

/*************************
*   3rd Party Includes   *
**************************/

/***************************
*   Game Engine Includes   *
****************************/
#include "VertexDefs.h"
#include "GraphicsDefs.h"
#include "VertexLayout.h"
#include "IVertexBuffer.h"
#include "fmt\format.h"

/********************
*   Forward Decls   *
*********************/
class GraphicDevice;

/*****************
*   Class Decl   *
******************/
template<class T>
class VertexBuffer sealed : public IVertexBuffer
{
    private:

        /************************
        *   Private Variables   *
        *************************/
#pragma region Private Variables

        /// <summary>
        /// Vertex Buffer in RAM
        /// </summary>
        T* m_VertexBuffer = nullptr;

        /// <summary>
        /// When Map, this is the Vertex Buffer(VRAM)
        /// </summary>
        T* m_VideoVB = nullptr;

#pragma endregion

        /********************************
        *   Private Framework Methods   *
        *********************************/
#pragma region Private Framework Methods

        /// <summary>
        /// Commit new Data from Vertex Buffer in RAM to VRAM
        /// </summary>
        /// <param name="offset">Offset in Vertex Buffer(RAM) to where to begin copying from</param>
        /// <param name="elementCount">Number of elements to copy</param>
        /// <returns>AEResult::Ok commit succeeded</returns>
        AEResult CommitVertexData(uint32_t offset, uint32_t elementCount)
        {
            if(m_VideoVB == nullptr)
            {
                return AEResult::Fail;
            }

            uint32_t copySize = VertexSize() * elementCount;
            memcpy(m_VideoVB + offset, m_VertexBuffer + offset, copySize);

            return AEResult::Ok;
        }

        /// <summary>
        /// Map the VRAM Vertex Buffer
        /// </summary>
        /// <param name="mapType">Tells how the Vertex Buffer will be access</param>
        /// <returns>AEResult::Ok Map succeeded</returns>
        AEResult MapBuffer(D3D11_MAP mapType)
        {
            D3D11_MAPPED_SUBRESOURCE mappedData = { 0 };

            AETODO("Check Map flags");
            AETODO("Check Sub Resource");
            HRESULT hr = m_GraphicDevice.GetDeviceContextDX()->Map(m_VertexBufferDX, 0, mapType, 0, &mappedData);

            if(hr != S_OK)
            {
                DisplayError(hr);

                return AEResult::Fail;
            }

            m_VideoVB = static_cast<T*>(mappedData.pData);

            return AEResult::Ok;
        }

        /// <summary>
        /// UnMap the Vertex Buffer from VRAM
        /// </summary>
        /// <returns>AEResult::Ok UnMap succeeded</returns>
        AEResult UnMapBuffer()
        {
            AETODO("Check Subresource");
            m_GraphicDevice.GetDeviceContextDX()->Unmap(m_VertexBufferDX, 0);

            m_VideoVB = nullptr;

            return AEResult::Ok;
        }

#pragma endregion

    public:

        /***************************************
        *   Constructor & Destructor Methods   *
        ****************************************/
#pragma region Constructor & Destructor Methods

        /// <summary>
        /// VertexBuffer Constructor
        /// </summary>
        /// <param name="graphicDevice">Graphic Device to be associated with this Vertex Buffer</param>
        /// <param name="bufferUsage">How will the buffer be use</param>
        /// <param name="bufferAccess">How will the CPU Access the memory of the buffer</param>
        VertexBuffer(GraphicDevice& graphicDevice, GraphicBufferUsage bufferUsage = GraphicBufferUsage::Static, GraphicBufferAccess bufferAccess = GraphicBufferAccess::None)
            : IVertexBuffer(graphicDevice, bufferUsage, bufferAccess)
            , m_VertexBuffer(nullptr)
            , m_VideoVB(nullptr)
        {
        }

        /// <summary>
        /// Default VertexBuffer Destructor
        /// </summary>
        virtual ~VertexBuffer()
        {
            DeleteMemArr(m_VertexBuffer);
        }

#pragma endregion

        /***************************
        *   Override Get Methods   *
        ****************************/
#pragma region Override Get Methods

        /// <summary>
        /// Returns Vertex Type for this Buffer
        /// </summary>
        /// <returns>Vertex Type for Buffer</returns>
        virtual VertexType GetVertexType() const
        {
            return T::GetVertexType();
        }

#pragma endregion

        /************************
        *   Framework Methods   *
        *************************/
#pragma region Framework Methods

        /// <summary>
        /// Copies the array to the Vertex Buffer and makes it ready for use
        /// </summary>
        /// <param name="vertexBuff">Array to be copied</param>
        /// <param name="size">Size of the Array</param>
        AEResult CopyVertexBuffer(T vertexBuff[], uint32_t size)
        {
            AEAssert(vertexBuff != nullptr);

            if(vertexBuff == nullptr)
            {
                return AEResult::Fail;
            }

            //Delete Any Vertex Buffer
            DeleteMemArr(m_VertexBuffer);

            m_VertexBuffer = new T[size];
            m_Size = size;

            memcpy(m_VertexBuffer, vertexBuff, VertexSize() * size);

            m_IsReady = false;

            return AEResult::Ok;
        }

        /// <summary>
        /// Copies the array to the Vertex Buffer and makes it ready for use
        /// </summary>
        /// <param name="vertexBuff">Array to be copied</param>
        void CopyVertexBuffer(const std::vector<T>& vertexBuff)
        {
            //Delete Any Vertex Buffer
            DeleteMemArr(m_VertexBuffer);

            uint32_t vbSize = (uint32_t)vertexBuff.size();

            m_VertexBuffer = new T[vbSize];
            m_Size = vbSize;

            for(uint32_t i = 0; i < vbSize; ++i)
            {
                m_VertexBuffer[i] = vertexBuff[i];
            }

            m_IsReady = false;
        }

        /// <summary>
        /// Copies the data from the array to the Vertex Buffer
        /// </summary>
        /// <param name="offset">Offset in array to where to begin copying from</param>
        /// <param name="vertexData">Vertex Array</param>
        /// <param name="startIndex">Start Index in Vertex Buffer to begin the copy</param>
        /// <param name="elementCount">Number of elements to copy</param>
        /// <param name="mapType">Tells how the Vertex Buffer will be access</param>
        /// <returns>AEResult::Ok if copy succeeded</returns>
        AEResult SetVertexData(uint32_t offset, T vertexData[], uint32_t startIndex, uint32_t elementCount, D3D11_MAP mapType)
        {
            AEAssert(vertexData != nullptr);

            if(!m_IsReady)
            {
                if(BuildVertexBuffer() != AEResult::Ok)
                {
                    return AEResult::Fail;
                }
            }

            if(startIndex >= m_Size || (startIndex + elementCount) > m_Size)
            {
                return AEResult::Fail;
            }

            if(MapBuffer(mapType) != AEResult::Ok)
            {
                return AEResult::Fail;
            }

            uint32_t copySize = VertexSize() * elementCount;
            memcpy(m_VertexBuffer + startIndex, vertexData + offset, copySize);

            if(CommitVertexData(startIndex, elementCount) != AEResult::Ok)
            {
                return AEResult::Fail;
            }

            UnMapBuffer();

            return AEResult::Ok;
        }

#pragma endregion

        /***********************************
         *   Override Framework Methods    *
         **********************************/
#pragma region Override Framework Methods

        /// <summary>
        /// Builds the Vertex Buffer.
        /// </summary>
        /// <returns>AEResult::Ok if Build Vertex Buffer succeeded</returns>
        AEResult BuildVertexBuffer() override
        {
            if(m_VertexBuffer == nullptr || m_IsReady)
            {
                return AEResult::Fail;
            }

            D3D11_BUFFER_DESC vbDesc = { 0 };

            vbDesc.Usage = AEGraphicHelpers::GetDXUsage(m_BufferUsage);
            vbDesc.ByteWidth = sizeof(T) * m_Size;
            vbDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
            vbDesc.CPUAccessFlags = AEGraphicHelpers::GetDXBufferAccess(m_BufferAccess);
            vbDesc.MiscFlags = 0;
            vbDesc.StructureByteStride = 0;

            D3D11_SUBRESOURCE_DATA vbInitData = { 0 };
            vbInitData.pSysMem = m_VertexBuffer;

            HRESULT hr = m_GraphicDevice.GetDeviceDX()->CreateBuffer(&vbDesc, &vbInitData, &m_VertexBufferDX);

            if(hr != S_OK)
            {
                DisplayError(hr);

                return AEResult::Fail;
            }

            AEGraphicHelpers::SetDebugObjectName(m_VertexBufferDX, AE_DEBUG_VB_NAME_PREFIX + m_Name);

            m_IsReady = true;

            return AEResult::Ok;
        }

        /// <summary>
        /// Size of the Vertex that the Vertex Buffer has
        /// </summary>
        /// <returns>Vertex Size</returns>
        inline uint32_t VertexSize() const override
        {
            return sizeof(T);
        }

        /// <summary>
        /// Vertex Layout of the Vertex that the Vertex Buffer has
        /// </summary>
        /// <returns>Vertex Layout of the Vertex</returns>
        const VertexLayout* GetVertexLayout() override
        {
            if(m_VertexBuffer == nullptr || !m_IsReady)
            {
                return nullptr;
            }

            return T::GetVertexLayout(m_GraphicDevice);
        }

#pragma endregion

};

#endif


text:
#include "tensorflow_serving/servables/tensorflow/saved_model_warmup_util.h"

#include "google/protobuf/wrappers.pb.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "tensorflow/cc/saved_model/constants.h"
#include "tensorflow/cc/saved_model/signature_constants.h"
#include "tensorflow/core/example/example.pb.h"
#include "tensorflow/core/example/feature.pb.h"
#include "tensorflow/core/framework/tensor.pb.h"
#include "tensorflow/core/framework/tensor_shape.pb.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/lib/io/path.h"
#include "tensorflow/core/lib/io/record_writer.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/errors.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/platform/threadpool_options.h"
#include "tensorflow_serving/apis/classification.pb.h"
#include "tensorflow_serving/apis/inference.pb.h"
#include "tensorflow_serving/apis/input.pb.h"
#include "tensorflow_serving/apis/model.pb.h"
#include "tensorflow_serving/apis/predict.pb.h"
#include "tensorflow_serving/apis/prediction_log.pb.h"
#include "tensorflow_serving/apis/regression.pb.h"
#include "tensorflow_serving/servables/tensorflow/saved_model_warmup_test_util.h"
#include "tensorflow_serving/servables/tensorflow/session_bundle_config.pb.h"

namespace tensorflow {
namespace serving {
namespace internal {
namespace {

class SavedModelBundleWarmupUtilTest : public ::testing::TestWithParam<bool> {
 protected:
  SavedModelBundleWarmupUtilTest() : warmup_request_counter_(0) {}
  bool ParallelWarmUp() { return GetParam(); }
  ModelWarmupOptions CreateModelWarmupOptions() {
    ModelWarmupOptions options;
    if (ParallelWarmUp()) {
      options.mutable_num_model_warmup_threads()->set_value(3);
    }
    return options;
  }
  void FakeRunWarmupRequest() { warmup_request_counter_++; }
  int warmup_request_counter_;
};

TEST_P(SavedModelBundleWarmupUtilTest, NoWarmupDataFile) {
  string base_path = io::JoinPath(testing::TmpDir(), "NoWarmupDataFile");
  TF_ASSERT_OK(Env::Default()->RecursivelyCreateDir(
      io::JoinPath(base_path, kSavedModelAssetsExtraDirectory)));

  SavedModelBundle saved_model_bundle;
  AddSignatures(&saved_model_bundle.meta_graph_def);
  TF_EXPECT_OK(RunSavedModelWarmup(CreateModelWarmupOptions(), base_path,
                                   [this](PredictionLog prediction_log) {
                                     this->FakeRunWarmupRequest();
                                     return OkStatus();
                                   }));
  EXPECT_EQ(warmup_request_counter_, 0);
}

TEST_P(SavedModelBundleWarmupUtilTest, WarmupDataFileEmpty) {
  string base_path = io::JoinPath(testing::TmpDir(), "WarmupDataFileEmpty");
  TF_ASSERT_OK(Env::Default()->RecursivelyCreateDir(
      io::JoinPath(base_path, kSavedModelAssetsExtraDirectory)));
  string fname = io::JoinPath(base_path, kSavedModelAssetsExtraDirectory,
                              internal::WarmupConsts::kRequestsFileName);

  std::vector<string> warmup_records;
  TF_ASSERT_OK(WriteWarmupData(fname, warmup_records, 0));
  SavedModelBundle saved_model_bundle;
  AddSignatures(&saved_model_bundle.meta_graph_def);
  TF_EXPECT_OK(RunSavedModelWarmup(CreateModelWarmupOptions(), base_path,
                                   [this](PredictionLog prediction_log) {
                                     this->FakeRunWarmupRequest();
                                     return OkStatus();
                                   }));
  EXPECT_EQ(warmup_request_counter_, 0);
}

TEST_P(SavedModelBundleWarmupUtilTest, UnsupportedFileFormat) {
  string base_path = io::JoinPath(testing::TmpDir(), "UnsupportedFileFormat");
  TF_ASSERT_OK(Env::Default()->RecursivelyCreateDir(
      io::JoinPath(base_path, kSavedModelAssetsExtraDirectory)));
  const string fname = io::JoinPath(base_path, kSavedModelAssetsExtraDirectory,
                                    internal::WarmupConsts::kRequestsFileName);

  std::vector<string> warmup_records;
  // Add unsupported log type
  PredictionLog prediction_log;
  PopulatePredictionLog(&prediction_log, PredictionLog::kSessionRunLog);
  warmup_records.push_back(prediction_log.SerializeAsString());

  TF_ASSERT_OK(WriteWarmupDataAsSerializedProtos(fname, warmup_records, 10));
  SavedModelBundle saved_model_bundle;
  AddSignatures(&saved_model_bundle.meta_graph_def);
  const Status status = RunSavedModelWarmup(
      CreateModelWarmupOptions(), base_path,
      [](PredictionLog prediction_log) { return OkStatus(); });
  ASSERT_FALSE(status.ok());
  EXPECT_EQ(::tensorflow::error::DATA_LOSS, status.code()) << status;
  EXPECT_THAT(status.ToString(),
              ::testing::HasSubstr(
                  "Please verify your warmup data is in TFRecord format"));
}

TEST_P(SavedModelBundleWarmupUtilTest, TooManyWarmupRecords) {
  string base_path = io::JoinPath(testing::TmpDir(), "TooManyWarmupRecords");
  TF_ASSERT_OK(Env::Default()->RecursivelyCreateDir(
      io::JoinPath(base_path, kSavedModelAssetsExtraDirectory)));
  string fname = io::JoinPath(base_path, kSavedModelAssetsExtraDirectory,
                              internal::WarmupConsts::kRequestsFileName);

  std::vector<string> warmup_records;
  AddMixedWarmupData(&warmup_records);
  TF_ASSERT_OK(WriteWarmupData(fname, warmup_records,
                               internal::WarmupConsts::kMaxNumRecords + 1));
  SavedModelBundle saved_model_bundle;
  AddSignatures(&saved_model_bundle.meta_graph_def);
  const Status status = RunSavedModelWarmup(
      CreateModelWarmupOptions(), base_path,
      [](PredictionLog prediction_log) { return OkStatus(); });
  ASSERT_FALSE(status.ok());
  EXPECT_EQ(::tensorflow::error::INVALID_ARGUMENT, status.code()) << status;
  EXPECT_THAT(
      status.ToString(),
      ::testing::HasSubstr("Number of warmup records exceeds the maximum"));
}

TEST_P(SavedModelBundleWarmupUtilTest, UnparsableRecord) {
  string base_path = io::JoinPath(testing::TmpDir(), "UnparsableRecord");
  TF_ASSERT_OK(Env::Default()->RecursivelyCreateDir(
      io::JoinPath(base_path, kSavedModelAssetsExtraDirectory)));
  string fname = io::JoinPath(base_path, kSavedModelAssetsExtraDirectory,
                              internal::WarmupConsts::kRequestsFileName);

  std::vector<string> warmup_records = {"malformed_record"};
  TF_ASSERT_OK(WriteWarmupData(fname, warmup_records, 10));
  SavedModelBundle saved_model_bundle;
  const Status status = RunSavedModelWarmup(
      CreateModelWarmupOptions(), base_path,
      [](PredictionLog prediction_log) { return OkStatus(); });
  ASSERT_FALSE(status.ok());
  EXPECT_EQ(::tensorflow::error::INVALID_ARGUMENT, status.code()) << status;
  EXPECT_THAT(status.ToString(),
              ::testing::HasSubstr("Failed to parse warmup record"));
}

TEST_P(SavedModelBundleWarmupUtilTest, RunFailure) {
  string base_path = io::JoinPath(testing::TmpDir(), "RunFailure");
  TF_ASSERT_OK(Env::Default()->RecursivelyCreateDir(
      io::JoinPath(base_path, kSavedModelAssetsExtraDirectory)));
  string fname = io::JoinPath(base_path, kSavedModelAssetsExtraDirectory,
                              internal::WarmupConsts::kRequestsFileName);

  int num_warmup_records = 10;
  std::vector<string> warmup_records;
  AddMixedWarmupData(&warmup_records);
  TF_ASSERT_OK(WriteWarmupData(fname, warmup_records, num_warmup_records));
  SavedModelBundle saved_model_bundle;
  AddSignatures(&saved_model_bundle.meta_graph_def);
  Status status = RunSavedModelWarmup(
      CreateModelWarmupOptions(), base_path, [](PredictionLog prediction_log) {
        return errors::InvalidArgument("Run failed");
      });
  ASSERT_FALSE(status.ok());
  EXPECT_EQ(::tensorflow::error::INVALID_ARGUMENT, status.code()) << status;
  EXPECT_THAT(status.ToString(), ::testing::HasSubstr("Run failed"));
}
INSTANTIATE_TEST_SUITE_P(ParallelWarmUp, SavedModelBundleWarmupUtilTest,
                         ::testing::Bool());
}  // namespace
}  // namespace internal
}  // namespace serving
}  // namespace tensorflow


text:
<?php

/**
 *
 * @Author Rizki Mufrizal <mufrizalrizki@gmail.com>
 * @Since Jan 24, 2016
 * @Time 6:17:04 PM
 * @Encoding UTF-8
 * @Project Belajar-CodeIgniter
 * @Package Expression package is undefined on line 12, column 15 in Templates/Scripting/PHPClass.php.
 *
 */
require APPPATH . '/libraries/REST_Controller.php';

class KaryawanRestController extends REST_Controller {

    public function __construct($config = 'rest') {
        parent::__construct();
        header('Access-Control-Allow-Origin: *');
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
        $this->load->model('Karyawan');
    }

    //ambil data karyawan get
    public function karyawans_get() {

        $page = $this->query('page');
        $size = $this->query('size');

        $response = array(
            'content' => $this->Karyawan->getKaryawans(($page - 1) * $size, $size)->result(),
            'totalPages' => ceil($this->Karyawan->getCountKaryawan() / $size)
        );

        $this->response($response, REST_Controller::HTTP_OK);
    }

    //ambil data karyawan get
    public function karyawan_get() {

        $key = $this->query('key');
        $value = $this->query('value');

        $response = array(
            'content' => $this->Karyawan->getKaryawan($key, $value)->result()
        );

        $this->response($response, REST_Controller::HTTP_OK);
    }

    //simpan data karyawan post
    public function karyawan_post() {
        $karyawan = [
            'nama' => $this->post('nama'),
            'jenisKelamin' => $this->post('jenisKelamin'),
            'tanggalLahir' => $this->post('tanggalLahir'),
            'alamat' => $this->post('alamat')
        ];
        $this->Karyawan->saveKaryawan($karyawan);

        $message = [
            'success' => TRUE,
            'info' => 'Data Karyawan Tersimpan'
        ];

        $this->set_response($message, REST_Controller::HTTP_CREATED);
    }

    //update data karyawan put
    public function karyawan_put() {
        $idKaryawan = $this->query('idKaryawan');
        $karyawan = array(
            'nama' => $this->put('nama'),
            'jenisKelamin' => $this->put('jenisKelamin'),
            'tanggalLahir' => $this->put('tanggalLahir'),
            'alamat' => $this->put('alamat')
        );

        $this->Karyawan->updateKaryawan($karyawan, $idKaryawan);

        $message = [
            'success' => TRUE,
            'info' => 'Data Karyawan berhasil di update'
        ];

        $this->set_response($message, REST_Controller::HTTP_OK);
    }

    //hapus data karyawan delete
    public function karyawan_delete() {
        $idKaryawan = $this->query('idKaryawan');

        $this->Karyawan->deleteKaryawan($idKaryawan);

        $message = [
            'success' => TRUE,
            'info' => 'Data Karyawan berhasil di hapus'
        ];

        $this->set_response($message, REST_Controller::HTTP_OK);
    }

}


text:
<?php

/**
 * The "values" collection of methods.
 * Typical usage is:
 *  <code>
 *   $sheetsService = new Google_Service_Sheets(...);
 *   $values = $sheetsService->values;
 *  </code>
 */
class Google_Service_Sheets_Resource_SpreadsheetsValues extends Google_Service_Resource
{
  /**
   * Appends values to a spreadsheet. The input range is used to search for
   * existing data and find a "table" within that range. Values will be appended
   * to the next row of the table, starting with the first column of the table.
   * See the [guide](/sheets/guides/values#appending_values) and [sample
   * code](/sheets/samples/writing#append_values) for specific details of how
   * tables are detected and data is appended.
   *
   * The caller must specify the spreadsheet ID, range, and a valueInputOption.
   * The `valueInputOption` only controls how the input data will be added to the
   * sheet (column-wise or row-wise), it does not influence what cell the data
   * starts being written to. (values.append)
   *
   * @param string $spreadsheetId The ID of the spreadsheet to update.
   * @param string $range The A1 notation of a range to search for a logical table
   * of data. Values will be appended after the last row of the table.
   * @param Google_Service_Sheets_ValueRange $postBody
   * @param array $optParams Optional parameters.
   *
   * @opt_param string valueInputOption How the input data should be interpreted.
   * @opt_param string insertDataOption How the input data should be inserted.
   * @return Google_Service_Sheets_AppendValuesResponse
   */
  public function append($spreadsheetId, $range, Google_Service_Sheets_ValueRange $postBody, $optParams = array())
  {
    $params = array('spreadsheetId' => $spreadsheetId, 'range' => $range, 'postBody' => $postBody);
    $params = array_merge($params, $optParams);
    return $this->call('append', array($params), "Google_Service_Sheets_AppendValuesResponse");
  }
  /**
   * Clears one or more ranges of values from a spreadsheet. The caller must
   * specify the spreadsheet ID and one or more ranges. Only values are cleared --
   * all other properties of the cell (such as formatting, data validation, etc..)
   * are kept. (values.batchClear)
   *
   * @param string $spreadsheetId The ID of the spreadsheet to update.
   * @param Google_Service_Sheets_BatchClearValuesRequest $postBody
   * @param array $optParams Optional parameters.
   * @return Google_Service_Sheets_BatchClearValuesResponse
   */
  public function batchClear($spreadsheetId, Google_Service_Sheets_BatchClearValuesRequest $postBody, $optParams = array())
  {
    $params = array('spreadsheetId' => $spreadsheetId, 'postBody' => $postBody);
    $params = array_merge($params, $optParams);
    return $this->call('batchClear', array($params), "Google_Service_Sheets_BatchClearValuesResponse");
  }
  /**
   * Returns one or more ranges of values from a spreadsheet. The caller must
   * specify the spreadsheet ID and one or more ranges. (values.batchGet)
   *
   * @param string $spreadsheetId The ID of the spreadsheet to retrieve data from.
   * @param array $optParams Optional parameters.
   *
   * @opt_param string ranges The A1 notation of the values to retrieve.
   * @opt_param string valueRenderOption How values should be represented in the
   * output.
   * @opt_param string dateTimeRenderOption How dates, times, and durations should
   * be represented in the output. This is ignored if value_render_option is
   * FORMATTED_VALUE.
   * @opt_param string majorDimension The major dimension that results should use.
   *
   * For example, if the spreadsheet data is: `A1=1,B1=2,A2=3,B2=4`, then
   * requesting `range=A1:B2,majorDimension=ROWS` will return `[[1,2],[3,4]]`,
   * whereas requesting `range=A1:B2,majorDimension=COLUMNS` will return
   * `[[1,3],[2,4]]`.
   * @return Google_Service_Sheets_BatchGetValuesResponse
   */
  public function batchGet($spreadsheetId, $optParams = array())
  {
    $params = array('spreadsheetId' => $spreadsheetId);
    $params = array_merge($params, $optParams);
    return $this->call('batchGet', array($params), "Google_Service_Sheets_BatchGetValuesResponse");
  }
  /**
   * Sets values in one or more ranges of a spreadsheet. The caller must specify
   * the spreadsheet ID, a valueInputOption, and one or more ValueRanges.
   * (values.batchUpdate)
   *
   * @param string $spreadsheetId The ID of the spreadsheet to update.
   * @param Google_Service_Sheets_BatchUpdateValuesRequest $postBody
   * @param array $optParams Optional parameters.
   * @return Google_Service_Sheets_BatchUpdateValuesResponse
   */
  public function batchUpdate($spreadsheetId, Google_Service_Sheets_BatchUpdateValuesRequest $postBody, $optParams = array())
  {
    $params = array('spreadsheetId' => $spreadsheetId, 'postBody' => $postBody);
    $params = array_merge($params, $optParams);
    return $this->call('batchUpdate', array($params), "Google_Service_Sheets_BatchUpdateValuesResponse");
  }
  /**
   * Clears values from a spreadsheet. The caller must specify the spreadsheet ID
   * and range. Only values are cleared -- all other properties of the cell (such
   * as formatting, data validation, etc..) are kept. (values.clear)
   *
   * @param string $spreadsheetId The ID of the spreadsheet to update.
   * @param string $range The A1 notation of the values to clear.
   * @param Google_Service_Sheets_ClearValuesRequest $postBody
   * @param array $optParams Optional parameters.
   * @return Google_Service_Sheets_ClearValuesResponse
   */
  public function clear($spreadsheetId, $range, Google_Service_Sheets_ClearValuesRequest $postBody, $optParams = array())
  {
    $params = array('spreadsheetId' => $spreadsheetId, 'range' => $range, 'postBody' => $postBody);
    $params = array_merge($params, $optParams);
    return $this->call('clear', array($params), "Google_Service_Sheets_ClearValuesResponse");
  }
  /**
   * Returns a range of values from a spreadsheet. The caller must specify the
   * spreadsheet ID and a range. (values.get)
   *
   * @param string $spreadsheetId The ID of the spreadsheet to retrieve data from.
   * @param string $range The A1 notation of the values to retrieve.
   * @param array $optParams Optional parameters.
   *
   * @opt_param string valueRenderOption How values should be represented in the
   * output.
   * @opt_param string dateTimeRenderOption How dates, times, and durations should
   * be represented in the output. This is ignored if value_render_option is
   * FORMATTED_VALUE.
   * @opt_param string majorDimension The major dimension that results should use.
   *
   * For example, if the spreadsheet data is: `A1=1,B1=2,A2=3,B2=4`, then
   * requesting `range=A1:B2,majorDimension=ROWS` will return `[[1,2],[3,4]]`,
   * whereas requesting `range=A1:B2,majorDimension=COLUMNS` will return
   * `[[1,3],[2,4]]`.
   * @return Google_Service_Sheets_ValueRange
   */
  public function get($spreadsheetId, $range, $optParams = array())
  {
    $params = array('spreadsheetId' => $spreadsheetId, 'range' => $range);
    $params = array_merge($params, $optParams);
    return $this->call('get', array($params), "Google_Service_Sheets_ValueRange");
  }
  /**
   * Sets values in a range of a spreadsheet. The caller must specify the
   * spreadsheet ID, range, and a valueInputOption. (values.update)
   *
   * @param string $spreadsheetId The ID of the spreadsheet to update.
   * @param string $range The A1 notation of the values to update.
   * @param Google_Service_Sheets_ValueRange $postBody
   * @param array $optParams Optional parameters.
   *
   * @opt_param string valueInputOption How the input data should be interpreted.
   * @return Google_Service_Sheets_UpdateValuesResponse
   */
  public function update($spreadsheetId, $range, Google_Service_Sheets_ValueRange $postBody, $optParams = array())
  {
    $params = array('spreadsheetId' => $spreadsheetId, 'range' => $range, 'postBody' => $postBody);
    $params = array_merge($params, $optParams);
    return $this->call('update', array($params), "Google_Service_Sheets_UpdateValuesResponse");
  }
}


text:
package org.gnucash.android.importer;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.provider.OpenableColumns;
import android.util.Log;
import android.widget.Toast;

import com.crashlytics.android.Crashlytics;

import org.gnucash.android.R;
import org.gnucash.android.db.DatabaseSchema;
import org.gnucash.android.db.adapter.BooksDbAdapter;
import org.gnucash.android.ui.util.TaskDelegate;
import org.gnucash.android.util.BookUtils;

import java.io.InputStream;

/**
 * Imports a GnuCash (desktop) account file and displays a progress dialog.
 * The AccountsActivity is opened when importing is done.
 */
public class ImportAsyncTask extends AsyncTask<Uri, Void, Boolean> {
    private final Activity mContext;
    private TaskDelegate mDelegate;
    private ProgressDialog mProgressDialog;

    private String mImportedBookUID;

    public ImportAsyncTask(Activity context){
        this.mContext = context;
    }

    public ImportAsyncTask(Activity context, TaskDelegate delegate){
        this.mContext = context;
        this.mDelegate = delegate;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        mProgressDialog = new ProgressDialog(mContext);
        mProgressDialog.setTitle(R.string.title_progress_importing_accounts);
        mProgressDialog.setIndeterminate(true);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mProgressDialog.show();

        //these methods must be called after progressDialog.show()
        mProgressDialog.setProgressNumberFormat(null);
        mProgressDialog.setProgressPercentFormat(null);

    }

    @Override
    protected Boolean doInBackground(Uri... uris) {
        try {
            InputStream accountInputStream = mContext.getContentResolver().openInputStream(uris[0]);
            mImportedBookUID = GncXmlImporter.parse(accountInputStream);

        } catch (Exception exception){
            Log.e(ImportAsyncTask.class.getName(), "" + exception.getMessage());
            Crashlytics.log("Could not open: " + uris[0].toString());
            Crashlytics.logException(exception);
            exception.printStackTrace();

            final String err_msg = exception.getLocalizedMessage();
            Crashlytics.log(err_msg);
            mContext.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(mContext,
                            mContext.getString(R.string.toast_error_importing_accounts) + "\n" + err_msg,
                            Toast.LENGTH_LONG).show();
                }
            });

            return false;
        }

        Cursor cursor = mContext.getContentResolver().query(uris[0], null, null, null, null);
        if (cursor != null && cursor.moveToFirst()) {
            int nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
            String displayName = cursor.getString(nameIndex);
            ContentValues contentValues = new ContentValues();
            contentValues.put(DatabaseSchema.BookEntry.COLUMN_DISPLAY_NAME, displayName);
            contentValues.put(DatabaseSchema.BookEntry.COLUMN_SOURCE_URI, uris[0].toString());
            BooksDbAdapter.getInstance().updateRecord(mImportedBookUID, contentValues);

            cursor.close();
        }

        //set the preferences to their default values
        mContext.getSharedPreferences(mImportedBookUID, Context.MODE_PRIVATE)
                .edit()
                .putBoolean(mContext.getString(R.string.key_use_double_entry), true)
                .apply();

        return true;
    }

    @Override
    protected void onPostExecute(Boolean importSuccess) {
        try {
            if (mProgressDialog != null && mProgressDialog.isShowing())
                mProgressDialog.dismiss();
        } catch (IllegalArgumentException ex){
            //TODO: This is a hack to catch "View not attached to window" exceptions
            //FIXME by moving the creation and display of the progress dialog to the Fragment
        } finally {
            mProgressDialog = null;
        }

        int message = importSuccess ? R.string.toast_success_importing_accounts : R.string.toast_error_importing_accounts;
        Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();

        if (mImportedBookUID != null)
            BookUtils.loadBook(mImportedBookUID);

        if (mDelegate != null)
            mDelegate.onTaskComplete();
    }
}


text:
var sig = require('sig-js'),
    event = require('sig-event'),
    eio = require('engine.io-client')

function client() {
  var self = {}

  self.engine = eio.apply(null, arguments)
  self.in = sig.functor(input(self))
  self.out = sig.functor(output(self))

  self.close = function() {
    self.in().end()
    self.out().end()
    self.engine.close()
    return self
  }

  return self
}

function input(client) {
  return event(client.engine, 'message')
    .map(JSON.parse)
}

function output(client) {
  var engine = client.engine
  var s = sig()

  s.map(JSON.stringify)
   .each(function(d) { engine.send(d) })
   .done()

  return s
}

module.exports = client


text:
'use strict';

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }

var FixedDataTableHelper = require('./FixedDataTableHelper');
var ImmutableObject = require('./ImmutableObject');
var React = require('./React');
var ReactComponentWithPureRenderMixin = require('./ReactComponentWithPureRenderMixin');
var FixedDataTableCell = require('./FixedDataTableCell.react');

var cx = require('./cx');
var renderToString = FixedDataTableHelper.renderToString;
var translateDOMPositionXY = require('./translateDOMPositionXY');

var PropTypes = React.PropTypes;

var DIR_SIGN = FixedDataTableHelper.DIR_SIGN;
var EMPTY_OBJECT = new ImmutableObject({});

var FixedDataTableCellGroupImpl = React.createClass({
  displayName: 'FixedDataTableCellGroupImpl',

  mixins: [ReactComponentWithPureRenderMixin],

  propTypes: {

    /**
     * Array of <FixedDataTableColumn />.
     */
    columns: PropTypes.array.isRequired,

    /**
     * The row data to render. The data format can be a simple Map object
     * or an Array of data.
     */
    data: PropTypes.oneOfType([PropTypes.object, PropTypes.array]),

    left: PropTypes.number,

    onColumnResize: PropTypes.func,

    rowHeight: PropTypes.number.isRequired,

    rowIndex: PropTypes.number.isRequired,

    width: PropTypes.number.isRequired,

    zIndex: PropTypes.number.isRequired
  },

  render: function render() /*object*/{
    var props = this.props;
    var columns = props.columns;
    var cells = new Array(columns.length);

    var currentPosition = 0;
    for (var i = 0, j = columns.length; i < j; i++) {
      var columnProps = columns[i].props;
      if (!columnProps.allowCellsRecycling || currentPosition - props.left <= props.width && currentPosition - props.left + columnProps.width >= 0) {
        var key = 'cell_' + i;
        cells[i] = this._renderCell(props.data, props.rowIndex, props.rowHeight, columnProps, currentPosition, key);
      }
      currentPosition += columnProps.width;
    }

    var contentWidth = this._getColumnsWidth(columns);

    var style = {
      height: props.height,
      position: 'absolute',
      width: contentWidth,
      zIndex: props.zIndex
    };
    translateDOMPositionXY(style, -1 * DIR_SIGN * props.left, 0);

    return React.createElement(
      'div',
      {
        className: cx('fixedDataTableCellGroupLayout/cellGroup'),
        style: style },
      cells
    );
  },

  _renderCell: function _renderCell(
  /*?object|array*/rowData,
  /*number*/rowIndex,
  /*number*/height,
  /*object*/columnProps,
  /*number*/left,
  /*string*/key) /*object*/{
    var cellRenderer = columnProps.cellRenderer || renderToString;
    var columnData = columnProps.columnData || EMPTY_OBJECT;
    var cellDataKey = columnProps.dataKey;
    var isFooterCell = columnProps.isFooterCell;
    var isHeaderCell = columnProps.isHeaderCell;
    var cellData;

    if (isHeaderCell || isFooterCell) {
      if (rowData == null || rowData[cellDataKey] == null) {
        cellData = columnProps.label;
      } else {
        cellData = rowData[cellDataKey];
      }
    } else {
      var cellDataGetter = columnProps.cellDataGetter;
      cellData = cellDataGetter ? cellDataGetter(cellDataKey, rowData) : rowData[cellDataKey];
    }

    var cellIsResizable = columnProps.isResizable && this.props.onColumnResize;
    var onColumnResize = cellIsResizable ? this.props.onColumnResize : null;

    var className;
    if (isHeaderCell || isFooterCell) {
      className = isHeaderCell ? columnProps.headerClassName : columnProps.footerClassName;
    } else {
      className = columnProps.cellClassName;
    }

    return React.createElement(FixedDataTableCell, {
      align: columnProps.align,
      cellData: cellData,
      cellDataKey: cellDataKey,
      cellRenderer: cellRenderer,
      className: className,
      columnData: columnData,
      height: height,
      isFooterCell: isFooterCell,
      isHeaderCell: isHeaderCell,
      key: key,
      maxWidth: columnProps.maxWidth,
      minWidth: columnProps.minWidth,
      onColumnResize: onColumnResize,
      rowData: rowData,
      rowIndex: rowIndex,
      width: columnProps.width,
      left: left
    });
  },

  _getColumnsWidth: function _getColumnsWidth(columns) {
    var width = 0;
    for (var i = 0; i < columns.length; ++i) {
      width += columns[i].props.width;
    }
    return width;
  }
});

var FixedDataTableCellGroup = React.createClass({
  displayName: 'FixedDataTableCellGroup',

  mixins: [ReactComponentWithPureRenderMixin],

  propTypes: {
    /**
     * Height of the row.
     */
    height: PropTypes.number.isRequired,

    offsetLeft: PropTypes.number,

    /**
     * Z-index on which the row will be displayed. Used e.g. for keeping
     * header and footer in front of other rows.
     */
    zIndex: PropTypes.number.isRequired
  },

  getDefaultProps: function getDefaultProps() /*object*/{
    return {
      offsetLeft: 0
    };
  },

  render: function render() /*object*/{
    var _props = this.props;
    var offsetLeft = _props.offsetLeft;

    var props = _objectWithoutProperties(_props, ['offsetLeft']);

    var style = {
      height: props.height
    };

    if (DIR_SIGN === 1) {
      style.left = offsetLeft;
    } else {
      style.right = offsetLeft;
    }

    var onColumnResize = props.onColumnResize ? this._onColumnResize : null;

    return React.createElement(
      'div',
      {
        style: style,
        className: cx('fixedDataTableCellGroupLayout/cellGroupWrapper') },
      React.createElement(FixedDataTableCellGroupImpl, _extends({}, props, {
        onColumnResize: onColumnResize
      }))
    );
  },

  _onColumnResize: function _onColumnResize(
  /*number*/left,
  /*number*/width,
  /*?number*/minWidth,
  /*?number*/maxWidth,
  /*string|number*/cellDataKey,
  /*object*/event) {
    this.props.onColumnResize && this.props.onColumnResize(this.props.offsetLeft, left - this.props.left + width, width, minWidth, maxWidth, cellDataKey, event);
  }
});

module.exports = FixedDataTableCellGroup;


text:
from DistributedMinigameAI import *
from direct.distributed.ClockDelta import *
from direct.fsm import ClassicFSM, State
from direct.fsm import State
from direct.task import Task
import PhotoGameGlobals
from toontown.minigame import PhotoGameBase
import random

class DistributedPhotoGameAI(DistributedMinigameAI, PhotoGameBase.PhotoGameBase):
    notify = DirectNotifyGlobal.directNotify.newCategory('DistributedPhotoGameAI')

    def __init__(self, air, minigameId):
        DistributedMinigameAI.__init__(self, air, minigameId)
        PhotoGameBase.PhotoGameBase.__init__(self)
        self.gameFSM = ClassicFSM.ClassicFSM('DistributedPhotoGameAI', [State.State('inactive', self.enterInactive, self.exitInactive, ['play']), State.State('play', self.enterPlay, self.exitPlay, ['cleanup']), State.State('cleanup', self.enterCleanup, self.exitCleanup, ['inactive'])], 'inactive', 'inactive')
        self.addChildGameFSM(self.gameFSM)

    def delete(self):
        self.notify.debug('delete')
        del self.gameFSM
        DistributedMinigameAI.delete(self)

    def setGameReady(self):
        self.notify.debug('setGameReady')
        DistributedMinigameAI.setGameReady(self)

    def setGameStart(self, timestamp):
        self.notify.debug('setGameStart')
        DistributedMinigameAI.setGameStart(self, timestamp)
        assignmentTemplates = self.generateAssignmentTemplates(PhotoGameGlobals.ONSCREENASSIGNMENTS)
        self.assignmentData = self.generateAssignmentData(assignmentTemplates)
        self.gameFSM.request('play')
        self.filmCountList = [0,
         0,
         0,
         0]

    def setGameAbort(self):
        self.notify.debug('setGameAbort')
        if self.gameFSM.getCurrentState():
            self.gameFSM.request('cleanup')
        DistributedMinigameAI.setGameAbort(self)

    def gameOver(self):
        self.notify.debug('gameOver')
        self.gameFSM.request('cleanup')
        DistributedMinigameAI.gameOver(self)

    def enterInactive(self):
        self.notify.debug('enterInactive')

    def exitInactive(self):
        pass

    def enterPlay(self):
        self.notify.debug('enterPlay')
        if not config.GetBool('endless-photo-game', 0):
            taskMgr.doMethodLater(self.data['TIME'], self.timerExpired, self.taskName('gameTimer'))

    def timerExpired(self, task = None):
        self.notify.debug('timer expired')
        self.calculateScores()
        self.gameOver()
        if task:
            return task.done

    def __playing(self):
        if not hasattr(self, 'gameFSM'):
            return 0
        return self.gameFSM.getCurrentState().getName() == 'play'

    def generateAssignmentData(self, assignmentTemplates):
        assignmentData = []
        for template in assignmentTemplates:
            playerScores = [0,
             0,
             0,
             0]
            highScorer = None
            dataEntry = [template[0],
             template[1],
             playerScores,
             highScorer]
            assignmentData.append(dataEntry)

        return assignmentData

    def checkForFilmOut(self):
        numOut = 0
        for entry in self.filmCountList:
            if entry >= self.data['FILMCOUNT']:
                numOut += 1

        numPlayers = 0
        for entry in self.avIdList:
            if entry:
                numPlayers += 1

        if numOut >= numPlayers:
            self.timerExpired()

    def filmOut(self):
        avId = self.air.getAvatarIdFromSender()
        if avId not in self.avIdList:
            self.air.writeServerEvent('suspicious', avId, 'PhotoGameAI.filmOut: unknown avatar')
            return
        if self.gameFSM.getCurrentState() is None or self.gameFSM.getCurrentState().getName() != 'play':
            self.air.writeServerEvent('suspicious', avId, 'PhotoGameAI.filmOut: game not in play state')
            return
        playerIndex = self.avIdList.index(avId)
        self.filmCountList[playerIndex] = self.data['FILMCOUNT']
        self.checkForFilmOut()
        return

    def newClientPhotoScore(self, subjectIndex, pose, score):
        avId = self.air.getAvatarIdFromSender()
        if self.gameFSM.getCurrentState() is None or self.gameFSM.getCurrentState().getName() != 'play':
            if self.gameFSM.getCurrentState() is None:
                gameState = None
            else:
                gameState = self.gameFSM.getCurrentState().getName()
            self.air.writeServerEvent('suspicious', avId, 'PhotoGameAI.newClientPhotoScore: game not in play state %s' % gameState)
            return
        if score > PhotoGameGlobals.NUMSTARS:
            score = 0.0
        if avId not in self.avIdList:
            self.air.writeServerEvent('suspicious', avId, 'PhotoGameAI.newClientPhotoScore: non-player avatar')
            return
        playerIndex = self.avIdList.index(avId)
        self.filmCountList[playerIndex] += 1
        self.checkForFilmOut()
        if self.filmCountList[playerIndex] >= self.data['FILMCOUNT']:
            self.notify.debug('player used more film than possible')
            return
        assignmentIndex = None
        for dataIndex in range(len(self.assignmentData)):
            assignment = self.assignmentData[dataIndex]
            if assignment[0] == subjectIndex and assignment[1] == pose:
                assignmentIndex = dataIndex

        if assignmentIndex != None and self.assignmentData[assignmentIndex][2][playerIndex] < score:
            self.assignmentData[assignmentIndex][2][playerIndex] = score
            highScorer = self.assignmentData[assignmentIndex][3]
            if highScorer == None:
                self.assignmentData[assignmentIndex][3] = playerIndex
            elif self.assignmentData[assignmentIndex][2][highScorer] < self.assignmentData[assignmentIndex][2][playerIndex]:
                self.assignmentData[assignmentIndex][3] = playerIndex
            self.sendUpdate('newAIPhotoScore', [avId, assignmentIndex, score])
        self.notify.debug('newClientPhotoScore %s %s %s %s' % (avId,
         subjectIndex,
         pose,
         score))
        for data in self.assignmentData:
            self.notify.debug(str(data))

        return

    def calculateScores(self):
        playerBonus = [0.0,
         0.0,
         0.0,
         0.0]
        teamScore = 0.0
        for data in self.assignmentData:
            scores = data[2]
            highestIndex = data[3]
            if highestIndex != None:
                highestScore = scores[highestIndex]
                self.notify.debug('\nHighIndex:%s' % highestIndex)
                self.notify.debug('scores')
                self.notify.debug(str(scores))
                teamScore += highestScore
                if highestIndex != None:
                    playerBonus[highestIndex] += 1.0

        for avIdKey in self.scoreDict:
            playerIndex = self.avIdList.index(avIdKey)
            playerScore = playerBonus[playerIndex] + teamScore
            self.scoreDict[avIdKey] = playerScore

        self.notify.debug('Calculated Scores')
        self.notify.debug('playerbonus')
        self.notify.debug(str(playerBonus))
        self.notify.debug('teamscore')
        self.notify.debug(str(teamScore))
        self.notify.debug('dict')
        self.notify.debug(str(self.scoreDict))
        return

    def exitPlay(self):
        taskMgr.remove(self.taskName('gameTimer'))
        taskMgr.remove(self.taskName('game-over'))

    def enterCleanup(self):
        self.notify.debug('enterCleanup')
        self.gameFSM.request('inactive')

    def exitCleanup(self):
        pass


text:
import sys
import tkinter as tk
import tkinter.ttk as ttk

class ClickInvoke(tk.Tk):
    def __init__(self):
        super().__init__()
        self.b1 = ttk.Button(text='Button 1', name='b1', command=self.click1)
        self.b1.pack(side='left')
        self.b2 = ttk.Button(text='Button 2', name='b2', command=self.click2)
        self.b2.pack(side='left')

    def click1(self):
        print('Button 1 clicked.')

    def click2(self):
        print('Button 2 clicked.')
        self.b1.invoke()

def main():
    app = ClickInvoke()
    app.mainloop()

if __name__ == '__main__':
    sys.exit(main())

#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# -*- coding: utf-8 -*-
# test_clickinvoke.py

import unittest

import clickinvoke

class TestClickInvoke(unittest.TestCase):
    def setUp(self):
        self.app = clickinvoke.ClickInvoke()

    def tearDown(self):
        self.app.destroy()

    def test_button1(self):
        self.app.children['b1'].invoke()

    def test_button2(self):
        self.app.children['b2'].invoke()