text:
Stacked Ensembles
-----------------

Introduction
~~~~~~~~~~~~

Ensemble machine learning methods use multiple learning algorithms to obtain better predictive performance than could be obtained from any of the constituent learning algorithms. Many of the popular modern machine learning algorithms are actually ensembles. For example, `Random Forest <http://docs.h2o.ai/h2o/latest-stable/h2o-docs/data-science/drf.html>`__ and `Gradient Boosting Machine (GBM) <http://docs.h2o.ai/h2o/latest-stable/h2o-docs/data-science/gbm.html>`__ are both ensemble learners.  Both bagging (e.g. Random Forest) and boosting (e.g. GBM) are methods for ensembling that take a collection of weak learners (e.g. decision tree) and form a single, strong learner.

H2O's Stacked Ensemble method is a supervised ensemble machine learning algorithm that finds the optimal combination of a collection of prediction algorithms using a process called stacking.  Like all supervised models in H2O, Stacked Ensemeble supports regression, binary classification, and multiclass classification.

Native support for ensembles of H2O algorithms was added into core H2O in version 3.10.3.1.  A separate implementation, the **h2oEnsemble** R package, is also still `available <https://github.com/h2oai/h2o-3/tree/master/h2o-r/ensemble>`__, however for new projects we recommend using the native H2O version, documented below.

Stacking / Super Learning
~~~~~~~~~~~~~~~~~~~~~~~~~

Stacking, also called Super Learning [3_] or Stacked Regression [2_], is a class of algorithms that involves training a second-level "metalearner" to find the optimal combination of the base learners.  Unlike bagging and boosting, the goal in stacking is to ensemble strong, diverse sets of learners together.

Although the concept of stacking was originally developed in 1992 [1_], the theoretical guarantees for stacking were not proven until the publication of a paper titled, `"Super Learner" <https://doi.org/10.2202/1544-6115.1309>`__, in 2007 [3_].  In this paper, it was shown that the Super Learner ensemble represents an asymptotically optimal system for learning.

There are some ensemble methods that are broadly labeled as stacking, however, the Super Learner ensemble is distinguished by the use of cross-validation to form what is called the "level-one" data, or the data that the metalearning or "combiner" algorithm is trained on.  More detail about the Super Learner algorithm is provided below.

Super Learner Algorithm
'''''''''''''''''''''''

The steps below describe the individual tasks involved in training and testing a Super Learner ensemble.  H2O automates most of the steps below so that you can quickly and easily build ensembles of H2O models.

1. Set up the ensemble.

   a. Specify a list of L base algorithms (with a specific set of model parameters).
   b. Specify a metalearning algorithm.

2. Train the ensemble.

   a. Train each of the L base algorithms on the training set.
   b. Perform k-fold cross-validation on each of these learners and collect the cross-validated predicted values from each of the L algorithms.
   c. The N cross-validated predicted values from each of the L algorithms can be combined to form a new N x L matrix. This matrix, along with the original response vector, is called the "level-one" data. (N = number of rows in the training set.)
   d. Train the metalearning algorithm on the level-one data.
      The "ensemble model" consists of the L base learning models and the metalearning model, which can then be used to generate predictions on a test set.

3. Predict on new data.

   a. To generate ensemble predictions, first generate predictions from the base learners.
   b. Feed those predictions into the metalearner to generate the ensemble prediction.

Training Base Models for the Ensemble
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Before training a stacked ensemble, you will need to train and cross-validate a set of "base models" which will make up the ensemble.  In order to stack these models together, a few things are required:

- The models must be cross-validated using the same number of folds (e.g. ``nfolds = 5`` or use the same ``fold_column`` across base learners).

- The cross-validated predictions from all of the models must be preserved by setting ``keep_cross_validation_predictions`` to True.  This is the data which is used to train the metalearner, or "combiner", algorithm in the ensemble.

- You can train these models manually, or you can use a group of models from a grid search.

- The models must be trained on the same ``training_frame``.  The rows must be identical, but you can use different sets of predictor columns, ``x``, across models if you choose.  Using base models trained on different subsets of the feature space will add more randomness/diversity to the set of base models, which in theory can improve ensemble performance.  However, using all available predictor columns for each base model will often still yield the best results (the more data, the better the models).

**Note:** You can train a Stacked Ensemble model using only monotonic models by specifying ``monotone_constraints`` in AutoML and creating at least 2 monotonic models.

Defining a Stacked Ensemble Model
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

-  `y <algo-params/y.html>`__: (Required) Specify the index or column name of the column to use as the dependent variable (response column). The response column can be numeric (regression) or categorical (classification).

-  `x <algo-params/x.html>`__: (Optional) Specify a vector containing the names or indices of the predictor variables to use when building the model.   If ``x`` is missing, then all columns except ``y`` are used.  The only use for ``x`` is to get the correct training set so that we can compute ensemble training metrics.

-  `training_frame <algo-params/training_frame.html>`__ (Required) Specify the dataset used to build the model.  In a Stacked Ensemble model, the training frame is used only to retreive the response column (needed for training the metalearner) and also to compute training metrics for the ensemble model.

-  `validation_frame <algo-params/validation_frame.html>`__: (Optional) Specify the dataset to use for tuning the model.  The validation frame will be passed through to the metalearner for tuning.

-  `blending_frame <algo-params/blending_frame.html>`__: (Optional) Specify a frame to be used for computing the predictions that serve as the training frame for the metalearner. This triggers blending mode if provided.

-  `model_id <algo-params/model_id.html>`__: (Optional) Specify a custom name for the model to use as a reference. By default, H2O automatically generates a destination key.

-  `base_models <algo-params/base_models.html>`__: (Required) Specify a list of models (or model IDs) that can be stacked together.  Models must have been cross-validated (i.e. ``nfolds``>1 or ``fold_column`` was specified), they all must use the same cross-validation folds, and ``keep_cross_validation_predictions`` must have been set to True. One way to guarantee identical folds across base models is to set ``fold_assignment = "Modulo"`` in all the base models.  It is also possible to get identical folds by setting ``fold_assignment = "Random"`` when the same seed is used in all base models.

-  `metalearner_algorithm <algo-params/metalearner_algorithm.html>`__ (Optional) Specify the metalearner algorithm type.  Options include:

 - ``"AUTO"`` (GLM with non negative weights & standardization turned off, and if ``validation_frame`` is present, then ``lambda_search`` is set to True; may change over time). This is the default.
 - ``"glm"`` (GLM with default parameters)
 - ``"gbm"`` (GBM with default parameters)
 - ``"drf"`` (Random Forest with default parameters)
 - ``"deeplearning"`` (Deep Learning with default parameters)
 - ``"naivebayes"`` (NaiveBayes with default parameters)
 - ``"xgboost"`` (if available, XGBoost with default parameters)

-  `metalearner_params <algo-params/metalearner_params.html>`__: (Optional) If a ``metalearner_algorithm`` is specified, then you can also specify a list of customized parameters for that algorithm (for example, a GBM with ``ntrees=100``, ``max_depth=10``, etc.)

-  `metalearner_nfolds <algo-params/nfolds.html>`__: (Optional) Specify the number of folds for cross-validation of the metalearning algorithm.  Defaults to 0 (no cross-validation).  If you want to compare the cross-validated performance of the ensemble model to the cross-validated performance of the base learners or other algorithms, you should make use of this option.

-  `metalearner_fold_assignment <algo-params/fold_assignment.html>`__: (Optional; Applicable only if a value for ``metalearner_nfolds`` is specified) Specify the cross-validation fold assignment scheme for the metalearner. The available options are AUTO (which is Random), Random, Modulo, or Stratified (which will stratify the folds based on the response variable for classification problems). This value defaults to AUTO.

-  `metalearner_fold_column <algo-params/fold_column.html>`__: (Optional; Cannot be used at the same time as ``nfolds``) Specify the name of the column that contains the cross-validation fold assignment per observation for cross-validation of the metalearner.  The column can be numeric (e.g. fold index or other integer value) or it can be categorical.  The number of folds is equal to the number of unique values in this column.

-  `metalearner_transform <algo-params/metalearner_transform.html>`__: (Optional) Specify the transformation used on predictions from the base models in order to make a level one frame. Options include:

 - ``"NONE"`` (no transform applied)
 - ``"Logit"`` (applicable only to classification tasks, use logit transformation on the predicted probabilities)

-  `offset_column <algo-params/offset_column.html>`__: (Optional; Availability depends on the ``metalearner_algorithm``) Specify a column to use as the offset.

-  `weights_column <algo-params/weights_column.html>`__: (Optional) Specifies a column with observation weights. Giving some observation a weight of zero is equivalent to excluding it from the dataset; giving an observation a relative weight of 2 is equivalent to repeating that row twice. Negative weights are not allowed.

-  **keep_levelone_frame**: (Optional) Keep the level one data frame that's constructed for the metalearning step. Defaults to False.

-  `max_runtime_secs <algo-params/max_runtime_secs.html>`__: (Optional) Maximum allowed runtime in seconds for the metalearner model training. Use 0 to disable the time limit. Defaults to 0.

-  `seed <algo-params/seed.html>`__: (Optional) Seed for random numbers; passed through to the metalearner algorithm. Defaults to -1 (time-based random number).

-  `export_checkpoints_dir <algo-params/export_checkpoints_dir.html>`__: Specify a directory to which generated models will automatically be exported.

You can follow the progress of H2O's Stacked Ensemble development `here <https://0xdata.atlassian.net/issues/?filter=19301>`__.

Examples
~~~~~~~~

Below is a simple example showing how to build a Stacked Ensembles model.

.. tabs::
   .. code-tab:: r R

        library(h2o)
        h2o.init()

        # Import a sample binary outcome train/test set into H2O
        train <- h2o.importFile("https://s3.amazonaws.com/erin-data/higgs/higgs_train_10k.csv")
        test <- h2o.importFile("https://s3.amazonaws.com/erin-data/higgs/higgs_test_5k.csv")

        # Identify predictors and response
        y <- "response"
        x <- setdiff(names(train), y)

        # For binary classification, response should be a factor
        train[, y] <- as.factor(train[, y])
        test[, y] <- as.factor(test[, y])

        # Number of CV folds (to generate level-one data for stacking)
        nfolds <- 5

        # There are a few ways to assemble a list of models to stack toegether:
        # 1. Train individual models and put them in a list
        # 2. Train a grid of models
        # 3. Train several grids of models
        # Note: All base models must have the same cross-validation folds and
        # the cross-validated predicted values must be kept.

        # 1. Generate a 2-model ensemble (GBM + RF)

        # Train & Cross-validate a GBM
        my_gbm <- h2o.gbm(x = x,
                          y = y,
                          training_frame = train,
                          distribution = "bernoulli",
                          ntrees = 10,
                          max_depth = 3,
                          min_rows = 2,
                          learn_rate = 0.2,
                          nfolds = nfolds,
                          keep_cross_validation_predictions = TRUE,
                          seed = 1)

        # Train & Cross-validate a RF
        my_rf <- h2o.randomForest(x = x,
                                  y = y,
                                  training_frame = train,
                                  ntrees = 50,
                                  nfolds = nfolds,
                                  keep_cross_validation_predictions = TRUE,
                                  seed = 1)

        # Train a stacked ensemble using the GBM and RF above
        ensemble <- h2o.stackedEnsemble(x = x,
                                        y = y,
                                        training_frame = train,
                                        base_models = list(my_gbm, my_rf))

        # Eval ensemble performance on a test set
        perf <- h2o.performance(ensemble, newdata = test)

        # Compare to base learner performance on the test set
        perf_gbm_test <- h2o.performance(my_gbm, newdata = test)
        perf_rf_test <- h2o.performance(my_rf, newdata = test)
        baselearner_best_auc_test <- max(h2o.auc(perf_gbm_test), h2o.auc(perf_rf_test))
        ensemble_auc_test <- h2o.auc(perf)
        print(sprintf("Best Base-learner Test AUC:  %s", baselearner_best_auc_test))
        print(sprintf("Ensemble Test AUC:  %s", ensemble_auc_test))
        # [1] "Best Base-learner Test AUC:  0.76979821502548"
        # [1] "Ensemble Test AUC:  0.773501212640419"

        # Generate predictions on a test set (if neccessary)
        pred <- h2o.predict(ensemble, newdata = test)

        # 2. Generate a random grid of models and stack them together

        # GBM Hyperparamters
        learn_rate_opt <- c(0.01, 0.03)
        max_depth_opt <- c(3, 4, 5, 6, 9)
        sample_rate_opt <- c(0.7, 0.8, 0.9, 1.0)
        col_sample_rate_opt <- c(0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8)
        hyper_params <- list(learn_rate = learn_rate_opt,
                             max_depth = max_depth_opt,
                             sample_rate = sample_rate_opt,
                             col_sample_rate = col_sample_rate_opt)

        search_criteria <- list(strategy = "RandomDiscrete",
                                max_models = 3,
                                seed = 1)

        gbm_grid <- h2o.grid(algorithm = "gbm",
                             grid_id = "gbm_grid_binomial",
                             x = x,
                             y = y,
                             training_frame = train,
                             ntrees = 10,
                             seed = 1,
                             nfolds = nfolds,
                             keep_cross_validation_predictions = TRUE,
                             hyper_params = hyper_params,
                             search_criteria = search_criteria)

        # Train a stacked ensemble using the GBM grid
        ensemble <- h2o.stackedEnsemble(x = x,
                                        y = y,
                                        training_frame = train,
                                        base_models = gbm_grid@model_ids)

        # Eval ensemble performance on a test set
        perf <- h2o.performance(ensemble, newdata = test)

        # Compare to base learner performance on the test set
        .getauc <- function(mm) h2o.auc(h2o.performance(h2o.getModel(mm), newdata = test))
        baselearner_aucs <- sapply(gbm_grid@model_ids, .getauc)
        baselearner_best_auc_test <- max(baselearner_aucs)
        ensemble_auc_test <- h2o.auc(perf)
        print(sprintf("Best Base-learner Test AUC:  %s", baselearner_best_auc_test))
        print(sprintf("Ensemble Test AUC:  %s", ensemble_auc_test))
        # [1] "Best Base-learner Test AUC:  0.748146530400473"
        # [1] "Ensemble Test AUC:  0.773501212640419"

        # Generate predictions on a test set (if neccessary)
        pred <- h2o.predict(ensemble, newdata = test)

   .. code-tab:: python

        import h2o
        from h2o.estimators.random_forest import H2ORandomForestEstimator
        from h2o.estimators.gbm import H2OGradientBoostingEstimator
        from h2o.estimators.stackedensemble import H2OStackedEnsembleEstimator
        from h2o.grid.grid_search import H2OGridSearch
        from __future__ import print_function
        h2o.init()

        # Import a sample binary outcome train/test set into H2O
        train = h2o.import_file("https://s3.amazonaws.com/erin-data/higgs/higgs_train_10k.csv")
        test = h2o.import_file("https://s3.amazonaws.com/erin-data/higgs/higgs_test_5k.csv")

        # Identify predictors and response
        x = train.columns
        y = "response"
        x.remove(y)

        # For binary classification, response should be a factor
        train[y] = train[y].asfactor()
        test[y] = test[y].asfactor()

        # Number of CV folds (to generate level-one data for stacking)
        nfolds = 5

        # There are a few ways to assemble a list of models to stack together:
        # 1. Train individual models and put them in a list
        # 2. Train a grid of models
        # 3. Train several grids of models
        # Note: All base models must have the same cross-validation folds and
        # the cross-validated predicted values must be kept.

        # 1. Generate a 2-model ensemble (GBM + RF)

        # Train and cross-validate a GBM
        my_gbm = H2OGradientBoostingEstimator(distribution="bernoulli",
                                              ntrees=10,
                                              max_depth=3,
                                              min_rows=2,
                                              learn_rate=0.2,
                                              nfolds=nfolds,
                                              fold_assignment="Modulo",
                                              keep_cross_validation_predictions=True,
                                              seed=1)
        my_gbm.train(x=x, y=y, training_frame=train)

        # Train and cross-validate a RF
        my_rf = H2ORandomForestEstimator(ntrees=50,
                                         nfolds=nfolds,
                                         fold_assignment="Modulo",
                                         keep_cross_validation_predictions=True,
                                         seed=1)
        my_rf.train(x=x, y=y, training_frame=train)

        # Train a stacked ensemble using the GBM and GLM above
        ensemble = H2OStackedEnsembleEstimator(model_id="my_ensemble_binomial",
                                               base_models=[my_gbm, my_rf])
        ensemble.train(x=x, y=y, training_frame=train)

        # Eval ensemble performance on the test data
        perf_stack_test = ensemble.model_performance(test)

        # Compare to base learner performance on the test set
        perf_gbm_test = my_gbm.model_performance(test)
        perf_rf_test = my_rf.model_performance(test)
        baselearner_best_auc_test = max(perf_gbm_test.auc(), perf_rf_test.auc())
        stack_auc_test = perf_stack_test.auc()
        print("Best Base-learner Test AUC:  {0}".format(baselearner_best_auc_test))
        print("Ensemble Test AUC:  {0}".format(stack_auc_test))

        # Generate predictions on a test set (if neccessary)
        pred = ensemble.predict(test)

        # 2. Generate a random grid of models and stack them together

        # Specify GBM hyperparameters for the grid
        hyper_params = {"learn_rate": [0.01, 0.03],
                        "max_depth": [3, 4, 5, 6, 9],
                        "sample_rate": [0.7, 0.8, 0.9, 1.0],
                        "col_sample_rate": [0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8]}
        search_criteria = {"strategy": "RandomDiscrete", "max_models": 3, "seed": 1}

        # Train the grid
        grid = H2OGridSearch(model=H2OGradientBoostingEstimator(ntrees=10,
                                                                seed=1,
                                                                nfolds=nfolds,
                                                                fold_assignment="Modulo",
                                                                keep_cross_validation_predictions=True),
                             hyper_params=hyper_params,
                             search_criteria=search_criteria,
                             grid_id="gbm_grid_binomial")
        grid.train(x=x, y=y, training_frame=train)

        # Train a stacked ensemble using the GBM grid
        ensemble = H2OStackedEnsembleEstimator(model_id="my_ensemble_gbm_grid_binomial",
                                               base_models=grid.model_ids)
        ensemble.train(x=x, y=y, training_frame=train)

        # Eval ensemble performance on the test data
        perf_stack_test = ensemble.model_performance(test)

        # Compare to base learner performance on the test set
        baselearner_best_auc_test = max([h2o.get_model(model).model_performance(test_data=test).auc() for model in grid.model_ids])
        stack_auc_test = perf_stack_test.auc()
        print("Best Base-learner Test AUC:  {0}".format(baselearner_best_auc_test))
        print("Ensemble Test AUC:  {0}".format(stack_auc_test))

        # Generate predictions on a test set (if neccessary)
        pred = ensemble.predict(test)

   .. code-tab:: scala

        import org.apache.spark.h2o._
        import water.Key
        import java.io.File

        val h2oContext = H2OContext.getOrCreate(sc)
        import h2oContext._
        import h2oContext.implicits._

        // Import data from the local file system as an H2O DataFrame
        val prostateData = new H2OFrame(new File("/Users/jsmith/src/github.com/h2oai/sparkling-water/examples/smalldata/prostate.csv"))

        // Build a Deep Learning model
        import _root_.hex.deeplearning.DeepLearning
        import _root_.hex.deeplearning.DeepLearningModel.DeepLearningParameters
        val dlParams = new DeepLearningParameters()
        dlParams._epochs = 100
        dlParams._train = prostateData
        dlParams._response_column = 'CAPSULE
        dlParams._variable_importances = true
        dlParams._nfolds = 5
        dlParams._seed = 1111
        dlParams._keep_cross_validation_predictions = true;
        val dl = new DeepLearning(dlParams, Key.make("dlProstateModel.hex"))
        val dlModel = dl.trainModel.get

        // Build a GBM model
        import _root_.hex.tree.gbm.GBM
        import _root_.hex.tree.gbm.GBMModel.GBMParameters
        val gbmParams = new GBMParameters()
        gbmParams._train = prostateData
        gbmParams._response_column = 'CAPSULE
        gbmParams._nfolds = 5
        gbmParams._seed = 1111
        gbmParams._keep_cross_validation_predictions = true;
        val gbm = new GBM(gbmParams,Key.make("gbmRegModel.hex"))
        val gbmModel = gbm.trainModel().get()

        // Import required classes for Stacked Ensembles
        import _root_.hex.Model
        import _root_.hex.ensemble.StackedEnsembleModel
        import _root_.hex.ensemble.StackedEnsemble

        // Define Stacked Ensemble parameters
        val stackedEnsembleParameters = new StackedEnsembleModel.StackedEnsembleParameters()
        stackedEnsembleParameters._train = prostateData._key
        stackedEnsembleParameters._response_column = 'CAPSULE

        // Pass in the keys for the GBM and Deep Learning using one of the following options
        // Option 1
        stackedEnsembleParameters._base_models = Array(gbmRegModel._key.asInstanceOf[T_MODEL_KEY], dlModel._key.asInstanceOf[T_MODEL_KEY])
        // Option 2
        stackedEnsembleParameters._base_models = Array(gbmRegModel, dlModel).map(model => model._key.asInstanceOf[T_MODEL_KEY])

        // Define the Stacked Ensemble job
        val stackedEnsembleJob = new StackedEnsemble(stackedEnsembleParameters)

        // Build the Stacked Ensemble model
        val stackedEnsembleModel = stackedEnsembleJob.trainModel().get();

        // Review the Stacked Ensemble model
        stackedEnsembleModel

        // Review the parameters (meta learner) from the Stacked Ensemble model
        stackedEnsembleModel._output._metalearner

FAQ
~~~

-  **How do I save ensemble models?**

  H2O now supports saving and loading ensemble models. The steps are the same as those described in the `Saving and Loading a Model <../save-and-load-model.html>`__ section.  For productionizing Stacked Ensemble models, we recommend using `MOJOs <http://docs.h2o.ai/h2o/latest-stable/h2o-docs/productionizing.html>`__.

-  **Will an stacked ensemble always perform better than a single model?**

  Hopefully, but it's not always the case (especially if you have very small data).  That's why it always a good idea to check the performance of your stacked ensemble and compare it against the performance of the individual base learners.

-  **How do I improve the performance of an ensemble?**

  If you find that your ensemble is not performing better than the best base learner, then you can try a few different things.  First make sure to try the default metalearner ("AUTO") and then try the other options for ``metalearner_algorithm``.  Additionally, the custom parameters could be passed to ``metalearner_params`` (e.g., a GBM with ``ntrees=1000``, ``max_depth=10``, etc.)

  Second, look to see if there are base learners that are performing much worse than the other base learners (for example, a GLM).  If so, remove them from the ensemble and try again.

  You can also try adding more models to the ensemble, especially models that add diversity to your set of base models.  Training a random grid of models (or multiple random grids, one for each algorithm type) is a good way to generate a diverse set of base learners.

-  **How does the algorithm handle missing values during training?**

  This is handled by the base algorithms of the ensemble.  See the documentation for those algorithms to find out more information.

-  **How does the algorithm handle missing values during testing?**

  This is handled by the base algorithms of the ensemble.  See the documentation for those algorithms to find out more information.

-  **What happens if the response has missing values?**

  No errors will occur, but nothing will be learned from rows containing missing values in the response column.

-  **What happens when you try to predict on a categorical level not seen during training?**

  This is handled by the base algorithms of the ensemble.  See the documentation for those algorithms to find out more information.

-  **How does the algorithm handle highly imbalanced data in a response
   column?**

  In the base learners, specify ``balance_classes``, ``class_sampling_factors`` and ``max_after_balance_size`` to control over/under-sampling.

Additional Information
~~~~~~~~~~~~~~~~~~~~~~

- An `Ensemble slidedeck <https://github.com/h2oai/h2o-meetups/blob/master/2017_01_05_H2O_Ensemble_New_Developments/h2o_ensemble_new_developments_jan2017.pdf>`__ from January 2017 provides a summary of the new Stacked Ensemble method in H2O, along with a comparison to the pre-existing `h2oEnsemble R package <https://github.com/h2oai/h2o-3/tree/master/h2o-r/ensemble>`__.

- `Python Stacked Ensemble tests <https://github.com/h2oai/h2o-3/tree/master/h2o-py/tests/testdir_algos/stackedensemble>`__ are available in the H2O-3 GitHub repository.

- `R Stacked Enemble tests <https://github.com/h2oai/h2o-3/tree/master/h2o-r/tests/testdir_algos/stackedensemble>`__ are available in the H2O-3 GitHub repository.

References
~~~~~~~~~~

.. _1:

[1] `David H. Wolpert. "Stacked Generalization." Neural Networks. Volume 5. (1992) <http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.56.1533>`__

.. _2:

[2] `Leo Breiman. "Stacked Regressions." Machine Learning, 24, 49-64 (1996) <http://statistics.berkeley.edu/sites/default/files/tech-reports/367.pdf>`__

.. _3:

[3] `Mark J van der Laan, Eric C Polley, and Alan E Hubbard. "Super Learner." Journal of the American
Statistical Applications in Genetics and Molecular Biology. Volume 6, Issue 1. (September 2007). <https://doi.org/10.2202/1544-6115.1309>`__

.. _4:

[4] `LeDell, E. "Scalable Ensemble Learning and Computationally Efficient Variance Estimation" (Doctoral Dissertation). University of California, Berkeley, USA. (2015) <http://www.stat.berkeley.edu/~ledell/papers/ledell-phd-thesis.pdf>`__


text:
package ru.job4j.chess;

import org.junit.Test;
import static org.junit.Assert.assertEquals;
//import static org.junit.Assert.assertTrue;
/**
 * Класс BoardTest тестирует класс Board.
 *
 * @author Goureyev Ilya (mailto:ill-jah@yandex.ru)
 * @version 1
 * @since 2017-05-04
 */
public class BoardTest {
    /**
     * Тестирует addFigure().
     */
    @Test
    public void checkIsFigureOnBoard() {
        String position = "c1";
        Board board = new Board();
        Cell cell = board.getCell(position);
        Bishop bishop = new Bishop(cell, Color.BLACK);
        assertEquals(board.getFigureByPosition(position), bishop);
    }
    /**
     * Тестирует пользовательское исключение IllegalPositionException.
     */
    @Test(expected = IllegalPositionException.class)
    public void testIllegalPositionExceptionColGreaterThenH() {
        Board board = new Board();
        Cell cell = board.getCell("I1");
    }
    /**
     * Тестирует пользовательское исключение IllegalPositionException.
     */
    @Test(expected = IllegalPositionException.class)
    public void testIllegalPositionExceptionRowLowerThen1() {
        Board board = new Board();
        Cell cell = board.getCell("c0");
    }
    /**
     * Тестирует пользовательское исключение IllegalPositionException.
     */
    @Test(expected = IllegalPositionException.class)
    public void testIllegalPositionExceptionRowGreaterThen8() {
        Board board = new Board();
        Cell cell = board.getCell("f9");
    }
    /**
     * Тестирует пользовательское исключение FigureNotFoundException.
     */
    @Test(expected = FigureNotFoundException.class)
    public void testMoveFigureNotFoundException() {
        Board board = new Board();
        try {
            board.move(board.getCell("f8"), board.getCell("a1"));
        } catch (ImposibleMoveException | OccupiedWayException ex) {
            ex.printStackTrace();
        }
    }
    /**
     * Тестирует пользовательское исключение ImposibleMoveException.
     */
    @Test(expected = ImposibleMoveException.class)
    public void testMoveImposibleMoveException() {
        Board board = new Board();
        Cell cell = board.getCell("f8");
        Bishop bishop = new Bishop(cell, Color.WHITE);
        try {
            board.move(cell, board.getCell("a1"));
        } catch (FigureNotFoundException | OccupiedWayException ex) {
            ex.printStackTrace();
        }
    }
    /**
     * Тестирует пользовательское исключение OccupiedWayException.
     */
    @Test(expected = OccupiedWayException.class)
    public void testMoveOccupiedWayException() {
        Board board = new Board();
        Cell cell = board.getCell("c8");
        Bishop bishop1 = new Bishop(cell, Color.WHITE);
        Bishop bishop2 = new Bishop(board.getCell("f5"), Color.BLACK);
        try {
            board.move(cell, board.getCell("h3"));
        } catch (FigureNotFoundException | ImposibleMoveException ex) {
            ex.printStackTrace();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php
namespace QuickBooksOnline\API\Data;

/**
 * @xmlNamespace http://schema.intuit.com/finance/v3
 * @xmlType
 * @xmlName IPPCDCQuery
 * @var IPPCDCQuery
 * @xmlDefinition CDCQuery entity describing need for query
 */
class IPPCDCQuery
	{

		/**
		* Initializes this object, optionally with pre-defined property values
		*
		* Initializes this object and it's property members, using the dictionary
		* of key/value pairs passed as an optional argument.
		*
		* @param dictionary $keyValInitializers key/value pairs to be populated into object's properties
		* @param boolean $verbose specifies whether object should echo warnings
		*/
		public function __construct($keyValInitializers=array(), $verbose=FALSE)
		{
			foreach($keyValInitializers as $initPropName => $initPropVal)
			{
				if (property_exists('IPPCDCQuery',$initPropName) || property_exists('QuickBooksOnline\API\Data\IPPCDCQuery',$initPropName))
				{
					$this->{$initPropName} = $initPropVal;
				}
				else
				{
					if ($verbose)
						echo "Property does not exist ($initPropName) in class (".get_class($this).")";
				}
			}
		}

	/**
	 * @Definition Coma separated entity list of entities required
	 * @xmlType element
	 * @xmlNamespace http://schema.intuit.com/finance/v3
	 * @xmlMinOccurs 0
	 * @xmlName Entities
	 * @var string
	 */
	public $Entities;
	/**
	 * @Definition Time after which changes are required on the entities that are updated, created, deleted
	 * @xmlType element
	 * @xmlNamespace http://schema.intuit.com/finance/v3
	 * @xmlMinOccurs 0
	 * @xmlName ChangedSince
	 * @var string
	 */
	public $ChangedSince;

} // end class IPPCDCQuery


text:
package com.osc.tweet.events;

/**
 * Event to show user's information.
 */
public final class ShowUserInformationEvent {
	/**
	 * The oschina.net user-id of the user who will be shown.
	 */
	private long mUserId;

	/**
	 * Constructor of {@link ShowUserInformationEvent}
	 *
	 * @param userId
	 * 		The oschina.net user-id of the user who will be shown.
	 */
	public ShowUserInformationEvent(long userId) {
		mUserId = userId;
	}

	/**
	 * @return The oschina.net user-id of the user who will be shown.
	 */
	public long getUserId() {
		return mUserId;
	}
}


text:
define(['jquery', 'oae.core'], function($, oae) {

    return function(uid) {

        // The widget container
        var $rootel = $('#' + uid);

        // Variable that will keep track of the element that triggered the clickover
        var $trigger = null;

        // Variable that will keep track of the current page context.
        // This can be a content item or a discussion item.
        var contextProfile = null;

        // Variables that will keep track of the resourceType of the resource(s) being shared (i.e. `content`, `discussion`)
        var resourceType = null;

        // Variable that will keep track of the resources to share. For each resource, the `id` and `resourceSubType` will be stored
        var selectedResources = null;

        /**
         * Toggle the share clickover
         */
        var toggleShareClickover = function() {
            // Emulate a click on the clickover trigger
            $trigger.click();
        };

        /**
         * Share the selected resources with the selected users and groups. When the sharing has completed,
         * the clickover will close.
         */
        var setUpShare = function() {
            $(document).on('click', '#share-save', function() {
                // Disable the share button
                $('#share-save', $rootel).prop('disabled', true);

                // Extract the resource ids and principal ids
                var resources = _.pluck(selectedResources, 'id');
                var principals = _.pluck(oae.api.util.autoSuggest().getSelection($rootel), 'id');
                // A different API function needs to be used, depending on whether we're sharing a
                // discussion or a content item
                var shareFunction = null;
                if (resourceType === 'content') {
                    shareFunction = oae.api.content.shareContent;
                } else if (resourceType === 'discussion') {
                    shareFunction = oae.api.discussion.shareDiscussion;
                }

                var done = 0;
                var share = function() {
                    shareFunction(resources[done], principals, function(err) {
                        done++;
                        if (done === resources.length) {
                            /*!
                             * TODO: The share action will return an error every time all of the selected
                             * principals have the content/discussion already in their library. Because this
                             * isn't actually a failure and there are many permutations, we need to come up
                             * with a good way of tracking the successes/errors. Currently, we only show an
                             * error message when the current user is not allowed to share.
                             */
                            var data = {
                                'count': resources.length,
                                'err': err && err.code === 401,
                                'mylibrary': _.indexOf(principals, oae.data.me.id) !== -1,
                                'resourceType': resourceType,
                                'resourceSubType': selectedResources[0].resourceSubType
                            };

                            var notificationTitle = oae.api.util.template().render($('#share-notification-title-template', $rootel), data);
                            var notificationBody = oae.api.util.template().render($('#share-notification-body-template', $rootel), data);
                            oae.api.util.notification(notificationTitle, notificationBody, data.err ? 'error': 'success');

                            // Deselect all items in the list
                            $(document).trigger('oae.list.deselectall');

                            // Hide the clickover
                            toggleShareClickover();
                        } else {
                            share();
                        }
                    });
                };
                share();
            });
        };

        /**
         * Disable/enable the share button when an item has been added/removed from the autosuggest field.
         */
        var autoSuggestChanged = function() {
            $('#share-save', $rootel).prop('disabled', oae.api.util.autoSuggest().getSelection($rootel).length ? false : true);
        };

        /**
         * Initializes the autosuggest field used to select the people and groups to share with
         */
        var setUpAutoSuggest = function() {
            var ghosts = [];

            // We offer `My Library` or `My Discssions` as a ghost item, unless the user is
            // looking at his personal content/discussion library
            if (!contextProfile || contextProfile.id !== oae.data.me.id) {
                // If a content item is being shared, we add `My Library` as the ghost option
                if (resourceType === 'content') {
                    ghosts.push({
                        'id': oae.data.me.id,
                        'displayName': oae.api.i18n.translate('__MSG__MY_LIBRARY__')
                    });
                // If a discussion is being shared, we add `My Discussions` as the ghost option
                } else if (resourceType === 'discussion') {
                    ghosts.push({
                        'id': oae.data.me.id,
                        'displayName': oae.api.i18n.translate('__MSG__MY_DISCUSSIONS__')
                    });
                }
            }

            // Initialize the autoSuggest field
            oae.api.util.autoSuggest().setup($('#share-autosuggest', $rootel), {
                'ghosts': ghosts,
                'selectionChanged': autoSuggestChanged
            }, null, function() {
                // Focus on the autosuggest field once it has been set up
                oae.api.util.autoSuggest().focus($rootel);
            });
        };

        /**
         * Determine whether or not the share widget is triggered for an individual element or for
         * a number of selected items in a list. In case it has been trigger by an individual resource,
         * we expect to find a `data-id` attribute on the element, as well as a `data-resouceSubType`
         * attribute for the various content types. If the `data-id` attribute cannot be found, we assume
         * that the selected items from a list are being shared
         */
        var getContext = function() {
            // The resourceType data attribute should be available on all share triggers
            // and will tell us what type of resource is being shared (i.e., content, discussion)
            resourceType = $trigger.attr('data-resourceType');
            // If an individual item is shared, we expect to find the data-id attribute
            if ($trigger.attr('data-id')) {
                selectedResources = [{
                    'id': $trigger.attr('data-id'),
                    'resourceSubType': $trigger.attr('data-resourceSubType')
                }];
                setUpAutoSuggest();
            // If the selected items in a list are being shared, we first request the current page context.
            // If the current page context is the current user's personal library, we don't offer 'My Library'
            // as a ghost item, otherwise we always do. After that, we request the selected items from the current list
            } else {
                // Get the page context
                $(document).on('oae.context.send.share', function(ev, data) {
                    contextProfile = data;

                    // Get the list selection
                    $(document).on('oae.list.sendSelection.share', function(ev, data) {
                        selectedResources = data.results;
                        setUpAutoSuggest();
                    });
                    $(document).trigger('oae.list.getSelection', 'share');
                });
                $(document).trigger('oae.context.get', 'share');
            }
        };

        /**
         * Initializes the share clickover
         */
        var setUpShareClickover = function() {
            $(document).on('click', '.oae-trigger-share', function() {
                $trigger = $(this);
                // Trigger the share clickover
                oae.api.util.clickover($trigger, $('.share-widget'), {
                    'onShown': function($currentRootEl) {
                        $rootel = $currentRootEl;
                        // Work around a Chrome bug (https://code.google.com/p/chromium/issues/detail?id=268718) where
                        // it sometimes forgets to update z-index by forcing a repaint. Without the workaround, the share
                        // popover will be displaybed behind a content preview that uses an iframe.
                        // @see https://github.com/oaeproject/3akai-ux/pull/3436
                        $rootel[0].style.webkitTransform = 'scale(1)';
                        getContext();
                    }
                });
            });

            // Close the clickover when the cancel button is clicked
            $(document).on('click', '#share-cancel', toggleShareClickover);
        };

        setUpShare();
        setUpShareClickover();

    };
});


text:
import { Box, color, Flex, ResponsiveImage, Serif } from "@artsy/palette"
import { OtherCollectionEntity_member } from "__generated__/OtherCollectionEntity_member.graphql"
import * as Schema from "Artsy/Analytics/Schema"
import { useTracking } from "Artsy/Analytics/useTracking"
import { RouterLink } from "Artsy/Router/RouterLink"
import React from "react"
import { createFragmentContainer, graphql } from "react-relay"
import { data as sd } from "sharify"
import styled from "styled-components"

export interface CollectionProps {
  member: OtherCollectionEntity_member
  itemNumber: number
}

export const OtherCollectionEntity: React.FC<CollectionProps> = ({
  itemNumber,
  member,
}) => {
  const { slug, thumbnail, title } = member
  const { trackEvent } = useTracking()

  const handleClick = () => {
    trackEvent({
      action_type: Schema.ActionType.Click,
      context_page: Schema.PageName.CollectionPage,
      context_module: Schema.ContextModule.OtherCollectionsRail,
      context_page_owner_type: Schema.OwnerType.Collection,
      type: Schema.Type.Thumbnail,
      destination_path: `${sd.APP_URL}/collection/${slug}`,
      item_number: itemNumber,
    })
  }

  return (
    <StyledLink to={`/collection/${slug}`} onClick={handleClick}>
      <Flex alignItems="center" height="60px">
        {thumbnail && (
          <ImageContainer>
            <ThumbnailImage src={thumbnail} />
          </ImageContainer>
        )}
        <Box>
          <TitleContainer size="3" px={2}>
            {title}
          </TitleContainer>
        </Box>
      </Flex>
    </StyledLink>
  )
}

export const OtherCollectionsRailsContainer = createFragmentContainer(
  OtherCollectionEntity,
  {
    member: graphql`
      fragment OtherCollectionEntity_member on MarketingCollection {
        slug
        thumbnail
        title
      }
    `,
  }
)

export const StyledLink = styled(RouterLink)`
  text-decoration: none;
  -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
  border: 1px solid ${color("black10")};
  border-radius: 2px;
  margin-right: 10px;

  &:hover {
    text-decoration: none;
    border: 1px solid ${color("black60")};
  }
`

export const ImageContainer = styled(Box)`
  height: 60px;
  width: 60px;
`

export const ThumbnailImage = styled(ResponsiveImage)`
  background-size: cover;
  border-radius: 2px 1px 1px 2px;
`

const TitleContainer = styled(Serif)`
  width: max-content;
  white-space: nowrap;
`


text:
package java.lang;

import java.util.WeakHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Lazily associate a computed value with (potentially) every type.
 * For example, if a dynamic language needs to construct a message dispatch
 * table for each class encountered at a message send call site,
 * it can use a {@code ClassValue} to cache information needed to
 * perform the message send quickly, for each class encountered.
 * @author John Rose, JSR 292 EG
 * @since 1.7
 */
public abstract class ClassValue<T> {
    /**
     * Sole constructor.  (For invocation by subclass constructors, typically
     * implicit.)
     */
    protected ClassValue() {
    }

    /**
     * Computes the given class's derived value for this {@code ClassValue}.
     *

     * This method will be invoked within the first thread that accesses
     * the value with the {@link #get get} method.
     *

     * Normally, this method is invoked at most once per class,
     * but it may be invoked again if there has been a call to
     * {@link #remove remove}.
     *

     * If this method throws an exception, the corresponding call to {@code get}
     * will terminate abnormally with that exception, and no class value will be recorded.
     *
     * @param type the type whose class value must be computed
     * @return the newly computed value associated with this {@code ClassValue}, for the given class or interface
     * @see #get
     * @see #remove
     */
    protected abstract T computeValue(Class<?> type);

    /**
     * Returns the value for the given class.
     * If no value has yet been computed, it is obtained by
     * an invocation of the {@link #computeValue computeValue} method.
     *

     * The actual installation of the value on the class
     * is performed atomically.
     * At that point, if several racing threads have
     * computed values, one is chosen, and returned to
     * all the racing threads.
     *

     * The {@code type} parameter is typically a class, but it may be any type,
     * such as an interface, a primitive type (like {@code int.class}), or {@code void.class}.
     *

     * In the absence of {@code remove} calls, a class value has a simple
     * state diagram:  uninitialized and initialized.
     * When {@code remove} calls are made,
     * the rules for value observation are more complex.
     * See the documentation for {@link #remove remove} for more information.
     *
     * @param type the type whose class value must be computed or retrieved
     * @return the current value associated with this {@code ClassValue}, for the given class or interface
     * @throws NullPointerException if the argument is null
     * @see #remove
     * @see #computeValue
     */
    public T get(Class<?> type) {
        ClassValueMap map = getMap(type);
        if (map != null) {
            Object x = map.get(this);
            if (x != null) {
                return (T) map.unmaskNull(x);
            }
        }
        return setComputedValue(type);
    }

    /**
     * Removes the associated value for the given class.
     * If this value is subsequently {@linkplain #get read} for the same class,
     * its value will be reinitialized by invoking its {@link #computeValue computeValue} method.
     * This may result in an additional invocation of the
     * {@code computeValue} method for the given class.
     *

     * In order to explain the interaction between {@code get} and {@code remove} calls,
     * we must model the state transitions of a class value to take into account
     * the alternation between uninitialized and initialized states.
     * To do this, number these states sequentially from zero, and note that
     * uninitialized (or removed) states are numbered with even numbers,
     * while initialized (or re-initialized) states have odd numbers.
     *

     * When a thread {@code T} removes a class value in state {@code 2N},
     * nothing happens, since the class value is already uninitialized.
     * Otherwise, the state is advanced atomically to {@code 2N+1}.
     *

     * When a thread {@code T} queries a class value in state {@code 2N},
     * the thread first attempts to initialize the class value to state {@code 2N+1}
     * by invoking {@code computeValue} and installing the resulting value.
     *

     * When {@code T} attempts to install the newly computed value,
     * if the state is still at {@code 2N}, the class value will be initialized
     * with the computed value, advancing it to state {@code 2N+1}.
     *

     * Otherwise, whether the new state is even or odd,
     * {@code T} will discard the newly computed value
     * and retry the {@code get} operation.
     *

     * Discarding and retrying is an important proviso,
     * since otherwise {@code T} could potentially install
     * a disastrously stale value.  For example:
     *

     *
{@code T} calls {@code CV.get(C)} and sees state {@code 2N}
     *
{@code T} quickly computes a time-dependent value {@code V0} and gets ready to install it
     *
{@code T} is hit by an unlucky paging or scheduling event, and goes to sleep for a long time
     *
...meanwhile, {@code T2} also calls {@code CV.get(C)} and sees state {@code 2N}
     *
{@code T2} quickly computes a similar time-dependent value {@code V1} and installs it on {@code CV.get(C)}
     *
{@code T2} (or a third thread) then calls {@code CV.remove(C)}, undoing {@code T2}'s work
     *
 the previous actions of {@code T2} are repeated several times
     *
 also, the relevant computed values change over time: {@code V1}, {@code V2}, ...
     *
...meanwhile, {@code T} wakes up and attempts to install {@code V0}; this must fail
     *

     * We can assume in the above scenario that {@code CV.computeValue} uses locks to properly
     * observe the time-dependent states as it computes {@code V1}, etc.
     * This does not remove the threat of a stale value, since there is a window of time
     * between the return of {@code computeValue} in {@code T} and the installation
     * of the the new value.  No user synchronization is possible during this time.
     *
     * @param type the type whose class value must be removed
     * @throws NullPointerException if the argument is null
     */
    public void remove(Class<?> type) {
        ClassValueMap map = getMap(type);
        if (map != null) {
            synchronized (map) {
                map.remove(this);
            }
        }
    }

    /// Implementation...
    // FIXME: Use a data structure here similar that of ThreadLocal (7030453).

    private static final AtomicInteger STORE_BARRIER = new AtomicInteger();

    /** Slow path for {@link #get}. */
    private T setComputedValue(Class<?> type) {
        ClassValueMap map = getMap(type);
        if (map == null) {
            map = initializeMap(type);
        }
        T value = computeValue(type);
        STORE_BARRIER.lazySet(0);
        // All stores pending from computeValue are completed.
        synchronized (map) {
            // Warm up the table with a null entry.
            map.preInitializeEntry(this);
        }
        STORE_BARRIER.lazySet(0);
        // All stores pending from table expansion are completed.
        synchronized (map) {
            value = (T) map.initializeEntry(this, value);
            // One might fear a possible race condition here
            // if the code for map.put has flushed the write
            // to map.table[*] before the writes to the Map.Entry
            // are done.  This is not possible, since we have
            // warmed up the table with an empty entry.
        }
        return value;
    }

    // Replace this map by a per-class slot.
    private static final WeakHashMap<Class<?>, ClassValueMap> ROOT
        = new WeakHashMap<Class<?>, ClassValueMap>();

    private static ClassValueMap getMap(Class<?> type) {
        type.getClass();  // test for null
        return ROOT.get(type);
    }

    private static ClassValueMap initializeMap(Class<?> type) {
        synchronized (ClassValue.class) {
            ClassValueMap map = ROOT.get(type);
            if (map == null)
                ROOT.put(type, map = new ClassValueMap());
            return map;
        }
    }

    static class ClassValueMap extends WeakHashMap<ClassValue, Object> {
        /** Make sure this table contains an Entry for the given key, even if it is empty. */
        void preInitializeEntry(ClassValue key) {
            if (!this.containsKey(key))
                this.put(key, null);
        }
        /** Make sure this table contains a non-empty Entry for the given key. */
        Object initializeEntry(ClassValue key, Object value) {
            Object prior = this.get(key);
            if (prior != null) {
                return unmaskNull(prior);
            }
            this.put(key, maskNull(value));
            return value;
        }

        Object maskNull(Object x) {
            return x == null ? this : x;
        }
        Object unmaskNull(Object x) {
            return x == this ? null : x;
        }
    }
}


text:
module DeprecationMixin
  extend ActiveSupport::Concern

  module ClassMethods
    private

    def deprecate_belongs_to(old_belongs_to, new_belongs_to)
      deprecate_attribute_methods(old_belongs_to, new_belongs_to)
      ["_id", "_id=", "_id?"].each do |suffix|
        define_method("#{old_belongs_to}#{suffix}") do |*args|
          args.present? ? send("#{new_belongs_to}#{suffix}", *args) : send("#{new_belongs_to}#{suffix}")
        end
        Vmdb::Deprecation.deprecate_methods(self, "#{old_belongs_to}#{suffix}" => "#{new_belongs_to}#{suffix}")
      end
      virtual_belongs_to(old_belongs_to)
    end

    def deprecate_attribute(old_attribute, new_attribute)
      deprecate_attribute_methods(old_attribute, new_attribute)
      virtual_attribute(old_attribute, -> { type_for_attribute(new_attribute.to_s) })
      hide_attribute(old_attribute)
    end

    def deprecate_attribute_methods(old_attribute, new_attribute)
      alias_attribute old_attribute, new_attribute
      ["", "=", "?"].each { |suffix| Vmdb::Deprecation.deprecate_methods(self, "#{old_attribute}#{suffix}" => "#{new_attribute}#{suffix}") }
    end
  end
end


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="@dimen/dlg_action_margin"
    android:paddingLeft="@dimen/dlg_action_margin"
    android:paddingRight="@dimen/dlg_action_margin"
    android:paddingBottom="@dimen/dlg_bottom_margin">

    <LinearLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/dlg_content_margin"
        android:paddingRight="@dimen/dlg_content_margin"
        android:paddingLeft="@dimen/dlg_content_margin"
        android:paddingBottom="@dimen/dlg_action_margin"
        android:layout_alignParentTop="true"
        android:orientation="vertical">

        <TextView
            android:id="@+id/title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            style="@style/DialogTitle"
            android:text="@string/export_data"/>
        <TextView
            android:layout_marginTop="8dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/export_type"
            android:textAppearance="@style/TextAppearance.AppCompat.Caption"/>
        <Spinner android:id="@+id/spinner"
            android:layout_width="wrap_content"
            android:layout_height="@dimen/list_avatar_size"
            android:spinnerMode="dropdown"
            style="@style/Widget.AppCompat.Spinner.DropDown"
            android:gravity="left|center_vertical"
            android:layout_marginLeft="0dp"/>

    </LinearLayout>

    <Button android:id="@+id/ok"
        style="@style/Button.Flat.Accent"
        android:layout_width="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_below="@id/container"
        android:text="@string/start"
        android:layout_height="wrap_content" />

    <Button android:id="@+id/cancel"
        style="@style/Button.Flat.Accent"
        android:layout_width="wrap_content"
        android:layout_below="@id/container"
        android:layout_toLeftOf="@id/ok"
        android:text="@android:string/cancel"
        android:layout_height="wrap_content" />

</RelativeLayout>


text:
#pragma once

#include <string>
#include <list>
#include <map>
#include <sstream>
#include <numeric>

namespace utility
{

/** Join all elements in [first, last[ with op.
 *
 *  If their is no element to join, return empty.
 *
 * Example (joining strings):
 * @verbatim
 * let op = [](auto l, auto r){ return l + "|" + r; }
 * let [first, last[ = list<string>{"1", "2", "3"}
 * then join(first, last, op) == "1|2|3"
 * @endverbatim
 */
template <class T, class InputIt, class BinaryOperation>
T join(InputIt first, InputIt last, BinaryOperation op, T empty = T{})
{
    if (first == last) {
        return empty;
    }
    auto init = *first++;

    return std::accumulate(first, last, init, op);
}

/**
* Format the items of a map into a string as a list of key-value pairs. The map must be
* composed of pairs of strings.
*
* @param[in] lstr A list of strings
* @param[in] separator The separator to use between each item
*
* @return the concatenated elements.
*/
std::string asString(const std::list<std::string> &lstr, const std::string &separator = "\n");

/**
 * Format the items of a map into a string as a list of key-value pairs. The map must be
 * composed of pairs of strings.
 *
 * @param[in] mapStr A map of strings
 * @param[in] strItemSeparator The separator to use between each item (key-value pair)
 * @param[in] strKeyValueSeparator The separator to use between key and value
 *
 * @returns the pretty-printed map
 */
std::string asString(const std::map<std::string, std::string> &mapStr,
                     const std::string &strItemSeparator = ", ",
                     const std::string &strKeyValueSeparator = ":");

/** Utility to underline */
void appendTitle(std::string &strTo, const std::string &strTitle);

/**
 * Checks if a string has the written representation of an hexadecimal
 * number (Which is the prefix "0x" or "0X" in C++).
 *
 * @param[in] strValue value as string
 *
 * @return true if the string is written as hexa, false otherwise.
 */
bool isHexadecimal(const std::string &strValue);

} // utility


text:
<?php

namespace WiderFunnel\Items;

/**
 * Class Variation
 * @package WiderFunnel\Items;
 */
class Variation extends ItemAbstract
{
    //
}


text:
package com.morihacky.android.rxjava.pagination;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;

import com.morihacky.android.rxjava.MainActivity;
import com.morihacky.android.rxjava.R;
import com.morihacky.android.rxjava.fragments.BaseFragment;
import com.morihacky.android.rxjava.rxbus.RxBus;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.Bind;
import butterknife.ButterKnife;
import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.subjects.PublishSubject;
import rx.subscriptions.CompositeSubscription;

public class PaginationFragment extends BaseFragment {

    @Bind(R.id.list_paging) RecyclerView _pagingList;
    @Bind(R.id.progress_paging) ProgressBar _progressBar;

    private CompositeSubscription _subscriptions;
    private PaginationAdapter _adapter;
    private RxBus _bus;
    private PublishSubject<Integer> _paginator;

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        _bus = ((MainActivity) getActivity()).getRxBusSingleton();

        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        _pagingList.setLayoutManager(layoutManager);

        _adapter = new PaginationAdapter(_bus);
        _pagingList.setAdapter(_adapter);

        _paginator = PublishSubject.create();
    }

    @Override
    public void onStart() {
        super.onStart();
        _subscriptions = new CompositeSubscription();

        Subscription s2 =//
              _paginator//
                    .onBackpressureDrop()//
                    .concatMap(nextPage -> _itemsFromNetworkCall(nextPage + 1, 10))//
                    .observeOn(AndroidSchedulers.mainThread()).map(items -> {
                  int start = _adapter.getItemCount() - 1;

                  _adapter.addItems(items);
                  _adapter.notifyItemRangeInserted(start, 10);

                  _progressBar.setVisibility(View.INVISIBLE);
                  return null;
              })//
                    .subscribe();

        // I'm using an Rxbus purely to hear from a nested button click
        // we don't really need Rx for this part. it's just easy ¯\_(ツ)_/¯
        Subscription s1 = _bus.asObservable().subscribe(event -> {
            if (event instanceof PaginationAdapter.ItemBtnViewHolder.PageEvent) {

                // trigger the paginator for the next event
                int nextPage = _adapter.getItemCount() - 1;
                _paginator.onNext(nextPage);

            }
        });

        _subscriptions.add(s1);
        _subscriptions.add(s2);
    }

    @Override
    public void onStop() {
        super.onStop();
        _subscriptions.clear();
    }

    /**
     * Fake Observable that simulates a network call and then sends down a list of items
     */
    private Observable<List<String>> _itemsFromNetworkCall(int start, int count) {
        return Observable.just(true)
              .observeOn(AndroidSchedulers.mainThread())
              .doOnNext(dummy -> _progressBar.setVisibility(View.VISIBLE))
              .delay(2, TimeUnit.SECONDS)
              .map(dummy -> {
                  List<String> items = new ArrayList<>();
                  for (int i = 0; i < count; i++) {
                      items.add("Item " + (start + i));
                  }
                  return items;
              });
    }

    // -----------------------------------------------------------------------------------
    // WIRING up the views required for this example

    @Override
    public View onCreateView(LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View layout = inflater.inflate(R.layout.fragment_pagination, container, false);
        ButterKnife.bind(this, layout);
        return layout;
    }

}


text:
#ifndef _IOPORT_BUFFER_H
#define _IOPORT_BUFFER_H 1

#include <libopticon/ioport.h>

/* =============================== TYPES =============================== */

/** Storage for buffer-type ioports */
typedef struct bufferstorage_s {
    char        *buf; /** The buffer, not ours. */
    size_t       bufsz; /** Size of the buffer */
    unsigned int pos; /** Write cursor */
    unsigned int rpos; /** Read cursor */
    uint8_t      owned; /** 1 if buf is owned by object */
} bufferstorage;

/* ============================= FUNCTIONS ============================= */

ioport      *ioport_create_buffer (void *buf, size_t sz);

#endif


text:
ACCEPTED

#### According to
Interim Register of Marine and Nonmarine Genera

#### Published in
J Paleontol 78 (4), July: 642.

#### Original name
null

### Remarks
null


text:
![2.3 stars](../../images/ic_star_black_18dp_1x.png)![2.3 stars](../../images/ic_star_black_18dp_1x.png)![2.3 stars](../../images/ic_star_half_black_18dp_1x.png)![2.3 stars](../../images/ic_star_border_black_18dp_1x.png)![2.3 stars](../../images/ic_star_border_black_18dp_1x.png) 2

To use the What beer? skill, try saying...

* *Alexa, ask what beer goes with a burger?*

* *Alexa, ask what beer goes with fish?*

* *Alexa, ask what beer goes with dessert?*

How often have you sat down to a great meal only to be disappointed in your choice of beverage. Have you ever wondered what beer would pair nicely with tonight's meal. If so you no longer need to worry over these choices. Just ask "What beer?" and let "What beer?" help you complete that perfect meal. Please note that "What beer?" recommends alcoholic beverages, and as such may not be suitable for all ages, especially for those who are under the legal drinking limit in their country.

***

### Skill Details

* **Invocation Name:** what beer
* **Category:** null
* **ID:** amzn1.echo-sdk-ams.app.37bdc492-64b8-4272-94f6-28cdba52cff7
* **ASIN:** B01HCLE8VQ
* **Author:** Nick Stumpos
* **Release Date:** June 27, 2016 @ 05:15:46
* **In-App Purchasing:** No


text:
/*
 * File:   NetworkWrappingProcessor.h
 * Author: daniel
 *
 * Created on June 14, 2015, 10:05 AM
 */

#ifndef NETWORKWRAPPINGPROCESSOR_H
#define	NETWORKWRAPPINGPROCESSOR_H

#include "AudioProcessor.h"
#include "NetworkWrapper.h"

/*!
 * AudioProcessor which simply forwards the packages to the underlying NetworkWrapper
 */
class NetworkWrappingProcessor : public AudioProcessor
{
public:
    /*!
     * \param wrapper The underlying NetworkWrapper
     */
    NetworkWrappingProcessor(std::string name, NetworkWrapper *wrapper);
    ~NetworkWrappingProcessor();

    unsigned int getSupportedAudioFormats() const;
    unsigned int getSupportedSampleRates() const;

    unsigned int processInputData(void* inputBuffer, const unsigned int inputBufferByteSize, StreamData* userData);
    unsigned int processOutputData(void* outputBuffer, const unsigned int outputBufferByteSize, StreamData* userData);

private:
    NetworkWrapper *wrapper;
};

#endif	/* NETWORKWRAPPINGPROCESSOR_H */


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace EA4S.Test {
    public class TestGame : MiniGame
    {
        public IntroductionGameState IntroductionState { get; private set; }
        public QuestionGameState QuestionState { get; private set; }
        public PlayGameState PlayState { get; private set; }
        public ResultGameState ResultState { get; private set; }

        protected override void OnInitialize(IGameContext context)
        {
            IntroductionState = new IntroductionGameState(this);
            QuestionState = new QuestionGameState(this);
            PlayState = new PlayGameState(this);
            ResultState = new ResultGameState(this);
        }

        protected override IGameState GetInitialState()
        {
            return IntroductionState;
        }

        protected override IGameConfiguration GetConfiguration()
        {
            return TestConfiguration.Instance;
        }
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" />
<title>ThrottlingFilter xref</title>
<link type="text/css" rel="stylesheet" href="../../../stylesheet.css" />

View Javadoc

1
18
19  package org.mortbay.servlet;
20
21  import java.io.IOException;
22  import java.util.LinkedList;
23  import java.util.List;
24
25  import javax.servlet.Filter;
26  import javax.servlet.FilterChain;
27  import javax.servlet.FilterConfig;
28  import javax.servlet.ServletException;
29  import javax.servlet.ServletRequest;
30  import javax.servlet.ServletResponse;
31  import javax.servlet.http.HttpServletRequest;
32  import javax.servlet.http.HttpServletResponse;
33
34  import org.mortbay.log.Log;
35  import org.mortbay.util.ajax.Continuation;
36
37  /**
38   * This filter protects a web application from having to handle an unmanageable load.
39   * <p>
40   * For servers where there is 1 application with standardized resource restrictions, then this affect can be easily
41   *  controlled by limiting the size of the {@link org.mortbay.jetty.Server#setThreadPool server thread pool}, however
42   *  where there are multiple applications, or a single application has different resource requirements for different
43   *  URLs, then this filter can assist in managing the number of requests being services at any point in time.
44   * <p>
45   * The filter has 3 configurable values, which may be set as init parameters:
46   * <OL>
47   *  <LI><code>maximum</code> determines the maxmimum number of requests that may be on the filter chain at any point in time.
48   *      <i>(See below for a more detailed explanation)</i></LI>
49   * <LI><code>block</code> determines how long (in milliseconds) a request will be queued before it is rejected.
50   *      Set this to -1 to block indefinately.</LI>
51   * <LI><code>queue</code> determines how many requests can be queued simultaneously - any additional requests will be rejected.
52   *      Set this to 0 to turn off queueing.</LI>
53   * </OL>
54   *
55   * <b>Request Counting</b>: The filter counts how many requests are currently being services by the rest of the filter chain
56   *  (including any servlets that may be configured to handle the request). Request counting is <i>per instance</i> of the filter.
57   *  There is no syncronization between virtual machines, and the request count is not shared between multiple instances of the filter.
58   *  Thus a web.xml file such as <pre>
59   *  &lt;filter&gt;&lt;filter-name&gt;throttle1&lt;/filter-name&gt;
60   *          &lt;filter-class&gt;org.adjective.spiral.filter.ThrottlingFilter&lt;/filter-class&gt;
61   *  &lt;filter&gt;&lt;filter-name&gt;throttle2&lt;/filter-name&gt;
62   *          &lt;filter-class&gt;org.adjective.spiral.filter.ThrottlingFilter&lt;/filter-class&gt;</pre>
63   *  creates 2 separate filters with individual request counts.
64   * <p>
65   * <b>Queueing</b>: When the number of active requests exceed the <code>maximum</code> requests will be queued. This queue regulates
66   *  the flow of connections. Once the number of requests on the queue reached the <code>queue</code> threshold, then any new requests
67   *  will be rejected. Requests are queued for a maximum of <code>block</code> milliseconds - is no capacity is made available in this
68   *  time then the request will be rejected. The oldest pending request is removed from the queue and processed as soon as the number
69   *  of pending requests falls below the <code>maximum</code> value (<i>i.e.</i> when a request is completed)
70   * <p>
71   * <b>Rejection</b>: Requests are rejected when the number of requests in progress has reached <i>maximum</i> and either the queue
72   * is full; or a request has been queued for more than <code>block</code> milliseconds. The rejection is performed by calling the
73   * method {@link #rejectRequest}. By default this method sends the HTTP status code {@link HttpServletResponse#SC_SERVICE_UNAVAILABLE 503},
74   * but this may be over-ridden in derived classes.
75   * <p>
76   * This filter works best with the {@link org.mortbay.jetty.nio.SelectChannelConnector}, as {@link org.mortbay.jetty.RetryRequest} based
77   * {@link org.mortbay.util.ajax.Continuation}s can be used to free the thread and other resources associated with the queued requests.
78   *
79   * @author - Tim Vernum
80   */
81  public class ThrottlingFilter implements Filter
82  {
83
84      private int _maximum;
85      private int _current;
86      private long _queueTimeout;
87      private long _queueSize;
88      private final Object _lock;
89      private final List _queue;
90
91      public ThrottlingFilter()
92      {
93          _current = 0;
94          _lock = new Object();
95          _queue = new LinkedList();
96      }
97
98      public void init(FilterConfig filterConfig)
99          throws ServletException
100     {
101         _maximum = getIntegerParameter(filterConfig, "maximum", 10);
102         _queueTimeout = getIntegerParameter(filterConfig, "block", 5000);
103         _queueSize = getIntegerParameter(filterConfig, "queue", 500);
104
105         if (_queueTimeout == -1)
106         {
107             _queueTimeout = Integer.MAX_VALUE;
108         }
109
110         Log.debug("Config{maximum:" + _maximum + ", block:" + _queueTimeout + ", queue:" + _queueSize + "}", null, null);
111     }
112
113     private int getIntegerParameter(FilterConfig filterConfig, String name, int defaultValue)
114         throws ServletException
115     {
116         String value = filterConfig.getInitParameter(name);
117         if (value == null)
118         {
119             return defaultValue;
120         }
121         try
122         {
123             return Integer.parseInt(value);
124         }
125         catch (NumberFormatException e)
126         {
127             throw new ServletException("Parameter " + name + " must be a number (was " + value + " instead)");
128         }
129     }
130
131     public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
132         throws IOException, ServletException
133     {
134         doFilter((HttpServletRequest) request, (HttpServletResponse) response, chain);
135     }
136
137     public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
138         throws IOException, ServletException
139     {
140         Continuation continuation = getContinuation(request);
141
142         boolean accepted = false;
143         try
144         {
145             // Is the request accepted?
146             accepted=acceptRequest();
147             if (!accepted)
148             {
149                 // Has the request been tried before?
150                 if (continuation.isPending())
151                 {
152                     Log.debug("Request {} / {} was already queued, rejecting", request.getRequestURI(), continuation);
153                     dropFromQueue(continuation);
154                     continuation.reset();
155                 }
156                 // No if we can queue the request
157                 else if (queueRequest(request, response, continuation))
158                     // Try to get it accepted again (after wait in queue).
159                     accepted=acceptRequest();
160             }
161
162             // Handle if we are accepted, else reject
163             if (accepted)
164                 chain.doFilter(request, response);
165             else
166                 rejectRequest(request, response);
167         }
168         finally
169         {
170             if (accepted)
171             {
172                 releaseRequest();
173                 popQueue();
174             }
175         }
176
177     }
178
179     private void dropFromQueue(Continuation continuation)
180     {
181         _queue.remove(continuation);
182         continuation.reset();
183     }
184
185     protected void rejectRequest(HttpServletRequest request, HttpServletResponse response) throws IOException
186     {
187         response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "Too many active connections to resource "
188                 + request.getRequestURI());
189     }
190
191     private void popQueue()
192     {
193         Continuation continuation;
194         synchronized (_queue)
195         {
196             if (_queue.isEmpty())
197             {
198                 return;
199             }
200             continuation = (Continuation) _queue.remove(0);
201         }
202         Log.debug("Resuming continuation {}", continuation, null);
203         continuation.resume();
204     }
205
206     private void releaseRequest()
207     {
208         synchronized (_lock)
209         {
210             _current--;
211         }
212     }
213
214     private boolean acceptRequest()
215     {
216         synchronized (_lock)
217         {
218             if (_current < _maximum)
219             {
220                 _current++;
221                 return true;
222             }
223         }
224         return false;
225     }
226
227     private boolean queueRequest(HttpServletRequest request, HttpServletResponse response, Continuation continuation) throws IOException,
228             ServletException
229     {
230         synchronized (_queue)
231         {
232             if (_queue.size() >= _queueSize)
233             {
234                 Log.debug("Queue is full, rejecting request {}", request.getRequestURI(), null);
235                 return false;
236             }
237
238             Log.debug("Queuing request {} / {}", request.getRequestURI(), continuation);
239             _queue.add(continuation);
240         }
241
242         continuation.suspend(_queueTimeout);
243         Log.debug("Resuming blocking continuation for request {}", request.getRequestURI(), null);
244         return true;
245     }
246
247     private Continuation getContinuation(ServletRequest request)
248     {
249         return (Continuation) request.getAttribute("org.mortbay.jetty.ajax.Continuation");
250     }
251
252     public void destroy()
253     {
254         _queue.clear();
255     }
256
257 }

This page was automatically generated by Maven


text:
<?php

declare(strict_types=1);

namespace Sylius\Component\Core\Model;

use Sylius\Component\User\Model\UserInterface as BaseUserInterface;

interface AdminUserInterface extends BaseUserInterface
{
    public const DEFAULT_ADMIN_ROLE = 'ROLE_ADMINISTRATION_ACCESS';

    public function getFirstName(): ?string;

    public function setFirstName(?string $firstName): void;

    public function getLastName(): ?string;

    public function setLastName(?string $lastName): void;

    public function getLocaleCode(): ?string;

    public function setLocaleCode(?string $code): void;
}


text:
class FooController < UIViewController

  include RMExtensions::CollectionView

  cell_class FooCell

  def on_render
    SomeClass.some_async_fetch do |err, res|
      self.collection_view_data = res
    end
  end

  def on_select(cell, index_path)
    ap ['on_select', cell]
  end

end

class FooCell < UICollectionViewCell

  include RMExtensions::CollectionViewCell

  cell_id 'foo_cell'

  content_view do
    add UIImageView, named: :photo
    add UILabel, named: :welcome
  end

  def on_render
    @welcome.get.text = model.text
  end

end

class CollectionViewsStylesheet < ApplicationStylesheet

  def setup
    @margin = 0
    @foo_cell_size = {w: app_width/3, h: app_width/3}
  end

  def collection_view(st, cell_size)
    st.view.contentInset = [@margin, @margin, @margin, @margin]

    st.view.collectionViewLayout.tap do |cl|
      cl.itemSize = [cell_size[:w], cell_size[:h]]
      cl.scrollDirection = UICollectionViewScrollDirectionVertical
      cl.headerReferenceSize = [0, 0]
      cl.minimumInteritemSpacing = @margin
      cl.minimumLineSpacing = @margin
    end
  end

  def collection_foo_cell(st)
    full_screen(st)
    collection_view(st, @foo_cell_size)
    st.background_color = color.white
  end

  def foo_cell(st)
    st.frame = @foo_cell_size
    st.background_color = color.random
  end

  def foo_cell_photo(st)
    st.frame = @foo_cell_size.merge({t: 0, l: 0})
  end

  def foo_cell_welcome(st)
    st.frame = {t: 20, l: 0, w: @foo_cell_size[:w], h: 30}
    st.color = color.random
    st.font = font.system(18)
    st.centered = :horizontal
    st.text_alignment = :center
  end

end


text:
const mongoose = require('mongoose')
const Schema = mongoose.Schema

let RefinementSchema = new Schema({
  name: {
    type: String,
    required: true
  },
  value: {
    type: String,
    require: true
  },
  type: {
    type: String,
    required: true
  },
  online: {
    type: Boolean,
    default: true
  },
  category: {
    type: String,
    required: true
  }
})

module.exports = mongoose.model('Refinement', RefinementSchema)


text:
using namespace std;

void Common::ClearScreen(){
		Console::GetInstance().ClearScreen();
}

int Common::input(){
    // Converts character code to number, returns.
    while (true){
        // Gets character code for input.
		int getchCode = Console::GetInstance().GetChar();

        if (getchCode >= 48 && getchCode <= 57){
            return getchCode-48;
        }

        // Yes/no return
        else if (getchCode == 121 || getchCode == 89 || getchCode == 110 ||
                 getchCode == 78){
            return getchCode;
        }
    }
}

void Common::ColourPrint(string text, Console::EColour colour){
	Console::GetInstance().SetColour(colour);
	cout << text;
	Console::GetInstance().SetColour(Console::Default);
}

void Common::Sleep(int ms){
	std::this_thread::sleep_for(std::chrono::milliseconds(ms));
}

bool Common::IsPlaying;

const int Common::SLEEP_MS = 800;

const int Common::NUM_ITEMS = 5;


text:
package com.intellij.execution.dashboard.actions;

import com.intellij.execution.dashboard.RunDashboardManager;
import com.intellij.execution.dashboard.RunDashboardManagerImpl;
import com.intellij.openapi.actionSystem.ActionUpdateThread;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.ToggleAction;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.Project;
import org.jetbrains.annotations.NotNull;

final class OpenRunningConfigInNewTabAction extends ToggleAction implements DumbAware {

  @Override
  public @NotNull ActionUpdateThread getActionUpdateThread() {
    return ActionUpdateThread.BGT;
  }

  @Override
  public boolean isSelected(@NotNull AnActionEvent e) {
    Project project = e.getProject();
    if (project == null) return false;

    return ((RunDashboardManagerImpl)RunDashboardManager.getInstance(project)).isOpenRunningConfigInNewTab();
  }

  @Override
  public void setSelected(@NotNull AnActionEvent e, boolean state) {
    Project project = e.getProject();
    if (project == null) return;

    ((RunDashboardManagerImpl)RunDashboardManager.getInstance(project)).setOpenRunningConfigInNewTab(state);
  }
}


text:
namespace views {
class Checkbox;
}

namespace ash {

// Dialog for multi-profiles Window teleportation warning. When a user sends
// ("teleports") a window to another user's desktop, this dialog confirms that
// the user understands what that entails.
class TeleportWarningDialog : public views::DialogDelegateView {
 public:
  // This callback and its parameters match ShowTeleportWarningDialogCallback.
  typedef base::OnceCallback<void(bool, bool)> OnAcceptCallback;

  explicit TeleportWarningDialog(OnAcceptCallback callback);

  TeleportWarningDialog(const TeleportWarningDialog&) = delete;
  TeleportWarningDialog& operator=(const TeleportWarningDialog&) = delete;

  ~TeleportWarningDialog() override;

  static void Show(OnAcceptCallback callback);

  // views::View overrides.
  gfx::Size CalculatePreferredSize() const override;

 private:
  void InitDialog();

  views::Checkbox* never_show_again_checkbox_;

  OnAcceptCallback on_accept_;
};

}  // namespace ash

#endif  // ASH_SESSION_TELEPORT_WARNING_DIALOG_H_


text:
def populateIC():
	global ic_dict
	f=open('IC-combination.txt','r')
	for line in f:
		data=line.split("\t")
		term=data[0].strip()
		ic=data[2].strip()
		if re.match('^[0-9.]+$',ic):
			ic_dict[term]=float(ic)
		else:
			print ic,term
			ic_dict[term]=ic

def getIC(anc1,anc2):
	global ic_dict
	common=set.intersection(anc1,anc2)
	maxIC=0
	t=""
	for term in common:
		ic=ic_dict[term.strip()]
		if ic > maxIC:
			maxIC=ic
			t=term
	return (float(maxIC)/float(ic_dict['Maximum']))

def getancestors(line):
	#this will return a set
	global ancestor_dict
	line=line.strip()
	ancestors=ancestor_dict[line]
	return ancestors

def populateancestors(file):
	file=file.replace("Classes","Ancestors")
	f = open(file,'r')
	global ancestor_dict
	for line in f:
		terms=line.split("\t")
		child=terms[0].strip()
		ancestor=terms[1].strip()
		if child in ancestor_dict:
			ancestor_dict[child].add(ancestor)
		else:
			ancestor_dict[child]=set()
			ancestor_dict[child].add(child)
			ancestor_dict[child].add(ancestor)

def populatemapping():
	global idmap_dict
	inp=open('id_mapping.txt','r')
	#1	s1e659a80-0e70-4a22-94a1-53f3672868e2
	#1_0	s69d469cb-64a0-4f1d-9785-c55f20383bb0
	for line in inp:
		temp=line.split("\t")
		idmap_dict[temp[0].strip()]=temp[1].strip()

def main():
	# input files are class files like Classes-40674.txt or New-Classes-40674.txt
	out=open("LatexTableOut.txt",'a')
	global characterscoresIC
	global characterscoresSimJ
	inputfile1="Classes-"+str(sys.argv[1])
	inputfile2="Classes-"+str(sys.argv[2])
	qualities=int(sys.argv[3])
	file1=open(inputfile1,'r')
	populateancestors(inputfile1)
	populateancestors(inputfile2)
	populateIC()
	IClist=[]
	SimJlist=[]
	Linlist=[]
	line1count=1
	pereqscorefile="./CombinedComparisons/"+"PerEQ_"+inputfile1.replace(".tsv","").replace("Classes-","")+ "--"+inputfile2.replace("NR--","").replace("Transformed_","").replace("KR--","").replace(".tsv","").replace("Classes-","")+".tsv"
	if qualities==1:
		outputfile="./CombinedComparisons/"+inputfile1.replace(".tsv","").replace("Classes-","")+ "--"+inputfile2.replace("NR--","").replace("Transformed_","").replace("KR--","").replace(".tsv","").replace("Classes-","")+".tsv"
	else:
		outputfile="./CombinedComparisons/NoQualitites_"+inputfile1.replace(".tsv","").replace("Classes-","")+ "--"+inputfile2.replace("NR--","").replace("Transformed_","").replace("KR--","").replace(".tsv","").replace("Classes-","")+".tsv"

	pereq=open(pereqscorefile,'w')
	outputfile=outputfile.replace(".txt","")
	res=open(outputfile,'w')
	res.write("Character Number"+"\t"+"State Number"+"\t"+"SimJ Score" +"\t"+"NIC Score"+"\n")
	pereq.write("Character Number"+"\t"+"State Number"+"\t"+ "Curator 1 EQ Number"+"\t"+"Curator 2 EQ Number"+"\t"+ "SimJ Score"+"\t"+"NIC Score"+ "\n")
	for line1 in file1:
		file2=open(inputfile2,'r')
		line2count=1
		line1count=line1count+1
		for line2 in file2:

			line2count=line2count+1

			#format is character\tstate\tclassname
			# do the below only if the characters and the states are the same.
			data1=line1.split("\t")
			data2=line2.split("\t")
			character1=data1[0].strip()
			state1=data1[1].strip()
			character2=data2[0].strip()
			state2=data2[1].strip()
			class1=data1[2].strip()
			class2=data2[2].strip()
			eqnumber1=data1[3].strip()
			eqnumber2=data2[3].strip()

			key=character1+"\t"+state1

			simj=0
			ic=0
			if character1 == character2 and state1 == state2:
				if class1.strip() !="" and class2.strip()!="":
					#print "C "+character1+" S "+state1+ " class1 "+class1+" class2 "+class2
					#print " doing curator1 character "+character1+ " state "+state1+" doing curator2 character "+ character2+ " state2 "+state2
					ancestors1=getancestors(class1) #this is a set
					ancestors2=getancestors(class2)
					ic=getIC(ancestors1,ancestors2)
					normicmean=str(round(float(numpy.mean(IClist))/float(ic_dict['Maximum']),3))
					unionset=set.union(ancestors1,ancestors2)
					commonancestors= set.intersection(ancestors1,ancestors2)

					simj=float(len(commonancestors))/float(len(unionset))

				else:
					simj=0
				pereq.write(str(character1)+"\t"+str(state1)+"\t"+eqnumber1+"\t"+eqnumber2+  "\t"+str(simj)+"\t"+str(ic)+"\n")
				characterscoresSimJ[key].append(simj)
				characterscoresIC[key].append(ic)

	#get the max values for each character-state comparison here and add to IClist and SimJ list

	for characterstate in characterscoresSimJ:
		tmp=characterstate.split("\t")
		character=tmp[0]
		state=tmp[1]

		icmaxscore=max(characterscoresIC[characterstate])
		IClist.append(icmaxscore)

		simjmaxscore=max(characterscoresSimJ[characterstate])
		SimJlist.append(simjmaxscore)

		res.write(character+"\t"+state+"\t"+str(simjmaxscore)+"\t"+str(icmaxscore)+"\n")

	simjmean=str(round(numpy.mean(SimJlist),3))
	simjmedian=str(round(numpy.median(SimJlist),3))
	normicmean=str(round(numpy.mean(IClist),3))
	normicmedian=str(round(numpy.median(IClist),3))

	print "\n\n"+outputfile.replace("CombinedComparisons","").replace(".//","").replace("Classes-","")
	print "\tMean SimJ",simjmean
	print "\tMedian SimJ",simjmedian

	print "\tMean IC",normicmean
	print "\tMedian IC",normicmedian

	outfile=outputfile.replace("CombinedComparisons","").replace(".//","").replace("Classes-","")
	out.write(outfile+ " & "+simjmean+" & "+simjmedian+" & "+normicmean+" & "+normicmedian +" \\\\"+"\n")

if __name__ == "__main__":
	from collections import defaultdict
	characterscoresIC = defaultdict(list)
	characterscoresSimJ = defaultdict(list)
	import numpy
	import sys
	import math
	import re
	ancestor_dict=dict()
	ic_dict={}
	idmap_dict={}
	main()


text:
<?php get_header(); ?>

			<?php get_template_part('includes/breadcrumbs'); ?>

					<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

							<?php if (get_option('webly_integration_single_top') <> '' && get_option('webly_integrate_singletop_enable') == 'on') echo(get_option('webly_integration_single_top')); ?>

							<?php if (get_option('webly_thumbnails') == 'on') { ?>
								<?php
									$thumb = '';
									$width = 200;
									$height = 200;
									$classtext = 'post-thumb';
									$titletext = get_the_title();
									$thumbnail = get_thumbnail($width,$height,$classtext,$titletext,$titletext,false,'Entry');
									$thumb = $thumbnail["thumb"];
								?>

								<?php if($thumb <> '') { ?>

										<?php print_thumbnail($thumb, $thumbnail["use_timthumb"], $titletext, $width, $height, $classtext); ?>

								<?php } ?>
							<?php } ?>

							<?php the_content(); ?>
							<?php wp_link_pages(array('before' => '
'.esc_html__('Pages','Webly').': ', 'after' => '
', 'next_or_number' => 'number')); ?>
							<?php edit_post_link(esc_html__('Edit this page','Webly')); ?>

						<?php if (get_option('webly_integration_single_bottom') <> '' && get_option('webly_integrate_singlebottom_enable') == 'on') echo(get_option('webly_integration_single_bottom')); ?>

						<?php if (get_option('webly_468_enable') == 'on') { ?>
								  <?php if(get_option('webly_468_adsense') <> '') echo(get_option('webly_468_adsense'));
								else { ?>
								   <a href="<?php echo esc_url(get_option('webly_468_url')); ?>"><img src="<?php echo esc_url(get_option('webly_468_image')); ?>" alt="468 ad" class="foursixeight" />
						   <?php } ?>
						<?php } ?>

						<?php if (get_option('webly_show_postcomments') == 'on') comments_template('', true); ?>
					<?php endwhile; endif; ?>

					<?php get_sidebar(); ?>

<?php get_footer(); ?>


text:
<?php

namespace Post\Form;

use DoctrineModule\Form\Element\ObjectSelect;
use Doctrine\Common\Persistence\ObjectManager;
use DoctrineModule\Persistence\ObjectManagerAwareInterface;

use Post\Form\PostFilter;
use Zend\Form\Element\Button;
use Zend\Form\Element\Checkbox;
use Zend\Form\Element\Text;
use Zend\Form\Element\Textarea;
use Zend\Form\Form;

class PostForm extends Form implements ObjectManagerAwareInterface
{

    protected $objectManager;

    public function __construct(ObjectManager $objectManager)
    {
        $this->setObjectManager($objectManager);

        parent::__construct(null);
        $this->setAttribute('method', 'POST');

        //Input Titulo
        $titulo = new Text('titulo');
        $titulo->setLabel('Titulo')
                ->setAttributes(array(
                    'maxlenght' => 80
        ));
        $this->add($titulo);

        //Input Descricao
        $descricao = new Textarea('descricao');
        $descricao->setLabel('Descricao')
                ->setAttributes(array(
                    'maxlenght' => 150
        ));
        $this->add($descricao);

        //Input Texto
        $texto = new Textarea('texto');
        $texto->setLabel('Texto');
        $this->add($texto);

        //Checkbox Ativo
        $ativo = new Checkbox('ativo');
        $ativo->setLabel('Ativo');
        $this->add($ativo);

        $categoria = new ObjectSelect('category');
        $categoria->setLabel('Categoria')
            ->setOptions(array(
                'object_manager'    => $this->getObjectManager(),
                'target_class'      => 'Categoria\Entity\Category',
                'property'          => 'nome',
                'empty_option'     => '--Selecione--',
                'is_method'         => true,
                'find_method'       => array(
                    'name'      => 'findBy',
                    'params'    => array(
                        'criteria'  => array(),
                        'orderBy'   => array('nome' => 'ASC'),
                    ),
                ),
        ));
        $this->add($categoria);

        //Botao submit
        $button = new Button('submit');
        $button->setLabel('Salvar')
                ->setAttributes(array(
                    'type' => 'submit',
                    'class' => 'btn'
        ));
        $this->add($button);

        $this->setInputFilter(new PostFilter($categoria->getValueOptions()));
    }

    /**
     * Set the object manager
     *
     * @param ObjectManager $objectManager
     */
    public function setObjectManager(ObjectManager $objectManager)
    {
        $this->objectManager = $objectManager;
    }

    /**
     * Get the object manager
     *
     * @return ObjectManager
     */
    public function getObjectManager()
    {
        return $this->objectManager;
    }

}