text:
from __future__ import absolute_import, division, print_function, unicode_literals

from h2o.estimators.estimator_base import H2OEstimator
from h2o.exceptions import H2OValueError
from h2o.frame import H2OFrame
from h2o.utils.typechecks import assert_is_type, Enum, numeric

class H2OIsolationForestEstimator(H2OEstimator):
    """
    Isolation Forest

    Builds an Isolation Forest model. Isolation Forest algorithm samples the training frame
    and in each iteration builds a tree that partitions the space of the sample observations until
    it isolates each observation. Length of the path from root to a leaf node of the resulting tree
    is used to calculate the anomaly score. Anomalies are easier to isolate and their average
    tree path is expected to be shorter than paths of regular observations.
    """

    algo = "isolationforest"
    supervised_learning = False
    _options_ = {'model_extensions': ['h2o.model.extensions.Trees']}

    def __init__(self,
                 model_id=None,  # type: Optional[Union[None, str, H2OEstimator]]
                 training_frame=None,  # type: Optional[Union[None, str, H2OFrame]]
                 score_each_iteration=False,  # type: bool
                 score_tree_interval=0,  # type: int
                 ignored_columns=None,  # type: Optional[List[str]]
                 ignore_const_cols=True,  # type: bool
                 ntrees=50,  # type: int
                 max_depth=8,  # type: int
                 min_rows=1.0,  # type: float
                 max_runtime_secs=0.0,  # type: float
                 seed=-1,  # type: int
                 build_tree_one_node=False,  # type: bool
                 mtries=-1,  # type: int
                 sample_size=256,  # type: int
                 sample_rate=-1.0,  # type: float
                 col_sample_rate_change_per_level=1.0,  # type: float
                 col_sample_rate_per_tree=1.0,  # type: float
                 categorical_encoding="auto",  # type: Literal["auto", "enum", "one_hot_internal", "one_hot_explicit", "binary", "eigen", "label_encoder", "sort_by_response", "enum_limited"]
                 stopping_rounds=0,  # type: int
                 stopping_metric="auto",  # type: Literal["auto", "anomaly_score", "deviance", "logloss", "mse", "rmse", "mae", "rmsle", "auc", "aucpr", "misclassification", "mean_per_class_error"]
                 stopping_tolerance=0.01,  # type: float
                 export_checkpoints_dir=None,  # type: Optional[str]
                 contamination=-1.0,  # type: float
                 validation_frame=None,  # type: Optional[Union[None, str, H2OFrame]]
                 validation_response_column=None,  # type: Optional[str]
                 ):
        """
        :param model_id: Destination id for this model; auto-generated if not specified.
               Defaults to ``None``.
        :type model_id: Union[None, str, H2OEstimator], optional
        :param training_frame: Id of the training data frame.
               Defaults to ``None``.
        :type training_frame: Union[None, str, H2OFrame], optional
        :param score_each_iteration: Whether to score during each iteration of model training.
               Defaults to ``False``.
        :type score_each_iteration: bool
        :param score_tree_interval: Score the model after every so many trees. Disabled if set to 0.
               Defaults to ``0``.
        :type score_tree_interval: int
        :param ignored_columns: Names of columns to ignore for training.
               Defaults to ``None``.
        :type ignored_columns: List[str], optional
        :param ignore_const_cols: Ignore constant columns.
               Defaults to ``True``.
        :type ignore_const_cols: bool
        :param ntrees: Number of trees.
               Defaults to ``50``.
        :type ntrees: int
        :param max_depth: Maximum tree depth (0 for unlimited).
               Defaults to ``8``.
        :type max_depth: int
        :param min_rows: Fewest allowed (weighted) observations in a leaf.
               Defaults to ``1.0``.
        :type min_rows: float
        :param max_runtime_secs: Maximum allowed runtime in seconds for model training. Use 0 to disable.
               Defaults to ``0.0``.
        :type max_runtime_secs: float
        :param seed: Seed for pseudo random number generator (if applicable)
               Defaults to ``-1``.
        :type seed: int
        :param build_tree_one_node: Run on one node only; no network overhead but fewer cpus used. Suitable for small
               datasets.
               Defaults to ``False``.
        :type build_tree_one_node: bool
        :param mtries: Number of variables randomly sampled as candidates at each split. If set to -1, defaults (number
               of predictors)/3.
               Defaults to ``-1``.
        :type mtries: int
        :param sample_size: Number of randomly sampled observations used to train each Isolation Forest tree. Only one
               of parameters sample_size and sample_rate should be defined. If sample_rate is defined, sample_size will
               be ignored.
               Defaults to ``256``.
        :type sample_size: int
        :param sample_rate: Rate of randomly sampled observations used to train each Isolation Forest tree. Needs to be
               in range from 0.0 to 1.0. If set to -1, sample_rate is disabled and sample_size will be used instead.
               Defaults to ``-1.0``.
        :type sample_rate: float
        :param col_sample_rate_change_per_level: Relative change of the column sampling rate for every level (must be >
               0.0 and <= 2.0)
               Defaults to ``1.0``.
        :type col_sample_rate_change_per_level: float
        :param col_sample_rate_per_tree: Column sample rate per tree (from 0.0 to 1.0)
               Defaults to ``1.0``.
        :type col_sample_rate_per_tree: float
        :param categorical_encoding: Encoding scheme for categorical features
               Defaults to ``"auto"``.
        :type categorical_encoding: Literal["auto", "enum", "one_hot_internal", "one_hot_explicit", "binary", "eigen", "label_encoder",
               "sort_by_response", "enum_limited"]
        :param stopping_rounds: Early stopping based on convergence of stopping_metric. Stop if simple moving average of
               length k of the stopping_metric does not improve for k:=stopping_rounds scoring events (0 to disable)
               Defaults to ``0``.
        :type stopping_rounds: int
        :param stopping_metric: Metric to use for early stopping (AUTO: logloss for classification, deviance for
               regression and anomaly_score for Isolation Forest). Note that custom and custom_increasing can only be
               used in GBM and DRF with the Python client.
               Defaults to ``"auto"``.
        :type stopping_metric: Literal["auto", "anomaly_score", "deviance", "logloss", "mse", "rmse", "mae", "rmsle", "auc", "aucpr",
               "misclassification", "mean_per_class_error"]
        :param stopping_tolerance: Relative tolerance for metric-based stopping criterion (stop if relative improvement
               is not at least this much)
               Defaults to ``0.01``.
        :type stopping_tolerance: float
        :param export_checkpoints_dir: Automatically export generated models to this directory.
               Defaults to ``None``.
        :type export_checkpoints_dir: str, optional
        :param contamination: Contamination ratio - the proportion of anomalies in the input dataset. If undefined (-1)
               the predict function will not mark observations as anomalies and only anomaly score will be returned.
               Defaults to -1 (undefined).
               Defaults to ``-1.0``.
        :type contamination: float
        :param validation_frame: Id of the validation data frame.
               Defaults to ``None``.
        :type validation_frame: Union[None, str, H2OFrame], optional
        :param validation_response_column: (experimental) Name of the response column in the validation frame. Response
               column should be binary and indicate not anomaly/anomaly.
               Defaults to ``None``.
        :type validation_response_column: str, optional
        """
        super(H2OIsolationForestEstimator, self).__init__()
        self._parms = {}
        self._id = self._parms['model_id'] = model_id
        self.training_frame = training_frame
        self.score_each_iteration = score_each_iteration
        self.score_tree_interval = score_tree_interval
        self.ignored_columns = ignored_columns
        self.ignore_const_cols = ignore_const_cols
        self.ntrees = ntrees
        self.max_depth = max_depth
        self.min_rows = min_rows
        self.max_runtime_secs = max_runtime_secs
        self.seed = seed
        self.build_tree_one_node = build_tree_one_node
        self.mtries = mtries
        self.sample_size = sample_size
        self.sample_rate = sample_rate
        self.col_sample_rate_change_per_level = col_sample_rate_change_per_level
        self.col_sample_rate_per_tree = col_sample_rate_per_tree
        self.categorical_encoding = categorical_encoding
        self.stopping_rounds = stopping_rounds
        self.stopping_metric = stopping_metric
        self.stopping_tolerance = stopping_tolerance
        self.export_checkpoints_dir = export_checkpoints_dir
        self.contamination = contamination
        self.validation_frame = validation_frame
        self.validation_response_column = validation_response_column

    @property
    def training_frame(self):
        """
        Id of the training data frame.

        Type: ``Union[None, str, H2OFrame]``.

        :examples:

        >>> cars = h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/junit/cars_20mpg.csv")
        >>> predictors = ["displacement","power","weight","acceleration","year"]
        >>> cars_if = H2OIsolationForestEstimator(seed=1234)
        >>> cars_if.train(x=predictors,
        ...               training_frame=cars)
        >>> cars_if.model_performance()
        """
        return self._parms.get("training_frame")

    @training_frame.setter
    def training_frame(self, training_frame):
        self._parms["training_frame"] = H2OFrame._validate(training_frame, 'training_frame')

    @property
    def score_each_iteration(self):
        """
        Whether to score during each iteration of model training.

        Type: ``bool``, defaults to ``False``.

        :examples:

        >>> cars = h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/junit/cars_20mpg.csv")
        >>> predictors = ["displacement","power","weight","acceleration","year"]
        >>> cars_if = H2OIsolationForestEstimator(score_each_iteration=True,
        ...                                       ntrees=55,
        ...                                       seed=1234)
        >>> cars_if.train(x=predictors,
        ...               training_frame=cars)
        >>> cars_if.model_performance()
        """
        return self._parms.get("score_each_iteration")

    @score_each_iteration.setter
    def score_each_iteration(self, score_each_iteration):
        assert_is_type(score_each_iteration, None, bool)
        self._parms["score_each_iteration"] = score_each_iteration

    @property
    def score_tree_interval(self):
        """
        Score the model after every so many trees. Disabled if set to 0.

        Type: ``int``, defaults to ``0``.

        :examples:

        >>> cars = h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/junit/cars_20mpg.csv")
        >>> predictors = ["displacement","power","weight","acceleration","year"]
        >>> cars_if = H2OIsolationForestEstimator(score_tree_interval=5,
        ...                                       seed=1234)
        >>> cars_if.train(x=predictors,
        ...               training_frame=cars)
        >>> cars_if.model_performance()
        """
        return self._parms.get("score_tree_interval")

    @score_tree_interval.setter
    def score_tree_interval(self, score_tree_interval):
        assert_is_type(score_tree_interval, None, int)
        self._parms["score_tree_interval"] = score_tree_interval

    @property
    def ignored_columns(self):
        """
        Names of columns to ignore for training.

        Type: ``List[str]``.
        """
        return self._parms.get("ignored_columns")

    @ignored_columns.setter
    def ignored_columns(self, ignored_columns):
        assert_is_type(ignored_columns, None, [str])
        self._parms["ignored_columns"] = ignored_columns

    @property
    def ignore_const_cols(self):
        """
        Ignore constant columns.

        Type: ``bool``, defaults to ``True``.

        :examples:

        >>> cars = h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/junit/cars_20mpg.csv")
        >>> predictors = ["displacement","power","weight","acceleration","year","const_1","const_2"]
        >>> cars["const_1"] = 6
        >>> cars["const_2"] = 7
        >>> train, valid = cars.split_frame(ratios=[.8], seed=1234)
        >>> cars_if = H2OIsolationForestEstimator(seed=1234,
        ...                                       ignore_const_cols=True)
        >>> cars_if.train(x=predictors,
        ...               training_frame=cars)
        >>> cars_if.model_performance()
        """
        return self._parms.get("ignore_const_cols")

    @ignore_const_cols.setter
    def ignore_const_cols(self, ignore_const_cols):
        assert_is_type(ignore_const_cols, None, bool)
        self._parms["ignore_const_cols"] = ignore_const_cols

    @property
    def ntrees(self):
        """
        Number of trees.

        Type: ``int``, defaults to ``50``.

        :examples:

        >>> titanic = h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/gbm_test/titanic.csv")
        >>> predictors = titanic.columns
        >>> tree_num = [20, 50, 80, 110, 140, 170, 200]
        >>> label = ["20", "50", "80", "110", "140", "170", "200"]
        >>> for key, num in enumerate(tree_num):
        ...     titanic_if = H2OIsolationForestEstimator(ntrees=num,
        ...                                              seed=1234)
        ...     titanic_if.train(x=predictors,
        ...                      training_frame=titanic)
        ...     print(label[key], 'training score', titanic_if.mse(train=True))
        """
        return self._parms.get("ntrees")

    @ntrees.setter
    def ntrees(self, ntrees):
        assert_is_type(ntrees, None, int)
        self._parms["ntrees"] = ntrees

    @property
    def max_depth(self):
        """
        Maximum tree depth (0 for unlimited).

        Type: ``int``, defaults to ``8``.

        :examples:

        >>> cars = h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/junit/cars_20mpg.csv")
        >>> predictors = ["displacement","power","weight","acceleration","year"]
        >>> cars_if = H2OIsolationForestEstimator(max_depth=2,
        ...                                       seed=1234)
        >>> cars_if.train(x=predictors,
        ...               training_frame=cars)
        >>> cars_if.model_performance()
        """
        return self._parms.get("max_depth")

    @max_depth.setter
    def max_depth(self, max_depth):
        assert_is_type(max_depth, None, int)
        self._parms["max_depth"] = max_depth

    @property
    def min_rows(self):
        """
        Fewest allowed (weighted) observations in a leaf.

        Type: ``float``, defaults to ``1.0``.

        :examples:

        >>> cars = h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/junit/cars_20mpg.csv")
        >>> predictors = ["displacement","power","weight","acceleration","year"]
        >>> cars_if = H2OIsolationForestEstimator(min_rows=16,
        ...                                       seed=1234)
        >>> cars_if.train(x=predictors,
        ...               training_frame=cars)
        >>> cars_if.model_performance()
        """
        return self._parms.get("min_rows")

    @min_rows.setter
    def min_rows(self, min_rows):
        assert_is_type(min_rows, None, numeric)
        self._parms["min_rows"] = min_rows

    @property
    def max_runtime_secs(self):
        """
        Maximum allowed runtime in seconds for model training. Use 0 to disable.

        Type: ``float``, defaults to ``0.0``.

        :examples:

        >>> cars = h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/junit/cars_20mpg.csv")
        >>> predictors = ["displacement","power","weight","acceleration","year"]
        >>> cars_if = H2OIsolationForestEstimator(max_runtime_secs=10,
        ...                                       ntrees=10000,
        ...                                       max_depth=10,
        ...                                       seed=1234)
        >>> cars_if.train(x=predictors,
        ...               training_frame=cars)
        >>> cars_if.model_performance()
        """
        return self._parms.get("max_runtime_secs")

    @max_runtime_secs.setter
    def max_runtime_secs(self, max_runtime_secs):
        assert_is_type(max_runtime_secs, None, numeric)
        self._parms["max_runtime_secs"] = max_runtime_secs

    @property
    def seed(self):
        """
        Seed for pseudo random number generator (if applicable)

        Type: ``int``, defaults to ``-1``.

        :examples:

        >>> airlines= h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/airlines/allyears2k_headers.zip")
        >>> predictors = ["Origin", "Dest", "Year", "UniqueCarrier",
        ...               "DayOfWeek", "Month", "Distance", "FlightNum"]
        >>> isofor_w_seed = H2OIsolationForestEstimator(seed=1234)
        >>> isofor_w_seed.train(x=predictors,
        ...                     training_frame=airlines)
        >>> isofor_wo_seed = H2OIsolationForestEstimator()
        >>> isofor_wo_seed.train(x=predictors,
        ...                      training_frame=airlines)
        >>> isofor_w_seed.model_performance()
        >>> isofor_wo_seed.model_performance()
        """
        return self._parms.get("seed")

    @seed.setter
    def seed(self, seed):
        assert_is_type(seed, None, int)
        self._parms["seed"] = seed

    @property
    def build_tree_one_node(self):
        """
        Run on one node only; no network overhead but fewer cpus used. Suitable for small datasets.

        Type: ``bool``, defaults to ``False``.

        :examples:

        >>> cars = h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/junit/cars_20mpg.csv")
        >>> predictors = ["displacement","power","weight","acceleration","year"]
        >>> cars_if = H2OIsolationForestEstimator(build_tree_one_node=True,
        ...                                       seed=1234)
        >>> cars_if.train(x=predictors,
        ...               training_frame=cars)
        >>> cars_if.model_performance()
        """
        return self._parms.get("build_tree_one_node")

    @build_tree_one_node.setter
    def build_tree_one_node(self, build_tree_one_node):
        assert_is_type(build_tree_one_node, None, bool)
        self._parms["build_tree_one_node"] = build_tree_one_node

    @property
    def mtries(self):
        """
        Number of variables randomly sampled as candidates at each split. If set to -1, defaults (number of
        predictors)/3.

        Type: ``int``, defaults to ``-1``.

        :examples:

        >>> covtype = h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/covtype/covtype.20k.data")
        >>> predictors = covtype.columns[0:54]
        >>> cov_if = H2OIsolationForestEstimator(mtries=30, seed=1234)
        >>> cov_if.train(x=predictors,
        ...              training_frame=covtype)
        >>> cov_if.model_performance()
        """
        return self._parms.get("mtries")

    @mtries.setter
    def mtries(self, mtries):
        assert_is_type(mtries, None, int)
        self._parms["mtries"] = mtries

    @property
    def sample_size(self):
        """
        Number of randomly sampled observations used to train each Isolation Forest tree. Only one of parameters
        sample_size and sample_rate should be defined. If sample_rate is defined, sample_size will be ignored.

        Type: ``int``, defaults to ``256``.

        :examples:

        >>> train = h2o.import_file("http://s3.amazonaws.com/h2o-public-test-data/smalldata/anomaly/ecg_discord_train.csv")
        >>> isofor_model = H2OIsolationForestEstimator(sample_size=5,
        ...                                            ntrees=7)
        >>> isofor_model.train(training_frame=train)
        >>> isofor_model.model_performance()
        """
        return self._parms.get("sample_size")

    @sample_size.setter
    def sample_size(self, sample_size):
        assert_is_type(sample_size, None, int)
        self._parms["sample_size"] = sample_size

    @property
    def sample_rate(self):
        """
        Rate of randomly sampled observations used to train each Isolation Forest tree. Needs to be in range from 0.0 to
        1.0. If set to -1, sample_rate is disabled and sample_size will be used instead.

        Type: ``float``, defaults to ``-1.0``.

        :examples:

        >>> airlines= h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/airlines/allyears2k_headers.zip")
        >>> predictors = ["Origin", "Dest", "Year", "UniqueCarrier",
        ...               "DayOfWeek", "Month", "Distance", "FlightNum"]
        >>> airlines_if = H2OIsolationForestEstimator(sample_rate=.7,
        ...                                           seed=1234)
        >>> airlines_if.train(x=predictors,
        ...                   training_frame=airlines)
        >>> airlines_if.model_performance()
        """
        return self._parms.get("sample_rate")

    @sample_rate.setter
    def sample_rate(self, sample_rate):
        assert_is_type(sample_rate, None, numeric)
        self._parms["sample_rate"] = sample_rate

    @property
    def col_sample_rate_change_per_level(self):
        """
        Relative change of the column sampling rate for every level (must be > 0.0 and <= 2.0)

        Type: ``float``, defaults to ``1.0``.

        :examples:

        >>> airlines= h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/airlines/allyears2k_headers.zip")
        >>> predictors = ["Origin", "Dest", "Year", "UniqueCarrier",
        ...               "DayOfWeek", "Month", "Distance", "FlightNum"]
        >>> airlines_if = H2OIsolationForestEstimator(col_sample_rate_change_per_level=.9,
        ...                                           seed=1234)
        >>> airlines_if.train(x=predictors,
        ...                   training_frame=airlines)
        >>> airlines_if.model_performance()
        """
        return self._parms.get("col_sample_rate_change_per_level")

    @col_sample_rate_change_per_level.setter
    def col_sample_rate_change_per_level(self, col_sample_rate_change_per_level):
        assert_is_type(col_sample_rate_change_per_level, None, numeric)
        self._parms["col_sample_rate_change_per_level"] = col_sample_rate_change_per_level

    @property
    def col_sample_rate_per_tree(self):
        """
        Column sample rate per tree (from 0.0 to 1.0)

        Type: ``float``, defaults to ``1.0``.

        :examples:

        >>> airlines= h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/airlines/allyears2k_headers.zip")
        >>> predictors = ["Origin", "Dest", "Year", "UniqueCarrier",
        ...               "DayOfWeek", "Month", "Distance", "FlightNum"]
        >>> airlines_if = H2OIsolationForestEstimator(col_sample_rate_per_tree=.7,
        ...                                           seed=1234)
        >>> airlines_if.train(x=predictors,
        ...                   training_frame=airlines)
        >>> airlines_if.model_performance()
        """
        return self._parms.get("col_sample_rate_per_tree")

    @col_sample_rate_per_tree.setter
    def col_sample_rate_per_tree(self, col_sample_rate_per_tree):
        assert_is_type(col_sample_rate_per_tree, None, numeric)
        self._parms["col_sample_rate_per_tree"] = col_sample_rate_per_tree

    @property
    def categorical_encoding(self):
        """
        Encoding scheme for categorical features

        Type: ``Literal["auto", "enum", "one_hot_internal", "one_hot_explicit", "binary", "eigen", "label_encoder",
        "sort_by_response", "enum_limited"]``, defaults to ``"auto"``.

        :examples:

        >>> airlines= h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/airlines/allyears2k_headers.zip")
        >>> predictors = ["Origin", "Dest", "Year", "UniqueCarrier",
        ...               "DayOfWeek", "Month", "Distance", "FlightNum"]
        >>> encoding = "one_hot_explicit"
        >>> airlines_if = H2OIsolationForestEstimator(categorical_encoding=encoding,
        ...                                           seed=1234)
        >>> airlines_if.train(x=predictors,
        ...                   training_frame=airlines)
        >>> airlines_if.model_performance()
        """
        return self._parms.get("categorical_encoding")

    @categorical_encoding.setter
    def categorical_encoding(self, categorical_encoding):
        assert_is_type(categorical_encoding, None, Enum("auto", "enum", "one_hot_internal", "one_hot_explicit", "binary", "eigen", "label_encoder", "sort_by_response", "enum_limited"))
        self._parms["categorical_encoding"] = categorical_encoding

    @property
    def stopping_rounds(self):
        """
        Early stopping based on convergence of stopping_metric. Stop if simple moving average of length k of the
        stopping_metric does not improve for k:=stopping_rounds scoring events (0 to disable)

        Type: ``int``, defaults to ``0``.

        :examples:

        >>> airlines= h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/airlines/allyears2k_headers.zip")
        >>> predictors = ["Origin", "Dest", "Year", "UniqueCarrier",
        ...               "DayOfWeek", "Month", "Distance", "FlightNum"]
        >>> airlines_if = H2OIsolationForestEstimator(stopping_metric="auto",
        ...                                           stopping_rounds=3,
        ...                                           stopping_tolerance=1e-2,
        ...                                           seed=1234)
        >>> airlines_if.train(x=predictors,
        ...                   training_frame=airlines)
        >>> airlines_if.model_performance()
        """
        return self._parms.get("stopping_rounds")

    @stopping_rounds.setter
    def stopping_rounds(self, stopping_rounds):
        assert_is_type(stopping_rounds, None, int)
        self._parms["stopping_rounds"] = stopping_rounds

    @property
    def stopping_metric(self):
        """
        Metric to use for early stopping (AUTO: logloss for classification, deviance for regression and anomaly_score
        for Isolation Forest). Note that custom and custom_increasing can only be used in GBM and DRF with the Python
        client.

        Type: ``Literal["auto", "anomaly_score", "deviance", "logloss", "mse", "rmse", "mae", "rmsle", "auc", "aucpr",
        "misclassification", "mean_per_class_error"]``, defaults to ``"auto"``.

        :examples:

        >>> airlines= h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/airlines/allyears2k_headers.zip")
        >>> predictors = ["Origin", "Dest", "Year", "UniqueCarrier",
        ...               "DayOfWeek", "Month", "Distance", "FlightNum"]
        >>> airlines_if = H2OIsolationForestEstimator(stopping_metric="auto",
        ...                                           stopping_rounds=3,
        ...                                           stopping_tolerance=1e-2,
        ...                                           seed=1234)
        >>> airlines_if.train(x=predictors,
        ...                   training_frame=airlines)
        >>> airlines_if.model_performance()
        """
        return self._parms.get("stopping_metric")

    @stopping_metric.setter
    def stopping_metric(self, stopping_metric):
        assert_is_type(stopping_metric, None, Enum("auto", "anomaly_score", "deviance", "logloss", "mse", "rmse", "mae", "rmsle", "auc", "aucpr", "misclassification", "mean_per_class_error"))
        self._parms["stopping_metric"] = stopping_metric

    @property
    def stopping_tolerance(self):
        """
        Relative tolerance for metric-based stopping criterion (stop if relative improvement is not at least this much)

        Type: ``float``, defaults to ``0.01``.

        :examples:

        >>> airlines= h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/airlines/allyears2k_headers.zip")
        >>> predictors = ["Origin", "Dest", "Year", "UniqueCarrier",
        ...               "DayOfWeek", "Month", "Distance", "FlightNum"]
        >>> airlines_if = H2OIsolationForestEstimator(stopping_metric="auto",
        ...                                           stopping_rounds=3,
        ...                                           stopping_tolerance=1e-2,
        ...                                           seed=1234)
        >>> airlines_if.train(x=predictors,
        ...                   training_frame=airlines)
        >>> airlines_if.model_performance()
        """
        return self._parms.get("stopping_tolerance")

    @stopping_tolerance.setter
    def stopping_tolerance(self, stopping_tolerance):
        assert_is_type(stopping_tolerance, None, numeric)
        self._parms["stopping_tolerance"] = stopping_tolerance

    @property
    def export_checkpoints_dir(self):
        """
        Automatically export generated models to this directory.

        Type: ``str``.

        :examples:

        >>> import tempfile
        >>> from os import listdir
        >>> airlines = h2o.import_file("http://s3.amazonaws.com/h2o-public-test-data/smalldata/airlines/allyears2k_headers.zip", destination_frame="air.hex")
        >>> predictors = ["DayofMonth", "DayOfWeek"]
        >>> checkpoints_dir = tempfile.mkdtemp()
        >>> air_if = H2OIsolationForestEstimator(max_depth=3,
        ...                                      seed=1234,
        ...                                      export_checkpoints_dir=checkpoints_dir)
        >>> air_if.train(x=predictors,
        ...              training_frame=airlines)
        >>> len(listdir(checkpoints_dir))
        """
        return self._parms.get("export_checkpoints_dir")

    @export_checkpoints_dir.setter
    def export_checkpoints_dir(self, export_checkpoints_dir):
        assert_is_type(export_checkpoints_dir, None, str)
        self._parms["export_checkpoints_dir"] = export_checkpoints_dir

    @property
    def contamination(self):
        """
        Contamination ratio - the proportion of anomalies in the input dataset. If undefined (-1) the predict function
        will not mark observations as anomalies and only anomaly score will be returned. Defaults to -1 (undefined).

        Type: ``float``, defaults to ``-1.0``.
        """
        return self._parms.get("contamination")

    @contamination.setter
    def contamination(self, contamination):
        assert_is_type(contamination, None, numeric)
        self._parms["contamination"] = contamination

    @property
    def validation_frame(self):
        """
        Id of the validation data frame.

        Type: ``Union[None, str, H2OFrame]``.
        """
        return self._parms.get("validation_frame")

    @validation_frame.setter
    def validation_frame(self, validation_frame):
        self._parms["validation_frame"] = H2OFrame._validate(validation_frame, 'validation_frame')

    @property
    def validation_response_column(self):
        """
        (experimental) Name of the response column in the validation frame. Response column should be binary and
        indicate not anomaly/anomaly.

        Type: ``str``.
        """
        return self._parms.get("validation_response_column")

    @validation_response_column.setter
    def validation_response_column(self, validation_response_column):
        assert_is_type(validation_response_column, None, str)
        self._parms["validation_response_column"] = validation_response_column


text:
Package.describe({
  name: 'zurb:foundation-sites',
  summary: 'Foundation 6 - The most advanced responsive front-end framework in the world.',
  version: '6.4.3',
  git: 'https://github.com/zurb/foundation-sites.git',
  documentation: 'meteor-README.md'
});

Package.onUse(function(api) {
  api.versionsFrom('1.2.1');
  api.imply('fourseven:scss@3.4.1');
  api.use(['ecmascript', 'jquery', 'fourseven:scss@3.4.1'], 'client');
  api.addFiles('dist/js/foundation.js', 'client');
  api.addFiles([

    'scss/foundation.scss',
    'scss/_global.scss',
    'scss/settings/_settings.scss',

    'scss/components/_accordion-menu.scss',
    'scss/components/_accordion.scss',
    'scss/components/_badge.scss',
    'scss/components/_breadcrumbs.scss',
    'scss/components/_button-group.scss',
    'scss/components/_button.scss',
    'scss/components/_callout.scss',
    'scss/components/_close-button.scss',
    'scss/components/_drilldown.scss',
    'scss/components/_dropdown-menu.scss',
    'scss/components/_dropdown.scss',
    'scss/components/_flex.scss',
    'scss/components/_float.scss',
    'scss/components/_label.scss',
    'scss/components/_media-object.scss',
    'scss/components/_menu-icon.scss',
    'scss/components/_menu.scss',
    'scss/components/_off-canvas.scss',
    'scss/components/_orbit.scss',
    'scss/components/_pagination.scss',
    'scss/components/_progress-bar.scss',
    'scss/components/_responsive-embed.scss',
    'scss/components/_reveal.scss',
    'scss/components/_slider.scss',
    'scss/components/_sticky.scss',
    'scss/components/_switch.scss',
    'scss/components/_table.scss',
    'scss/components/_tabs.scss',
    'scss/components/_thumbnail.scss',
    'scss/components/_title-bar.scss',
    'scss/components/_tooltip.scss',
    'scss/components/_top-bar.scss',
    'scss/components/_visibility.scss',

    'scss/forms/_checkbox.scss',
    'scss/forms/_error.scss',
    'scss/forms/_fieldset.scss',
    'scss/forms/_forms.scss',
    'scss/forms/_help-text.scss',
    'scss/forms/_input-group.scss',
    'scss/forms/_label.scss',
    'scss/forms/_meter.scss',
    'scss/forms/_progress.scss',
    'scss/forms/_range.scss',
    'scss/forms/_select.scss',
    'scss/forms/_text.scss',

    'scss/grid/_classes.scss',
    'scss/grid/_column.scss',
    'scss/grid/_flex-grid.scss',
    'scss/grid/_grid.scss',
    'scss/grid/_gutter.scss',
    'scss/grid/_layout.scss',
    'scss/grid/_position.scss',
    'scss/grid/_row.scss',
    'scss/grid/_size.scss',

    'scss/typography/_alignment.scss',
    'scss/typography/_base.scss',
    'scss/typography/_helpers.scss',
    'scss/typography/_print.scss',
    'scss/typography/_typography.scss',

    'scss/util/_breakpoint.scss',
    'scss/util/_color.scss',
    'scss/util/_flex.scss',
    'scss/util/_mixins.scss',
    'scss/util/_selector.scss',
    'scss/util/_unit.scss',
    'scss/util/_util.scss',
    'scss/util/_value.scss'

  ], 'client', {isImport: true});
});

redpajama_set_name: RedPajamaGithub


text:
package org.eclipse.emf.cdo.eresource;

import org.eclipse.emf.cdo.CDOObject;

import org.eclipse.emf.common.util.URI;

import java.io.IOException;
import java.util.Map;

/**
 *  A representation of the model object 'CDO Resource Node'.
 *
 * @noextend This interface is not intended to be extended by clients.
 * @noimplement This interface is not intended to be implemented by clients.
 *

 *              The following features are supported:
 *

 *
{@link org.eclipse.emf.cdo.eresource.CDOResourceNode#getFolder Folder}

 *
{@link org.eclipse.emf.cdo.eresource.CDOResourceNode#getName Name}

 *
{@link org.eclipse.emf.cdo.eresource.CDOResourceNode#getPath Path}

 *

 *

 * @see org.eclipse.emf.cdo.eresource.EresourcePackage#getCDOResourceNode()
 * @model abstract="true"
 * @extends CDOObject
 * @generated
 */
public interface CDOResourceNode extends CDOObject
{
  /**
   * @ADDED
   * @since 2.0
   */
  public static final String ROOT_PATH = "/"; //$NON-NLS-1$

  /**
   * @ADDED
   * @since 2.0
   */
  public static final String ROOT_NAME = null;

  /**
   * @ADDED
   * @since 2.0
   */
  public boolean isRoot();

  /**
   * Returns the value of the 'Folder' container reference. It is bidirectional and its opposite is '
   * {@link org.eclipse.emf.cdo.eresource.CDOResourceFolder#getNodes Nodes}'.
   *

   * If the meaning of the 'Folder' container reference isn't clear, there really should be more of a
   * description here...
   *

   *
   *
   * @return the value of the 'Folder' container reference.
   * @see #setFolder(CDOResourceFolder)
   * @see org.eclipse.emf.cdo.eresource.EresourcePackage#getCDOResourceNode_Folder()
   * @see org.eclipse.emf.cdo.eresource.CDOResourceFolder#getNodes
   * @model opposite="nodes" transient="false"
   * @generated
   */
  CDOResourceFolder getFolder();

  /**
   * Sets the value of the '{@link org.eclipse.emf.cdo.eresource.CDOResourceNode#getFolder Folder}' container
   * reference.
   *
   * @param value
   *          the new value of the 'Folder' container reference.
   * @see #getFolder()
   * @generated
   */
  void setFolder(CDOResourceFolder value);

  /**
   * Returns the value of the 'Name' attribute.
   *

   * If the meaning of the 'Name' attribute isn't clear, there really should be more of a description here...
   *

   *
   *
   * @return the value of the 'Name' attribute.
   * @see #setName(String)
   * @see org.eclipse.emf.cdo.eresource.EresourcePackage#getCDOResourceNode_Name()
   * @model annotation="http://www.eclipse.org/CDO/DBStore columnType='VARCHAR' columnLength='255'"
   * @generated
   */
  String getName();

  /**
   * Sets the value of the '{@link org.eclipse.emf.cdo.eresource.CDOResourceNode#getName Name}' attribute.
   *
   * @param value
   *          the new value of the 'Name' attribute.
   * @see #getName()
   * @generated
   */
  void setName(String value);

  /**
   * Returns the value of the 'Path' attribute.
   *

   * If the meaning of the 'Path' attribute isn't clear, there really should be more of a description here...
   *

   *
   *
   * @return the value of the 'Path' attribute.
   * @see #setPath(String)
   * @see org.eclipse.emf.cdo.eresource.EresourcePackage#getCDOResourceNode_Path()
   * @model transient="true" volatile="true" derived="true"
   * @generated
   */
  String getPath();

  /**
   * Sets the value of the '{@link org.eclipse.emf.cdo.eresource.CDOResourceNode#getPath Path}' attribute.
   *
   * @param value
   *          the new value of the 'Path' attribute.
   * @see #getPath()
   * @generated
   */
  void setPath(String value);

  /**
   * @ADDED
   */
  public URI getURI();

  /**
   * @ADDED
   */
  public void delete(Map<?, ?> options) throws IOException;

} // CDOResourceNode


text:
id: 25775bda-55d0-41cf-9ff9-406745eec7ac
post_id: 5abd02f7-3f18-473f-adfe-210a102ff64d
draft: false
author:
    name: AB
    email: jshannara@hotmail.com
    ip: 82.131.34.199
---

The anime would have been awesome if serialized by a studio capable of actually doing it any justice. The source material is way superior to this crappy adaptation by DEEN and at least on par with Higurashi if not better.

In the VN, once you realize that all the "magic" happening in real world is just stories used in order to cover up for real events, it actually becomes challenging to try to break to the truth. BUT I have to agree - the anime failed to deliver the challenge to the viewers properly.


text:
<?php
// MediaWiki settings for Contribution Scores
// Information: https://www.mediawiki.org/wiki/Extension:Contribution_Scores

require_once "$IP/extensions/Echo/Echo.php";


text:
from ctypes import cdll, c_double, c_int32
import os

lib = cdll.LoadLibrary(os.path.join(os.path.dirname(__file__), "target/release/libmonte.dylib"))
# need to change restype as it defaults to an int
lib.estimate_pi.restype = c_double
lib.estimate_pi.argtypes = [c_int32, c_int32]

def estimate_pi(sims, needles):
    return lib.estimate_pi(sims, needles)


text:
package burai.app.project.viewer.run;

import burai.app.QEFXMainController;
import burai.app.project.QEFXProjectController;
import burai.run.RunningManager;
import burai.run.RunningNode;
import burai.ssh.SSHJob;

public class RunAction {

    private QEFXProjectController controller;

    public RunAction(QEFXProjectController controller) {
        if (controller == null) {
            throw new IllegalArgumentException("controller is null.");
        }

        this.controller = controller;
    }

    public void runCalculation(RunEvent runEvent) {
        if (runEvent == null) {
            return;
        }

        if (runEvent.getRunningNode() != null) {
            this.runOnLocalMachine(runEvent.getRunningNode());

        } else if (runEvent.getSSHJob() != null) {
            this.runOnSSHServer(runEvent.getSSHJob());
        }
    }

    private void runOnLocalMachine(RunningNode runningNode) {
        if (runningNode == null) {
            return;
        }

        RunningManager.getInstance().addNode(runningNode);

        QEFXMainController mainController = this.controller.getMainController();
        if (mainController == null) {
            return;
        }

        mainController.offerOnHomeTabSelected(explorerFacade -> {
            if (explorerFacade != null && (!explorerFacade.isCalculatingMode())) {
                explorerFacade.setCalculatingMode();
            }
        });

        mainController.showHome();
    }

    private void runOnSSHServer(SSHJob sshJob) {
        if (sshJob == null) {
            return;
        }

        sshJob.postJobToServer();
    }
}


text:
module Shoulda
  module Matchers
    module ActiveModel
      # The `allow_value` matcher is used to test that an attribute of a model
      # can or cannot be set to a particular value or values. It is most
      # commonly used in conjunction with the `validates_format_of` validation.
      #
      # #### should
      #
      # In the positive form, `allow_value` asserts that an attribute can be
      # set to one or more values, succeeding if none of the values cause the
      # record to be invalid:
      #
      #     class UserProfile
      #       include ActiveModel::Model
      #       attr_accessor :website_url
      #
      #       validates_format_of :website_url, with: URI.regexp
      #     end
      #
      #     # RSpec
      #     describe UserProfile do
      #       it do
      #         should allow_value('http://foo.com', 'http://bar.com/baz').
      #           for(:website_url)
      #       end
      #     end
      #
      #     # Test::Unit
      #     class UserProfileTest < ActiveSupport::TestCase
      #       should allow_value('http://foo.com', 'http://bar.com/baz').
      #         for(:website_url)
      #     end
      #
      # #### should_not
      #
      # In the negative form, `allow_value` asserts that an attribute cannot be
      # set to one or more values, succeeding if the *first* value causes the
      # record to be invalid.
      #
      # **This can be surprising** so in this case if you need to check that
      # *all* of the values are invalid, use separate assertions:
      #
      #     class UserProfile
      #       include ActiveModel::Model
      #       attr_accessor :website_url
      #
      #       validates_format_of :website_url, with: URI.regexp
      #     end
      #
      #     describe UserProfile do
      #       # One assertion: 'buz' and 'bar' will not be tested
      #       it { should_not allow_value('fiz', 'buz', 'bar').for(:website_url) }
      #
      #       # Three assertions, all tested separately
      #       it { should_not allow_value('fiz').for(:website_url) }
      #       it { should_not allow_value('buz').for(:website_url) }
      #       it { should_not allow_value('bar').for(:website_url) }
      #     end
      #
      # #### Qualifiers
      #
      # ##### on
      #
      # Use `on` if your validation applies only under a certain context.
      #
      #     class UserProfile
      #       include ActiveModel::Model
      #       attr_accessor :birthday_as_string
      #
      #       validates_format_of :birthday_as_string,
      #         with: /^(\d+)-(\d+)-(\d+)$/,
      #         on: :create
      #     end
      #
      #     # RSpec
      #     describe UserProfile do
      #       it do
      #         should allow_value('2013-01-01').
      #           for(:birthday_as_string).
      #           on(:create)
      #       end
      #     end
      #
      #     # Test::Unit
      #     class UserProfileTest < ActiveSupport::TestCase
      #       should allow_value('2013-01-01').
      #         for(:birthday_as_string).
      #         on(:create)
      #     end
      #
      # ##### with_message
      #
      # Use `with_message` if you are using a custom validation message.
      #
      #     class UserProfile
      #       include ActiveModel::Model
      #       attr_accessor :state
      #
      #       validates_format_of :state,
      #         with: /^(open|closed)$/,
      #         message: 'State must be open or closed'
      #     end
      #
      #     # RSpec
      #     describe UserProfile do
      #       it do
      #         should allow_value('open', 'closed').
      #           for(:state).
      #           with_message('State must be open or closed')
      #       end
      #     end
      #
      #     # Test::Unit
      #     class UserProfileTest < ActiveSupport::TestCase
      #       should allow_value('open', 'closed').
      #         for(:state).
      #         with_message('State must be open or closed')
      #     end
      #
      # Use `with_message` with the `:against` option if the attribute the
      # validation message is stored under is different from the attribute
      # being validated.
      #
      #     class UserProfile
      #       include ActiveModel::Model
      #       attr_accessor :sports_team
      #
      #       validate :sports_team_must_be_valid
      #
      #       private
      #
      #       def sports_team_must_be_valid
      #         if sports_team !~ /^(Broncos|Titans)$/i
      #           self.errors.add :chosen_sports_team,
      #             'Must be either a Broncos fan or a Titans fan'
      #         end
      #       end
      #     end
      #
      #     # RSpec
      #     describe UserProfile do
      #       it do
      #         should allow_value('Broncos', 'Titans').
      #           for(:sports_team).
      #           with_message('Must be either a Broncos or Titans fan',
      #             against: :chosen_sports_team
      #           )
      #       end
      #     end
      #
      #     # Test::Unit
      #     class UserProfileTest < ActiveSupport::TestCase
      #       should allow_value('Broncos', 'Titans').
      #         for(:sports_team).
      #         with_message('Must be either a Broncos or Titans fan',
      #           against: :chosen_sports_team
      #         )
      #     end
      #
      # @return [AllowValueMatcher]
      #
      def allow_value(*values)
        if values.empty?
          raise ArgumentError, 'need at least one argument'
        else
          AllowValueMatcher.new(*values)
        end
      end

      # @private
      class AllowValueMatcher
        include Helpers

        attr_accessor :attribute_with_message
        attr_accessor :options

        def initialize(*values)
          self.values_to_match = values
          self.message_finder_factory = ValidationMessageFinder
          self.options = {}
          self.after_setting_value_callback = -> {}
        end

        def for(attribute)
          self.attribute_to_set = attribute
          self.attribute_to_check_message_against = attribute
          self
        end

        def on(context)
          @context = context
          self
        end

        def with_message(message, options={})
          self.options[:expected_message] = message
          self.options[:expected_message_values] = options.fetch(:values, {})

          if options.key?(:against)
            self.attribute_to_check_message_against = options[:against]
          end

          self
        end

        def strict
          self.message_finder_factory = ExceptionMessageFinder
          self
        end

        def _after_setting_value(&callback)
          self.after_setting_value_callback = callback
        end

        def matches?(instance)
          self.instance = instance

          values_to_match.none? do |value|
            self.value = value
            set_value(value)
            errors_match?
          end
        end

        def failure_message
          "Did not expect #{expectation},\ngot error: #{matched_error}"
        end
        alias failure_message_for_should failure_message

        def failure_message_when_negated
          "Expected #{expectation},\ngot#{error_description}"
        end
        alias failure_message_for_should_not failure_message_when_negated

        def description
          message_finder.allow_description(allowed_values)
        end

        protected

        attr_accessor :values_to_match, :message_finder_factory,
          :instance, :attribute_to_set, :attribute_to_check_message_against,
          :context, :value, :matched_error, :after_setting_value_callback

        def set_value(value)
          instance.__send__("#{attribute_to_set}=", value)
          after_setting_value_callback.call
        end

        def errors_match?
          has_messages? && errors_for_attribute_match?
        end

        def has_messages?
          message_finder.has_messages?
        end

        def errors_for_attribute_match?
          if expected_message
            self.matched_error = errors_match_regexp? || errors_match_string?
          else
            errors_for_attribute.compact.any?
          end
        end

        def errors_for_attribute
          message_finder.messages
        end

        def errors_match_regexp?
          if Regexp === expected_message
            errors_for_attribute.detect { |e| e =~ expected_message }
          end
        end

        def errors_match_string?
          if errors_for_attribute.include?(expected_message)
            expected_message
          end
        end

        def expectation
          parts = [
            error_source,
            includes_expected_message,
            "when #{attribute_to_set} is set to #{value.inspect}"
          ]

          parts.join(' ').squeeze(' ')
        end

        def includes_expected_message
          if expected_message
            "to include #{expected_message.inspect}"
          else
            ''
          end
        end

        def error_source
          message_finder.source_description
        end

        def error_description
          message_finder.messages_description
        end

        def allowed_values
          if values_to_match.length > 1
            "any of [#{values_to_match.map(&:inspect).join(', ')}]"
          else
            values_to_match.first.inspect
          end
        end

        def expected_message
          if options.key?(:expected_message)
            if Symbol === options[:expected_message]
              default_expected_message
            else
              options[:expected_message]
            end
          end
        end

        def default_expected_message
          message_finder.expected_message_from(default_attribute_message)
        end

        def default_attribute_message
          default_error_message(
            options[:expected_message],
            default_attribute_message_values
          )
        end

        def default_attribute_message_values
          defaults = {
            model_name: model_name,
            instance: instance,
            attribute: attribute_to_check_message_against,
          }

          defaults.merge(options[:expected_message_values])
        end

        def model_name
          instance.class.to_s.underscore
        end

        def message_finder
          message_finder_factory.new(instance, attribute_to_check_message_against, context)
        end
      end
    end
  end
end


text:
$.gridify = function (table, opt) {
  var options = {
    resizeZoneWidth:10
  };

  $.extend(options, opt);

  var box = $("<div>").addClass("gdfWrapper");
  box.append(table);

  var head = table.clone();
  head.addClass("fixHead");
  //remove non head
  head.find("tbody").remove();
  box.append(head);

  box.append(table);

  var hTh=head.find(".gdfColHeader");
  var cTh=table.find(".gdfColHeader");
  for (var i=0; i<hTh.length;i++){
    hTh.eq(i).data("fTh",cTh.eq(i));
  }

  //--------- set table to 0 to prevent a strange 100%
  table.width(0);
  head.width(0);

  //----------------------  header management start
  head.find("th.gdfColHeader.gdfResizable:not(.gdfied)").mouseover(function () {
    $(this).addClass("gdfColHeaderOver");

  }).bind("mouseout.gdf",function () {
      $(this).removeClass("gdfColHeaderOver");
      if (!$.gridify.columInResize) {
        $("body").removeClass("gdfHResizing");
      }

    }).bind("mousemove.gdf",function (e) {
      if (!$.gridify.columInResize) {
        var colHeader = $(this);
        var mousePos = e.pageX - colHeader.offset().left;

        if (colHeader.width() - mousePos < options.resizeZoneWidth) {
          $("body").addClass("gdfHResizing");
        } else {
          $("body").removeClass("gdfHResizing");
        }
      }

    }).bind("mousedown.gdf",function (e) {
      var colHeader = $(this);
      var mousePos = e.pageX - colHeader.offset().left;
      if (colHeader.width() - mousePos < options.resizeZoneWidth) {
        $("body").unselectable();
        $.gridify.columInResize = $(this);
        //bind event for start resizing
        //console.debug("start resizing");
        $(document).bind("mousemove.gdf",function (e) {
          //manage resizing
          var w = e.pageX - $.gridify.columInResize.offset().left;
          $.gridify.columInResize.width(w);
          $.gridify.columInResize.data("fTh").width(w);

          //bind mouse up on body to stop resizing
        }).bind("mouseup.gdf", function () {
            //console.debug("stop resizing");
            $(this).unbind("mousemove.gdf").unbind("mouseup.gdf").clearUnselectable();
            $("body").removeClass("gdfHResizing");
            delete $.gridify.columInResize;
          });
      }
    }).addClass("gdfied unselectable").attr("unselectable", "true");

  //----------------------  cell management start wrapping
  table.find("td.gdfCell:not(.gdfied)").each(function () {
    var cell = $(this);
    if (cell.is(".gdfEditable")) {
      var inp = $("<input type='text'>").addClass("gdfCellInput");
      inp.val(cell.text());
      cell.empty().append(inp);
    } else {
      var wrp = $("<div>").addClass("gdfCellWrap");
      wrp.html(cell.html());
      cell.empty().append(wrp);
    }
  }).addClass("gdfied");

  return box;
};

$.splittify = {
  init: function(where, first, second,perc) {

    perc=perc || 50;

    var element = $("<div>").addClass("splitterContainer");
    var firstBox = $("<div>").addClass("splitElement splitBox1");
    var splitterBar = $("<div>").addClass("splitElement vSplitBar").attr("unselectable", "on").html("|").css("padding-top",where.height()/2+"px");
    var secondBox = $("<div>").addClass("splitElement splitBox2");

    var splitter= new Splitter(element,firstBox,secondBox,splitterBar);
    splitter.perc=perc;

    firstBox.append(first);
    secondBox.append(second);

    element.append(firstBox).append(secondBox).append(splitterBar);

    where.append(element);

    var w = where.innerWidth();
    var fbw = w *perc/ 100 - splitterBar.width();
    var realW=firstBox.get(0).scrollWidth;
    fbw=fbw>realW?realW:fbw;
    firstBox.width(fbw).css({left:0});
    splitterBar.css({left:firstBox.width()});
    secondBox.width(w -fbw-splitterBar.width() ).css({left:firstBox.width() + splitterBar.width()});

    splitterBar.bind("mousedown.gdf", function(e) {
      $.splittify.splitterBar = $(this);
      //bind event for start resizing
      //console.debug("start splitting");
      var realW=firstBox.get(0).scrollWidth;
      $("body").unselectable().bind("mousemove.gdf", function(e) {
        //manage resizing
        //console.debug(e.pageX - $.gridify.columInResize.offset().left)
        var sb = $.splittify.splitterBar;
        var pos = e.pageX - sb.parent().offset().left;
        var w = sb.parent().width();
        var fbw=firstBox;

        pos=pos>splitter.firstBoxMinWidth?pos:splitter.firstBoxMinWidth;
        pos=pos<realW-10?pos:realW-10;
        sb.css({left:pos});
        firstBox.width(pos);
        secondBox.css({left:pos + sb.width(),width:w - pos - sb.width()});
        splitter.perc=(firstBox.width()/splitter.element.width())*100;

        //bind mouse up on body to stop resizing
      }).bind("mouseup.gdf", function() {
        //console.debug("stop splitting");
        $(this).unbind("mousemove.gdf").unbind("mouseup.gdf").clearUnselectable();
        delete $.splittify.splitterBar;

      });
    });

    // keep both side in synch when scroll
    var stopScroll=false;
    var fs=firstBox.add(secondBox);
    fs.scroll(function(e) {
      var el = $(this);
      var top = el.scrollTop();
      if (el.is(".splitBox1") && stopScroll!="splitBox2"){
        stopScroll="splitBox1";
        secondBox.scrollTop(top);
      }else if (el.is(".splitBox2") && stopScroll!="splitBox1"){
        stopScroll="splitBox2";
        firstBox.scrollTop(top);
      }
      secondBox.find(".fixHead").css('top', top);
      firstBox.find(".fixHead").css('top', top);

      where.stopTime("reset").oneTime(100,"reset",function(){stopScroll="";})
    });

    function Splitter(element,firstBox, secondBox, splitterBar) {
      this.element=element;
      this.firstBox = firstBox;
      this.secondBox = secondBox;
      this.splitterBar = splitterBar;
      this.perc=0;
      this.firstBoxMinWidth=0;

      this.resize=function(newPerc){
        //console.debug("resize",newPerc)
        this.perc=newPerc?newPerc:this.perc;
        var totW=this.element.width();
        var realW=this.firstBox.get(0).scrollWidth;
        var newW=totW*this.perc/100;
        newW=newW>this.firstBoxMinWidth?newW:this.firstBoxMinWidth;
        newW=newW<realW?newW:realW;
        this.firstBox.css({width:newW});
        this.splitterBar.css({left:newW});
        this.secondBox.css({left:newW + this.splitterBar.width(),width:totW - newW - this.splitterBar.width()});
      }
    }

    return splitter;
  }
};

//<%------------------------------------------------------------------------  UTILITIES ---------------------------------------------------------------%>
  function computeStart(start) {
    return computeStartDate(start).getTime();
  }
  function computeStartDate(start) {
    var d = new Date(start+3600000*12);
    d.setHours(0, 0, 0, 0);
    //move to next working day
    while (isHoliday(d)) {
      d.setDate(d.getDate() + 1);
    }
    d.setHours(0, 0, 0, 0);
    return d;
  }

  function computeEnd(end) {
    return computeEndDate(end).getTime()
  }
  function computeEndDate(end) {
    var d = new Date(end-3600000*12);
    d.setHours(23, 59, 59, 999);
    //move to next working day
    while (isHoliday(d)) {
      d.setDate(d.getDate() + 1);
    }
    d.setHours(23, 59, 59, 999);
    return d;
  }

  function computeEndByDuration(start, duration) {
    var d = new Date(start);
    //console.debug("computeEndByDuration start ",d,duration)
    var q = duration - 1;
    while (q > 0) {
      d.setDate(d.getDate() + 1);
      if (!isHoliday(d))
        q--;
    }
    d.setHours(23, 59, 59, 999);
    return d.getTime();
  }

  function incrementDateByWorkingDays(date, days) {
    var d = new Date(date);
    d.incrementDateByWorkingDays(days);
    return d.getTime();
  }

function recomputeDuration(start, end) {
   //console.debug("recomputeDuration");
   return new Date(start).distanceInWorkingDays(new Date(end));
 }

//This prototype is provided by the Mozilla foundation and
//is distributed under the MIT license.
//http://www.ibiblio.org/pub/Linux/LICENSES/mit.license

if (!Array.prototype.filter){
  Array.prototype.filter = function (fun) {
    var len = this.length;
    if (typeof fun != "function")
      throw new TypeError();

    var res = new Array();
    var thisp = arguments[1];
    for (var i = 0; i < len; i++) {
      if (i in this) {
        var val = this[i]; // in case fun mutates this
        if (fun.call(thisp, val, i, this))
          res.push(val);
      }
    }
    return res;
  };
}


text:
package opt

import (
	"github.com/algolia/algoliasearch-client-go/v3/algolia/opt"
)

// ExtractSearchableAttributes returns the first found SearchableAttributesOption from the
// given variadic arguments or nil otherwise.
func ExtractSearchableAttributes(opts ...interface{}) *opt.SearchableAttributesOption {
	for _, o := range opts {
		if v, ok := o.(*opt.SearchableAttributesOption); ok {
			return v
		}
	}
	return nil
}


text:
'use strict';

var currencyCloud = require('../../lib/currency-cloud');
var expect = require('chai').expect;
var mock = require('../mocks');
var contactsMock = mock.contacts();
var prepost = require('../prepost');
var recorder = prepost.recorder('currency-cloud');
var setup = prepost.setup;
var teardown = prepost.teardown;

var getPrerequisites = function () {
  var promise = currencyCloud.accounts.getCurrent()
    .then(function (account) {
      var contact = new contactsMock.contact1();
      contact.accountId = account.id;

      return currencyCloud.contacts.create(contact)
        .then(function (res) {
          return res.id;
        });
    });

  return promise;
};

describe('currency-cloud', function () {
  before(function (done) {
    recorder.read();
    setup.login()
      .then(function () {
        done();
      });
  });

  after(function (done) {
    teardown.logout()
      .then(function () {
        recorder.write(done);
      });
  });

  describe('onBehalfOf', function () {
    it('fails if required parameters are missing', function () {
      expect(function () {
        currencyCloud.onBehalfOf(/*no params*/);
      }).to.throw();
      expect(function () {
        currencyCloud.onBehalfOf('id');
      }).to.throw();
    });

    it('fails if id parameter is invalid', function () {
      expect(function () {
        currencyCloud.onBehalfOf('wrong');
      }).to.throw();
    });

    it('fails if already been called and not yet completed', function (done) {
      getPrerequisites()
        .then(function (contactId) {
          return currencyCloud.onBehalfOf(contactId, function () {
            return currencyCloud.beneficiaries.create(new mock.beneficiaries.beneficiary1())
              .then(function () {
                expect(function () {
                  currencyCloud.onBehalfOf('deadbeef-dead-beef-dead-beefdeadbeef', function () {
                  });
                }).to.throw();
                done();
              });
          });
        })
        .catch(done);
    });

    it('executes API calls on behalf of specified id; once completed, resets the id', function (done) {
      getPrerequisites()
        .then(function (contactId) {
          return currencyCloud.onBehalfOf(contactId, function () {
            return currencyCloud.beneficiaries.create(new mock.beneficiaries.beneficiary1())
              .then(function (beneficiary) {
                expect(beneficiary.creatorContactId).equals(contactId);
              });
          })
            .then(function () {
              return currencyCloud.contacts.getCurrent()
                .then(function (current) {
                  return currencyCloud.beneficiaries.create(new mock.beneficiaries.beneficiary1())
                    .then(function (beneficiary) {
                      expect(beneficiary.creatorContactId).equals(current.id);
                      done();
                    });
                });
            });
        })
        .catch(done);
    });
  });

  describe('APIerror', function () {
    it('returns properly structured error', function (done) {
      var params = {
        currency: 'US',
        bankAccountCountry: 'US'
      };

      currencyCloud.reference.getBeneficiaryRequiredDetails(params)
        .then(function () {
          done(new Error('should have failed.'));
        })
        .catch(function (err) {
          expect(err.platform).is.not.empty;

          expect(err.request.parameters).eql(params);
          expect(err.request.verb).is.not.empty;
          expect(err.request.url).is.not.empty;

          expect(err.response.statusCode).equals(400);
          expect(err.response.date).is.not.empty;
          expect(err.response.requestId).is.not.empty;

          expect(err.errors).to.have.length.above(0);

          done();
        });
    });
  });
});


text:
<?php
declare(strict_types=1);

namespace Cake\Test\TestCase\Database\Expression;

use Cake\Database\Expression\QueryExpression;
use Cake\Database\Expression\TupleComparison;
use Cake\Database\ValueBinder;
use Cake\TestSuite\TestCase;
use InvalidArgumentException;

/**
 * Tests TupleComparison class
 */
class TupleComparisonTest extends TestCase
{
    /**
     * Tests generating a function with no arguments
     */
    public function testsSimpleTuple(): void
    {
        $f = new TupleComparison(['field1', 'field2'], [1, 2], ['integer', 'integer'], '=');
        $binder = new ValueBinder();
        $this->assertSame('(field1, field2) = (:tuple0, :tuple1)', $f->sql($binder));
        $this->assertSame(1, $binder->bindings()[':tuple0']['value']);
        $this->assertSame(2, $binder->bindings()[':tuple1']['value']);
        $this->assertSame('integer', $binder->bindings()[':tuple0']['type']);
        $this->assertSame('integer', $binder->bindings()[':tuple1']['type']);
    }

    /**
     * Tests generating tuples in the fields side containing expressions
     */
    public function testTupleWithExpressionFields(): void
    {
        $field1 = new QueryExpression(['a' => 1]);
        $f = new TupleComparison([$field1, 'field2'], [4, 5], ['integer', 'integer'], '>');
        $binder = new ValueBinder();
        $this->assertSame('(a = :c0, field2) > (:tuple1, :tuple2)', $f->sql($binder));
        $this->assertSame(1, $binder->bindings()[':c0']['value']);
        $this->assertSame(4, $binder->bindings()[':tuple1']['value']);
        $this->assertSame(5, $binder->bindings()[':tuple2']['value']);
    }

    /**
     * Tests generating tuples in the values side containing expressions
     */
    public function testTupleWithExpressionValues(): void
    {
        $value1 = new QueryExpression(['a' => 1]);
        $f = new TupleComparison(['field1', 'field2'], [$value1, 2], ['integer', 'integer'], '=');
        $binder = new ValueBinder();
        $this->assertSame('(field1, field2) = (a = :c0, :tuple1)', $f->sql($binder));
        $this->assertSame(1, $binder->bindings()[':c0']['value']);
        $this->assertSame(2, $binder->bindings()[':tuple1']['value']);
    }

    /**
     * Tests generating tuples using the IN conjunction
     */
    public function testTupleWithInComparison(): void
    {
        $f = new TupleComparison(
            ['field1', 'field2'],
            [[1, 2], [3, 4]],
            ['integer', 'integer'],
            'IN'
        );
        $binder = new ValueBinder();
        $this->assertSame('(field1, field2) IN ((:tuple0,:tuple1), (:tuple2,:tuple3))', $f->sql($binder));
        $this->assertSame(1, $binder->bindings()[':tuple0']['value']);
        $this->assertSame(2, $binder->bindings()[':tuple1']['value']);
        $this->assertSame(3, $binder->bindings()[':tuple2']['value']);
        $this->assertSame(4, $binder->bindings()[':tuple3']['value']);
    }

    /**
     * Tests traversing
     */
    public function testTraverse(): void
    {
        $value1 = new QueryExpression(['a' => 1]);
        $field2 = new QueryExpression(['b' => 2]);
        $f = new TupleComparison(['field1', $field2], [$value1, 2], ['integer', 'integer'], '=');
        $binder = new ValueBinder();
        $expressions = [];

        $collector = function ($e) use (&$expressions): void {
            $expressions[] = $e;
        };

        $f->traverse($collector);
        $this->assertCount(4, $expressions);
        $this->assertSame($field2, $expressions[0]);
        $this->assertSame($value1, $expressions[2]);

        $f = new TupleComparison(
            ['field1', $field2],
            [[1, 2], [3, $value1]],
            ['integer', 'integer'],
            'IN'
        );
        $expressions = [];
        $f->traverse($collector);
        $this->assertCount(4, $expressions);
        $this->assertSame($field2, $expressions[0]);
        $this->assertSame($value1, $expressions[2]);
    }

    /**
     * Tests that a single ExpressionInterface can be used as the value for
     * comparison
     */
    public function testValueAsSingleExpression(): void
    {
        $value = new QueryExpression('SELECT 1, 1');
        $f = new TupleComparison(['field1', 'field2'], $value);
        $binder = new ValueBinder();
        $this->assertSame('(field1, field2) = (SELECT 1, 1)', $f->sql($binder));
    }

    /**
     * Tests that a single ExpressionInterface can be used as the field for
     * comparison
     */
    public function testFieldAsSingleExpression(): void
    {
        $value = [1, 1];
        $f = new TupleComparison(new QueryExpression('a, b'), $value);
        $binder = new ValueBinder();
        $this->assertSame('(a, b) = (:tuple0, :tuple1)', $f->sql($binder));
    }

    public function testMultiTupleComparisonRequiresMultiTupleValue(): void
    {
        $this->expectException(InvalidArgumentException::class);
        $this->expectExceptionMessage('Multi-tuple comparisons require a multi-tuple value, single-tuple given.');

        new TupleComparison(
            ['field1', 'field2'],
            [1, 1],
            ['integer', 'integer'],
            'IN'
        );
    }

    public function testSingleTupleComparisonRequiresSingleTupleValue(): void
    {
        $this->expectException(InvalidArgumentException::class);
        $this->expectExceptionMessage('Single-tuple comparisons require a single-tuple value, multi-tuple given.');

        new TupleComparison(
            ['field1', 'field2'],
            [[1, 1], [2, 2]],
            ['integer', 'integer'],
            '='
        );
    }
}


text:
"""
This file contains classes and methods to generate input files

The FiniteDifferencesPhononFlow
"""

from qepy.pw import PwIn
from qepy.ph import PhIn
from qepy.pwxml import PwXML
from qepy.lattice import *
from qepy.matdyn import Matdyn
from qepy import qepyenv
from yambopy.io.inputfile import YamboIn
from yambopy.tools.duck import isiter
from yambopy.flow import PwTask, PhTask, P2yTask, YamboTask, DynmatTask, YambopyFlow, AbinitTask, E2yTask

__all__ = [
"FiniteDifferencesPhononFlow",
"KpointsConvergenceFlow",
"PwNscfYamboIPChiTasks",
"YamboQPBSETasks",
"PwNscfTasks",
"PwBandsTasks",
"PwRelaxTasks",
"PhPhononTasks"
]

class FiniteDifferencesPhononFlow():
    """
    This class takes as an input one structure and a phonon calculation.
    It produces a flow with the QE input files displaced along the phonon modes

    Author: Henrique Miranda
    """
    def __init__(self,structure,phonon_modes):
        self.structure = structure
        if not isinstance(phonon_modes,Matdyn):
            raise ValueError('phonon_modes must be an instance of Matdyn')
        self.phonon_modes = phonon_modes

    def get_tasks(self,path,kpoints,ecut,nscf_bands,nscf_kpoints=None,
                  imodes_list=None,displacements=[0.01,-0.01],iqpoint=0,**kwargs):
        """
        Create a flow with all the tasks to perform the calculation

        Arguments:
            generator: a builder function that takes structure, kpoints, ecut,
                       nscf_bands, nscf_kpoints and kwargs as argument and returns the
                       tasks to be performed at each displacement
        """

        if imodes_list is None: imodes_list = list(range(self.phonon_modes.nmodes))
        if not isiter(displacements): displacements = [displacements]
        generator = kwargs.pop("generator",PwNscfYamboIPChiTasks)

        #create qe input from structure
        pwin = PwIn.from_structure_dict(self.structure,kpoints=kpoints,ecut=ecut)

        tasks = []
        #
        # Undisplaced structure
        #
        tasks.extend(generator(pwin.get_structure(),kpoints,ecut,nscf_bands,nscf_kpoints=nscf_kpoints,**kwargs))

        #
        # Displaced structures
        #
        reference = [dict(imode=None,displacement=0)]

        for imode in imodes_list:
            #get phonon mode
            cart_mode = self.phonon_modes.modes[iqpoint,imode]
            #iterate over displacements
            for displacement in displacements:
                #displace structure
                input_mock = pwin.get_displaced(cart_mode, displacement=displacement)
                displaced_structure = input_mock.get_structure()

                #generate tasks
                new_tasks = generator(displaced_structure,kpoints,ecut,
                                      nscf_bands,nscf_kpoints=nscf_kpoints,**kwargs)
                #save task
                tasks.extend(new_tasks)
                reference.append([dict(imode=None,displacement=displacement)])

        #store a reference for each of the tasks
        self.reference = reference
        return tasks

    def get_flow(self,path,kpoints,ecut,nscf_bands,nscf_kpoints=None,imodes_list=None,**kwargs):

        tasks = self.get_tasks(path=path,kpoints=kpoints,ecut=ecut,nscf_bands=nscf_bands,
                               nscf_kpoints=nscf_kpoints,imodes_list=imodes_list,**kwargs)

        #put all the tasks in a flow
        self.yambo_flow = YambopyFlow.from_tasks(path,tasks)
        return self.yambo_flow

    def get_dchi(self):
        """Collect all tasks producing eps files"""
        raise NotImplementedError('TODO')
        #find all the optical tasks
        #calculate finite differences
        pass

    def plot_ax(self,what):
        """ Collect and plot the results

        Arguments:
            what: what to plot can be eps for optical response
        """
        raise NotImplementedError('TODO')
        #plot finite differences
        pass

    @property
    def path(self):
        return self.yambo_flow.path

class KpointsConvergenceFlow():
    """
    This class takes as an input one structure.
    It produces a flow with the QE input files with different number of kpoints
    and then runs a task staring from the QE input

    Author: Henrique Miranda
    """
    def __init__(self,structure):
        self.structure = structure

    def get_tasks(self,scf_kpoints,nscf_kpoints_list,ecut,nscf_bands,**kwargs):
        """
        Create a flow with all the tasks to perform the calculation

        Arguments:
            generator: a builder function that takes structure, kpoints, ecut,
                       nscf_bands, nscf_kpoints and kwargs as argument and returns the
                       tasks to be performed at each displacement
        """
        generator = kwargs.pop("generator",PwNscfYamboIPChiTasks)

        #create a QE scf task and run
        qe_input = PwIn.from_structure_dict(self.structure,kpoints=scf_kpoints,ecut=ecut)
        qe_scf_task = PwTask.from_input(qe_input)
        tasks = [qe_scf_task]

        for nscf_kpoints in nscf_kpoints_list:

            #generate tasks
            new_tasks = generator(structure=self.structure,kpoints=scf_kpoints,
                                  nscf_kpoints=nscf_kpoints,
                                  ecut=ecut,nscf_bands=nscf_bands,**kwargs)
            tasks.extend(new_tasks)

        return tasks

    def get_flow(self,path,scf_kpoints,nscf_kpoints_list,ecut,nscf_bands,**kwargs):
        tasks = self.get_tasks(scf_kpoints=scf_kpoints,ecut=ecut,nscf_bands=nscf_bands,
                               nscf_kpoints_list=nscf_kpoints_list,**kwargs)

        #put all the tasks in a flow
        self.yambo_flow = YambopyFlow.from_tasks(path,tasks,**kwargs)
        return self.yambo_flow

class BandsConvergenceFlow():
    """
    This class takes as an input one structure.
    It produces a flow with the QE input files for nscf calculation with the max number of bands
    Then adds one yambo task with different number of bands

    Author: Henrique Miranda
    """
    def __init__(self,structure):
        self.structure = structure

    def get_tasks(self,scf_kpoints,ecut,nscf_kpoints,bands_list,**kwargs):
        """
        Create a flow with all the tasks to perform the calculation

        Arguments:
            generator: a builder function that takes structure, kpoints, ecut,
                       nscf_bands, nscf_kpoints and kwargs as argument and returns the
                       tasks to be performed at each displacement
        """
        generator = kwargs.pop("generator",YamboIPChiTask)
        conv_thr = kwargs.pop("conv_thr",qepyenv.CONV_THR)

        #create a QE scf task and run
        nscf_bands = max(bands_list)
        tasks = PwNscfTasks(self.structure,kpoints=scf_kpoints,ecut=ecut,
                            nscf_bands=nscf_bands,nscf_kpoints=nscf_kpoints,conv_thr=conv_thr)
        qe_scf_task, qe_nscf_task, p2y_task = tasks
        tasks = list(tasks)

        link_task = p2y_task
        new_task  = p2y_task
        #we invert the list and compute from higher bands to lower
        #this avoids recomputing the dipoles
        for bands in sorted(bands_list,reverse=True):
            #generate tasks
            new_task = generator(link_task,bands=bands,dependencies=new_task,**kwargs)
            tasks.append(new_task)
            link_task = [p2y_task,new_task]

        return tasks

    def get_flow(self,path,scf_kpoints,ecut,nscf_kpoints,bands_list,**kwargs):
        tasks = self.get_tasks(scf_kpoints=scf_kpoints,ecut=ecut,nscf_kpoints=nscf_kpoints,
                               bands_list=bands_list,**kwargs)

        #put all the tasks in a flow
        self.yambo_flow = YambopyFlow.from_tasks(path,tasks,**kwargs)
        return self.yambo_flow

#inject some code in the initialization
def copy_pp(self):
    """
    This code is to be executed during the initialization of the SOC calculation
    It uses the dielectric function calculated without spin orbit coupling to
    calculate the QP corrections with spin-orbit coupling
    """
    import os
    import glob
    import shutil
    from netCDF4 import Dataset
    nospin_task = self.get_vars('nospin_task')
    spin_bands = self.get_vars('spin_bands')
    src = os.path.join(nospin_task.path,'run')
    dst = os.path.join(self.path,'run')
    if not os.path.isdir(dst): os.mkdir(dst)

    #link all the pp files
    ppfiles = glob.glob(os.path.join(src,'ndb.pp*'))
    for ppfile_path in ppfiles:
        ppfile = os.path.basename(ppfile_path)
        shutil.copy(ppfile_path,os.path.join(dst,ppfile))

    #change the spin value in the main file
    #also need to change the number of bands so yambo will read it
    main_pp = os.path.join(dst,'ndb.pp')
    with Dataset(main_pp,'r+') as dst_db:
        dst_db.variables['SPIN_VARS'][1]=2
        dst_db.variables['X_PARS_1'][2]=spin_bands

def update_cell_and_positions(self):
    """
    Code executed after the lattice relaxation to read the
    resulting cell parameters
    """
    from qepy import PwXML
    pwtask = self.get_vars("pwtask")
    prefix = pwtask.pwinput.prefix
    pwxml = PwXML(prefix,path=pwtask.path)
    self.pwinput.update_structure_from_xml(pwxml)

def get_scissor(self):
    """
    This code is to be executed during the intialization of a BSE calculation
    with scissor operator. It computes the scissor shift from a QP database
    and sets the BSE input accordingly
    """
    import os
    from yambopy.dbs.qpdb import YamboQPDB
    qp_task = self.get_vars('qp_task')
    valence = self.get_vars('valence')
    qp_path = os.path.join(qp_task.path,'run')
    #read qp database
    qpdb = YamboQPDB.from_db(folder=qp_path)
    scissor = qpdb.get_scissor(valence,verbose=0)[:3]
    #set scissor in the current input file
    self.yamboin_dict['KfnQP_E'] = list(scissor)

class SpinOrbitFlow():
    """
    Perform a yambo calculation including spin-orbit coupling.
    The dielectric function is calculated from the system without spin-orbit
    This has been tested for GW and BSE

    Author: Henrique Miranda
    """
    def __init__(self,structure,structure_spin=None):
        self.structure_nospin = structure
        if structure_spin is None: self.structure_spin = structure

    def get_tasks(self,scf_kpoints,ecut,nscf_kpoints,chi_bands,spin_bands,**kwargs):
        """
        Get a list of tasks executing this flow
        """
        tasks=[]
        conv_thr = kwargs.pop("conv_thr",qepyenv.CONV_THR)

        #create a yambo qp run
        yamboin_default_dict = dict(BndsRnXp=[1,chi_bands],
                                    NGsBlkXp=[1,'Ry'],
                                    EXXRLvcs=[10,'Ry'],
                                    QPkrange=[1,1,1,spin_bands],
                                    GbndRnge=[1,spin_bands])

        yamboin_dict = kwargs.pop("yamboin_dict",yamboin_default_dict)
        generator = kwargs.pop("generator",YamboQPTask)
        pp_runlevel = kwargs.pop("pp_runlevel",'-p p -V all')
        qp_runlevel = kwargs.pop("qp_runlevel",'-p p -g n -V all')
        spin_runlevel = kwargs.pop("spin_runlevel",qp_runlevel)

        #without spin
        new_tasks = PwNscfTasks(self.structure_nospin,kpoints=scf_kpoints,ecut=ecut,
                            nscf_bands=chi_bands,nscf_kpoints=nscf_kpoints,conv_thr=conv_thr)
        qe_scf_task, qe_nscf_task, p2y_task = new_tasks

        nospin_task = generator(p2y_task,runlevel=pp_runlevel,yamboin_dict=yamboin_dict,dependencies=p2y_task,**kwargs)

        tasks.extend( [qe_scf_task, qe_nscf_task, p2y_task, nospin_task] )

        #with spin
        new_tasks = PwNscfTasks(self.structure_spin,kpoints=scf_kpoints,ecut=ecut,
                            nscf_bands=spin_bands,nscf_kpoints=nscf_kpoints,conv_thr=conv_thr)
        qe_scf_task, qe_nscf_task, p2y_task = new_tasks

        #patch the input files to include spin-orbit coupling
        qe_scf_task.get_instances_from_inputs(PwIn)[0].set_spinorbit()
        qe_nscf_task.get_instances_from_inputs(PwIn)[0].set_spinorbit()

        spin_task = generator(p2y_task,runlevel=spin_runlevel,yamboin_dict=yamboin_dict,dependencies=p2y_task,**kwargs)

        tasks.extend( [qe_scf_task, qe_nscf_task, p2y_task, spin_task] )

        spin_task.set_vars('spin_bands',spin_bands)
        spin_task.set_vars('nospin_task',nospin_task)
        spin_task.set_code('initialize',copy_pp)

        return tasks

    def get_flow(self,path,scf_kpoints,ecut,nscf_kpoints,chi_bands,spin_bands,**kwargs):
        tasks = self.get_tasks(scf_kpoints=scf_kpoints,ecut=ecut,nscf_kpoints=nscf_kpoints,
                               chi_bands=chi_bands,spin_bands=spin_bands,**kwargs)

        #put all the tasks in a flow
        self.yambo_flow = YambopyFlow.from_tasks(path,tasks,**kwargs)
        return self.yambo_flow

def PwNscfYamboIPChiTasks(structure,kpoints,ecut,nscf_bands,
                          yambo_runlevel='-o c -V all',nscf_kpoints=None,**kwargs):
    """
    Return the PwNscfTasks and a YamboTask for and IP calculation
    """
    conv_thr = kwargs.pop("conv_thr",qepyenv.CONV_THR)

    #create scf, nscf and p2y task
    tmp_tasks = PwNscfTasks(structure,kpoints,ecut,nscf_bands,nscf_kpoints,conv_thr=conv_thr)
    qe_scf_task,qe_nscf_task,p2y_task = tmp_tasks

    yambo_task = YamboIPChiTask(p2y_task,yambo_runlevel=yambo_runlevel,**kwargs)

    return qe_scf_task,qe_nscf_task,p2y_task,yambo_task

def YamboIPChiTask(p2y_task,**kwargs):
    """
    Return a yambo IP task
    """
    yambo_ip_default_dict = dict(QpntsRXd=[1,1],
                                 ETStpsXd=1000)
    yambo_ip_dict = kwargs.pop('yambo_ip_dict',yambo_ip_default_dict)
    yambo_runlevel = kwargs.pop('yambo_runlevel','-o c -V all')
    bands = kwargs.pop('bands',None)
    dependencies = kwargs.pop('dependencies',p2y_task)
    if bands: yambo_ip_dict['BndsRnXd'] = [1,bands]

    #add yambo_task
    yambo_task = YamboTask.from_runlevel(p2y_task,yambo_runlevel,yambo_ip_dict,
                                         dependencies=dependencies)
    return yambo_task

def YamboQPBSETasks(p2y_task,qp_dict,bse_dict,qp_runlevel='-p p -g n -V all',
                    bse_runlevel='-p p -k sex -y d -V all',valence=False,**kwargs):
    """
    Return a QP and BSE calculation
    """
    import copy
    dependencies = kwargs.pop('dependencies',p2y_task)
    inputs = [p2y_task]
    additional_inputs = kwargs.pop('additional_inputs',None)
    if additional_inputs:
        if not isiter(additional_inputs): additional_inputs = [additional_inputs]
        inputs.extend(additional_inputs)

    #create a yambo qp run
    qp_task = YamboTask.from_runlevel(inputs,qp_runlevel,qp_dict,dependencies=dependencies)

    #create a yambo qp+bse run
    bse_dict['KfnQPdb']="E < run/ndb.QP"
    qp_bse_task = YamboTask.from_runlevel([p2y_task,qp_task],bse_runlevel,bse_dict,
                                          dependencies=qp_task)

    #create a yambo scissor+bse run
    if valence:
        bse_dict = copy.deepcopy(bse_dict)
        bse_dict.pop('KfnQPdb')
        scissor_bse_task = YamboTask.from_runlevel([p2y_task,qp_task],bse_runlevel,bse_dict,
                                                   dependencies=qp_task)
        scissor_bse_task.set_vars('qp_task',qp_task)
        scissor_bse_task.set_vars('valence',valence)
        scissor_bse_task.set_code('initialize',get_scissor)
        return qp_task, qp_bse_task, scissor_bse_task

    return qp_task, qp_bse_task

def YamboQPTask(p2y_task,yamboin_dict,runlevel='-p p -g n -V all',**kwargs):
    """
    Return a QP calculation
    """
    #create a yambo qp run
    dependencies = kwargs.pop('dependencies',p2y_task)
    qp_task = YamboTask.from_runlevel(p2y_task,runlevel,yamboin_dict,dependencies=p2y_task)

    return qp_task

def PhPhononTasks(structure,kpoints,ecut,qpoints=None):
    """
    Return a ScfTask, a PhTask and Matdyn task
    """

    #create a QE scf task and run
    qe_input = PwIn.from_structure_dict(structure,kpoints=kpoints,ecut=ecut)
    qe_scf_task = PwTask.from_input(qe_input)

    #create phonon tasks
    if qpoints is None: qpoints = qe_input.kpoints
    ph_input = PhIn.from_qpoints(qpoints)
    ph_task = PhTask.from_scf_task([ph_input,qe_scf_task],dependencies=qe_scf_task)

    #create matdyn task
    matdyn_task = DynmatTask.from_phonon_task(ph_task,dependencies=ph_task)

    return qe_scf_task, ph_task, matdyn_task

def PwNscfTasks(structure,kpoints,ecut,nscf_bands,nscf_kpoints=None,**kwargs):
    """
    Return a ScfTask, NscfTask and P2yTask preparing for a Yambo calculation
    """
    scf_conv_thr = kwargs.pop("conv_thr",qepyenv.CONV_THR)
    scf_conv_thr = kwargs.pop("scf_conv_thr",scf_conv_thr)
    nscf_conv_thr = kwargs.pop("nscf_conv_thr",scf_conv_thr*10)
    nscf_paralelization = kwargs.pop("nscf_paralelization","")

    #create a QE scf task and run
    qe_input = PwIn.from_structure_dict(structure,kpoints=kpoints,ecut=ecut,conv_thr=scf_conv_thr)
    qe_scf_task = PwTask.from_input(qe_input)

    # pseudo_dir
    pseudo_dir = kwargs.pop("pseudo_dir", None)
    if pseudo_dir: qe_input.control['pseudo_dir'] = "'%s'" % pseudo_dir

    #Spin
    spin = kwargs.pop("spin", None)
    if spin is "spinor": qe_input.set_spinorbit()
    if spin is "polarized": qe_input_scf.set_spinpolarized()

    #Magnetization
    starting_magnetization = kwargs.pop("starting_magnetization", None)
    qe_input.set_magnetization(starting_magnetization)

    #create a QE nscf task and run
    if nscf_kpoints is None: nscf_kpoints = kpoints
    qe_input = qe_input.copy().set_nscf(nscf_bands,nscf_kpoints,conv_thr=nscf_conv_thr)
    qe_nscf_task = PwTask.from_input([qe_input,qe_scf_task],dependencies=qe_scf_task,paralelization=nscf_paralelization)

    #create a p2y nscf task and run
    p2y_task = P2yTask.from_nscf_task(qe_nscf_task)

    return qe_scf_task, qe_nscf_task, p2y_task

def PwBandsTasks(structure,kpoints,ecut,nscf_bands,path_kpoints,**kwargs):
    """
    Return a ScfTask and BandsTask (Author: AMS, HM)

    Args:
        kpoints: the k-mesh for the scf calculation
        ecut: the planewave basis cutoff
        nscf_bands: number of bands in the nscf_calculation
        path_kpoints: the k-points along the path
        spin: can be 'polarized' for calculation with spin or 'spinor' for calculation with spin-orbit
        starting_magnetization: a list with the starting magnetizations for each atomic type
    """
    scf_conv_thr = kwargs.pop("conv_thr",qepyenv.CONV_THR)
    scf_conv_thr = kwargs.pop("scf_conv_thr",scf_conv_thr)
    bands_conv_thr = kwargs.pop("nscf_conv_thr",scf_conv_thr*10)

    #create a QE scf task
    qe_input = PwIn.from_structure_dict(structure,kpoints=kpoints,ecut=ecut,conv_thr=scf_conv_thr)

    # pseudo_dir
    pseudo_dir = kwargs.pop("pseudo_dir", None)
    if pseudo_dir: qe_input.control['pseudo_dir'] = "'%s'" % pseudo_dir

    #Spin
    spin = kwargs.pop("spin", None)
    if spin is "spinor": qe_input.set_spinorbit()
    if spin is "polarized": qe_input.set_spinpolarized()

    #Magnetization
    starting_magnetization = kwargs.pop("starting_magnetization", None)
    qe_input.set_magnetization(starting_magnetization)

    pseudo_dir = kwargs.pop("pseudo_dir", None)
    if pseudo_dir: qe_input.control['pseudo_dir'] = "'%s'" % pseudo_dir

    scf_paralelization = kwargs.pop("scf_paralelization","")
    qe_scf_task = PwTask.from_input(qe_input,paralelization=scf_paralelization)

    #create a QE bands task
    qe_input_bands = qe_input.copy().set_bands(nscf_bands,path_kpoints=path_kpoints,conv_thr=bands_conv_thr,**kwargs)
    nscf_paralelization = kwargs.pop("nscf_paralelization","")
    qe_bands_task = PwTask.from_input([qe_input_bands,qe_scf_task],dependencies=qe_scf_task,paralelization=nscf_paralelization,**kwargs)

    return qe_scf_task, qe_bands_task

def PwRelaxTasks(structure,kpoints,ecut,cell_dofree='all',**kwargs):
    """
    Return a RelaxTask and ScfTask (Author: AMS, HM)

    Args:
        kpoints: the k-mesh for the scf calculation
        ecut: the planewave basis cutoff
        cell_free
        spin: can be 'polarized' for calculation with spin or 'spinor' for calculation with spin-orbit
        starting_magnetization: a list with the starting magnetizations for each atomic type
    """
    #raise NotImplementedError('This function is under development!')

    scf_conv_thr = kwargs.pop("conv_thr",qepyenv.CONV_THR)
    scf_conv_thr = kwargs.pop("scf_conv_thr",scf_conv_thr)
    paralelization = kwargs.pop("paralelization","")

    #create a QE input scf
    qe_input_scf = PwIn.from_structure_dict(structure,kpoints=kpoints,ecut=ecut,conv_thr=scf_conv_thr)

    #Spin
    spin = kwargs.pop("spin", None)
    if spin is "spinor": qe_input_scf.set_spinorbit()
    if spin is "polarized": qe_input_scf.set_spinpolarized()

    #Magnetization
    starting_magnetization = kwargs.pop("starting_magnetization", None)
    qe_input_scf.set_magnetization(starting_magnetization)

    pseudo_dir = kwargs.pop("pseudo_dir", None)
    if pseudo_dir: qe_input_scf.control['pseudo_dir'] = "'%s'" % pseudo_dir

    #create a QE relax-atom task
    qe_input_relax_atoms = qe_input_scf.copy().set_relax(cell_dofree=None)
    qe_relax_atoms_task = PwTask.from_input(qe_input_relax_atoms,paralelization=paralelization)

    #create a QE relax-cell task
    qe_input_relax_cell = qe_input_scf.copy().set_relax(cell_dofree=cell_dofree)
    qe_relax_cell_task = PwTask.from_input([qe_input_relax_cell,qe_input_relax_atoms],dependencies=qe_relax_atoms_task,paralelization=paralelization)
    qe_relax_cell_task.set_vars("pwtask",qe_relax_atoms_task)
    qe_relax_cell_task.set_code("initialize",update_cell_and_positions)

    #create a QE scf task
    qe_scf_task = PwTask.from_input([qe_input_scf,qe_input_relax_cell],dependencies=qe_relax_cell_task,paralelization=paralelization)
    qe_scf_task.set_vars("pwtask",qe_relax_cell_task)
    qe_scf_task.set_code("initialize",update_cell_and_positions)

    return qe_relax_atoms_task, qe_relax_cell_task, qe_scf_task

def AbinitNscfTasks(structure,kpoints,ecut,nscf_bands,nscf_kpoints=None,**kwargs):
    from abipy.core.structure import Structure
    from abipy.abio.factories import scf_for_phonons
    from pymatgen.core.units import bohr_to_ang

    #extract pseudos
    pseudo_list = []
    for atype,(mass,pseudo) in structure['atypes'].items():
        pseudo_list.append(pseudo)
    pseudo_table = kwargs.pop("pseudo_table",pseudo_list)

    #create a PwInput file just to read the ibrav from structure
    qe_input = PwIn.from_structure_dict(structure)
    lattice,coords,species = qe_input.get_cell()
    lattice = [[col*bohr_to_ang for col in row] for row in lattice]
    structure = Structure(lattice,species,coords)

    #create an AbinitInput file from structure
    spin_mode = kwargs.pop('spin_mode','unpolarized')
    smearing = kwargs.pop('smearing','nosmearing')
    inp = scf_for_phonons(structure, pseudo_table, spin_mode=spin_mode,
                          smearing=smearing, ecut=ecut/2)

    return AbinitNscfTasksFromAbinitInput(inp,kpoints,ecut,nscf_bands,nscf_kpoints=nscf_kpoints,**kwargs)

def AbinitNscfTasksFromAbinitInput(inp,kpoints,ecut,nscf_bands,nscf_kpoints=None,**kwargs):
    tolwfr = kwargs.pop("tolwfr",1e-22)
    nbdbuf = kwargs.pop("nbdbuf",int(nscf_bands*0.15))

    #scf
    inp = inp.deepcopy()
    inp.set_kmesh(ngkpt=kpoints,
                  kptopt=1,
                  shiftk=(0,0,0))
    abinit_scf_task = AbinitTask.from_input(inp)

    #nscf
    inp = inp.deepcopy()
    if nscf_kpoints is None: nscf_kpoints = kpoints
    inp.set_kmesh(ngkpt=nscf_kpoints,
                  kptopt=1,
                  shiftk=(0,0,0))
    inp.set_vars(iscf=-2,
                 getden=1,
                 nband=nscf_bands+nbdbuf,
                 nbdbuf=nbdbuf)
    abinit_nscf_task = AbinitTask.from_input([inp,abinit_scf_task],dependencies=abinit_scf_task)

    #e2y task
    e2y_task = E2yTask.from_nscf_task(abinit_nscf_task)

    return abinit_scf_task, abinit_nscf_task, e2y_task