text:
"""
Todo: cross-check the F-value with stats model
"""
from __future__ import division
import itertools
import warnings
import numpy as np
from scipy import stats, sparse

from numpy.testing import run_module_suite
from sklearn.utils.testing import assert_equal
from sklearn.utils.testing import assert_almost_equal
from sklearn.utils.testing import assert_raises
from sklearn.utils.testing import assert_true
from sklearn.utils.testing import assert_array_equal
from sklearn.utils.testing import assert_array_almost_equal
from sklearn.utils.testing import assert_not_in
from sklearn.utils.testing import assert_less
from sklearn.utils.testing import assert_warns
from sklearn.utils.testing import ignore_warnings
from sklearn.utils.testing import assert_warns_message
from sklearn.utils.testing import assert_greater
from sklearn.utils.testing import assert_greater_equal
from sklearn.utils import safe_mask

from sklearn.datasets.samples_generator import (make_classification,
                                                make_regression)
from sklearn.feature_selection import (
    chi2, f_classif, f_oneway, f_regression, mutual_info_classif,
    mutual_info_regression, SelectPercentile, SelectKBest, SelectFpr,
    SelectFdr, SelectFwe, GenericUnivariateSelect)

##############################################################################
# Test the score functions

def test_f_oneway_vs_scipy_stats():
    # Test that our f_oneway gives the same result as scipy.stats
    rng = np.random.RandomState(0)
    X1 = rng.randn(10, 3)
    X2 = 1 + rng.randn(10, 3)
    f, pv = stats.f_oneway(X1, X2)
    f2, pv2 = f_oneway(X1, X2)
    assert_true(np.allclose(f, f2))
    assert_true(np.allclose(pv, pv2))

def test_f_oneway_ints():
    # Smoke test f_oneway on integers: that it does raise casting errors
    # with recent numpys
    rng = np.random.RandomState(0)
    X = rng.randint(10, size=(10, 10))
    y = np.arange(10)
    fint, pint = f_oneway(X, y)

    # test that is gives the same result as with float
    f, p = f_oneway(X.astype(np.float), y)
    assert_array_almost_equal(f, fint, decimal=4)
    assert_array_almost_equal(p, pint, decimal=4)

def test_f_classif():
    # Test whether the F test yields meaningful results
    # on a simple simulated classification problem
    X, y = make_classification(n_samples=200, n_features=20,
                               n_informative=3, n_redundant=2,
                               n_repeated=0, n_classes=8,
                               n_clusters_per_class=1, flip_y=0.0,
                               class_sep=10, shuffle=False, random_state=0)

    F, pv = f_classif(X, y)
    F_sparse, pv_sparse = f_classif(sparse.csr_matrix(X), y)
    assert_true((F > 0).all())
    assert_true((pv > 0).all())
    assert_true((pv < 1).all())
    assert_true((pv[:5] < 0.05).all())
    assert_true((pv[5:] > 1.e-4).all())
    assert_array_almost_equal(F_sparse, F)
    assert_array_almost_equal(pv_sparse, pv)

def test_f_regression():
    # Test whether the F test yields meaningful results
    # on a simple simulated regression problem
    X, y = make_regression(n_samples=200, n_features=20, n_informative=5,
                           shuffle=False, random_state=0)

    F, pv = f_regression(X, y)
    assert_true((F > 0).all())
    assert_true((pv > 0).all())
    assert_true((pv < 1).all())
    assert_true((pv[:5] < 0.05).all())
    assert_true((pv[5:] > 1.e-4).all())

    # again without centering, compare with sparse
    F, pv = f_regression(X, y, center=False)
    F_sparse, pv_sparse = f_regression(sparse.csr_matrix(X), y, center=False)
    assert_array_almost_equal(F_sparse, F)
    assert_array_almost_equal(pv_sparse, pv)

def test_f_regression_input_dtype():
    # Test whether f_regression returns the same value
    # for any numeric data_type
    rng = np.random.RandomState(0)
    X = rng.rand(10, 20)
    y = np.arange(10).astype(np.int)

    F1, pv1 = f_regression(X, y)
    F2, pv2 = f_regression(X, y.astype(np.float))
    assert_array_almost_equal(F1, F2, 5)
    assert_array_almost_equal(pv1, pv2, 5)

def test_f_regression_center():
    # Test whether f_regression preserves dof according to 'center' argument
    # We use two centered variates so we have a simple relationship between
    # F-score with variates centering and F-score without variates centering.
    # Create toy example
    X = np.arange(-5, 6).reshape(-1, 1)  # X has zero mean
    n_samples = X.size
    Y = np.ones(n_samples)
    Y[::2] *= -1.
    Y[0] = 0.  # have Y mean being null

    F1, _ = f_regression(X, Y, center=True)
    F2, _ = f_regression(X, Y, center=False)
    assert_array_almost_equal(F1 * (n_samples - 1.) / (n_samples - 2.), F2)
    assert_almost_equal(F2[0], 0.232558139)  # value from statsmodels OLS

def test_f_classif_multi_class():
    # Test whether the F test yields meaningful results
    # on a simple simulated classification problem
    X, y = make_classification(n_samples=200, n_features=20,
                               n_informative=3, n_redundant=2,
                               n_repeated=0, n_classes=8,
                               n_clusters_per_class=1, flip_y=0.0,
                               class_sep=10, shuffle=False, random_state=0)

    F, pv = f_classif(X, y)
    assert_true((F > 0).all())
    assert_true((pv > 0).all())
    assert_true((pv < 1).all())
    assert_true((pv[:5] < 0.05).all())
    assert_true((pv[5:] > 1.e-4).all())

def test_select_percentile_classif():
    # Test whether the relative univariate feature selection
    # gets the correct items in a simple classification problem
    # with the percentile heuristic
    X, y = make_classification(n_samples=200, n_features=20,
                               n_informative=3, n_redundant=2,
                               n_repeated=0, n_classes=8,
                               n_clusters_per_class=1, flip_y=0.0,
                               class_sep=10, shuffle=False, random_state=0)

    univariate_filter = SelectPercentile(f_classif, percentile=25)
    X_r = univariate_filter.fit(X, y).transform(X)
    X_r2 = GenericUnivariateSelect(f_classif, mode='percentile',
                                   param=25).fit(X, y).transform(X)
    assert_array_equal(X_r, X_r2)
    support = univariate_filter.get_support()
    gtruth = np.zeros(20)
    gtruth[:5] = 1
    assert_array_equal(support, gtruth)

def test_select_percentile_classif_sparse():
    # Test whether the relative univariate feature selection
    # gets the correct items in a simple classification problem
    # with the percentile heuristic
    X, y = make_classification(n_samples=200, n_features=20,
                               n_informative=3, n_redundant=2,
                               n_repeated=0, n_classes=8,
                               n_clusters_per_class=1, flip_y=0.0,
                               class_sep=10, shuffle=False, random_state=0)
    X = sparse.csr_matrix(X)
    univariate_filter = SelectPercentile(f_classif, percentile=25)
    X_r = univariate_filter.fit(X, y).transform(X)
    X_r2 = GenericUnivariateSelect(f_classif, mode='percentile',
                                   param=25).fit(X, y).transform(X)
    assert_array_equal(X_r.toarray(), X_r2.toarray())
    support = univariate_filter.get_support()
    gtruth = np.zeros(20)
    gtruth[:5] = 1
    assert_array_equal(support, gtruth)

    X_r2inv = univariate_filter.inverse_transform(X_r2)
    assert_true(sparse.issparse(X_r2inv))
    support_mask = safe_mask(X_r2inv, support)
    assert_equal(X_r2inv.shape, X.shape)
    assert_array_equal(X_r2inv[:, support_mask].toarray(), X_r.toarray())
    # Check other columns are empty
    assert_equal(X_r2inv.getnnz(), X_r.getnnz())

##############################################################################
# Test univariate selection in classification settings

def test_select_kbest_classif():
    # Test whether the relative univariate feature selection
    # gets the correct items in a simple classification problem
    # with the k best heuristic
    X, y = make_classification(n_samples=200, n_features=20,
                               n_informative=3, n_redundant=2,
                               n_repeated=0, n_classes=8,
                               n_clusters_per_class=1, flip_y=0.0,
                               class_sep=10, shuffle=False, random_state=0)

    univariate_filter = SelectKBest(f_classif, k=5)
    X_r = univariate_filter.fit(X, y).transform(X)
    X_r2 = GenericUnivariateSelect(
        f_classif, mode='k_best', param=5).fit(X, y).transform(X)
    assert_array_equal(X_r, X_r2)
    support = univariate_filter.get_support()
    gtruth = np.zeros(20)
    gtruth[:5] = 1
    assert_array_equal(support, gtruth)

def test_select_kbest_all():
    # Test whether k="all" correctly returns all features.
    X, y = make_classification(n_samples=20, n_features=10,
                               shuffle=False, random_state=0)

    univariate_filter = SelectKBest(f_classif, k='all')
    X_r = univariate_filter.fit(X, y).transform(X)
    assert_array_equal(X, X_r)

def test_select_kbest_zero():
    # Test whether k=0 correctly returns no features.
    X, y = make_classification(n_samples=20, n_features=10,
                               shuffle=False, random_state=0)

    univariate_filter = SelectKBest(f_classif, k=0)
    univariate_filter.fit(X, y)
    support = univariate_filter.get_support()
    gtruth = np.zeros(10, dtype=bool)
    assert_array_equal(support, gtruth)
    X_selected = assert_warns_message(UserWarning, 'No features were selected',
                                      univariate_filter.transform, X)
    assert_equal(X_selected.shape, (20, 0))

def test_select_heuristics_classif():
    # Test whether the relative univariate feature selection
    # gets the correct items in a simple classification problem
    # with the fdr, fwe and fpr heuristics
    X, y = make_classification(n_samples=200, n_features=20,
                               n_informative=3, n_redundant=2,
                               n_repeated=0, n_classes=8,
                               n_clusters_per_class=1, flip_y=0.0,
                               class_sep=10, shuffle=False, random_state=0)

    univariate_filter = SelectFwe(f_classif, alpha=0.01)
    X_r = univariate_filter.fit(X, y).transform(X)
    gtruth = np.zeros(20)
    gtruth[:5] = 1
    for mode in ['fdr', 'fpr', 'fwe']:
        X_r2 = GenericUnivariateSelect(
            f_classif, mode=mode, param=0.01).fit(X, y).transform(X)
        assert_array_equal(X_r, X_r2)
        support = univariate_filter.get_support()
        assert_array_almost_equal(support, gtruth)

##############################################################################
# Test univariate selection in regression settings

def assert_best_scores_kept(score_filter):
    scores = score_filter.scores_
    support = score_filter.get_support()
    assert_array_equal(np.sort(scores[support]),
                       np.sort(scores)[-support.sum():])

def test_select_percentile_regression():
    # Test whether the relative univariate feature selection
    # gets the correct items in a simple regression problem
    # with the percentile heuristic
    X, y = make_regression(n_samples=200, n_features=20,
                           n_informative=5, shuffle=False, random_state=0)

    univariate_filter = SelectPercentile(f_regression, percentile=25)
    X_r = univariate_filter.fit(X, y).transform(X)
    assert_best_scores_kept(univariate_filter)
    X_r2 = GenericUnivariateSelect(
        f_regression, mode='percentile', param=25).fit(X, y).transform(X)
    assert_array_equal(X_r, X_r2)
    support = univariate_filter.get_support()
    gtruth = np.zeros(20)
    gtruth[:5] = 1
    assert_array_equal(support, gtruth)
    X_2 = X.copy()
    X_2[:, np.logical_not(support)] = 0
    assert_array_equal(X_2, univariate_filter.inverse_transform(X_r))
    # Check inverse_transform respects dtype
    assert_array_equal(X_2.astype(bool),
                       univariate_filter.inverse_transform(X_r.astype(bool)))

def test_select_percentile_regression_full():
    # Test whether the relative univariate feature selection
    # selects all features when '100%' is asked.
    X, y = make_regression(n_samples=200, n_features=20,
                           n_informative=5, shuffle=False, random_state=0)

    univariate_filter = SelectPercentile(f_regression, percentile=100)
    X_r = univariate_filter.fit(X, y).transform(X)
    assert_best_scores_kept(univariate_filter)
    X_r2 = GenericUnivariateSelect(
        f_regression, mode='percentile', param=100).fit(X, y).transform(X)
    assert_array_equal(X_r, X_r2)
    support = univariate_filter.get_support()
    gtruth = np.ones(20)
    assert_array_equal(support, gtruth)

def test_invalid_percentile():
    X, y = make_regression(n_samples=10, n_features=20,
                           n_informative=2, shuffle=False, random_state=0)

    assert_raises(ValueError, SelectPercentile(percentile=-1).fit, X, y)
    assert_raises(ValueError, SelectPercentile(percentile=101).fit, X, y)
    assert_raises(ValueError, GenericUnivariateSelect(mode='percentile',
                                                      param=-1).fit, X, y)
    assert_raises(ValueError, GenericUnivariateSelect(mode='percentile',
                                                      param=101).fit, X, y)

def test_select_kbest_regression():
    # Test whether the relative univariate feature selection
    # gets the correct items in a simple regression problem
    # with the k best heuristic
    X, y = make_regression(n_samples=200, n_features=20, n_informative=5,
                           shuffle=False, random_state=0, noise=10)

    univariate_filter = SelectKBest(f_regression, k=5)
    X_r = univariate_filter.fit(X, y).transform(X)
    assert_best_scores_kept(univariate_filter)
    X_r2 = GenericUnivariateSelect(
        f_regression, mode='k_best', param=5).fit(X, y).transform(X)
    assert_array_equal(X_r, X_r2)
    support = univariate_filter.get_support()
    gtruth = np.zeros(20)
    gtruth[:5] = 1
    assert_array_equal(support, gtruth)

def test_select_heuristics_regression():
    # Test whether the relative univariate feature selection
    # gets the correct items in a simple regression problem
    # with the fpr, fdr or fwe heuristics
    X, y = make_regression(n_samples=200, n_features=20, n_informative=5,
                           shuffle=False, random_state=0, noise=10)

    univariate_filter = SelectFpr(f_regression, alpha=0.01)
    X_r = univariate_filter.fit(X, y).transform(X)
    gtruth = np.zeros(20)
    gtruth[:5] = 1
    for mode in ['fdr', 'fpr', 'fwe']:
        X_r2 = GenericUnivariateSelect(
            f_regression, mode=mode, param=0.01).fit(X, y).transform(X)
        assert_array_equal(X_r, X_r2)
        support = univariate_filter.get_support()
        assert_array_equal(support[:5], np.ones((5, ), dtype=np.bool))
        assert_less(np.sum(support[5:] == 1), 3)

def test_select_fdr_regression():
    # Test that fdr heuristic actually has low FDR.
    def single_fdr(alpha, n_informative, random_state):
        X, y = make_regression(n_samples=150, n_features=20,
                               n_informative=n_informative, shuffle=False,
                               random_state=random_state, noise=10)

        with warnings.catch_warnings(record=True):
            # Warnings can be raised when no features are selected
            # (low alpha or very noisy data)
            univariate_filter = SelectFdr(f_regression, alpha=alpha)
            X_r = univariate_filter.fit(X, y).transform(X)
            X_r2 = GenericUnivariateSelect(
                f_regression, mode='fdr', param=alpha).fit(X, y).transform(X)

        assert_array_equal(X_r, X_r2)
        support = univariate_filter.get_support()
        num_false_positives = np.sum(support[n_informative:] == 1)
        num_true_positives = np.sum(support[:n_informative] == 1)

        if num_false_positives == 0:
            return 0.
        false_discovery_rate = (num_false_positives /
                                (num_true_positives + num_false_positives))
        return false_discovery_rate

    for alpha in [0.001, 0.01, 0.1]:
        for n_informative in [1, 5, 10]:
            # As per Benjamini-Hochberg, the expected false discovery rate
            # should be lower than alpha:
            # FDR = E(FP / (TP + FP)) <= alpha
            false_discovery_rate = np.mean([single_fdr(alpha, n_informative,
                                                       random_state) for
                                            random_state in range(30)])
            assert_greater_equal(alpha, false_discovery_rate)

            # Make sure that the empirical false discovery rate increases
            # with alpha:
            if false_discovery_rate != 0:
                assert_greater(false_discovery_rate, alpha / 10)

def test_select_fwe_regression():
    # Test whether the relative univariate feature selection
    # gets the correct items in a simple regression problem
    # with the fwe heuristic
    X, y = make_regression(n_samples=200, n_features=20,
                           n_informative=5, shuffle=False, random_state=0)

    univariate_filter = SelectFwe(f_regression, alpha=0.01)
    X_r = univariate_filter.fit(X, y).transform(X)
    X_r2 = GenericUnivariateSelect(
        f_regression, mode='fwe', param=0.01).fit(X, y).transform(X)
    assert_array_equal(X_r, X_r2)
    support = univariate_filter.get_support()
    gtruth = np.zeros(20)
    gtruth[:5] = 1
    assert_array_equal(support[:5], np.ones((5, ), dtype=np.bool))
    assert_less(np.sum(support[5:] == 1), 2)

def test_selectkbest_tiebreaking():
    # Test whether SelectKBest actually selects k features in case of ties.
    # Prior to 0.11, SelectKBest would return more features than requested.
    Xs = [[0, 1, 1], [0, 0, 1], [1, 0, 0], [1, 1, 0]]
    y = [1]
    dummy_score = lambda X, y: (X[0], X[0])
    for X in Xs:
        sel = SelectKBest(dummy_score, k=1)
        X1 = ignore_warnings(sel.fit_transform)([X], y)
        assert_equal(X1.shape[1], 1)
        assert_best_scores_kept(sel)

        sel = SelectKBest(dummy_score, k=2)
        X2 = ignore_warnings(sel.fit_transform)([X], y)
        assert_equal(X2.shape[1], 2)
        assert_best_scores_kept(sel)

def test_selectpercentile_tiebreaking():
    # Test if SelectPercentile selects the right n_features in case of ties.
    Xs = [[0, 1, 1], [0, 0, 1], [1, 0, 0], [1, 1, 0]]
    y = [1]
    dummy_score = lambda X, y: (X[0], X[0])
    for X in Xs:
        sel = SelectPercentile(dummy_score, percentile=34)
        X1 = ignore_warnings(sel.fit_transform)([X], y)
        assert_equal(X1.shape[1], 1)
        assert_best_scores_kept(sel)

        sel = SelectPercentile(dummy_score, percentile=67)
        X2 = ignore_warnings(sel.fit_transform)([X], y)
        assert_equal(X2.shape[1], 2)
        assert_best_scores_kept(sel)

def test_tied_pvalues():
    # Test whether k-best and percentiles work with tied pvalues from chi2.
    # chi2 will return the same p-values for the following features, but it
    # will return different scores.
    X0 = np.array([[10000, 9999, 9998], [1, 1, 1]])
    y = [0, 1]

    for perm in itertools.permutations((0, 1, 2)):
        X = X0[:, perm]
        Xt = SelectKBest(chi2, k=2).fit_transform(X, y)
        assert_equal(Xt.shape, (2, 2))
        assert_not_in(9998, Xt)

        Xt = SelectPercentile(chi2, percentile=67).fit_transform(X, y)
        assert_equal(Xt.shape, (2, 2))
        assert_not_in(9998, Xt)

def test_tied_scores():
    # Test for stable sorting in k-best with tied scores.
    X_train = np.array([[0, 0, 0], [1, 1, 1]])
    y_train = [0, 1]

    for n_features in [1, 2, 3]:
        sel = SelectKBest(chi2, k=n_features).fit(X_train, y_train)
        X_test = sel.transform([[0, 1, 2]])
        assert_array_equal(X_test[0], np.arange(3)[-n_features:])

def test_nans():
    # Assert that SelectKBest and SelectPercentile can handle NaNs.
    # First feature has zero variance to confuse f_classif (ANOVA) and
    # make it return a NaN.
    X = [[0, 1, 0], [0, -1, -1], [0, .5, .5]]
    y = [1, 0, 1]

    for select in (SelectKBest(f_classif, 2),
                   SelectPercentile(f_classif, percentile=67)):
        ignore_warnings(select.fit)(X, y)
        assert_array_equal(select.get_support(indices=True), np.array([1, 2]))

def test_score_func_error():
    X = [[0, 1, 0], [0, -1, -1], [0, .5, .5]]
    y = [1, 0, 1]

    for SelectFeatures in [SelectKBest, SelectPercentile, SelectFwe,
                           SelectFdr, SelectFpr, GenericUnivariateSelect]:
        assert_raises(TypeError, SelectFeatures(score_func=10).fit, X, y)

def test_invalid_k():
    X = [[0, 1, 0], [0, -1, -1], [0, .5, .5]]
    y = [1, 0, 1]

    assert_raises(ValueError, SelectKBest(k=-1).fit, X, y)
    assert_raises(ValueError, SelectKBest(k=4).fit, X, y)
    assert_raises(ValueError,
                  GenericUnivariateSelect(mode='k_best', param=-1).fit, X, y)
    assert_raises(ValueError,
                  GenericUnivariateSelect(mode='k_best', param=4).fit, X, y)

def test_f_classif_constant_feature():
    # Test that f_classif warns if a feature is constant throughout.

    X, y = make_classification(n_samples=10, n_features=5)
    X[:, 0] = 2.0
    assert_warns(UserWarning, f_classif, X, y)

def test_no_feature_selected():
    rng = np.random.RandomState(0)

    # Generate random uncorrelated data: a strict univariate test should
    # rejects all the features
    X = rng.rand(40, 10)
    y = rng.randint(0, 4, size=40)
    strict_selectors = [
        SelectFwe(alpha=0.01).fit(X, y),
        SelectFdr(alpha=0.01).fit(X, y),
        SelectFpr(alpha=0.01).fit(X, y),
        SelectPercentile(percentile=0).fit(X, y),
        SelectKBest(k=0).fit(X, y),
    ]
    for selector in strict_selectors:
        assert_array_equal(selector.get_support(), np.zeros(10))
        X_selected = assert_warns_message(
            UserWarning, 'No features were selected', selector.transform, X)
        assert_equal(X_selected.shape, (40, 0))

def test_mutual_info_classif():
    X, y = make_classification(n_samples=100, n_features=5,
                               n_informative=1, n_redundant=1,
                               n_repeated=0, n_classes=2,
                               n_clusters_per_class=1, flip_y=0.0,
                               class_sep=10, shuffle=False, random_state=0)

    # Test in KBest mode.
    univariate_filter = SelectKBest(mutual_info_classif, k=2)
    X_r = univariate_filter.fit(X, y).transform(X)
    X_r2 = GenericUnivariateSelect(
        mutual_info_classif, mode='k_best', param=2).fit(X, y).transform(X)
    assert_array_equal(X_r, X_r2)
    support = univariate_filter.get_support()
    gtruth = np.zeros(5)
    gtruth[:2] = 1
    assert_array_equal(support, gtruth)

    # Test in Percentile mode.
    univariate_filter = SelectPercentile(mutual_info_classif, percentile=40)
    X_r = univariate_filter.fit(X, y).transform(X)
    X_r2 = GenericUnivariateSelect(
        mutual_info_classif, mode='percentile', param=40).fit(X, y).transform(X)
    assert_array_equal(X_r, X_r2)
    support = univariate_filter.get_support()
    gtruth = np.zeros(5)
    gtruth[:2] = 1
    assert_array_equal(support, gtruth)

def test_mutual_info_regression():
    X, y = make_regression(n_samples=100, n_features=10, n_informative=2,
                           shuffle=False, random_state=0, noise=10)

    # Test in KBest mode.
    univariate_filter = SelectKBest(mutual_info_regression, k=2)
    X_r = univariate_filter.fit(X, y).transform(X)
    assert_best_scores_kept(univariate_filter)
    X_r2 = GenericUnivariateSelect(
        mutual_info_regression, mode='k_best', param=2).fit(X, y).transform(X)
    assert_array_equal(X_r, X_r2)
    support = univariate_filter.get_support()
    gtruth = np.zeros(10)
    gtruth[:2] = 1
    assert_array_equal(support, gtruth)

    # Test in Percentile mode.
    univariate_filter = SelectPercentile(mutual_info_regression, percentile=20)
    X_r = univariate_filter.fit(X, y).transform(X)
    X_r2 = GenericUnivariateSelect(mutual_info_regression, mode='percentile',
                                   param=20).fit(X, y).transform(X)
    assert_array_equal(X_r, X_r2)
    support = univariate_filter.get_support()
    gtruth = np.zeros(10)
    gtruth[:2] = 1
    assert_array_equal(support, gtruth)

if __name__ == '__main__':
    run_module_suite()


text:
import hook
import bnetprotocol
from misc import *
from config import config

#settings = config[__name__.split('.')[-1]]

def message_received(bn, d):
	if d.event == bnetprotocol.EID_TALK:
		msg_list = str(d.message).split(' ', 1)
		try:
			command, payload = msg_list
		except ValueError:
			command = msg_list[0]
			payload = ''
		if command == '.join' and len(payload) > 0:
			'''if str(d.message).split(' ')[0] == settings['trigger'] + 'join':'''
			bn.send_packet(bnetprotocol.SEND_SID_CHATCOMMAND('/join %s' % (payload)))
def install():
	hook.register('after-handle_sid_chatevent', message_received)

def uninstall():
	hook.unregister('after-handle_sid_chatevent', message_received)

redpajama_set_name: RedPajamaGithub


text:
import globalV
import os,sys,time
import FileDialog
import Tkinter as tk
import ttk
import numpy as np
from matplotlib import use; use("TkAgg")
from matplotlib.pyplot import xkcd
from matplotlib.figure import Figure
#from matplotlib import patheffects
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from scipy.ndimage import zoom
from scipy.signal import tukey
# Home made imports
from solvers import *
from animator import *
import creationFunctions

class topApp(tk.Tk):

    def __init__(self):

        tk.Tk.__init__(self)

        #self.geometry("650x500+300+300")
        tk.Tk.wm_title(self,"Numerical SE Sim")
        #self.resizable(0,0)
        #tk.Tk.wm_iconbitmap(self,'ih.ico') #Why does this kill the render?

        container = tk.Frame(self, relief="sunken")
        container.pack(side="top", padx=5,pady=5,fill="both",expand=True)
        #for i in np.arange(5):
        #    container.grid_rowconfigure(i,pad=3, weight=1)
        #    container.grid_columnconfigure(i,pad=3, weight=1)

        self.mainPageFrame = MainPage(container,self)
        #self.mainPageFrame.grid(row=0,column=0,sticky="nsew")
        self.mainPageFrame.tkraise()

    def quit(self):
        self.destroy()
        sys.exit()

class MainPage(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller

        # The main page frame owns the two figures, the Animator and the Graph communicate
        # through the figures
        self.psiFig = Figure(figsize=(8,6.5), dpi=100)#10# 8,8
        # Initializing the particle into a default config, editable later
        #self.myPart = Particle1d((lambda x: x*x*0.5)(np.linspace(-10,10,2000)),gaussian(0,1,10)(np.linspace(-10,10,2000)),
        #                N=2000,Lx=20.0,dt=.01,SOLVER=EigenSolver1d)

        X = np.linspace(-10,10,1024)
        V = creationFunctions.squareBarr(x0=0.1,width=.2,height=100)(X)
        V[np.abs(X)>9.9] = 10000

        self.myPart = Particle1d(V,creationFunctions.gaussian(-5,1,10)(X),
                         N=1024,Lx=20.0,dt=.01,SOLVER=EigenSolver1d)

        # This is the object that will push updates to the figure
        self.anim = Animator(self.myPart,self.psiFig)
        #self.toggleXKCD()
        self.initGrid()

        figContainer = tk.Frame(self, relief="sunken"); figContainer.pack(side=tk.LEFT)
        self.drawSpace = DrawableGraph(self.psiFig,figContainer)
        self.drawSpace.get_tk_widget().pack(side=tk.TOP)#grid(row=1,column=0)#,
                #rowspan=4,padx=5)#,sticky='EN')#pack(side=tk.BOTTOM)

        nonFigContainer = tk.Frame(self, relief="sunken")
        nonFigContainer.pack(side=tk.RIGHT)
        #constantContainer = tk.Frame(nonFigContainer, relief="sunken")

        nuclearContainer = tk.Frame(nonFigContainer, relief = "sunken"); nuclearContainer.pack(side = tk.TOP)
        label = tk.Label(nuclearContainer,text="Control Panel", font=("Comic",18)); label.pack()
        quitButton = ttk.Button(nuclearContainer,text="Quit",command=self.controller.quit); quitButton.pack(side=tk.RIGHT)
        resetButton = ttk.Button(nuclearContainer,text='Reset',command = ()); #TODO hook up reset
        resetButton.pack(side = tk.TOP)

        # Display |psi| or real(psi),im(psi)
        animOptionsContainer = tk.Frame(nonFigContainer, relief = "sunken"); animOptionsContainer.pack()

        subAnimCont = tk.Frame(animOptionsContainer, relief = "sunken"); subAnimCont.pack()
        updateButton = ttk.Button(subAnimCont,text="Redraw",command=self.changeGraph); updateButton.pack(side = tk.LEFT)
        playPauseButton = ttk.Button(subAnimCont,text='Play/Pause',command = globalV.pauseUnpause); playPauseButton.pack(side =tk.RIGHT)

        drawControlsContainer = tk.Frame(animOptionsContainer, relief = "sunken"); drawControlsContainer.pack()

        presetContainer = tk.Frame(animOptionsContainer, relief = "sunken"); presetContainer.pack()
        presetLabel = tk.Label(presetContainer,text="Presets", font=("Comic Sans",12)); presetLabel.pack()

        self.presetDictionary = {
                                'Barrier Partial Reflection':("gaussian(-5,1,10)(x)","squareBarr(x0=0.1,width=.2,height=100)(x)"),
                                'Airy functions':("gaussian(-5,1,13)(x)","15*x"),
                                'Harmonic Oscillator':("gaussian(0,2,5)(x)",".5*x**2"),
                                'Coherent State w = 2':("gaussian(6/sqrt(2),1/sqrt(2),0)(x)",".5*4*x**2"),
                                'Abs(x) with Bumps':("(x>-4)*(x<0)*(np.exp(1j*8*x)/np.sqrt(2))*(np.sin(np.pi*x/2))","8*abs(x)+(x<7)*(x>5)*50*(5-x)*(x-7)-(x<-5)*(x>-7)*50*(-5-x)*(-x-7)"),
                                'Coulomb Like':("gaussian(3,1,-12)(x)","-80/(.25*(x-3)**2+.5)-120/(.25*(x+3)**2+.5)")
                                 }

        self.preset = tk.StringVar(); self.preset.set('Barrier Partial Reflection')
        presetsBox = ttk.Combobox(presetContainer,textvariable=self.preset)
        presetsBox['values'] = [key for key in self.presetDictionary]
        presetsBox.pack(side=tk.BOTTOM)
        self.preset.trace('w',self.presetCallback)

        #Todo: Connect up dontInterpBox
        self.dontInterp = tk.BooleanVar()
        dontInterpBox = ttk.Checkbutton(drawControlsContainer,text="Don't Interpo",variable=self.dontInterp);# dontInterpBox.pack(side = tk.RIGHT)

        self.startingK = tk.DoubleVar() # Initial K for psi
        kSlider = ttk.Scale(drawControlsContainer,orient="h",from_=-30,to=30,variable=self.startingK)
        kSlider.pack()

        displayOptionsContainer = tk.Frame(animOptionsContainer, relief = "sunken"); displayOptionsContainer.pack(expand=True,fill=tk.X)
        dispTypeButton = ttk.Button(displayOptionsContainer,text='Display Re{'+globalV.uniPsi+'}', command = self.anim.switchDisplayType)
        dispTypeButton.pack(side=tk.LEFT)
        #XKCDButton = ttk.Button(displayOptionsContainer, text="XKCD", command=self.toggleXKCD); XKCDButton.pack(side=tk.RIGHT)
        EnergyButton = ttk.Button(displayOptionsContainer, text="Energies", command=self.anim.energyDisplaySwitch); EnergyButton.pack(side = tk.LEFT)
        interpButton = ttk.Checkbutton(displayOptionsContainer,variable=None, command=self.anim.switchInterp); interpButton.pack(side=tk.RIGHT)

        # Text inputs for psi and V
        inputContainer = tk.Frame(nonFigContainer, relief="sunken"); inputContainer.pack()
        inputLabel = ttk.Label(inputContainer,text="Direct input",font=("Comic",16)); inputLabel.pack(side=tk.TOP)

        psiContainer = tk.Frame(inputContainer, relief="sunken"); psiContainer.pack()
        psiDLabel = ttk.Label(psiContainer,text=globalV.uniPsi+"(x,0): example exp(-x**2 + 5*1j)"); psiDLabel.pack(side=tk.TOP)
        self.textPsi = tk.StringVar()
        psiInputBox = tk.Entry(psiContainer, textvariable=self.textPsi)
        psiInputBox.pack(side = tk.LEFT)
        self.usePsi = tk.BooleanVar()
        psiCheckBox = ttk.Checkbutton(psiContainer,text="Enable",variable=self.usePsi); psiCheckBox.pack(side = tk.RIGHT)

        vContainer = tk.Frame(inputContainer, relief="sunken"); vContainer.pack()
        vDLabel = ttk.Label(vContainer,text="V(x): example ((x<-5)|(x>5))*100"); vDLabel.pack(side = tk.TOP)
        self.textV = tk.StringVar()
        vxInputBox = tk.Entry(vContainer, textvariable=self.textV)
        vxInputBox.pack(side = tk.LEFT)
        self.useV = tk.BooleanVar()
        vCheckBox = ttk.Checkbutton(vContainer,text="Enable",variable=self.useV); vCheckBox.pack(side = tk.RIGHT)

        #todo add other button functions
        solverContainer = tk.Frame(nonFigContainer, relief = "sunken")
        solverContainer.pack(side=tk.BOTTOM)
        solverTypesContainer = tk.Frame(solverContainer, relief = "sunken")
        solverTypesContainer.pack(side = tk.TOP,expand=True)
        FinDiffButton = ttk.Button(solverTypesContainer, text="Finite Difference", command=(lambda: self.myPart.reInit(SOLVER=EigenSolver1d)))
        FinDiffButton.pack(side = tk.LEFT,fill=tk.BOTH)
        SplitStepButton = ttk.Button(solverTypesContainer, text="Split Step Fourier", command=(lambda: self.myPart.reInit(SOLVER=SplitStepper1d)))
        SplitStepButton.pack(side = tk.RIGHT,fill=tk.BOTH)

                # Solver settings
        solverSettingsContainer = tk.Frame(solverContainer, relief = "sunken")
        solverSettingsContainer.pack(side=tk.BOTTOM)

        stencilContainer = tk.Frame(solverSettingsContainer); stencilContainer.pack(side = tk.LEFT)
        stencilDescription = ttk.Label(stencilContainer,text="Hamiltonian Stencil"); stencilDescription.pack()
        self.numSTerms = tk.IntVar(); self.numSTerms.set(2)
        stencil3Button = ttk.Radiobutton(stencilContainer,text = "3 Term",variable = self.numSTerms, value = 1); stencil3Button.pack()
        stencil5Button = ttk.Radiobutton(stencilContainer,text = "5 Term",variable = self.numSTerms, value = 2); stencil5Button.pack()
        stencil7Button = ttk.Radiobutton(stencilContainer,text = "7 Term",variable = self.numSTerms, value = 3); stencil7Button.pack()
        stencil9Button = ttk.Radiobutton(stencilContainer,text = "9 Term",variable = self.numSTerms, value = 4); stencil9Button.pack()

        #Todo: fix placement of Nscale
        nContainer = tk.Frame(solverSettingsContainer, relief = "sunken"); nContainer.pack(side = tk.RIGHT)
        Ndescription = ttk.Label(nContainer,text="Samples: 1024",); Ndescription.pack(side=tk.TOP)
        self.vectorLength = tk.IntVar()
        self.vectorLength.set(10)
        NScale = ttk.Scale(nContainer,orient='v',from_=3,to=13,variable = self.vectorLength,
            command = lambda x: self.nPointsSliderCallback(Ndescription)); NScale.pack()

        # eigenSlider and coefficients
        altFigSettingsContainer = tk.Frame(figContainer,relief=tk.RAISED,borderwidth=1)
        altFigSettingsContainer.pack(side=tk.BOTTOM,expand=True,fill=tk.BOTH)
        self.eigenNum = tk.IntVar()
        fnum = tk.Label(altFigSettingsContainer)
        fnum.pack(side = tk.LEFT)
        cNum = tk.Label(altFigSettingsContainer)
        cNum.pack(side = tk.RIGHT)
        self.eigenFunctionSlider = ttk.Scale(altFigSettingsContainer,orient="h",from_=0,to=90,variable = self.eigenNum, command = lambda x: self.altGraphSliderCallback((fnum,cNum)) )
        self.eigenFunctionSlider.pack(expand=True,fill=tk.BOTH)

        # Button for controlling altgraph output

        self.altGraphType = tk.IntVar()
        energyBasis = ttk.Radiobutton(altFigSettingsContainer,text = "psi in H basis",variable=self.altGraphType,value=0); energyBasis.pack(side = tk.RIGHT)

    def presetCallback(self,*args,**kwargs):
        self.textPsi.set(self.presetDictionary[self.preset.get()][0])
        self.textV.set(self.presetDictionary[self.preset.get()][1])
        self.usePsi.set(True)
        self.useV.set(True)

    def nPointsSliderCallback(self,label):
        pointExponent = self.vectorLength.get()
        label.config(text = "Samples: %i"%2**pointExponent)

    #def threadedChangeGraph(self):
    #    thread.start_new_thread(self.changeGraph, ())
    def altGraphSliderCallback(self,(fnum,cNum)):
        Ni = self.eigenNum.get()
        fnum.config(text="N_%i"%Ni)
        if self.myPart.solverClass == EigenSolver1d:
            a,b = np.real(self.myPart.solver.basisCoeffs[Ni]),np.imag(self.myPart.solver.basisCoeffs[Ni])
            cNum.config(text="C*C = %.2E"%(a**2 +b**2))
            self.anim.eigenDisplayNum = Ni
            #print np.vdot(self.myPart.solver.basisCoeffs,self.myPart.solver.basisCoeffs)

    def changeGraph(self):
        # Get the drawn curves from the canvas
        dasCurves,updatePsi,updateV = self.drawSpace.extractCurves()

        # downSampling to 50 points with spline interpolation, then rescaling #### NWAS HERE, may have to mess with interpolation settings
        numSamples = 620.
        downSampleRatio = numSamples/float(np.shape(dasCurves)[1])

        rescaleRatio = self.anim.particle.N/float(numSamples)

        pYvY = zoom(dasCurves,(1,downSampleRatio),order = 1)
        pYvY = zoom(pYvY,(1,rescaleRatio),order=1).astype('complex128')

        if self.anim.displayType == 0: # For displaytype and thus drawtype is |psi|^2
            pYvY[0] = np.sqrt(np.abs(pYvY[0]))*np.exp(1j*self.startingK.get()*self.anim.particle.X)
        else:
            pYvY[0] = pYvY[0]*np.exp(1j*self.startingK.get()*self.anim.particle.X)

        oldPsi = self.anim.particle.getPsi()
        oldV = self.anim.particle.getV()
        # We may also need to rescale N if it has changed
        newN = 2**self.vectorLength.get()
        if self.anim.particle.N!= newN:
            scaleRatio = newN/float(self.anim.particle.N)
            oldPsi = zoom(np.real(oldPsi),scaleRatio,order = 1)+1j*zoom(np.imag(oldPsi),scaleRatio,order = 1)
            oldV = zoom(oldV,scaleRatio,order = 1)
            pYvY = zoom(np.real(pYvY),(1,scaleRatio),order=1) +1j*zoom(np.imag(pYvY),(1,scaleRatio),order=1)

        newPsi = pYvY[0] if (updatePsi) else oldPsi
        newV   = np.real(pYvY[1]) if (updateV)   else oldV

        # If the direct input boxes are checked, input is taken directly
        X = np.linspace(-self.anim.particle.Lx/2,self.anim.particle.Lx/2,newN) # note that this will inhibit future change of Lx

        if (self.usePsi.get()):
            lambdaPsi = creationFunctions.getFunctionFromText(self.textPsi.get())
            if lambdaPsi!=None: newPsi = lambdaPsi(X)
        if (self.useV.get()):
            lambdaV = creationFunctions.getFunctionFromText(self.textV.get())
            if lambdaV!=None: newV = lambdaV(X)

        # set the new particle settings
        self.anim.particle.reInit(psi = newPsi,Vx = newV,stencilNum = self.numSTerms.get(),N=newN)

        # We need to change the bounds on the altgraph eigenslider
        if self.anim.particle.solverClass == EigenSolver1d:
            newMaxNBasis = self.anim.particle.solver.eigenBasis.shape[1]-1
            self.eigenFunctionSlider.configure(to = newMaxNBasis)
            # For out of bounds safety
            self.anim.eigenDisplayNum = min(self.anim.eigenDisplayNum,newMaxNBasis)

    def initGrid(self):
        #ttk.Style().theme_use("xpnative")
        self.pack(fill=tk.BOTH,expand=1)

        self.columnconfigure(1, weight=1)
        self.columnconfigure(3, pad=7)
        self.rowconfigure(3, weight=1)
        self.rowconfigure(5, pad=7)

    def toggleXKCD(self):
        xkcd()# function is still broken, since funcanimation does not terminate
        #self.psiFig = mpl.figure.Figure(figsize=(8,6), dpi=100)
        #self.anim = Animator(self.myPart,self.psiFig)

# Remember to cut window off
#
class DrawableGraph(FigureCanvasTkAgg):
    def __init__(self,figure,master):
        FigureCanvasTkAgg.__init__(self,figure,master)
        self.master = master
        self.cWidth,self.cHeight = figure.get_figwidth()*figure.dpi,\
                      figure.get_figheight()*figure.dpi
        self.b1 = "up"
        self.b2 = "up"
        self.x1old,self.y1old = None,None
        self.x2old,self.y2old = None,None
        self.yCenter = 203 # center of the psiGraph in pixels
        self.yScale = -80. # Number of pixels from 0 to 1, takes into account reversed directions
        self.psiXlist,self.psiYlist = -1*np.ones(self.cWidth),self.yCenter*np.ones(self.cWidth)
        self.VXlist,self.VYlist = -1*np.ones(self.cWidth),self.yCenter*np.ones(self.cWidth)
        self.oldPsi = None # stores psYlist and
        self.oldV = None   # VYlist  for modification
        self.get_tk_widget().bind("<Motion>", self.motion)
        self.get_tk_widget().bind("<ButtonPress-1>", self.b1down) # left click
        self.get_tk_widget().bind("<ButtonRelease-1>", self.b1up) # for psi

        self.get_tk_widget().bind("<ButtonPress-3>", self.b2down) # right click
        self.get_tk_widget().bind("<ButtonRelease-3>", self.b2up) # for V(x)

        self.get_tk_widget().bind("<ButtonPress-2>",self.loadOldCurves) # So you can extend a curve
        self.get_tk_widget().bind("<space>",lambda event: globalV.pauseUnpause())

    def loadOldCurves(self,event):
        if self.oldPsi != None: self.psiYlist = self.oldPsi
        if self.oldV != None: self.psiYlist = self.oldV

    def extractCurves(self):
        pX,pY,vX,vY = self.psiXlist,self.psiYlist, self.VXlist,self.VYlist
        self.b1 = "up"
        self.b2 = "up"
        self.x1old,self.y1old = None,None
        self.x2old,self.y2old = None,None
        self.psiXlist,self.psiYlist = -1*np.ones(self.cWidth),self.yCenter*np.ones(self.cWidth)
        self.VXlist,self.VYlist = -1*np.ones(self.cWidth),self.yCenter*np.ones(self.cWidth)
        self.get_tk_widget().delete("line")
        # Apply tukey window function to psi
        pwY = tukey(620,alpha=.1)*(pY[100:720]-self.yCenter)/self.yScale
        vwY = vY[100:720]-self.yCenter
        dasCurves = np.array([pwY,vwY])
        thresholdPsi = np.sum(pX[100:720])>-610
        thresholdV = np.sum(vX[100:720])>-610
        if thresholdPsi: self.oldPsi = pY
        if thresholdV: self.oldV = vY
        return dasCurves, thresholdPsi, thresholdV# Thresholds on activation

    def b1down(self,event):
        if self.inBounds(event.x,event.y):
            self.b1 = "down"           #
            self.get_tk_widget().config(cursor="target") #
            #globalV.pause()

    def b2down(self,event):
        if self.inBounds(event.x,event.y):
            self.b2 = "down"           #
            self.get_tk_widget().config(cursor="tcross")
            #globalV.pause() #
            print event.x,event.y
            print self.get_tk_widget().winfo_height()

    def b1up(self, event):
        self.b1 = "up"
        self.x1old = None           # reset the line when you let go of the button
        self.y1old = None
        self.get_tk_widget().config(cursor="arrow")

    def b2up(self, event):
        self.b2 = "up"
        self.x2old = None           # reset the line when you let go of the button
        self.y2old = None
        self.get_tk_widget().config(cursor="arrow")

    def inBounds(self,x,y):
        xGood = (x<self.cWidth) and (x>=0)
        yGood = (y<self.cHeight) and (y>=0)
        return (xGood and yGood)

    def linearInterpRem(self,coords):
        xold,yold,xnew,ynew=coords
        slope = (ynew-yold)/float(xnew-xold)
        return lambda x: ((x-xold)*slope + yold) #Switch up down

    def motion(self,event):
        if (self.b1 == "down") and self.inBounds(event.x,event.y):
            if self.psiXlist[event.x]==-1:
                color = "black"
            else: color = "red";

            if self.x1old is not None:
                self.get_tk_widget().create_line(self.x1old,self.y1old,event.x,event.y,smooth=True,width=2,fill=color,tag="line")
                if color == "black" and self.x1old!=event.x:
                    coords = self.x1old,self.y1old,event.x,event.y
                    xinRange = np.arange(self.x1old,event.x+1)
                    self.psiXlist[self.x1old:event.x+1] = 1
                    self.psiYlist[self.x1old:event.x+1] = self.linearInterpRem(coords)(xinRange)
            self.x1old = event.x
            self.y1old = event.y

        if (self.b2 == "down") and self.inBounds(event.x,event.y):
            if self.VXlist[event.x]==-1:
                color = "blue"
            else: color = "purple";

            if self.x2old is not None:
                self.get_tk_widget().create_line(self.x2old,self.y2old,event.x,event.y,smooth=True,width=2,fill=color, tag="line")
                if color == "blue" and self.x2old != event.x:
                    coords = self.x2old,self.y2old,event.x,event.y
                    xinRange = np.arange(self.x2old,event.x+1)
                    self.VXlist[self.x2old:event.x+1] = 1
                    self.VYlist[self.x2old:event.x+1] = self.linearInterpRem(coords)(xinRange)
            self.x2old = event.x
            self.y2old = event.y

if __name__ == "__main__":
    app = topApp()
    app.mainPageFrame.anim.animate()
    app.mainloop()


text:
#ifndef _THRIFT_PROTOCOL_TPROTOCOLEXCEPTION_H_
#define _THRIFT_PROTOCOL_TPROTOCOLEXCEPTION_H_ 1

#include <thrift/lib/cpp/Thrift.h>

#include <string>

namespace apache { namespace thrift { namespace protocol {

/**
 * Class to encapsulate all the possible types of protocol errors that may
 * occur in various protocol systems. This provides a sort of generic
 * wrapper around the shitty UNIX E_ error codes that lets a common code
 * base of error handling to be used for various types of protocols, i.e.
 * pipes etc.
 *
 */
class TProtocolException : public apache::thrift::TLibraryException {
 public:

  /**
   * Error codes for the various types of exceptions.
   */
  enum TProtocolExceptionType
  { UNKNOWN = 0
  , INVALID_DATA = 1
  , NEGATIVE_SIZE = 2
  , SIZE_LIMIT = 3
  , BAD_VERSION = 4
  , NOT_IMPLEMENTED = 5
  , MISSING_REQUIRED_FIELD = 6
  };

  TProtocolException() :
    apache::thrift::TLibraryException(),
    type_(UNKNOWN) {}

  explicit TProtocolException(TProtocolExceptionType type) :
    apache::thrift::TLibraryException(),
    type_(type) {}

  explicit TProtocolException(const std::string& message) :
    apache::thrift::TLibraryException(message),
    type_(UNKNOWN) {}

  TProtocolException(TProtocolExceptionType type, const std::string& message) :
    apache::thrift::TLibraryException(message),
    type_(type) {}

  ~TProtocolException() throw() override {}

  /**
   * Returns an error code that provides information about the type of error
   * that has occurred.
   *
   * @return Error code
   */
  TProtocolExceptionType getType() const {
    return type_;
  }

  const char* what() const throw() override {
    if (message_.empty()) {
      switch (type_) {
        case UNKNOWN         : return "TProtocolException: Unknown protocol exception";
        case INVALID_DATA    : return "TProtocolException: Invalid data";
        case NEGATIVE_SIZE   : return "TProtocolException: Negative size";
        case SIZE_LIMIT      : return "TProtocolException: Exceeded size limit";
        case BAD_VERSION     : return "TProtocolException: Invalid version";
        case NOT_IMPLEMENTED : return "TProtocolException: Not implemented";
        case MISSING_REQUIRED_FIELD :
          return "TProtocolException: Missing required field";
        default              : return "TProtocolException: (Invalid exception type)";
      }
    } else {
      return message_.c_str();
    }
  }

  [[noreturn]] static void throwUnionMissingStop();
  [[noreturn]] static void throwReportedTypeMismatch();
  [[noreturn]] static void throwNegativeSize();
  [[noreturn]] static void throwExceededSizeLimit();
  [[noreturn]] static void throwMissingRequiredField(
      folly::StringPiece field,
      folly::StringPiece type);

 protected:
  /**
   * Error code
   */
  TProtocolExceptionType type_;

};

}}} // apache::thrift::protocol

#endif // #ifndef _THRIFT_PROTOCOL_TPROTOCOLEXCEPTION_H_


text:
#include "OsreEdApp.h"
#include "Gui/UIElementsWin32.h"

#include <osre/Platform/AbstractOSService.h>
#include <osre/Platform/PlatformInterface.h>

using namespace ::OSRE;
using namespace ::OSRE::App;
using namespace ::OSRE::Editor;
using namespace ::OSRE::Platform;

static constexpr char Tag[] = "osre_ed_main";

int main(int argc, char *argv[]) {
    OsreEdApp app(argc, argv);

    if (!UIElementsWin32::init()) {
        osre_error(Tag, "Cannot init platform-specific ui.");
        return -1;
    }

    const ui32 Margin = 10;
    ui32 width = 0, height = 0;
    UIElementsWin32::getMonitorResolution(width, height);
    if (!app.initWindow(Margin, Margin, width - Margin, height - Margin, "OSRE-Ed", false,
            RenderBackendType::OpenGLRenderBackend)) {
        osre_error(Tag, "Cannot create window.");
        return -1;
    }

    while (app.handleEvents()) {
        app.update();
        app.requestNextFrame();
    }

    MemoryStatistics::showStatistics();

    UIElementsWin32::release();

    return 0;
}


text:
"""
Kay decorator test.

:Copyright: (c) 2009 Takashi Matsuo <tmatsuo@candit.jp> All rights reserved.
:license: BSD, see LICENSE for more details.
"""

import unittest
import re

from google.appengine.api import apiproxy_stub_map
from google.appengine.api.capabilities import capability_stub
from google.appengine.api import datastore_file_stub
from google.appengine.api import urlfetch_stub
from google.appengine.api.memcache import memcache_stub
from google.appengine.api import user_service_stub

from werkzeug import BaseResponse, Client, Request

import kay
from kay.app import get_application
from kay.conf import LazySettings
from kay.ext.testutils.gae_test_base import GAETestBase
from kay.tests import capability_stub as mocked_capability_stub

class MaintenanceCheckTestCase(unittest.TestCase):

  def setUp(self):
    apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
    stub = datastore_file_stub.DatastoreFileStub('test','/dev/null',
                                                 '/dev/null')
    apiproxy_stub_map.apiproxy.RegisterStub('datastore_v3', stub)

    apiproxy_stub_map.apiproxy.RegisterStub(
      'user', user_service_stub.UserServiceStub())

    apiproxy_stub_map.apiproxy.RegisterStub(
      'memcache', memcache_stub.MemcacheServiceStub())

    apiproxy_stub_map.apiproxy.RegisterStub(
      'urlfetch', urlfetch_stub.URLFetchServiceStub())

    s = LazySettings(settings_module='kay.tests.settings')
    app = get_application(settings=s)
    self.client = Client(app, BaseResponse)
    if apiproxy_stub_map.apiproxy\
          ._APIProxyStubMap__stub_map.has_key('capability_service'):
      del(apiproxy_stub_map.apiproxy\
            ._APIProxyStubMap__stub_map['capability_service'])

  def tearDown(self):
    pass

  def test_success(self):
    """Test with normal CapabilityServiceStub"""
    apiproxy_stub_map.apiproxy.RegisterStub(
      'capability_service',
      capability_stub.CapabilityServiceStub())
    response = self.client.get('/')
    self.assertEqual(response.status_code, 200)

  def test_failure(self):
    """Test with DisabledCapabilityServiceStub
    """
    apiproxy_stub_map.apiproxy.RegisterStub(
      'capability_service',
      mocked_capability_stub.DisabledCapabilityServiceStub())
    response = self.client.get('/')
    self.assertEqual(response.status_code, 302)
    self.assertEqual(response.headers['Location'],
                     'http://localhost/maintenance_page')

    response = self.client.get('/index2')
    self.assertEqual(response.status_code, 302)
    self.assertEqual(response.headers['Location'],
                     'http://localhost/no_decorator')
    response = self.client.get('/no_decorator')
    self.assertEqual(response.status_code, 200)

class CronOnlyTestCase(GAETestBase):

  def setUp(self):
    s = LazySettings(settings_module='kay.tests.settings')
    app = get_application(settings=s)
    self.client = Client(app, BaseResponse)

  def test_cron_only(self):
    response = self.client.get("/cron",
            headers=(('X-AppEngine-Cron', 'true'),))
    self.assertEqual(response.status_code, 200)
    self.assertTrue(response.data == "OK")

  def test_cron_only_failure(self):
    response = self.client.get("/cron")
    self.assertEqual(response.status_code, 403)

class CronOnlyDebugTestCase(GAETestBase):

  def setUp(self):
    s = LazySettings(settings_module='kay.tests.settings')
    s.DEBUG = True
    app = get_application(settings=s)
    self.client = Client(app, BaseResponse)

  def test_cron_only_failure(self):
    from kay.utils import is_dev_server
    response = self.client.get("/cron")
    if is_dev_server():
      self.assertEqual(response.status_code, 200)
    else:
      self.assertEqual(response.status_code, 403)

  def test_cron_only(self):
    response = self.client.get("/cron",
            headers=(('X-AppEngine-Cron', 'true'),))
    self.assertEqual(response.status_code, 200)
    self.assertTrue(response.data == "OK")

if __name__ == "__main__":
  unittest.main()


text:
@echo off
pushd %~dp0
"%VS120COMNTOOLS%..\IDE\mstest" /test:Microsoft.Protocols.TestSuites.MS_OXCFOLD.S01_FolderRopOperations.MSOXCFOLD_S01_TC03_RopCreateFolderSuccess /testcontainer:..\..\MS-OXCFOLD\TestSuite\bin\Debug\MS-OXCFOLD_TestSuite.dll /runconfig:..\..\MS-OXCFOLD\MS-OXCFOLD.testsettings /unique
pause


text:
@interface DAPIPView ()
{
    UIImageView *_frameView;
    UIImageView *_displayView;
}

- (CGPoint)closestCornerUnit;
- (CGFloat)frameInsetFromDevice;
- (CGRect)boundsFromDevice;

@end

@implementation DAPIPView

@synthesize borderInsets = _borderInsets;

#pragma mark - Init Methods

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (id)init
{
    self = [self initWithFrame:[self boundsFromDevice]];
    if (self)
    {
        // Initialization code
    }
    return self;
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        // Initialization code
        _borderInsets = UIEdgeInsetsMake(1.0f,      // top
                                         1.0f,      // left
                                         1.0f,      // bottom
                                         1.0f);     // right

        _displayView = [[UIImageView alloc] init];
        _displayView.frame = super.bounds;
        _displayView.clipsToBounds = YES;
        _displayView.backgroundColor = [UIColor grayColor];
        _displayView.autoresizingMask = (UIViewAutoresizingFlexibleWidth |
                                         UIViewAutoresizingFlexibleHeight);
        [super addSubview:_displayView];

        _frameView = [[UIImageView alloc] init];
        _frameView.frame = CGRectMake(-[self frameInsetFromDevice],
                                      -[self frameInsetFromDevice],
                                      _displayView.bounds.size.width + [self frameInsetFromDevice] * 2.0f,
                                      _displayView.bounds.size.height + [self frameInsetFromDevice] * 2.0f);
        _frameView.backgroundColor = [UIColor clearColor];
        _frameView.autoresizingMask = (UIViewAutoresizingFlexibleWidth |
                                       UIViewAutoresizingFlexibleHeight);
        [super addSubview:_frameView];

        self.multipleTouchEnabled = NO;

        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(orientationDidChange)
                                                     name:UIDeviceOrientationDidChangeNotification
                                                   object:nil];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self)
    {
        // Initialization code
        _borderInsets = UIEdgeInsetsMake(1.0f,      // top
                                         1.0f,      // left
                                         1.0f,      // bottom
                                         1.0f);     // right

        _displayView = [[UIImageView alloc] init];
        _displayView.frame = super.bounds;
        _displayView.clipsToBounds = YES;
        _displayView.backgroundColor = [UIColor grayColor];
        _displayView.autoresizingMask = (UIViewAutoresizingFlexibleWidth |
                                         UIViewAutoresizingFlexibleHeight);
        [super addSubview:_displayView];

        _frameView = [[UIImageView alloc] init];
        _frameView.frame = CGRectMake(-[self frameInsetFromDevice],
                                      -[self frameInsetFromDevice],
                                      _displayView.bounds.size.width + [self frameInsetFromDevice] * 2.0f,
                                      _displayView.bounds.size.height + [self frameInsetFromDevice] * 2.0f);
        _frameView.backgroundColor = [UIColor clearColor];
        _frameView.autoresizingMask = (UIViewAutoresizingFlexibleWidth |
                                       UIViewAutoresizingFlexibleHeight);
        [super addSubview:_frameView];

        self.multipleTouchEnabled = NO;

        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(orientationDidChange)
                                                     name:UIDeviceOrientationDidChangeNotification
                                                   object:nil];
    }
    return self;
}

#pragma mark - Touch Methods

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesMoved:touches withEvent:event];
    UITouch *touch = [touches anyObject];

    CGPoint fromLocation = [touch previousLocationInView:self];
    CGPoint toLocation = [touch locationInView:self];
    CGPoint changeLocation = CGPointMake(toLocation.x - fromLocation.x,
                                         toLocation.y - fromLocation.y);

    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.2f];
    super.center = CGPointMake(self.center.x + changeLocation.x,
                              self.center.y + changeLocation.y);
    [UIView commitAnimations];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesEnded:touches withEvent:event];
    [self moveToClosestCornerAnimated:YES];
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesCancelled:touches withEvent:event];
    [self moveToClosestCornerAnimated:YES];
}

#pragma mark - Math

- (CGPoint)closestCornerUnit
{
    CGFloat xCenter = (self.superview.bounds.size.width + _borderInsets.left - _borderInsets.right)/2.0f;
    CGFloat yCenter = (self.superview.bounds.size.height + _borderInsets.top - _borderInsets.bottom)/2.0f;

    CGFloat xCenterDist = self.center.x - xCenter;
    CGFloat yCenterDist = self.center.y - yCenter;

    return CGPointMake(xCenterDist/fabs(xCenterDist),
                       yCenterDist/fabs(yCenterDist));
}

- (CGFloat)frameInsetFromDevice
{
    return ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone ? 11.0f : 16.0f);
}

- (CGRect)boundsFromDevice
{
    return ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone ? CGRectMake(0.0f,
                                                                                0.0f,
                                                                                68.0f,
                                                                                102.0f) : CGRectMake(0.0f,
                                                                                0.0f,
                                                                                135.0f,
                                                                                179.0f));
}

#pragma mark - Public Commands

- (void)moveToTopLeftAnimated:(BOOL)animated
{
    [self moveToCornerUnit:CGPointMake(-1.0f, -1.0f) animated:animated];
}

- (void)moveToTopRightAnimated:(BOOL)animated
{
    [self moveToCornerUnit:CGPointMake(1.0f, -1.0f) animated:animated];
}

- (void)moveToBottomLeftAnimated:(BOOL)animated
{
    [self moveToCornerUnit:CGPointMake(-1.0f, 1.0f) animated:animated];
}

- (void)moveToBottomRightAnimated:(BOOL)animated
{
    [self moveToCornerUnit:CGPointMake(1.0f, 1.0f) animated:animated];
}

#pragma mark - Private Commands

- (void)moveToClosestCornerAnimated:(BOOL)animated
{
    CGPoint closestCornerUnit = [self closestCornerUnit];
    [self moveToCornerUnit:closestCornerUnit animated:animated];
}

- (void)moveToCornerUnit:(CGPoint)unit animated:(BOOL)animated
{
    if (!self.superview)
        return;

    CGFloat xCenter = (self.superview.bounds.size.width + _borderInsets.left - _borderInsets.right)/2.0f;
    CGFloat yCenter = (self.superview.bounds.size.height + _borderInsets.top - _borderInsets.bottom)/2.0f;

    CGFloat xWidth = (self.superview.bounds.size.width - _borderInsets.left - _borderInsets.right - self.bounds.size.width - [self frameInsetFromDevice]*2.0f);
    CGFloat yHeight = (self.superview.bounds.size.height - _borderInsets.top - _borderInsets.bottom - self.bounds.size.height - [self frameInsetFromDevice]*2.0f);

    CGFloat widthDistance = (xCenter*2.0f - self.bounds.size.width - [self frameInsetFromDevice] - _borderInsets.left + _borderInsets.right)/2.0f;
    CGFloat heightDistance = (yCenter*2.0f - self.bounds.size.height - [self frameInsetFromDevice] - _borderInsets.top + _borderInsets.bottom)/2.0f;

    CGPoint cornerPoint = CGPointMake((widthDistance * unit.x)  + self.superview.bounds.size.width/2.0f,
                                      (heightDistance * unit.y) + self.superview.bounds.size.height/2.0f);

    cornerPoint = CGPointMake((xCenter) + (widthDistance * unit.x),
                              (yCenter) + (heightDistance * unit.y));

    cornerPoint = CGPointMake((xCenter) + (xWidth/2.0f * unit.x),
                              (yCenter) + (yHeight/2.0f * unit.y));

    CGFloat xd = cornerPoint.x - self.center.x;
    CGFloat yd = cornerPoint.y - self.center.y;

    CGFloat directDistance = sqrt(xd*xd + yd*yd);

    CGFloat distancePerSecond = ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone? 720.0f : 1440.0f);

    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:(animated ? directDistance/distancePerSecond : 0.0f)];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
    super.center = cornerPoint;
    [UIView commitAnimations];

    super.autoresizingMask = ((unit.x ? UIViewAutoresizingFlexibleLeftMargin : UIViewAutoresizingFlexibleRightMargin) |
                              (unit.y ? UIViewAutoresizingFlexibleTopMargin : UIViewAutoresizingFlexibleBottomMargin));
}

- (void)orientationDidChange
{
    UIImage *frameImage = _frameView.image;

    UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
    switch (orientation)
    {
        case UIDeviceOrientationPortrait:
        {
            if([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)
                frameImage = [UIImage imageNamed:@"pipiPhoneFramePortrait3x2"];
            else
                frameImage = [UIImage imageNamed:@"pipiPadFramePortrait4x3"];
        }
            break;
        case UIDeviceOrientationPortraitUpsideDown:
        {
            if([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)
                frameImage = [UIImage imageNamed:@"pipiPhoneFramePortraitUpsideDown3x2"];
            else
                frameImage = [UIImage imageNamed:@"pipiPadFramePortraitUpsideDown4x3"];
        }
            break;
        case UIDeviceOrientationLandscapeLeft:
        {
            if([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)
                frameImage = [UIImage imageNamed:@"pipiPhoneFrameLandscapeLeft3x2"];
            else
                frameImage = [UIImage imageNamed:@"pipiPadFrameLandscapeLeft4x3"];
        }
            break;
        case UIDeviceOrientationLandscapeRight:
        {
            if([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)
                frameImage = [UIImage imageNamed:@"pipiPhoneFrameLandscapeRight3x2"];
            else
                frameImage = [UIImage imageNamed:@"pipiPadFrameLandscapeRight4x3"];
        }
            break;
        default:
        {

        }
            break;
    }

    UIEdgeInsets capInsets = UIEdgeInsetsMake([self frameInsetFromDevice] * 2.0f,
                                              [self frameInsetFromDevice] * 2.0f,
                                              [self frameInsetFromDevice] * 2.0f,
                                              [self frameInsetFromDevice] * 2.0f);

    if ([frameImage respondsToSelector:@selector(resizableImageWithCapInsets:)])
        _frameView.image = [frameImage resizableImageWithCapInsets:capInsets];
    else
        _frameView.image = [frameImage stretchableImageWithLeftCapWidth:capInsets.left
                                                           topCapHeight:capInsets.top];

    _frameView.frame = CGRectMake(-[self frameInsetFromDevice],
                                  -[self frameInsetFromDevice],
                                  _frameView.bounds.size.width,
                                  _frameView.bounds.size.height);

    //[self moveToClosestCornerAnimated:YES];
}

#pragma mark - Class Overrides

- (CALayer *)layer
{
    return _displayView.layer;
}

- (void)addSubview:(UIView *)view
{
    [_displayView addSubview:view];
}

- (void)setFrame:(CGRect)frame
{
    [super setFrame:frame];
    [self moveToClosestCornerAnimated:YES];
}

- (void)setBounds:(CGRect)bounds
{
    [super setBounds:bounds];
    [self moveToClosestCornerAnimated:YES];
}

- (void)setCenter:(CGPoint)center
{

}

- (void)setAutoresizingMask:(UIViewAutoresizing)autoresizingMask
{

}

- (void)didMoveToSuperview
{
    [super didMoveToSuperview];
    [self moveToBottomRightAnimated:NO];
    [self orientationDidChange];
}

- (void)didMoveToWindow
{
    [super didMoveToWindow];
    [self moveToBottomRightAnimated:NO];
    [self orientationDidChange];
}

#pragma mark - Property Methods

- (void)setBorderInsets:(UIEdgeInsets)borderInsets
{
    _borderInsets = borderInsets;
    [self moveToClosestCornerAnimated:NO];
}

@end


text:
package org.apache.hadoop.hive.ql.exec;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.apache.hadoop.fs.Path;

public class DefaultBucketMatcher implements BucketMatcher {

  protected final Logger LOG = LoggerFactory.getLogger(this.getClass().getName());

  //MAPPING: bucket_file_name_in_big_table->{alias_table->corresonding_bucket_file_names}
  private Map<String, Map<String, List<String>>> aliasBucketMapping;

  private Map<String, Integer> bucketFileNameMapping;

  public DefaultBucketMatcher(){
    bucketFileNameMapping = new LinkedHashMap<String, Integer>();
  }

  public List<Path> getAliasBucketFiles(String refTableInputFile, String refTableAlias, String alias) {
    List<String> pathStr=aliasBucketMapping.get(alias).get(refTableInputFile);
    List<Path> paths = new ArrayList<Path>();
    if(pathStr!=null) {
      for (String p : pathStr) {
        LOG.info("Loading file " + p + " for " + alias + ". (" + refTableInputFile + ")");
        paths.add(new Path(p));
      }
    }
    return paths;
  }

  public void setAliasBucketFileNameMapping(
      Map<String,Map<String,List<String>>> aliasBucketFileNameMapping) {
    this.aliasBucketMapping = aliasBucketFileNameMapping;
  }

  public Map<String, Integer> getBucketFileNameMapping() {
    return bucketFileNameMapping;
  }

  public void setBucketFileNameMapping(Map<String, Integer> bucketFileNameMapping) {
    this.bucketFileNameMapping = bucketFileNameMapping;
  }

}


text:
module Songkick::Api

  class Venue

    # search :query => 'query'
    songkick :search, 'search/venues.:format', :query

    # i.e. calendar :venue_id => 123
    songkick :calendar, 'venues/:venue_id/calendar.:format'

  end

end


text:
<?php
use kartik\grid\GridView;
use \yii\bootstrap\Tabs;
use yii\widgets\Breadcrumbs;
use kartik\widgets\Alert;
/**
 * Created by PhpStorm.
 * User: marat
 * Date: 01.10.15
 * Time: 11:22
 */
//var_dump($bread);die;
echo  $this->render('_search_vin',['params'=>$params]);
echo (!empty($params['breadcrumbs']))?Breadcrumbs::widget(['links'=>$params['breadcrumbs']]):'';
echo Alert::widget([
    'options' => [
        'class' => 'alert-info'
    ],
    'body' => 'Выберите регион производства и модель.'
]);
foreach($regions->models as $region) {

    $items []=
        ['label' => Yii::t('autocatalog', $region->region),
            'content' =>'
'. GridView::widget([
                'dataProvider' => $provider[$region->region],
                'showHeader' => false,
                'layout' => "{items}\n{pager}",
                'bootstrap' => false,
                'columns' => [

                    [
                        'attribute' => 'family',
                        'format' => 'raw',
                        'value' => function ($model, $key, $index, $widget) {
                            return \yii\helpers\Html::a($model['family'], $model['url']);
//                            return \yii\helpers\Html::a($model['family'], \yii\helpers\Url::to($model['region'].'/'.$model['family'] ));
                        },]
                ],

            ]).'
',
            'active' =>  ($region->region==$params['region']),
            'options'=>['class'=>'acatalog-tabs'],
        ];}
    ?>

<?=Tabs::widget(['items'=>$items]);?>

<?php


text:
package org.kie.dmn.signavio.feel.runtime.functions;

import org.kie.dmn.api.feel.runtime.events.FEELEvent.Severity;
import org.kie.dmn.feel.lang.types.BuiltInType;
import org.kie.dmn.feel.runtime.events.InvalidParametersEvent;
import org.kie.dmn.feel.runtime.functions.BaseFEELFunction;
import org.kie.dmn.feel.runtime.functions.BuiltInFunctions;
import org.kie.dmn.feel.runtime.functions.DateAndTimeFunction;
import org.kie.dmn.feel.runtime.functions.FEELFnResult;
import org.kie.dmn.feel.runtime.functions.ParameterName;
import org.kie.dmn.feel.util.EvalHelper;

import java.math.BigDecimal;
import java.time.DateTimeException;
import java.time.Duration;
import java.time.temporal.Temporal;
import java.time.temporal.TemporalAccessor;
import java.util.function.Function;

public class MinutesDiffFunction
        extends BaseFEELFunction {

    public MinutesDiffFunction() {
        super( "minutesDiff" );
    }

    public FEELFnResult<BigDecimal> invoke(@ParameterName("datetime1") TemporalAccessor datetime1, @ParameterName("datetime2") TemporalAccessor datetime2) {
        if ( datetime1 == null ) {
            return FEELFnResult.ofError( new InvalidParametersEvent( Severity.ERROR, "datetime1", "cannot be null" ) );
        }
        if ( datetime2 == null ) {
            return FEELFnResult.ofError( new InvalidParametersEvent( Severity.ERROR, "datetime2", "cannot be null" ) );
        }

        try {
            return FEELFnResult.ofResult( EvalHelper.getBigDecimalOrNull( Duration.between( (Temporal) datetime1, (Temporal) datetime2 ).toMinutes() ) );
        } catch ( DateTimeException e ) {
            return FEELFnResult.ofError( new InvalidParametersEvent( Severity.ERROR, "datetime", "invalid 'date' or 'date and time' parameter", e ) );
        }
    }

    public FEELFnResult<BigDecimal> invoke(@ParameterName("datetime1") String datetime1, @ParameterName("datetime2") String datetime2) {
        if ( datetime1 == null ) {
            return FEELFnResult.ofError( new InvalidParametersEvent( Severity.ERROR, "datetime1", "cannot be null" ) );
        }
        if ( datetime2 == null ) {
            return FEELFnResult.ofError( new InvalidParametersEvent( Severity.ERROR, "datetime2", "cannot be null" ) );
        }

        try {
            TemporalAccessor dt1 =  BuiltInFunctions.getFunction( DateAndTimeFunction.class ).invoke( datetime1 ).cata( BuiltInType.justNull(), Function.identity() );
            TemporalAccessor dt2 =  BuiltInFunctions.getFunction( DateAndTimeFunction.class ).invoke( datetime2 ).cata( BuiltInType.justNull(), Function.identity() );
            return invoke( dt1, dt2 );
        } catch ( DateTimeException e ) {
            return FEELFnResult.ofError( new InvalidParametersEvent( Severity.ERROR, "datetime", "invalid 'date' or 'date and time' parameter", e ) );
        }
    }

}


text:
if [ -z "$MESOS_PORT" ]; then
	echo "MESOS_PORT must not be empty"
	exit 1
fi

if [ -z "$MESOS_MASTER" ]; then
	echo "MESOS_MASTER must not be empty"
	exit 1
fi

if [ -z "$MESOS_SWITCH_USER" ]; then
	echo "MESOS_SWITCH_USER must not be empty"
	exit 1
fi

if [ -z "$MESOS_CONTAINERIZERS" ]; then
	echo "MESOS_CONTAINERIZERS must not be empty"
	exit 1
fi

if [ -z "$MESOS_LOG_DIR" ]; then
	echo "MESOS_LOG_DIR must not be empty"
	exit 1
fi

if [ -z "$MESOS_WORK_DIR" ]; then
	echo "MESOS_WORK_DIR must not be empty"
	exit 1
fi

# Check required Thermos executor env variables

if [ -z "$MESOS_ROOT" ]; then
	echo "MESOS_ROOT is not set, will be set to MESOS_WORK_DIR:$MESOS_WORK_DIR"
	MESOS_ROOT=$MESOS_WORK_DIR
elif [ "$MESOS_ROOT" != "$MESOS_WORK_DIR" ]; then
	echo "MESOS_ROOT is set to $MESOS_ROOT, but must match MESOS_WORK_DIR:$MESOS_WORK_DIR"
	exit 1

fi

chown -R $USER:$USER $MESOS_ROOT $MESOS_WORK_DIR $MESOS_LOG_DIR

echo "Starting thermos ..."
sudo -E -u aurora nohup /usr/sbin/thermos_observer --port=${HTTP_PORT:-1338} \
 --mesos-root=${MESOS_ROOT} \
 --app_daemonize \
 --log_to_disk=NONE \
 --log_to_stderr=google:INFO

echo "Starting Mesos slave ..."
sudo -E -u aurora nohup mesos-slave

wait


text:
package option

const (
	// IPAMKubernetes is the value to select the Kubernetes PodCIDR based
	// hostscope IPAM mode
	IPAMKubernetes = "kubernetes"

	// IPAMCRD is the value to select the CRD-backed IPAM plugin for
	// option.IPAM
	IPAMCRD = "crd"

	// IPAMENI is the value to select the AWS ENI IPAM plugin for option.IPAM
	IPAMENI = "eni"

	// IPAMAzure is the value to select the Azure IPAM plugin for
	// option.IPAM
	IPAMAzure = "azure"

	// IPAMClusterPool is the value to select the cluster pool mode for
	// option.IPAM
	IPAMClusterPool = "cluster-pool"

	// IPAMClusterPoolV2 is the value to select cluster pool version 2
	IPAMClusterPoolV2 = "cluster-pool-v2beta"

	// IPAMAlibabaCloud is the value to select the AlibabaCloud ENI IPAM plugin for option.IPAM
	IPAMAlibabaCloud = "alibabacloud"

	// IPAMDelegatedPlugin is the value to select CNI delegated IPAM plugin mode.
	// In this mode, Cilium CNI invokes another CNI binary (the delegated plugin) for IPAM.
	// See https://www.cni.dev/docs/spec/#section-4-plugin-delegation
	IPAMDelegatedPlugin = "delegated-plugin"
)

const (
	IPAMMarkForRelease  = "marked-for-release"
	IPAMReadyForRelease = "ready-for-release"
	IPAMDoNotRelease    = "do-not-release"
	IPAMReleased        = "released"
)

// ENIPDBlockSizeIPv4 is the number of IPs available on an ENI IPv4 prefix. Currently, AWS only supports /28 fixed size
// prefixes. Every /28 prefix contains 16 IP addresses.
// See https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-prefix-eni.html#ec2-prefix-basics for more details
const ENIPDBlockSizeIPv4 = 16


text:
<?php

use Valit\Check;

require __DIR__ . '/../vendor/autoload.php';

/*
 * Using \Valit\Check to get a list of all all assertions.
 */
$email = 'Some.Email@Foo.COM';

$emailCheck = Check::that($email)
    ->as('email')
    ->isEmail()
    ->isShorterThan(255)
    ->isLowercase();

$statusMessages = $emailCheck->statusMessages();

print_r($statusMessages);

/*
    Array
    (
        [0] => PASS: email must be a syntax-valid email address
        [1] => PASS: email must be a string that is shorter than 255 characters
        [2] => FAIL: email must only contain lower case latin letters
    )
 */

/*
WORKING WITH VALIDATION RESULTS
===============================

The `Valit\Check` facade does not throw exceptions
if the value does not live up to the assertions,
rather you can use the following functions to
inspect the success and status of the check.

| --------------------- | ----------------------------------------------------------------- |
| Method                | Description                                                       |
| --------------------- | ----------------------------------------------------------------- |
| `success()`           | Did all assertions pass?                                          |
| `hasErrors()`         | Did one or more assertions fail?                                  |
| `firstErrorMessage()` | The first error message (if any)                                  |
| `errorMessages()`     | Array of error messages.                                          |
| `statusMessages()`    | Array of status message.                                          |
| `results()`           | Array of AssertionResult objects.                                 |
| `orThrowException()`  | Throw an InvalidValueException if one or more assertions failed.  |
| `valueOr($alt)`       | If value is valid, return it, otherwise return $alt.              |
| --------------------- | ----------------------------------------------------------------- |

*/


text:
#include <aws/waf/model/SizeConstraintSet.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace WAF
{
namespace Model
{

SizeConstraintSet::SizeConstraintSet() :
    m_sizeConstraintSetIdHasBeenSet(false),
    m_nameHasBeenSet(false),
    m_sizeConstraintsHasBeenSet(false)
{
}

SizeConstraintSet::SizeConstraintSet(JsonView jsonValue) :
    m_sizeConstraintSetIdHasBeenSet(false),
    m_nameHasBeenSet(false),
    m_sizeConstraintsHasBeenSet(false)
{
  *this = jsonValue;
}

SizeConstraintSet& SizeConstraintSet::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("SizeConstraintSetId"))
  {
    m_sizeConstraintSetId = jsonValue.GetString("SizeConstraintSetId");

    m_sizeConstraintSetIdHasBeenSet = true;
  }

  if(jsonValue.ValueExists("Name"))
  {
    m_name = jsonValue.GetString("Name");

    m_nameHasBeenSet = true;
  }

  if(jsonValue.ValueExists("SizeConstraints"))
  {
    Array<JsonView> sizeConstraintsJsonList = jsonValue.GetArray("SizeConstraints");
    for(unsigned sizeConstraintsIndex = 0; sizeConstraintsIndex < sizeConstraintsJsonList.GetLength(); ++sizeConstraintsIndex)
    {
      m_sizeConstraints.push_back(sizeConstraintsJsonList[sizeConstraintsIndex].AsObject());
    }
    m_sizeConstraintsHasBeenSet = true;
  }

  return *this;
}

JsonValue SizeConstraintSet::Jsonize() const
{
  JsonValue payload;

  if(m_sizeConstraintSetIdHasBeenSet)
  {
   payload.WithString("SizeConstraintSetId", m_sizeConstraintSetId);

  }

  if(m_nameHasBeenSet)
  {
   payload.WithString("Name", m_name);

  }

  if(m_sizeConstraintsHasBeenSet)
  {
   Array<JsonValue> sizeConstraintsJsonList(m_sizeConstraints.size());
   for(unsigned sizeConstraintsIndex = 0; sizeConstraintsIndex < sizeConstraintsJsonList.GetLength(); ++sizeConstraintsIndex)
   {
     sizeConstraintsJsonList[sizeConstraintsIndex].AsObject(m_sizeConstraints[sizeConstraintsIndex].Jsonize());
   }
   payload.WithArray("SizeConstraints", std::move(sizeConstraintsJsonList));

  }

  return payload;
}

} // namespace Model
} // namespace WAF
} // namespace Aws


text:
cask 'appcode' do
  version '3.3.2'
  sha256 '8a49a3942f396717db09e8fd757ffc50de88b072ddb63e41c1ee895fc2cd68d1'

  url "https://download.jetbrains.com/objc/AppCode-#{version}-custom-jdk-bundled.dmg"
  name 'AppCode'
  homepage 'https://www.jetbrains.com/objc/'
  license :commercial

  conflicts_with cask: 'appcode-eap'

  app 'AppCode.app'

  zap delete: [
                "~/.Appcode#{version.major_minor.no_dots}",
                '~/Library/Preferences/com.jetbrains.AppCode.plist',
                "~/Library/Preferences/AppCode#{version.major_minor.no_dots}",
                "~/Library/Application Support/AppCode#{version.major_minor.no_dots}",
                "~/Library/Caches/AppCode#{version.major_minor.no_dots}",
                "~/Library/Logs/AppCode#{version.major_minor.no_dots}",
              ]
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
	"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="FileManagerMapper">
	<sql id="commonColumns">id,file_type,file_title,download_url</sql>

	<resultMap type="FileManager" id="FileResultMap">
		<id column="id" property="id"/>
		<result column="file_type" property="fileType"/>
		<result column="file_title" property="fileTitle"/>
		<result column="download_url" property="downloadUrl"/>
	</resultMap>

	<!-- 根据id获取债权信息 -->
	<select id="findById" parameterType="PageData" resultType="FileManager" useCache="false">
	   <include refid="commonColumns"></include>
		from cr_file_manager
		where id = #{id}
	</select>

   <select id="count" parameterType="PageData" resultType="int">
		select count(1)
		from cr_file_manager u
		where 1=1
		<if test="fileType != null and fileType != ''">
	  	and file_type =#{fileType}
		</if>
	</select>

	<select id="list" parameterType="PageData" resultType="FileManager">
	  select
	   <include refid="commonColumns"></include>
		from cr_file_manager
		where 1=1
		<if test="fileType != null and fileType != ''">
	  	   and file_type =#{fileType}
		</if>
		limit #{from},#{size}
	</select>

</mapper>


text:
package de.oster.easysqlmigration.migration.jdbc.repository;

import org.springframework.jdbc.core.JdbcTemplate;

public abstract class SimpleJDBCRepository
{
    protected JdbcTemplate jdbcTemplate;

    public SimpleJDBCRepository(JdbcTemplate jdbcTemplate)
    {
        this.jdbcTemplate =  jdbcTemplate;
    }

    public SimpleJDBCRepository() {
    }

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate)
    {
        this.jdbcTemplate =  jdbcTemplate;
    }
}


text:
$: << File.expand_path(File.dirname(__FILE__))

require 'rubygems'
require 'cgi'
require 'hpricot'
require 'active_support'
require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/string/inflections'
require 'time'
require 'yaml'

require 'rockstar/base'
require 'rockstar/version'

require 'rockstar/album'
require 'rockstar/artist'
require 'rockstar/chart'
require 'rockstar/event'
require 'rockstar/geo'
require 'rockstar/library'
require 'rockstar/metro'
require 'rockstar/user'
require 'rockstar/tag'
require 'rockstar/track'
require 'rockstar/venue'
require 'rockstar/search'

require 'rockstar/auth'
require 'rockstar/session'
require 'rockstar/rest'

module Rockstar
  extend self

  def lastfm=(args)
    @api_key    = args["api_key"] || args[:api_key]
    @api_secret = args["api_secret"] || args[:api_secret]
  end

  def lastfm_api_key
    @api_key
  end

  def lastfm_api_secret
    @api_secret
  end
end


text:
<?php

include('../config.php');
include('../model/stripepayment.php');
include('../db/mysqldb.php');
include('../stripe-php-master/lib/Stripe.php');

?>

Stripe Payment Test Form

		<form action="" method="POST" id="payment-form">

		  		Name
		  		<input type="text" size="40" />

		      Card Number
		      <input type="text" size="20" data-stripe="number"/>

		      CVC
		      <input type="text" size="4" data-stripe="cvc"/>

		      Expiration (MM/YYYY)
		      <input type="text" size="2" data-stripe="exp-month"/>

		     /
		    <input type="text" size="4" data-stripe="exp-year"/>

		  <button type="submit">Submit Payment</button>
		</form>


text:
@implementation InstallerChoicesItemMO

- (NSDictionary *)dictValue
{
	return [NSDictionary dictionaryWithObjectsAndKeys:
			self.munki_choiceIdentifier, @"title",
			self.munki_choiceAttribute, @"subtitle",
			@"choicesitem", @"type",
			nil];
}

- (NSDictionary *)dictValueForSave
{
	NSMutableDictionary *tmpDict = [NSMutableDictionary dictionaryWithCapacity:3];
	if (self.munki_choiceIdentifier != nil) [tmpDict setObject:self.munki_choiceIdentifier forKey:@"choiceIdentifier"];
	if (self.munki_choiceAttribute != nil) [tmpDict setObject:self.munki_choiceAttribute forKey:@"choiceAttribute"];
    if (self.munki_attributeSetting != nil) {
        [tmpDict setObject:self.munki_attributeSetting forKey:@"attributeSetting"];
    } else {
        [tmpDict setObject:@NO forKey:@"attributeSetting"];
    }
	NSDictionary *returnDict = [NSDictionary dictionaryWithDictionary:tmpDict];
	return returnDict;
}

@end


text:
from flask_babel import lazy_gettext as _
from sqlalchemy import not_, or_
from sqlalchemy.orm.query import Query

from superset.connectors.sqla.models import SqlaTable
from superset.views.base import BaseFilter

class DatasetIsNullOrEmptyFilter(BaseFilter):  # pylint: disable=too-few-public-methods
    name = _("Null or Empty")
    arg_name = "dataset_is_null_or_empty"

    def apply(self, query: Query, value: bool) -> Query:
        filter_clause = or_(SqlaTable.sql.is_(None), SqlaTable.sql == "")

        if not value:
            filter_clause = not_(filter_clause)

        return query.filter(filter_clause)

class DatasetCertifiedFilter(BaseFilter):  # pylint: disable=too-few-public-methods
    name = _("Is certified")
    arg_name = "dataset_is_certified"

    def apply(self, query: Query, value: bool) -> Query:
        check_value = '%"certification":%'
        if value is True:
            return query.filter(SqlaTable.extra.ilike(check_value))
        if value is False:
            return query.filter(
                or_(
                    SqlaTable.extra.notlike(check_value),
                    SqlaTable.extra.is_(None),
                )
            )
        return query


text:
require_relative '../../config/application'

class Message < ActiveRecord::Base

end


text:
id: synth
title: Redex Synth Pass Example
---

> The code and artifacts for this example are on [GitHub](https://github.com/facebook/redex/tree/master/examples/Synth).

The synth optimizations attempt to remove synthetic methods and wrappers. This
improves performance by making access to field values faster and it also
reduces code size because the definition and invocation of synthetic methods
is eliminated.

## Removing synthetic methods for accessing static fields

This directory contains an Android Studio 1.5 project that illustrates how a
wrapper synthetic method is removed by Redex. The contrived example is
a simple Android application which makes use of this class:

```java
package com.facebook.redex.examples.synth;

public class Alpha {

    private static int alpha;

    public Alpha(int initialValue) {
        alpha = initialValue;
    }

    public class Beta {
        public int doubleAlpha() {
            return 2 * alpha;
        }
    }
}
```

The key thing to note here is that there is an inner class `Beta` which
has a method `doubleAlpha` which accesses a private static field `alpha` of
its outer class `Alpha`. A dump of the Dex bytecode for the `Alpha` class
confirms that the `alpha` field is `private` and `static`.

```
  Static fields     -
    #0              : (in Lcom/facebook/redex/examples/synth/Alpha;)
      name          : 'alpha'
      type          : 'I'
      access        : 0x000a (PRIVATE STATIC)
```

Java compilers will implement accesses] to this field from inner classes
by generating a synthetic getter method to allow the inner class to access
the private field of the outer
class. We can see the automatically generated synthetic method `access$000`
if we examine the Dex bytecode for the `Alpha` class:

```
Class #597            -
  Class descriptor  : 'Lcom/facebook/redex/examples/synth/Alpha;'
...
    #1              : (in Lcom/facebook/redex/examples/synth/Alpha;)
      name          : 'access$000'
      type          : '()I'
      access        : 0x1008 (STATIC SYNTHETIC)
      code          -
      registers     : 1
      ins           : 0
      outs          : 0
      insns size    : 3 16-bit code units
065f14:                                        |[065f14] com.facebook.redex.examples.synth.Alpha.access$000:()I
065f24: 6000 070b                              |0000: sget v0, Lcom/facebook/redex/examples/synth/Alpha;.alpha:I // field@0b07
065f28: 0f00                                   |0002: return v0
```

This generated synthetic method can be accessed by the inner class
which keeps the JVM happy. All it does is to read the state field
value using an `sget` instruction and return the read value.
This synthetic wrapper is used in the implementation of `doubleAlpha`:

```
  Virtual methods   -
    #0              : (in Lcom/facebook/redex/examples/synth/Alpha$Beta;)
      name          : 'doubleAlpha'
...
065ed8:                                        |[065ed8] com.facebook.redex.examples.synth.Alpha.Beta.doubleAlpha:()I
065ee8: 7100 1118 0000                         |0000: invoke-static {}, Lcom/facebook/redex/examples/synth/Alpha;.access$000:()I // method@1811
065eee: 0a00                                   |0003: move-result v0
065ef0: da00 0002                              |0004: mul-int/lit8 v0, v0, #int 2 // #02
065ef4: 0f00                                   |0006: return v0
```

For the `doubleAlpha` method in the inner class `Beta` to access the
private static field of the enclosing class an `invoke-static` call is made
to the synthetic wrapper method `access$000`.

Here is an example of the `doubleAlpha` method being used from a simple
Android application:

```java
package com.facebook.redex.examples.synth;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView textView = (TextView) findViewById(R.id.message);
        textView.setText("Redex Synth Example\n");

        Alpha a = new Alpha(12);
        Alpha.Beta b = a.new Beta();
        textView.append("Double Alpha(12) = " + b.doubleAlpha() + "\n");
    }
}
```

If we examined the Dex bytecode for the call to `doubleAlpha` we would
see something like this which shows a virtual call to the `doubleAlpha` method:

```
  Direct methods    -
    #0              : (in Lcom/facebook/redex/examples/synth/MainActivity;)
      name          : 'onCreate'
...
065fb6: 6e10 0f18 0100                         |0031: invoke-virtual {v1}, Lcom/facebook/redex/examples/synth/Alpha$Beta;.doubleAlpha:()I // method@180f
...
```

After running Redex the synthetic wrapper method will be removed and
the code for accessing the `alpha` static field will be inlined into
the code for the main activity:

```
  Direct methods    -
    #0              : (in Lcom/facebook/redex/examples/synth/MainActivity;)
      name          : 'onCreate'
...
07f246: 6005 4d06                              |0031: sget v5, Lcom/facebook/redex/examples/synth/Alpha;.alpha:I // field@064d
07f24a: da05 0502                              |0033: mul-int/lit8 v5, v5, #int 2 // #02
...

```

To make the access of the `alpha` field legal for the Dalvik VM we have
mutated the access permissions for this field:

```
  Static fields     -
    #0              : (in Lcom/facebook/redex/examples/synth/Alpha;)
      name          : 'alpha'
      type          : 'I'
      access        : 0x0009 (PUBLIC STATIC)

```

Similar optimizations exist for other synthetic wrapper scenarios e.g.
for instance fields.

## Example Code
The project in the `synth-example` directory can be opened with Android Studio 1.5 and
contains the sample here that illustrates the removal of synthetic
wrappers for static private fields.

The `Makefile` in this directory can be used once you have build a signed:
APK (`Build : Generate Signed APK...`) to produce the following items:
* `synth-example-release-redex.apk`: A Redex optimized version of the original APK.
* `classes.dump`: A dump of the Dex bytecode for the input APK `synth-example-release.apk`.
* `classes-redex.dump`: A dump of the Redex optimizd APK `synth-example-release-redex.apk`.

The environment variable `ANDROID_TOOLS` should be set to the location
of your Android SDK tools directory.

To produce these items:

```
$ make clean all
```


text:
package com.lightcrafts.media.jai.tilecodec;

import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;
import java.awt.image.SampleModel;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import com.lightcrafts.mediax.jai.ParameterListDescriptor;
import com.lightcrafts.mediax.jai.RasterFactory;
import com.lightcrafts.mediax.jai.tilecodec.TileCodecDescriptor;
import com.lightcrafts.mediax.jai.tilecodec.TileCodecParameterList;
import com.lightcrafts.mediax.jai.tilecodec.TileDecoderImpl;
import com.lightcrafts.mediax.jai.util.ImagingListener;
import com.sun.image.codec.jpeg.JPEGDecodeParam;
import com.sun.image.codec.jpeg.JPEGImageDecoder;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGQTable;
import com.lightcrafts.media.jai.util.ImageUtil;
/**
 * A concrete implementation of the TileDecoderImpl class
 * for the jpeg tile codec.
 */
public class JPEGTileDecoder extends TileDecoderImpl {
    /* The associated TileCodecDescriptor */
    private TileCodecDescriptor tcd = null;

    /**
     * Constructs a JPEGTileDecoder.
     * JPEGTileDecoder may throw a
     * IllegalArgumentException if param's
     * getParameterListDescriptor() method does not return
     * the same descriptor as that from the associated
     * TileCodecDescriptor's
     * getParameterListDescriptor method for the "tileDecoder"
     * registry mode.
     *
     *
 If param is null, then the default parameter list for decoding
     * as defined by the associated TileCodecDescriptor's
     * getDefaultParameters() method will be used for decoding.
     *
     * @param input The InputStream to decode data from.
     * @param param  The object containing the tile decoding parameters.
     * @throws IllegalArgumentException if input is null.
     * @throws IllegalArgumentException if param is not appropriate.
     */
    public JPEGTileDecoder(InputStream input, TileCodecParameterList param) {
	super("jpeg", input, param);
        tcd = TileCodecUtils.getTileCodecDescriptor("tileDecoder", "jpeg");
    }

    /**
     * Returns a Raster that contains the decoded contents
     * of the InputStream associated with this
     * TileDecoder.
     *
     *
This method can perform the decoding correctly only when
     * includesLocationInfoInfo() returns true.
     *
     * @throws IOException if an I/O error occurs while reading from the
     * associated InputStream.
     * @throws IllegalArgumentException if the associated
     * TileCodecDescriptor's includesLocationInfoInfo() returns false.
     */
    public Raster decode() throws IOException{
	if (!tcd.includesLocationInfo())
	    throw new IllegalArgumentException(
		JaiI18N.getString("JPEGTileDecoder0") );
	return decode(null);
    }

    public Raster decode(Point location) throws IOException{
	SampleModel sm = null;
	byte[] data = null;

        ObjectInputStream ois = new ObjectInputStream(inputStream);

        try {
	    // read the quality and qualitySet from the stream
	    paramList.setParameter("quality", ois.readFloat());
	    paramList.setParameter("qualitySet", ois.readBoolean());
            sm = TileCodecUtils.deserializeSampleModel(ois.readObject());
	    location = (Point)ois.readObject();
            data = (byte[]) ois.readObject();
        }
        catch (ClassNotFoundException e) {
            ImagingListener listener =
                ImageUtil.getImagingListener((RenderingHints)null);
            listener.errorOccurred(JaiI18N.getString("ClassNotFound"),
                                   e, this, false);
//            e.printStackTrace();
	    return null;
        }
	finally {
            ois.close();
	}

	ByteArrayInputStream bais = new ByteArrayInputStream(data);
        JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(bais);

        Raster ras = decoder.decodeAsRaster()
			.createTranslatedChild(location.x, location.y);
	extractParameters(decoder.getJPEGDecodeParam(),
			  ras.getSampleModel().getNumBands());

	// set the original sample model to the decoded raster
	if (sm != null) {
	    int minX = ras.getMinX();
	    int minY = ras.getMinY();
	    int h = ras.getHeight();
	    int w = ras.getWidth();
	    double[] buf = ras.getPixels(minX, minY, w, h, (double[])null);
	    ras = RasterFactory.createWritableRaster(sm,
						     new Point(minX, minY));
	    ((WritableRaster)ras).setPixels(minX, minY, w, h, buf);
	}
	return ras;
    }

    private void extractParameters(JPEGDecodeParam jdp, int bandNum) {

	// extract the horizontal subsampling rates
	int[] horizontalSubsampling = new int[bandNum];
	for (int i = 0; i < bandNum; i++)
	    horizontalSubsampling[i] = jdp.getHorizontalSubsampling(i);
	paramList.setParameter("horizontalSubsampling", horizontalSubsampling);

	// extract the vertical subsampling rates
	int[] verticalSubsampling = new int[bandNum];
	for (int i = 0; i < bandNum; i++)
	    verticalSubsampling[i] = jdp.getVerticalSubsampling(i);
	paramList.setParameter("verticalSubsampling", verticalSubsampling);

	// if the quality is not set, extract the quantization tables from
	// the stream; otherwise, define them with the default values.
	if (!paramList.getBooleanParameter("qualitySet"))
	    for (int i = 0; i < 4; i++) {
		JPEGQTable table = jdp.getQTable(i);
		paramList.setParameter("quantizationTable"+i,
		    (table == null) ? null : table.getTable());
	    }
	else {
	    ParameterListDescriptor pld
		= paramList.getParameterListDescriptor();
	    for (int i = 0; i < 4; i++) {
		paramList.setParameter("quantizationTable"+i,
		    pld.getParamDefaultValue("quantizationTable"+i));
	    }
	}

	// extract the quantizationTableMapping
	int[] quanTableMapping = new int[bandNum];
	for (int i = 0; i < bandNum; i++)
	    quanTableMapping[i] = jdp.getQTableComponentMapping(i);
	paramList.setParameter("quantizationTableMapping", quanTableMapping);

	// extract the writeTableInfo and writeImageInfo
	paramList.setParameter("writeTableInfo", jdp.isTableInfoValid());
	paramList.setParameter("writeImageInfo", jdp.isImageInfoValid());

	// extract the restart interval
	paramList.setParameter("restartInterval", jdp.getRestartInterval());

	// define writeJFIFHeader by examing the APP0_MARKER is set or not
	paramList.setParameter("writeJFIFHeader",
			       jdp.getMarker(JPEGDecodeParam.APP0_MARKER));
    }
}