text:
from itertools import product

import numpy as np
from scipy.sparse import (bsr_matrix, coo_matrix, csc_matrix, csr_matrix,
                          dok_matrix, lil_matrix)
from sklearn import metrics
from sklearn import neighbors, datasets
from sklearn.metrics.pairwise import pairwise_distances
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import train_test_split
from sklearn.utils.testing import assert_array_almost_equal
from sklearn.utils.testing import assert_array_equal
from sklearn.utils.testing import assert_equal
from sklearn.utils.testing import assert_greater
from sklearn.utils.testing import assert_raises
from sklearn.utils.testing import assert_true
from sklearn.utils.testing import assert_warns
from sklearn.utils.testing import ignore_warnings
from sklearn.utils.validation import check_random_state

rng = np.random.RandomState(0)
# load and shuffle iris dataset
iris = datasets.load_iris()
perm = rng.permutation(iris.target.size)
iris.data = iris.data[perm]
iris.target = iris.target[perm]

# load and shuffle digits
digits = datasets.load_digits()
perm = rng.permutation(digits.target.size)
digits.data = digits.data[perm]
digits.target = digits.target[perm]

SPARSE_TYPES = (bsr_matrix, coo_matrix, csc_matrix, csr_matrix, dok_matrix,
                lil_matrix)
SPARSE_OR_DENSE = SPARSE_TYPES + (np.asarray,)

ALGORITHMS = ('ball_tree', 'brute', 'kd_tree', 'auto')
P = (1, 2, 3, 4, np.inf)

# Filter deprecation warnings.
neighbors.kneighbors_graph = ignore_warnings(neighbors.kneighbors_graph)
neighbors.radius_neighbors_graph = ignore_warnings(
    neighbors.radius_neighbors_graph)

def _weight_func(dist):
    """ Weight function to replace lambda d: d ** -2.
    The lambda function is not valid because:
    if d==0 then 0^-2 is not valid. """

    # Dist could be multidimensional, flatten it so all values
    # can be looped
    with np.errstate(divide='ignore'):
        retval = 1. / dist
    return retval ** 2

def test_unsupervised_kneighbors(n_samples=20, n_features=5,
                                 n_query_pts=2, n_neighbors=5):
    # Test unsupervised neighbors methods
    X = rng.rand(n_samples, n_features)

    test = rng.rand(n_query_pts, n_features)

    for p in P:
        results_nodist = []
        results = []

        for algorithm in ALGORITHMS:
            neigh = neighbors.NearestNeighbors(n_neighbors=n_neighbors,
                                               algorithm=algorithm,
                                               p=p)
            neigh.fit(X)

            results_nodist.append(neigh.kneighbors(test,
                                                   return_distance=False))
            results.append(neigh.kneighbors(test, return_distance=True))

        for i in range(len(results) - 1):
            assert_array_almost_equal(results_nodist[i], results[i][1])
            assert_array_almost_equal(results[i][0], results[i + 1][0])
            assert_array_almost_equal(results[i][1], results[i + 1][1])

def test_unsupervised_inputs():
    # test the types of valid input into NearestNeighbors
    X = rng.random_sample((10, 3))

    nbrs_fid = neighbors.NearestNeighbors(n_neighbors=1)
    nbrs_fid.fit(X)

    dist1, ind1 = nbrs_fid.kneighbors(X)

    nbrs = neighbors.NearestNeighbors(n_neighbors=1)

    for input in (nbrs_fid, neighbors.BallTree(X), neighbors.KDTree(X)):
        nbrs.fit(input)
        dist2, ind2 = nbrs.kneighbors(X)

        assert_array_almost_equal(dist1, dist2)
        assert_array_almost_equal(ind1, ind2)

def test_precomputed(random_state=42):
    """Tests unsupervised NearestNeighbors with a distance matrix."""
    # Note: smaller samples may result in spurious test success
    rng = np.random.RandomState(random_state)
    X = rng.random_sample((10, 4))
    Y = rng.random_sample((3, 4))
    DXX = metrics.pairwise_distances(X, metric='euclidean')
    DYX = metrics.pairwise_distances(Y, X, metric='euclidean')
    for method in ['kneighbors']:
        # TODO: also test radius_neighbors, but requires different assertion

        # As a feature matrix (n_samples by n_features)
        nbrs_X = neighbors.NearestNeighbors(n_neighbors=3)
        nbrs_X.fit(X)
        dist_X, ind_X = getattr(nbrs_X, method)(Y)

        # As a dense distance matrix (n_samples by n_samples)
        nbrs_D = neighbors.NearestNeighbors(n_neighbors=3, algorithm='brute',
                                            metric='precomputed')
        nbrs_D.fit(DXX)
        dist_D, ind_D = getattr(nbrs_D, method)(DYX)
        assert_array_almost_equal(dist_X, dist_D)
        assert_array_almost_equal(ind_X, ind_D)

        # Check auto works too
        nbrs_D = neighbors.NearestNeighbors(n_neighbors=3, algorithm='auto',
                                            metric='precomputed')
        nbrs_D.fit(DXX)
        dist_D, ind_D = getattr(nbrs_D, method)(DYX)
        assert_array_almost_equal(dist_X, dist_D)
        assert_array_almost_equal(ind_X, ind_D)

        # Check X=None in prediction
        dist_X, ind_X = getattr(nbrs_X, method)(None)
        dist_D, ind_D = getattr(nbrs_D, method)(None)
        assert_array_almost_equal(dist_X, dist_D)
        assert_array_almost_equal(ind_X, ind_D)

        # Must raise a ValueError if the matrix is not of correct shape
        assert_raises(ValueError, getattr(nbrs_D, method), X)

    target = np.arange(X.shape[0])
    for Est in (neighbors.KNeighborsClassifier,
                neighbors.RadiusNeighborsClassifier,
                neighbors.KNeighborsRegressor,
                neighbors.RadiusNeighborsRegressor):
        print(Est)
        est = Est(metric='euclidean')
        est.radius = est.n_neighbors = 1
        pred_X = est.fit(X, target).predict(Y)
        est.metric = 'precomputed'
        pred_D = est.fit(DXX, target).predict(DYX)
        assert_array_almost_equal(pred_X, pred_D)

def test_precomputed_cross_validation():
    # Ensure array is split correctly
    rng = np.random.RandomState(0)
    X = rng.rand(20, 2)
    D = pairwise_distances(X, metric='euclidean')
    y = rng.randint(3, size=20)
    for Est in (neighbors.KNeighborsClassifier,
                neighbors.RadiusNeighborsClassifier,
                neighbors.KNeighborsRegressor,
                neighbors.RadiusNeighborsRegressor):
        metric_score = cross_val_score(Est(), X, y)
        precomp_score = cross_val_score(Est(metric='precomputed'), D, y)
        assert_array_equal(metric_score, precomp_score)

def test_unsupervised_radius_neighbors(n_samples=20, n_features=5,
                                       n_query_pts=2, radius=0.5,
                                       random_state=0):
    # Test unsupervised radius-based query
    rng = np.random.RandomState(random_state)

    X = rng.rand(n_samples, n_features)

    test = rng.rand(n_query_pts, n_features)

    for p in P:
        results = []

        for algorithm in ALGORITHMS:
            neigh = neighbors.NearestNeighbors(radius=radius,
                                               algorithm=algorithm,
                                               p=p)
            neigh.fit(X)

            ind1 = neigh.radius_neighbors(test, return_distance=False)

            # sort the results: this is not done automatically for
            # radius searches
            dist, ind = neigh.radius_neighbors(test, return_distance=True)
            for (d, i, i1) in zip(dist, ind, ind1):
                j = d.argsort()
                d[:] = d[j]
                i[:] = i[j]
                i1[:] = i1[j]
            results.append((dist, ind))

            assert_array_almost_equal(np.concatenate(list(ind)),
                                      np.concatenate(list(ind1)))

        for i in range(len(results) - 1):
            assert_array_almost_equal(np.concatenate(list(results[i][0])),
                                      np.concatenate(list(results[i + 1][0]))),
            assert_array_almost_equal(np.concatenate(list(results[i][1])),
                                      np.concatenate(list(results[i + 1][1])))

def test_kneighbors_classifier(n_samples=40,
                               n_features=5,
                               n_test_pts=10,
                               n_neighbors=5,
                               random_state=0):
    # Test k-neighbors classification
    rng = np.random.RandomState(random_state)
    X = 2 * rng.rand(n_samples, n_features) - 1
    y = ((X ** 2).sum(axis=1) < .5).astype(np.int)
    y_str = y.astype(str)

    weight_func = _weight_func

    for algorithm in ALGORITHMS:
        for weights in ['uniform', 'distance', weight_func]:
            knn = neighbors.KNeighborsClassifier(n_neighbors=n_neighbors,
                                                 weights=weights,
                                                 algorithm=algorithm)
            knn.fit(X, y)
            epsilon = 1e-5 * (2 * rng.rand(1, n_features) - 1)
            y_pred = knn.predict(X[:n_test_pts] + epsilon)
            assert_array_equal(y_pred, y[:n_test_pts])
            # Test prediction with y_str
            knn.fit(X, y_str)
            y_pred = knn.predict(X[:n_test_pts] + epsilon)
            assert_array_equal(y_pred, y_str[:n_test_pts])

def test_kneighbors_classifier_float_labels(n_samples=40, n_features=5,
                                            n_test_pts=10, n_neighbors=5,
                                            random_state=0):
    # Test k-neighbors classification
    rng = np.random.RandomState(random_state)
    X = 2 * rng.rand(n_samples, n_features) - 1
    y = ((X ** 2).sum(axis=1) < .5).astype(np.int)

    knn = neighbors.KNeighborsClassifier(n_neighbors=n_neighbors)
    knn.fit(X, y.astype(np.float))
    epsilon = 1e-5 * (2 * rng.rand(1, n_features) - 1)
    y_pred = knn.predict(X[:n_test_pts] + epsilon)
    assert_array_equal(y_pred, y[:n_test_pts])

def test_kneighbors_classifier_predict_proba():
    # Test KNeighborsClassifier.predict_proba() method
    X = np.array([[0, 2, 0],
                  [0, 2, 1],
                  [2, 0, 0],
                  [2, 2, 0],
                  [0, 0, 2],
                  [0, 0, 1]])
    y = np.array([4, 4, 5, 5, 1, 1])
    cls = neighbors.KNeighborsClassifier(n_neighbors=3, p=1)  # cityblock dist
    cls.fit(X, y)
    y_prob = cls.predict_proba(X)
    real_prob = np.array([[0, 2. / 3, 1. / 3],
                          [1. / 3, 2. / 3, 0],
                          [1. / 3, 0, 2. / 3],
                          [0, 1. / 3, 2. / 3],
                          [2. / 3, 1. / 3, 0],
                          [2. / 3, 1. / 3, 0]])
    assert_array_equal(real_prob, y_prob)
    # Check that it also works with non integer labels
    cls.fit(X, y.astype(str))
    y_prob = cls.predict_proba(X)
    assert_array_equal(real_prob, y_prob)
    # Check that it works with weights='distance'
    cls = neighbors.KNeighborsClassifier(
        n_neighbors=2, p=1, weights='distance')
    cls.fit(X, y)
    y_prob = cls.predict_proba(np.array([[0, 2, 0], [2, 2, 2]]))
    real_prob = np.array([[0, 1, 0], [0, 0.4, 0.6]])
    assert_array_almost_equal(real_prob, y_prob)

def test_radius_neighbors_classifier(n_samples=40,
                                     n_features=5,
                                     n_test_pts=10,
                                     radius=0.5,
                                     random_state=0):
    # Test radius-based classification
    rng = np.random.RandomState(random_state)
    X = 2 * rng.rand(n_samples, n_features) - 1
    y = ((X ** 2).sum(axis=1) < .5).astype(np.int)
    y_str = y.astype(str)

    weight_func = _weight_func

    for algorithm in ALGORITHMS:
        for weights in ['uniform', 'distance', weight_func]:
            neigh = neighbors.RadiusNeighborsClassifier(radius=radius,
                                                        weights=weights,
                                                        algorithm=algorithm)
            neigh.fit(X, y)
            epsilon = 1e-5 * (2 * rng.rand(1, n_features) - 1)
            y_pred = neigh.predict(X[:n_test_pts] + epsilon)
            assert_array_equal(y_pred, y[:n_test_pts])
            neigh.fit(X, y_str)
            y_pred = neigh.predict(X[:n_test_pts] + epsilon)
            assert_array_equal(y_pred, y_str[:n_test_pts])

def test_radius_neighbors_classifier_when_no_neighbors():
    # Test radius-based classifier when no neighbors found.
    # In this case it should rise an informative exception

    X = np.array([[1.0, 1.0], [2.0, 2.0]])
    y = np.array([1, 2])
    radius = 0.1

    z1 = np.array([[1.01, 1.01], [2.01, 2.01]])  # no outliers
    z2 = np.array([[1.01, 1.01], [1.4, 1.4]])  # one outlier

    weight_func = _weight_func

    for outlier_label in [0, -1, None]:
        for algorithm in ALGORITHMS:
            for weights in ['uniform', 'distance', weight_func]:
                rnc = neighbors.RadiusNeighborsClassifier
                clf = rnc(radius=radius, weights=weights, algorithm=algorithm,
                          outlier_label=outlier_label)
                clf.fit(X, y)
                assert_array_equal(np.array([1, 2]),
                                   clf.predict(z1))
                if outlier_label is None:
                    assert_raises(ValueError, clf.predict, z2)
                elif False:
                    assert_array_equal(np.array([1, outlier_label]),
                                       clf.predict(z2))

def test_radius_neighbors_classifier_outlier_labeling():
    # Test radius-based classifier when no neighbors found and outliers
    # are labeled.

    X = np.array([[1.0, 1.0], [2.0, 2.0]])
    y = np.array([1, 2])
    radius = 0.1

    z1 = np.array([[1.01, 1.01], [2.01, 2.01]])  # no outliers
    z2 = np.array([[1.01, 1.01], [1.4, 1.4]])  # one outlier
    correct_labels1 = np.array([1, 2])
    correct_labels2 = np.array([1, -1])

    weight_func = _weight_func

    for algorithm in ALGORITHMS:
        for weights in ['uniform', 'distance', weight_func]:
            clf = neighbors.RadiusNeighborsClassifier(radius=radius,
                                                      weights=weights,
                                                      algorithm=algorithm,
                                                      outlier_label=-1)
            clf.fit(X, y)
            assert_array_equal(correct_labels1, clf.predict(z1))
            assert_array_equal(correct_labels2, clf.predict(z2))

def test_radius_neighbors_classifier_zero_distance():
    # Test radius-based classifier, when distance to a sample is zero.

    X = np.array([[1.0, 1.0], [2.0, 2.0]])
    y = np.array([1, 2])
    radius = 0.1

    z1 = np.array([[1.01, 1.01], [2.0, 2.0]])
    correct_labels1 = np.array([1, 2])

    weight_func = _weight_func

    for algorithm in ALGORITHMS:
        for weights in ['uniform', 'distance', weight_func]:
            clf = neighbors.RadiusNeighborsClassifier(radius=radius,
                                                      weights=weights,
                                                      algorithm=algorithm)
            clf.fit(X, y)
            assert_array_equal(correct_labels1, clf.predict(z1))

def test_neighbors_regressors_zero_distance():
    # Test radius-based regressor, when distance to a sample is zero.

    X = np.array([[1.0, 1.0], [1.0, 1.0], [2.0, 2.0], [2.5, 2.5]])
    y = np.array([1.0, 1.5, 2.0, 0.0])
    radius = 0.2
    z = np.array([[1.1, 1.1], [2.0, 2.0]])

    rnn_correct_labels = np.array([1.25, 2.0])

    knn_correct_unif = np.array([1.25, 1.0])
    knn_correct_dist = np.array([1.25, 2.0])

    for algorithm in ALGORITHMS:
        # we don't test for weights=_weight_func since user will be expected
        # to handle zero distances themselves in the function.
        for weights in ['uniform', 'distance']:
            rnn = neighbors.RadiusNeighborsRegressor(radius=radius,
                                                     weights=weights,
                                                     algorithm=algorithm)
            rnn.fit(X, y)
            assert_array_almost_equal(rnn_correct_labels, rnn.predict(z))

        for weights, corr_labels in zip(['uniform', 'distance'],
                                        [knn_correct_unif, knn_correct_dist]):
            knn = neighbors.KNeighborsRegressor(n_neighbors=2,
                                                weights=weights,
                                                algorithm=algorithm)
            knn.fit(X, y)
            assert_array_almost_equal(corr_labels, knn.predict(z))

def test_radius_neighbors_boundary_handling():
    """Test whether points lying on boundary are handled consistently

    Also ensures that even with only one query point, an object array
    is returned rather than a 2d array.
    """

    X = np.array([[1.5], [3.0], [3.01]])
    radius = 3.0

    for algorithm in ALGORITHMS:
        nbrs = neighbors.NearestNeighbors(radius=radius,
                                          algorithm=algorithm).fit(X)
        results = nbrs.radius_neighbors([[0.0]], return_distance=False)
        assert_equal(results.shape, (1,))
        assert_equal(results.dtype, object)
        assert_array_equal(results[0], [0, 1])

def test_RadiusNeighborsClassifier_multioutput():
    # Test k-NN classifier on multioutput data
    rng = check_random_state(0)
    n_features = 2
    n_samples = 40
    n_output = 3

    X = rng.rand(n_samples, n_features)
    y = rng.randint(0, 3, (n_samples, n_output))

    X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)

    weights = [None, 'uniform', 'distance', _weight_func]

    for algorithm, weights in product(ALGORITHMS, weights):
        # Stack single output prediction
        y_pred_so = []
        for o in range(n_output):
            rnn = neighbors.RadiusNeighborsClassifier(weights=weights,
                                                      algorithm=algorithm)
            rnn.fit(X_train, y_train[:, o])
            y_pred_so.append(rnn.predict(X_test))

        y_pred_so = np.vstack(y_pred_so).T
        assert_equal(y_pred_so.shape, y_test.shape)

        # Multioutput prediction
        rnn_mo = neighbors.RadiusNeighborsClassifier(weights=weights,
                                                     algorithm=algorithm)
        rnn_mo.fit(X_train, y_train)
        y_pred_mo = rnn_mo.predict(X_test)

        assert_equal(y_pred_mo.shape, y_test.shape)
        assert_array_almost_equal(y_pred_mo, y_pred_so)

def test_kneighbors_classifier_sparse(n_samples=40,
                                      n_features=5,
                                      n_test_pts=10,
                                      n_neighbors=5,
                                      random_state=0):
    # Test k-NN classifier on sparse matrices
    # Like the above, but with various types of sparse matrices
    rng = np.random.RandomState(random_state)
    X = 2 * rng.rand(n_samples, n_features) - 1
    X *= X > .2
    y = ((X ** 2).sum(axis=1) < .5).astype(np.int)

    for sparsemat in SPARSE_TYPES:
        knn = neighbors.KNeighborsClassifier(n_neighbors=n_neighbors,
                                             algorithm='auto')
        knn.fit(sparsemat(X), y)
        epsilon = 1e-5 * (2 * rng.rand(1, n_features) - 1)
        for sparsev in SPARSE_TYPES + (np.asarray,):
            X_eps = sparsev(X[:n_test_pts] + epsilon)
            y_pred = knn.predict(X_eps)
            assert_array_equal(y_pred, y[:n_test_pts])

def test_KNeighborsClassifier_multioutput():
    # Test k-NN classifier on multioutput data
    rng = check_random_state(0)
    n_features = 5
    n_samples = 50
    n_output = 3

    X = rng.rand(n_samples, n_features)
    y = rng.randint(0, 3, (n_samples, n_output))

    X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)

    weights = [None, 'uniform', 'distance', _weight_func]

    for algorithm, weights in product(ALGORITHMS, weights):
        # Stack single output prediction
        y_pred_so = []
        y_pred_proba_so = []
        for o in range(n_output):
            knn = neighbors.KNeighborsClassifier(weights=weights,
                                                 algorithm=algorithm)
            knn.fit(X_train, y_train[:, o])
            y_pred_so.append(knn.predict(X_test))
            y_pred_proba_so.append(knn.predict_proba(X_test))

        y_pred_so = np.vstack(y_pred_so).T
        assert_equal(y_pred_so.shape, y_test.shape)
        assert_equal(len(y_pred_proba_so), n_output)

        # Multioutput prediction
        knn_mo = neighbors.KNeighborsClassifier(weights=weights,
                                                algorithm=algorithm)
        knn_mo.fit(X_train, y_train)
        y_pred_mo = knn_mo.predict(X_test)

        assert_equal(y_pred_mo.shape, y_test.shape)
        assert_array_almost_equal(y_pred_mo, y_pred_so)

        # Check proba
        y_pred_proba_mo = knn_mo.predict_proba(X_test)
        assert_equal(len(y_pred_proba_mo), n_output)

        for proba_mo, proba_so in zip(y_pred_proba_mo, y_pred_proba_so):
            assert_array_almost_equal(proba_mo, proba_so)

def test_kneighbors_regressor(n_samples=40,
                              n_features=5,
                              n_test_pts=10,
                              n_neighbors=3,
                              random_state=0):
    # Test k-neighbors regression
    rng = np.random.RandomState(random_state)
    X = 2 * rng.rand(n_samples, n_features) - 1
    y = np.sqrt((X ** 2).sum(1))
    y /= y.max()

    y_target = y[:n_test_pts]

    weight_func = _weight_func

    for algorithm in ALGORITHMS:
        for weights in ['uniform', 'distance', weight_func]:
            knn = neighbors.KNeighborsRegressor(n_neighbors=n_neighbors,
                                                weights=weights,
                                                algorithm=algorithm)
            knn.fit(X, y)
            epsilon = 1E-5 * (2 * rng.rand(1, n_features) - 1)
            y_pred = knn.predict(X[:n_test_pts] + epsilon)
            assert_true(np.all(abs(y_pred - y_target) < 0.3))

def test_KNeighborsRegressor_multioutput_uniform_weight():
    # Test k-neighbors in multi-output regression with uniform weight
    rng = check_random_state(0)
    n_features = 5
    n_samples = 40
    n_output = 4

    X = rng.rand(n_samples, n_features)
    y = rng.rand(n_samples, n_output)

    X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
    for algorithm, weights in product(ALGORITHMS, [None, 'uniform']):
        knn = neighbors.KNeighborsRegressor(weights=weights,
                                            algorithm=algorithm)
        knn.fit(X_train, y_train)

        neigh_idx = knn.kneighbors(X_test, return_distance=False)
        y_pred_idx = np.array([np.mean(y_train[idx], axis=0)
                               for idx in neigh_idx])

        y_pred = knn.predict(X_test)

        assert_equal(y_pred.shape, y_test.shape)
        assert_equal(y_pred_idx.shape, y_test.shape)
        assert_array_almost_equal(y_pred, y_pred_idx)

def test_kneighbors_regressor_multioutput(n_samples=40,
                                          n_features=5,
                                          n_test_pts=10,
                                          n_neighbors=3,
                                          random_state=0):
    # Test k-neighbors in multi-output regression
    rng = np.random.RandomState(random_state)
    X = 2 * rng.rand(n_samples, n_features) - 1
    y = np.sqrt((X ** 2).sum(1))
    y /= y.max()
    y = np.vstack([y, y]).T

    y_target = y[:n_test_pts]

    weights = ['uniform', 'distance', _weight_func]
    for algorithm, weights in product(ALGORITHMS, weights):
        knn = neighbors.KNeighborsRegressor(n_neighbors=n_neighbors,
                                            weights=weights,
                                            algorithm=algorithm)
        knn.fit(X, y)
        epsilon = 1E-5 * (2 * rng.rand(1, n_features) - 1)
        y_pred = knn.predict(X[:n_test_pts] + epsilon)
        assert_equal(y_pred.shape, y_target.shape)

        assert_true(np.all(np.abs(y_pred - y_target) < 0.3))

def test_radius_neighbors_regressor(n_samples=40,
                                    n_features=3,
                                    n_test_pts=10,
                                    radius=0.5,
                                    random_state=0):
    # Test radius-based neighbors regression
    rng = np.random.RandomState(random_state)
    X = 2 * rng.rand(n_samples, n_features) - 1
    y = np.sqrt((X ** 2).sum(1))
    y /= y.max()

    y_target = y[:n_test_pts]

    weight_func = _weight_func

    for algorithm in ALGORITHMS:
        for weights in ['uniform', 'distance', weight_func]:
            neigh = neighbors.RadiusNeighborsRegressor(radius=radius,
                                                       weights=weights,
                                                       algorithm=algorithm)
            neigh.fit(X, y)
            epsilon = 1E-5 * (2 * rng.rand(1, n_features) - 1)
            y_pred = neigh.predict(X[:n_test_pts] + epsilon)
            assert_true(np.all(abs(y_pred - y_target) < radius / 2))

def test_RadiusNeighborsRegressor_multioutput_with_uniform_weight():
    # Test radius neighbors in multi-output regression (uniform weight)

    rng = check_random_state(0)
    n_features = 5
    n_samples = 40
    n_output = 4

    X = rng.rand(n_samples, n_features)
    y = rng.rand(n_samples, n_output)
    X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)

    for algorithm, weights in product(ALGORITHMS, [None, 'uniform']):
        rnn = neighbors.RadiusNeighborsRegressor(weights=weights,
                                                 algorithm=algorithm)
        rnn.fit(X_train, y_train)

        neigh_idx = rnn.radius_neighbors(X_test, return_distance=False)
        y_pred_idx = np.array([np.mean(y_train[idx], axis=0)
                               for idx in neigh_idx])

        y_pred_idx = np.array(y_pred_idx)
        y_pred = rnn.predict(X_test)

        assert_equal(y_pred_idx.shape, y_test.shape)
        assert_equal(y_pred.shape, y_test.shape)
        assert_array_almost_equal(y_pred, y_pred_idx)

def test_RadiusNeighborsRegressor_multioutput(n_samples=40,
                                              n_features=5,
                                              n_test_pts=10,
                                              n_neighbors=3,
                                              random_state=0):
    # Test k-neighbors in multi-output regression with various weight
    rng = np.random.RandomState(random_state)
    X = 2 * rng.rand(n_samples, n_features) - 1
    y = np.sqrt((X ** 2).sum(1))
    y /= y.max()
    y = np.vstack([y, y]).T

    y_target = y[:n_test_pts]
    weights = ['uniform', 'distance', _weight_func]

    for algorithm, weights in product(ALGORITHMS, weights):
        rnn = neighbors.RadiusNeighborsRegressor(n_neighbors=n_neighbors,
                                                 weights=weights,
                                                 algorithm=algorithm)
        rnn.fit(X, y)
        epsilon = 1E-5 * (2 * rng.rand(1, n_features) - 1)
        y_pred = rnn.predict(X[:n_test_pts] + epsilon)

        assert_equal(y_pred.shape, y_target.shape)
        assert_true(np.all(np.abs(y_pred - y_target) < 0.3))

def test_kneighbors_regressor_sparse(n_samples=40,
                                     n_features=5,
                                     n_test_pts=10,
                                     n_neighbors=5,
                                     random_state=0):
    # Test radius-based regression on sparse matrices
    # Like the above, but with various types of sparse matrices
    rng = np.random.RandomState(random_state)
    X = 2 * rng.rand(n_samples, n_features) - 1
    y = ((X ** 2).sum(axis=1) < .25).astype(np.int)

    for sparsemat in SPARSE_TYPES:
        knn = neighbors.KNeighborsRegressor(n_neighbors=n_neighbors,
                                            algorithm='auto')
        knn.fit(sparsemat(X), y)
        for sparsev in SPARSE_OR_DENSE:
            X2 = sparsev(X)
            assert_true(np.mean(knn.predict(X2).round() == y) > 0.95)

def test_neighbors_iris():
    # Sanity checks on the iris dataset
    # Puts three points of each label in the plane and performs a
    # nearest neighbor query on points near the decision boundary.

    for algorithm in ALGORITHMS:
        clf = neighbors.KNeighborsClassifier(n_neighbors=1,
                                             algorithm=algorithm)
        clf.fit(iris.data, iris.target)
        assert_array_equal(clf.predict(iris.data), iris.target)

        clf.set_params(n_neighbors=9, algorithm=algorithm)
        clf.fit(iris.data, iris.target)
        assert_true(np.mean(clf.predict(iris.data) == iris.target) > 0.95)

        rgs = neighbors.KNeighborsRegressor(n_neighbors=5, algorithm=algorithm)
        rgs.fit(iris.data, iris.target)
        assert_greater(np.mean(rgs.predict(iris.data).round() == iris.target),
                       0.95)

def test_neighbors_digits():
    # Sanity check on the digits dataset
    # the 'brute' algorithm has been observed to fail if the input
    # dtype is uint8 due to overflow in distance calculations.

    X = digits.data.astype('uint8')
    Y = digits.target
    (n_samples, n_features) = X.shape
    train_test_boundary = int(n_samples * 0.8)
    train = np.arange(0, train_test_boundary)
    test = np.arange(train_test_boundary, n_samples)
    (X_train, Y_train, X_test, Y_test) = X[train], Y[train], X[test], Y[test]

    clf = neighbors.KNeighborsClassifier(n_neighbors=1, algorithm='brute')
    score_uint8 = clf.fit(X_train, Y_train).score(X_test, Y_test)
    score_float = clf.fit(X_train.astype(float), Y_train).score(
        X_test.astype(float), Y_test)
    assert_equal(score_uint8, score_float)

def test_kneighbors_graph():
    # Test kneighbors_graph to build the k-Nearest Neighbor graph.
    X = np.array([[0, 1], [1.01, 1.], [2, 0]])

    # n_neighbors = 1
    A = neighbors.kneighbors_graph(X, 1, mode='connectivity',
                                   include_self=True)
    assert_array_equal(A.toarray(), np.eye(A.shape[0]))

    A = neighbors.kneighbors_graph(X, 1, mode='distance')
    assert_array_almost_equal(
        A.toarray(),
        [[0.00, 1.01, 0.],
         [1.01, 0., 0.],
         [0.00, 1.40716026, 0.]])

    # n_neighbors = 2
    A = neighbors.kneighbors_graph(X, 2, mode='connectivity',
                                   include_self=True)
    assert_array_equal(
        A.toarray(),
        [[1., 1., 0.],
         [1., 1., 0.],
         [0., 1., 1.]])

    A = neighbors.kneighbors_graph(X, 2, mode='distance')
    assert_array_almost_equal(
        A.toarray(),
        [[0., 1.01, 2.23606798],
         [1.01, 0., 1.40716026],
         [2.23606798, 1.40716026, 0.]])

    # n_neighbors = 3
    A = neighbors.kneighbors_graph(X, 3, mode='connectivity',
                                   include_self=True)
    assert_array_almost_equal(
        A.toarray(),
        [[1, 1, 1], [1, 1, 1], [1, 1, 1]])

def test_kneighbors_graph_sparse(seed=36):
    # Test kneighbors_graph to build the k-Nearest Neighbor graph
    # for sparse input.
    rng = np.random.RandomState(seed)
    X = rng.randn(10, 10)
    Xcsr = csr_matrix(X)

    for n_neighbors in [1, 2, 3]:
        for mode in ["connectivity", "distance"]:
            assert_array_almost_equal(
                neighbors.kneighbors_graph(X,
                                           n_neighbors,
                                           mode=mode).toarray(),
                neighbors.kneighbors_graph(Xcsr,
                                           n_neighbors,
                                           mode=mode).toarray())

def test_radius_neighbors_graph():
    # Test radius_neighbors_graph to build the Nearest Neighbor graph.
    X = np.array([[0, 1], [1.01, 1.], [2, 0]])

    A = neighbors.radius_neighbors_graph(X, 1.5, mode='connectivity',
                                         include_self=True)
    assert_array_equal(
        A.toarray(),
        [[1., 1., 0.],
         [1., 1., 1.],
         [0., 1., 1.]])

    A = neighbors.radius_neighbors_graph(X, 1.5, mode='distance')
    assert_array_almost_equal(
        A.toarray(),
        [[0., 1.01, 0.],
         [1.01, 0., 1.40716026],
         [0., 1.40716026, 0.]])

def test_radius_neighbors_graph_sparse(seed=36):
    # Test radius_neighbors_graph to build the Nearest Neighbor graph
    # for sparse input.
    rng = np.random.RandomState(seed)
    X = rng.randn(10, 10)
    Xcsr = csr_matrix(X)

    for n_neighbors in [1, 2, 3]:
        for mode in ["connectivity", "distance"]:
            assert_array_almost_equal(
                neighbors.radius_neighbors_graph(X,
                                                 n_neighbors,
                                                 mode=mode).toarray(),
                neighbors.radius_neighbors_graph(Xcsr,
                                                 n_neighbors,
                                                 mode=mode).toarray())

def test_neighbors_badargs():
    # Test bad argument values: these should all raise ValueErrors
    assert_raises(ValueError,
                  neighbors.NearestNeighbors,
                  algorithm='blah')

    X = rng.random_sample((10, 2))
    Xsparse = csr_matrix(X)
    y = np.ones(10)

    for cls in (neighbors.KNeighborsClassifier,
                neighbors.RadiusNeighborsClassifier,
                neighbors.KNeighborsRegressor,
                neighbors.RadiusNeighborsRegressor):
        assert_raises(ValueError,
                      cls,
                      weights='blah')
        assert_raises(ValueError,
                      cls, p=-1)
        assert_raises(ValueError,
                      cls, algorithm='blah')
        nbrs = cls(algorithm='ball_tree', metric='haversine')
        assert_raises(ValueError,
                      nbrs.predict,
                      X)
        assert_raises(ValueError,
                      ignore_warnings(nbrs.fit),
                      Xsparse, y)
        nbrs = cls()
        assert_raises(ValueError,
                      nbrs.fit,
                      np.ones((0, 2)), np.ones(0))
        assert_raises(ValueError,
                      nbrs.fit,
                      X[:, :, None], y)
        nbrs.fit(X, y)
        assert_raises(ValueError,
                      nbrs.predict,
                      [[]])
        if (isinstance(cls, neighbors.KNeighborsClassifier) or
                isinstance(cls, neighbors.KNeighborsRegressor)):
            nbrs = cls(n_neighbors=-1)
            assert_raises(ValueError, nbrs.fit, X, y)

    nbrs = neighbors.NearestNeighbors().fit(X)

    assert_raises(ValueError, nbrs.kneighbors_graph, X, mode='blah')
    assert_raises(ValueError, nbrs.radius_neighbors_graph, X, mode='blah')

def test_neighbors_metrics(n_samples=20, n_features=3,
                           n_query_pts=2, n_neighbors=5):
    # Test computing the neighbors for various metrics
    # create a symmetric matrix
    V = rng.rand(n_features, n_features)
    VI = np.dot(V, V.T)

    metrics = [('euclidean', {}),
               ('manhattan', {}),
               ('minkowski', dict(p=1)),
               ('minkowski', dict(p=2)),
               ('minkowski', dict(p=3)),
               ('minkowski', dict(p=np.inf)),
               ('chebyshev', {}),
               ('seuclidean', dict(V=rng.rand(n_features))),
               ('wminkowski', dict(p=3, w=rng.rand(n_features))),
               ('mahalanobis', dict(VI=VI))]
    algorithms = ['brute', 'ball_tree', 'kd_tree']
    X = rng.rand(n_samples, n_features)

    test = rng.rand(n_query_pts, n_features)

    for metric, metric_params in metrics:
        results = []
        p = metric_params.pop('p', 2)
        for algorithm in algorithms:
            # KD tree doesn't support all metrics
            if (algorithm == 'kd_tree' and
                        metric not in neighbors.KDTree.valid_metrics):
                assert_raises(ValueError,
                              neighbors.NearestNeighbors,
                              algorithm=algorithm,
                              metric=metric, metric_params=metric_params)
                continue

            neigh = neighbors.NearestNeighbors(n_neighbors=n_neighbors,
                                               algorithm=algorithm,
                                               metric=metric, p=p,
                                               metric_params=metric_params)
            neigh.fit(X)
            results.append(neigh.kneighbors(test, return_distance=True))

        assert_array_almost_equal(results[0][0], results[1][0])
        assert_array_almost_equal(results[0][1], results[1][1])

def test_callable_metric():
    def custom_metric(x1, x2):
        return np.sqrt(np.sum(x1 ** 2 + x2 ** 2))

    X = np.random.RandomState(42).rand(20, 2)
    nbrs1 = neighbors.NearestNeighbors(3, algorithm='auto',
                                       metric=custom_metric)
    nbrs2 = neighbors.NearestNeighbors(3, algorithm='brute',
                                       metric=custom_metric)

    nbrs1.fit(X)
    nbrs2.fit(X)

    dist1, ind1 = nbrs1.kneighbors(X)
    dist2, ind2 = nbrs2.kneighbors(X)

    assert_array_almost_equal(dist1, dist2)

def test_metric_params_interface():
    assert_warns(SyntaxWarning, neighbors.KNeighborsClassifier,
                 metric_params={'p': 3})

def test_predict_sparse_ball_kd_tree():
    rng = np.random.RandomState(0)
    X = rng.rand(5, 5)
    y = rng.randint(0, 2, 5)
    nbrs1 = neighbors.KNeighborsClassifier(1, algorithm='kd_tree')
    nbrs2 = neighbors.KNeighborsRegressor(1, algorithm='ball_tree')
    for model in [nbrs1, nbrs2]:
        model.fit(X, y)
        assert_raises(ValueError, model.predict, csr_matrix(X))

def test_non_euclidean_kneighbors():
    rng = np.random.RandomState(0)
    X = rng.rand(5, 5)

    # Find a reasonable radius.
    dist_array = pairwise_distances(X).flatten()
    np.sort(dist_array)
    radius = dist_array[15]

    # Test kneighbors_graph
    for metric in ['manhattan', 'chebyshev']:
        nbrs_graph = neighbors.kneighbors_graph(
            X, 3, metric=metric, mode='connectivity',
            include_self=True).toarray()
        nbrs1 = neighbors.NearestNeighbors(3, metric=metric).fit(X)
        assert_array_equal(nbrs_graph, nbrs1.kneighbors_graph(X).toarray())

    # Test radiusneighbors_graph
    for metric in ['manhattan', 'chebyshev']:
        nbrs_graph = neighbors.radius_neighbors_graph(
            X, radius, metric=metric, mode='connectivity',
            include_self=True).toarray()
        nbrs1 = neighbors.NearestNeighbors(metric=metric, radius=radius).fit(X)
        assert_array_equal(nbrs_graph, nbrs1.radius_neighbors_graph(X).A)

    # Raise error when wrong parameters are supplied,
    X_nbrs = neighbors.NearestNeighbors(3, metric='manhattan')
    X_nbrs.fit(X)
    assert_raises(ValueError, neighbors.kneighbors_graph, X_nbrs, 3,
                  metric='euclidean')
    X_nbrs = neighbors.NearestNeighbors(radius=radius, metric='manhattan')
    X_nbrs.fit(X)
    assert_raises(ValueError, neighbors.radius_neighbors_graph, X_nbrs,
                  radius, metric='euclidean')

def check_object_arrays(nparray, list_check):
    for ind, ele in enumerate(nparray):
        assert_array_equal(ele, list_check[ind])

def test_k_and_radius_neighbors_train_is_not_query():
    # Test kneighbors et.al when query is not training data

    for algorithm in ALGORITHMS:
        nn = neighbors.NearestNeighbors(n_neighbors=1, algorithm=algorithm)

        X = [[0], [1]]
        nn.fit(X)
        test_data = [[2], [1]]

        # Test neighbors.
        dist, ind = nn.kneighbors(test_data)
        assert_array_equal(dist, [[1], [0]])
        assert_array_equal(ind, [[1], [1]])
        dist, ind = nn.radius_neighbors([[2], [1]], radius=1.5)
        check_object_arrays(dist, [[1], [1, 0]])
        check_object_arrays(ind, [[1], [0, 1]])

        # Test the graph variants.
        assert_array_equal(
            nn.kneighbors_graph(test_data).A, [[0., 1.], [0., 1.]])
        assert_array_equal(
            nn.kneighbors_graph([[2], [1]], mode='distance').A,
            np.array([[0., 1.], [0., 0.]]))
        rng = nn.radius_neighbors_graph([[2], [1]], radius=1.5)
        assert_array_equal(rng.A, [[0, 1], [1, 1]])

def test_k_and_radius_neighbors_X_None():
    # Test kneighbors et.al when query is None
    for algorithm in ALGORITHMS:

        nn = neighbors.NearestNeighbors(n_neighbors=1, algorithm=algorithm)

        X = [[0], [1]]
        nn.fit(X)

        dist, ind = nn.kneighbors()
        assert_array_equal(dist, [[1], [1]])
        assert_array_equal(ind, [[1], [0]])
        dist, ind = nn.radius_neighbors(None, radius=1.5)
        check_object_arrays(dist, [[1], [1]])
        check_object_arrays(ind, [[1], [0]])

        # Test the graph variants.
        rng = nn.radius_neighbors_graph(None, radius=1.5)
        kng = nn.kneighbors_graph(None)
        for graph in [rng, kng]:
            assert_array_equal(rng.A, [[0, 1], [1, 0]])
            assert_array_equal(rng.data, [1, 1])
            assert_array_equal(rng.indices, [1, 0])

        X = [[0, 1], [0, 1], [1, 1]]
        nn = neighbors.NearestNeighbors(n_neighbors=2, algorithm=algorithm)
        nn.fit(X)
        assert_array_equal(
            nn.kneighbors_graph().A,
            np.array([[0., 1., 1.], [1., 0., 1.], [1., 1., 0]]))

def test_k_and_radius_neighbors_duplicates():
    # Test behavior of kneighbors when duplicates are present in query

    for algorithm in ALGORITHMS:
        nn = neighbors.NearestNeighbors(n_neighbors=1, algorithm=algorithm)
        nn.fit([[0], [1]])

        # Do not do anything special to duplicates.
        kng = nn.kneighbors_graph([[0], [1]], mode='distance')
        assert_array_equal(
            kng.A,
            np.array([[0., 0.], [0., 0.]]))
        assert_array_equal(kng.data, [0., 0.])
        assert_array_equal(kng.indices, [0, 1])

        dist, ind = nn.radius_neighbors([[0], [1]], radius=1.5)
        check_object_arrays(dist, [[0, 1], [1, 0]])
        check_object_arrays(ind, [[0, 1], [0, 1]])

        rng = nn.radius_neighbors_graph([[0], [1]], radius=1.5)
        assert_array_equal(rng.A, np.ones((2, 2)))

        rng = nn.radius_neighbors_graph([[0], [1]], radius=1.5,
                                        mode='distance')
        assert_array_equal(rng.A, [[0, 1], [1, 0]])
        assert_array_equal(rng.indices, [0, 1, 0, 1])
        assert_array_equal(rng.data, [0, 1, 1, 0])

        # Mask the first duplicates when n_duplicates > n_neighbors.
        X = np.ones((3, 1))
        nn = neighbors.NearestNeighbors(n_neighbors=1)
        nn.fit(X)
        dist, ind = nn.kneighbors()
        assert_array_equal(dist, np.zeros((3, 1)))
        assert_array_equal(ind, [[1], [0], [1]])

        # Test that zeros are explicitly marked in kneighbors_graph.
        kng = nn.kneighbors_graph(mode='distance')
        assert_array_equal(
            kng.A, np.zeros((3, 3)))
        assert_array_equal(kng.data, np.zeros(3))
        assert_array_equal(kng.indices, [1., 0., 1.])
        assert_array_equal(
            nn.kneighbors_graph().A,
            np.array([[0., 1., 0.], [1., 0., 0.], [0., 1., 0.]]))

def test_include_self_neighbors_graph():
    # Test include_self parameter in neighbors_graph
    X = [[2, 3], [4, 5]]
    kng = neighbors.kneighbors_graph(X, 1, include_self=True).A
    kng_not_self = neighbors.kneighbors_graph(X, 1, include_self=False).A
    assert_array_equal(kng, [[1., 0.], [0., 1.]])
    assert_array_equal(kng_not_self, [[0., 1.], [1., 0.]])

    rng = neighbors.radius_neighbors_graph(X, 5.0, include_self=True).A
    rng_not_self = neighbors.radius_neighbors_graph(
        X, 5.0, include_self=False).A
    assert_array_equal(rng, [[1., 1.], [1., 1.]])
    assert_array_equal(rng_not_self, [[0., 1.], [1., 0.]])

def test_same_knn_parallel():
    X, y = datasets.make_classification(n_samples=30, n_features=5,
                                        n_redundant=0, random_state=0)
    X_train, X_test, y_train, y_test = train_test_split(X, y)

    def check_same_knn_parallel(algorithm):
        clf = neighbors.KNeighborsClassifier(n_neighbors=3,
                                             algorithm=algorithm)
        clf.fit(X_train, y_train)
        y = clf.predict(X_test)
        dist, ind = clf.kneighbors(X_test)
        graph = clf.kneighbors_graph(X_test, mode='distance').toarray()

        clf.set_params(n_jobs=3)
        clf.fit(X_train, y_train)
        y_parallel = clf.predict(X_test)
        dist_parallel, ind_parallel = clf.kneighbors(X_test)
        graph_parallel = \
            clf.kneighbors_graph(X_test, mode='distance').toarray()

        assert_array_equal(y, y_parallel)
        assert_array_almost_equal(dist, dist_parallel)
        assert_array_equal(ind, ind_parallel)
        assert_array_almost_equal(graph, graph_parallel)

    for algorithm in ALGORITHMS:
        yield check_same_knn_parallel, algorithm

def test_dtype_convert():
    classifier = neighbors.KNeighborsClassifier(n_neighbors=1)
    CLASSES = 15
    X = np.eye(CLASSES)
    y = [ch for ch in 'ABCDEFGHIJKLMNOPQRSTU'[:CLASSES]]

    result = classifier.fit(X, y).predict(X)
    assert_array_equal(result, y)


text:
"""This is "__init__.py" file of tests for maildaemon."""

import logging

from maildaemon._logging import configure_logging

configure_logging()
logging.getLogger().setLevel(logging.DEBUG)

redpajama_set_name: RedPajamaGithub


text:
{{extraction.mention_text}}

    in sentence {{extraction.sentence_index}}
    in article({{extraction.doc_id}}):

    <mindtagger-highlight-words from="extraction.begin_index" to="extraction.end_index" with-style="background-color: yellow;"/>


text:
package org.axonframework.serialization;

import org.axonframework.common.AxonConfigurationException;

/**
 * Exception indicating that a conversion is required between to upcasters, but there is no converter capable of doing
 * the conversion.
 *
 * @author Allard Buijze
 * @since 2.0
 */
public class CannotConvertBetweenTypesException extends AxonConfigurationException {

    private static final long serialVersionUID = 2707247238103378855L;

    /**
     * Initializes the exception with the given {@code message}.
     *
     * @param message The message describing the problem
     */
    public CannotConvertBetweenTypesException(String message) {
        super(message);
    }

    /**
     * Initializing the exception with given {@code message} and {@code cause}.
     *
     * @param message The message describing the problem
     * @param cause   The original cause of the exception
     */
    public CannotConvertBetweenTypesException(String message, Throwable cause) {
        super(message, cause);
    }
}


text:
package endpoints.algebra

import scala.language.higherKinds

trait Responses {

  /** Information carried by a response */
  type Response[A]

  /**
    * Empty response.
    */
  def emptyResponse: Response[Unit]

  /**
    * Text response.
    */
  def textResponse: Response[String]

}


text:
<tool id="EMBOSS: wordcount109" name="wordcount">
  <description>Counts words of a specified size in a DNA sequence</description>
  <command>wordcount -sequence $input1 -outfile $out_file1 -wordsize "$wordsize" -auto</command>
  <inputs>
    <param format="data" name="input1" type="data">
      Sequence
    </param>
    <param name="wordsize" size="5" type="text" value="4">
      Word size
    </param>
  </inputs>
  <outputs>
    <data format="txt" name="out_file1" />
  </outputs>
  <help>
    You can view the original documentation here_.

    .. _here: http://emboss.sourceforge.net/apps/wordcount.html
  </help>
</tool>


text:
using System.Text.Json;
using Azure.Core;

namespace Azure.ResourceManager.ContainerService.Models
{
    internal partial class ManagedClusterPodIdentityProvisioningInfo
    {
        internal static ManagedClusterPodIdentityProvisioningInfo DeserializeManagedClusterPodIdentityProvisioningInfo(JsonElement element)
        {
            Optional<ManagedClusterPodIdentityProvisioningError> error = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("error"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    error = ManagedClusterPodIdentityProvisioningError.DeserializeManagedClusterPodIdentityProvisioningError(property.Value);
                    continue;
                }
            }
            return new ManagedClusterPodIdentityProvisioningInfo(error.Value);
        }
    }
}


text:
package gwt.material.design.incubator.client.password;

import com.google.gwt.core.client.GWT;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.TextResource;

public interface PasswordStrengthTextBoxDebugClientBundle extends ClientBundle {
    PasswordStrengthTextBoxDebugClientBundle INSTANCE = GWT.create(PasswordStrengthTextBoxDebugClientBundle.class);

    @Source("resources/css/pwd-strength-meter.css")
    TextResource pwdStrengthMeterDebugCss();

    @Source("resources/js/pwd-strength-meter.js")
    TextResource pwdStrengthMeterDebugJs();
}


text:
<?php

declare(strict_types=1);

namespace Sylius\Bundle\ApiBundle\ApiPlatform\Bridge\Symfony\Bundle\Action;

use ApiPlatform\Core\Api\FormatsProviderInterface;
use ApiPlatform\Core\Documentation\Documentation;
use ApiPlatform\Core\Exception\RuntimeException;
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceNameCollectionFactoryInterface;
use ApiPlatform\Core\Util\RequestAttributesExtractor;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Twig\Environment as TwigEnvironment;

/**
 * Displays the documentation.
 *
 * @internal
 *
 * This class will be probably removed in Sylius 1.9
 */
final class SwaggerUiAction
{
    private ?array $formats;

    private $formatsProvider;

    /**
     * @param int[] $swaggerVersions
     */
    public function __construct(
        private ResourceNameCollectionFactoryInterface $resourceNameCollectionFactory,
        private ResourceMetadataFactoryInterface $resourceMetadataFactory,
        private NormalizerInterface $normalizer,
        private TwigEnvironment $twig,
        private UrlGeneratorInterface $urlGenerator,
        private string $title = '',
        private string $description = '',
        private string $version = '',
        $formats = [],
        private $oauthEnabled = false,
        private $oauthClientId = '',
        private $oauthClientSecret = '',
        private $oauthType = '',
        private $oauthFlow = '',
        private $oauthTokenUrl = '',
        private $oauthAuthorizationUrl = '',
        private $oauthScopes = [],
        private bool $showWebby = true,
        private bool $swaggerUiEnabled = false,
        private bool $reDocEnabled = false,
        private bool $graphqlEnabled = false,
        private bool $graphiQlEnabled = false,
        private bool $graphQlPlaygroundEnabled = false,
        private array $swaggerVersions = [2, 3],
    ) {
        if (\is_array($formats)) {
            $this->formats = $formats;

            return;
        }

        @trigger_error(sprintf(
            'Passing an array or an instance of "%s" as 5th parameter of the constructor of "%s" is deprecated since API Platform 2.5, pass an array instead',
            FormatsProviderInterface::class,
            __CLASS__,
        ), \E_USER_DEPRECATED);
        $this->formatsProvider = $formats;
    }

    public function __invoke(Request $request)
    {
        $attributes = RequestAttributesExtractor::extractAttributes($request);

        // BC check to be removed in 3.0
        if (null === $this->formatsProvider) {
            $formats = $attributes ? $this
                ->resourceMetadataFactory
                ->create($attributes['resource_class'])
                ->getOperationAttribute($attributes, 'output_formats', [], true) : $this->formats;
        } else {
            $formats = $this->formatsProvider->getFormatsFromAttributes($attributes);
        }

        $documentation = new Documentation($this->resourceNameCollectionFactory->create(), $this->title, $this->description, $this->version);

        return new Response($this->twig->render('@SyliusApi/SwaggerUi/index.html.twig', $this->getContext($request, $documentation) + ['formats' => $formats]));
    }

    /**
     * Gets the base Twig context.
     */
    private function getContext(Request $request, Documentation $documentation): array
    {
        $context = [
            'title' => $this->title,
            'description' => $this->description,
            'showWebby' => $this->showWebby,
            'swaggerUiEnabled' => $this->swaggerUiEnabled,
            'reDocEnabled' => $this->reDocEnabled,
            'graphqlEnabled' => $this->graphqlEnabled,
            'graphiQlEnabled' => $this->graphiQlEnabled,
            'graphQlPlaygroundEnabled' => $this->graphQlPlaygroundEnabled,
        ];

        $swaggerContext = ['spec_version' => $request->query->getInt('spec_version', $this->swaggerVersions[0] ?? 2)];
        if ('' !== $baseUrl = $request->getBaseUrl()) {
            $swaggerContext['base_url'] = $baseUrl;
        }

        $swaggerData = [
            'url' => $this->urlGenerator->generate('api_doc', ['format' => 'json']),
            'spec' => $this->normalizer->normalize($documentation, 'json', $swaggerContext),
        ];

        $swaggerData['oauth'] = [
            'enabled' => $this->oauthEnabled,
            'clientId' => $this->oauthClientId,
            'clientSecret' => $this->oauthClientSecret,
            'type' => $this->oauthType,
            'flow' => $this->oauthFlow,
            'tokenUrl' => $this->oauthTokenUrl,
            'authorizationUrl' => $this->oauthAuthorizationUrl,
            'scopes' => $this->oauthScopes,
        ];

        if ($request->isMethodSafe() && null !== $resourceClass = $request->attributes->get('_api_resource_class')) {
            $swaggerData['id'] = $request->attributes->get('id');
            $swaggerData['queryParameters'] = $request->query->all();

            $metadata = $this->resourceMetadataFactory->create($resourceClass);
            $swaggerData['shortName'] = $metadata->getShortName();

            if (null !== $collectionOperationName = $request->attributes->get('_api_collection_operation_name')) {
                $swaggerData['operationId'] = sprintf('%s%sCollection', $collectionOperationName, ucfirst($swaggerData['shortName']));
            } elseif (null !== $itemOperationName = $request->attributes->get('_api_item_operation_name')) {
                $swaggerData['operationId'] = sprintf('%s%sItem', $itemOperationName, ucfirst($swaggerData['shortName']));
            } elseif (null !== $subresourceOperationContext = $request->attributes->get('_api_subresource_context')) {
                $swaggerData['operationId'] = $subresourceOperationContext['operationId'];
            }

            [$swaggerData['path'], $swaggerData['method']] = $this->getPathAndMethod($swaggerData);
        }

        return $context + ['swagger_data' => $swaggerData];
    }

    private function getPathAndMethod(array $swaggerData): array
    {
        foreach ($swaggerData['spec']['paths'] as $path => $operations) {
            foreach ($operations as $method => $operation) {
                if ($operation['operationId'] === $swaggerData['operationId']) {
                    return [$path, $method];
                }
            }
        }

        throw new RuntimeException(sprintf('The operation "%s" cannot be found in the Swagger specification.', $swaggerData['operationId']));
    }
}


text:
#!/usr/bin/env python3

import collections
import copy
from os import getenv
from os.path import isdir, join
import re
import sys
import weakref, gc
from pympler import tracker

from PyQt4 import QtGui, QtCore
from PyQt4.QtCore import Qt

from libsyntyche.common import read_json, read_file, write_json, write_file, kill_theming, local_path, make_sure_config_exists
from libsyntyche.fileviewer import FileViewer
from indexframe import IndexFrame

class MainWindow(QtGui.QWidget):
    def __init__(self, configdir, activation_event, dry_run):
        super().__init__()
        self.setWindowTitle('Nomia')
        if configdir:
            self.configdir = configdir
        else:
            self.configdir = join(getenv('HOME'), '.config', 'nomia')
        activation_event.connect(self.reload_settings)
        self.force_quit_flag = False

        # Create layouts
        self.stack = QtGui.QStackedLayout(self)

        # Index viewer
        self.index_viewer = IndexFrame(self, dry_run, self.configdir)
        self.stack.addWidget(self.index_viewer)

        # Popup viewer
        self.popup_viewer = FileViewer(self)
        self.stack.addWidget(self.popup_viewer)
        self.popuphomekey = QtGui.QShortcut(QtGui.QKeySequence(),
                                            self.popup_viewer,
                                            self.show_index)

        # Load settings
        self.defaultstyle = read_json(local_path('defaultstyle.json'))
        self.css_template = read_file(local_path(join('templates','template.css')))
        self.index_css_template = read_file(local_path(join('templates','index_page.css')))
        self.settings, self.style = {}, {}
        self.reload_settings()
        self.index_viewer.populate_view()

        # Misc
        #self.connect_signals()
        self.show()

    def closeEvent(self, event):
        event.accept()

    def quit(self, force):
        # This flag is not used atm
        self.force_quit_flag = force
        self.close()

    def connect_signals(self):
        connects = (
            (self.index_viewer.quit,        self.close),
            (self.index_viewer.show_popup,  self.show_popup),
        )
        for signal, slot in connects:
            signal.connect(slot)

    def show_index(self):
        self.stack.setCurrentWidget(self.index_viewer)
        self.index_viewer.terminal.setFocus()

    def show_popup(self, *args):
        self.popup_viewer.set_page(*args)
        self.stack.setCurrentWidget(self.popup_viewer)

    def reload_settings(self):
        self.defaultstyle = read_json(local_path('defaultstyle.json'))
        self.css_template = read_file(local_path(join('templates','template.css')))
        self.index_css_template = read_file(local_path(join('templates','index_page.css')))

        settings, style, stylepath = read_config(self.configdir, self.defaultstyle)
        # TODO: FIX THIS UGLY ASS SHIT
        # Something somewhere fucks up and changes the settings dict,
        # therefor the deepcopy(). Fix pls.
        #if settings != self.settings:
        if settings['title']:
            self.setWindowTitle(settings['title'])
        else:
            self.setWindowTitle('Nomia')
        self.settings = copy.deepcopy(settings)
        self.index_viewer.update_settings(settings)
        self.popuphomekey.setKey(QtGui.QKeySequence(settings['hotkey home']))
        #if style != self.style:
        self.style = style.copy()
        self.update_style(style)
        write_json(stylepath, style)

    def update_style(self, style):
        try:
            css = self.css_template.format(**style)
            indexcss = self.index_css_template.format(**style)
        except KeyError as e:
            print(e)
            #self.index_viewer.error('Invalid style config: key missing')
            return
        self.setStyleSheet(css)
        self.index_viewer.defaulttagcolor = style['index entry tag default background']
        disclaimer = '/* AUTOGENERATED! NO POINT IN EDITING THIS */\n\n'
        write_file(join(self.configdir, '.index.css'), disclaimer + indexcss)
        self.index_viewer.css = indexcss
        self.index_viewer.refresh_view(keep_position=True)

    # ===== Input overrides ===========================
    def wheelEvent(self, ev):
        self.index_viewer.view.wheelEvent(ev)

    def keyPressEvent(self, ev):
        if self.stack.currentWidget() == self.index_viewer and ev.key() in (Qt.Key_PageUp, Qt.Key_PageDown):
            self.index_viewer.view.keyPressEvent(ev)
        else:
            return super().keyPressEvent(ev)

    def keyReleaseEvent(self, ev):
        if self.stack.currentWidget() == self.index_viewer and ev.key() in (Qt.Key_PageUp, Qt.Key_PageDown):
            self.index_viewer.view.keyReleaseEvent(ev)
        else:
            return super().keyReleaseEvent(ev)
    # =================================================

def read_config(configpath, defaultstyle):
    #if configdir:
    #    configpath = configdir
    #else:
    #    configpath = join(getenv('HOME'), '.config', 'nomia')
    configfile = join(configpath, 'settings.json')
    stylefile = join(configpath, 'style.json')
    make_sure_config_exists(configfile, local_path('defaultconfig.json'))
    make_sure_config_exists(stylefile, local_path('defaultstyle.json'))
    # Make sure to update the style with the defaultstyle's values
    newstyle = read_json(stylefile)
    style = defaultstyle.copy()
    style.update({k:v for k,v in newstyle.items() if k in defaultstyle})
    return read_json(configfile), style, stylefile

def main():
    import argparse
    parser = argparse.ArgumentParser()
    def valid_dir(dirname):
        if isdir(dirname):
            return dirname
        parser.error('Directory does not exist: {}'.format(dirname))
    parser.add_argument('-c', '--config-directory', type=valid_dir)
    parser.add_argument('-d', '--dry-run', action='store_true',
                        help='don\'t write anything to disk')
    args = parser.parse_args()

    app = QtGui.QApplication(sys.argv)

    class AppEventFilter(QtCore.QObject):
        activation_event = QtCore.pyqtSignal()
        def eventFilter(self, object, event):
            if event.type() == QtCore.QEvent.ApplicationActivate:
                self.activation_event.emit()
            return False
    app.event_filter = AppEventFilter()
    app.installEventFilter(app.event_filter)

    window = MainWindow(args.config_directory,
                        app.event_filter.activation_event,
                        args.dry_run)
    app.setActiveWindow(window)
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()


text:
using LogicalShift.Reason.Api;
using System;
using System.Collections.Generic;

namespace LogicalShift.Reason.Solvers
{
    /// <summary>
    /// Unifier that writes operations to a bytecode program
    /// </summary>
    public class ByteCodeUnifier : IQueryUnifier, IProgramUnifier, IUnifier
    {
        /// <summary>
        /// The program that is written by this unifier
        /// </summary>
        private readonly ByteCodeProgram _program;

        /// <summary>
        /// List of variables that have been used by an instruction
        /// </summary>
        private readonly HashSet<int> _usedVariables = new HashSet<int>();

        /// <summary>
        /// The ID that a particular variable has been bound to
        /// </summary>
        private readonly Dictionary<ILiteral, int> _bindingForVariable = new Dictionary<ILiteral,int>();

        public ByteCodeUnifier(ByteCodeProgram program)
        {
            if (program == null) throw new ArgumentNullException("program");
            _program = program;
        }

        /// <summary>
        /// Removes any variables marked as 'used'
        /// </summary>
        public void ClearVariables()
        {
            _usedVariables.Clear();
            _bindingForVariable.Clear();
        }

        public bool HasVariable(ILiteral variable)
        {
            var variableIndex = _bindingForVariable[variable];
            return _usedVariables.Contains(variableIndex);
        }

        public void BindVariable(int index, ILiteral variable)
        {
            _bindingForVariable[variable] = index;
        }

        public bool PutStructure(ILiteral termName, int termLength, ILiteral variable)
        {
            var variableIndex = _bindingForVariable[variable];
            _usedVariables.Add(variableIndex);

            _program.Write(Operation.PutStructure, termName, variableIndex, termLength);
            return true;
        }

        public bool SetVariable(ILiteral variable)
        {
            var variableIndex = _bindingForVariable[variable];
            _usedVariables.Add(variableIndex);

            _program.Write(Operation.SetVariable, variableIndex);
            return true;
        }

        public bool SetValue(ILiteral variable)
        {
            var variableIndex = _bindingForVariable[variable];
            _usedVariables.Add(variableIndex);

            _program.Write(Operation.SetValue, variableIndex);
            return true;
        }

        public bool PutVariable(ILiteral variable1, ILiteral variable2)
        {
            var variableIndex1 = _bindingForVariable[variable1];
            var variableIndex2 = _bindingForVariable[variable2];

            _usedVariables.Add(variableIndex1);
            _usedVariables.Add(variableIndex2);

            _program.Write(Operation.PutVariable, variableIndex1, variableIndex2);
            return true;
        }

        public bool PutValue(ILiteral variable1, ILiteral variable2)
        {
            var variableIndex1 = _bindingForVariable[variable1];
            var variableIndex2 = _bindingForVariable[variable2];

            _usedVariables.Add(variableIndex1);
            _usedVariables.Add(variableIndex2);

            _program.Write(Operation.PutValue, variableIndex1, variableIndex2);
            return true;
        }

        public bool GetStructure(ILiteral termName, int termLength, ILiteral variable)
        {
            var variableIndex = _bindingForVariable[variable];
            _usedVariables.Add(variableIndex);

            _program.Write(Operation.GetStructure, termName, variableIndex, termLength);
            return true;
        }

        public bool UnifyVariable(ILiteral variable)
        {
            var variableIndex = _bindingForVariable[variable];
            _usedVariables.Add(variableIndex);

            _program.Write(Operation.UnifyVariable, variableIndex);
            return true;
        }

        public bool UnifyValue(ILiteral variable)
        {
            var variableIndex = _bindingForVariable[variable];
            _usedVariables.Add(variableIndex);

            _program.Write(Operation.UnifyValue, variableIndex);
            return true;
        }

        public bool GetVariable(ILiteral variable1, ILiteral variable2)
        {
            var variableIndex1 = _bindingForVariable[variable1];
            var variableIndex2 = _bindingForVariable[variable2];

            _usedVariables.Add(variableIndex1);
            _usedVariables.Add(variableIndex2);

            _program.Write(Operation.GetVariable, variableIndex1, variableIndex2);
            return true;
        }

        public bool GetValue(ILiteral variable1, ILiteral variable2)
        {
            var variableIndex1 = _bindingForVariable[variable1];
            var variableIndex2 = _bindingForVariable[variable2];

            _usedVariables.Add(variableIndex1);
            _usedVariables.Add(variableIndex2);

            _program.Write(Operation.GetValue, variableIndex1, variableIndex2);
            return true;
        }

        public IQueryUnifier QueryUnifier
        {
            get { return this; }
        }

        public IProgramUnifier ProgramUnifier
        {
            get { return this; }
        }
    }
}


text:
from json import loads
from queue import Queue,Empty
from time import time

###### TEMPORARY ######
#import webserver
#######################

class twitch():
    def __init__(self,user):
        self.initialized = 0
        self.state = 0
        self.intaketries = 0
        self.inputqueue = Queue()
        self.outputqueue = Queue()
        self.cache = Queue()
        self.workingstack = []
        self.channels = {}
        self.addChannel(user)
        self.followers = []
        self.newFollowers = []
        self.numberFollowers = None
        self.latestFollower = None
        #self.getInitialFollowerInfo()#uh oh
        #self.getInitialLatestFollowers()#double uh oh
        self.streamData = None
        #self.numberSubscriber =
        #self.latestSubscriber =
        ###### TEMPORARY ######
        #webserver.start()
        #######################

    def getFollowersInfo(self):
        url = 'https://api.twitch.tv/kraken/channels/'+self.user+'/follows?limit=10'
        self.outputqueue.put([7,[1,url]])

    def tick(self):
        if(self.state==0):
            self.request()
        elif(self.state==1):
            self.intake()
        elif(self.state==2):
            self.prepare()
        elif(self.state==3):
            self.check()
        elif(self.state==4):
            self.notify()
        #self.newFollowers(self.user)

    def update(self):
        #get latest channel status/etc.
        self.intakeData()
        #self.requestStreamData(self.user)#

    def addChannel(self,channel):
        self.channels[channel]=[int(0),int(0)]

    def newFollowers(self,user):
        followers = self.getLatestFollower(user)
        numfollowers = self.getFollowerCount(user)
        if(self.latestFollower == followers):
            if(self.numberFollowers==numfollowers):
                #no changes
                pass
            else:
                #this is the tricky one
                #need to check created_at values
                pass
        else:
            #probably have a new follower
            if(self.numberFollowers<numfollowers):
                newusers = self.getLatestFollowers(self.user,numfollowers-self.numberFollowers)
                if(newusers[0]==self.latestFollower):
                    self.output([14,newusers[1:]])
                    self.latestFollower = newusers[-1]
            else:
                #could also be tricky
                #some followers have left
                #but may have new ones
                pass

    def requestFollowerData(self,user,limit='5'):
        request = "GET /kraken/channels/" + user
        request = request + "/follows?limit=" + limit
        request = request + " HTTP/1.1\r\nHost: api.twitch.tv\r\n\r\n"
        self.outputqueue.put([4,request])

    def requestStreamData(self,user):
        #get stream status/info
        request = "GET /kraken/streams/" + user
        request = request + " HTTP/1.1\r\nHost: api.twitch.tv\r\n\r\n"
        self.outputqueue.put([4,request])

    def intakeData(self):
        #take data from inputqueue
        try:
            data = self.inputqueue.get_nowait()
        except Empty:
            pass

    def request(self):
        #request either follower/subscriber/stream data based on time elapsed
        for channel in self.channels:
            now = time()
            if(now - self.channels[channel][0] > 30):
                self.channels[channel][0] = now
                self.requestStreamData(channel)
                self.state = 1
            elif(now - self.channels[channel][1] > 15):
                self.channels[channel][1] = now
                self.requestFollowerData(channel)
                self.state = 1

    def intake(self):
        #take data from inputqueue if time differential is great enough
        try:
            data = self.inputqueue.get_nowait()
        except Empty:
            if(self.intaketries < 1000):
                self.intaketries = self.intaketries + 1
            else:
                self.state = 0
                self.intaketries = 0
        else:
            self.workingstack.append(data)
            self.state = 2

    def prepare(self):
        #prepare input for processing
        data = self.workingstack.pop()
        data = data[1]
        try:
            data = data.split("\r\n\r\n")
            data = data[1]
        except IndexError:
            self.state = 0
        else:
            data = data.split('\r\n')
            try:
                data = data[1]
            except IndexError:
                data = data[0]
            try:
                data = loads(data)
            except ValueError:
                self.state = 0
            else:
                self.workingstack.append(data)
                self.state = 3

    def check(self):
        #process input
        data = self.workingstack.pop()
        try:
            newlist = []
            for item in data["follows"]:
                newlist.append(item["user"]["display_name"])

        except KeyError:
            try:
                if(data["stream"]):#need to research "null" behavior
                    pass#not finished
                self.state = 0
            except KeyError:
                self.state = 0
                #not finished

        else:
            self.numberFollowers = int(data["_total"])
            #may need to trim followers list at some point
            for user in newlist:
                if user in self.followers:
                    pass
                else:
                    self.followers.append(user)
                    self.newFollowers.append(user)
            if(self.newFollowers):
                self.state = 4
            else:
                self.state = 0

    def notify(self):
        #notify streamer of new follower
        if(self.initialized == 1):
            for user in self.newFollowers:
                self.newFollowerMessage(user)
        else:
            self.initialized = 1
        self.newFollowers = []
        self.state = 0

    def newFollowerMessage(self,user):
        #send notification for new follower to chat - or something else..
        self.outputqueue.put([2,"Resistance is futile. "+user+" has been assimilated. Welcome to the collective."])

        ###### TEMPORARY ######
        #try:
        #    webserver.newFollowerAnimation(user)
        #except:
        #    pass
        #######################

    def sortData(self,data):
        #sort data pulled from queue
        #should be a list where first entry is an identifier code
        #if(data[0]==#... etc.
        #then create different functions for different types of data
        #need id code for streamData,followerdata,
        #if(data[0]==7):
            #self.createJSONobject(data[1])
        pass

    def getStreamInfo(self,userName):
        #deprecated
        errFlag = 0
        try:
            try:
                url = 'https://api.twitch.tv/kraken/streams/' + userName
            except TypeError:
                url = 'https://api.twitch.tv/kraken/streams/' + str(userName)
            streamData = urlopen(url)
            streamData = streamData.read()

        except:
            errFlag = 1
            streamData = 0

        return(streamData,errFlag)

    def getTwitchState(self,streamData):
        errFlag = 0
        try:
            streamData = loads(streamData.decode())
            isStreaming = streamData['stream']
            if(isStreaming!=None):
                isStreaming = 'true'
            else:
                isStreaming = 'false'

        except:
            try:
                streamData = str(streamData)
                streamData = streamData.split(':')
                if ('null' in streamData[6]):
                    isStreaming = 'false'
                else:
                    isStreaming = 'true'

                errFlag = 1

            except:
                errFlag = 2
                isStreaming = 'null'

        return(isStreaming,errFlag)

    def getFollowerCount(self,userName):
        errFlag = 0

        try:
            try:
                url = 'https://api.twitch.tv/kraken/channels/'+userName+'/follows?limit=1'
            except TypeError:
                url = 'https://api.twitch.tv/kraken/channels/'+str(userName)+'/follows?limit=1'

            try:
                followerData = urlopen(url)
                followerData = followerData.read()
                followerData = followerData.decode()
                followers = loads(followerData)['_total']
                followers = int(followers)

            except TypeError:
                #currently broken
                followerData = urlopen(url)
                followerData = followerData.read()
                followerData = str(followerData)
                followers = int(followerData.split(':')[1].split(',')[0])

                errFlag = 2

        except:
            errFlag = 1
            followers = 'null'

        return(followers,errFlag)

    def getNewFollowers(self,userName,lastCheck,newCheck):
        errFlag = 0
        delta = -1

        try:
            delta = newCheck - lastCheck

        except TypeError:
            try:
                delta = int(newCheck) - int(lastCheck)

            except ValueError:
                errFlag = 1
                followers = ['null']

        except:
            followers = ['null']
            errFlag = errFlag + 1

        if(delta == 0):
            followers = ['null']
            errFlag = errFlag + 10

        elif(delta >= 1):
            if(delta <= 100):
                (followers,errorflag) = getNewFollowersNames(userName,delta,0)
                followers = followers

            else:
                (followers,errorflag) = getNewFollowersNames(userName,100,0)
                followers = followers
        else:
            followers = ['null']
            errFlag = errFlag + 3

        return(followers,errFlag,delta)

    def getNewFollowersNames(self,userName,limit,offset):
        errFlag = 0
        followers = []

        try:
            int(limit)
            int(offset)
        except:
            followers = ['null']
            errFlag = -1
            return(followers,errFlag)

        if(limit == 0):
            followers = ['null']
            return(followers,errFlag)

        try:
            if(limit > 100 or offset < 0):
                errFlag = 1
                followers = ['null']

                return(followers,errFlag)
            else:

                url = 'https://api.twitch.tv/kraken/channels/'
                url = url + str(userName) + '/follows?direction=DESC&limit='
                url = url + str(limit)
                url = url + '&offset='
                url = url + str(offset)

                try:
                    followerData = urlopen(url)
                    followerData = followerData.read()

                    followerData = followerData.decode()
                    followerData = loads(followerData)

                    for i in range(0, limit):
                        followers.append(followerData['follows'][i]['user']['display_name'])

                except:
                    #currently broken
                    followerData = urlopen(url)
                    followerData = followerData.read()

                    followerData = str(followerData)

                    for i in range(0, limit):
                        followers.append(followerData.split(':')[15 + i*22])
                        followers[i] = followers[i].split(',')[0].strip('"')

                    errFlag = 3

        except:
            errFlag = 2
            followers = ['null']

        return(followers,errFlag)

    def getLiveViewerCount(self,streamData):
        errFlag = 0

        try:
            currentlyViewing = loads(streamData.decode())
            currentlyViewing = currentlyViewing['stream']['viewers']
        except:
            try:
                streamData = str(streamData)
                currentlyViewing = int(streamData.split(':')[9].split(',')[0])
                errFlag = 1

            except:
                errFlag = 2
                currentlyViewing = 'null'

        return(currentlyViewing,errFlag)

    def getGameTitle(self,streamData):
        errFlag = 0
        try:
            streamData = loads(streamData.decode())
            gameTitle = streamData['stream']['game']
        except:
            try:
                streamData = str(streamData)
                gameTitle = streamData.split(':')[8].split(',')[0].strip('"')
                errFlag = 1

            except:
                errFlag = 2
                gameTitle = 'null'

        return(gameTitle,errFlag)

    def getAuthorization(self,userName):
        errFlag = 0

        try:
            #need to get from data module
            1/0

        except:
            errFlag = 1
            passToken = 0

        return(passToken,errFlag)

    def getStreamStatus(self,streamData):
        errFlag = 0

        try:
            streamData = loads(streamData.decode())
            streamStatus = streamData['stream']['channel']['status']
        except:
            errFlag = 1
            streamStatus = 'null'

        return(streamStatus,errFlag)

    def getLatestSubscribers(userName,quantity):
        pass

    def getLatestFollowers(self,userName,quantity):
        (followers,errorflag) = self.getNewFollowers(userName,0,quantity)
        return(followers)

    def getLatestFollower(self,userName):
        (followers,errorflag) = self.getNewFollowers(userName,0,1)
        return(followers)

    def getAllFollowers(self,userName):
        followers = []
        (count,error1) = self.getFollowerCount(userName)
        if(error1==0):
            i=0
            ii=0
            error2list = []
            while(i<count):
                ii = ii + 1
                if(i+100<=count):
                    (following,error2)=self.getNewFollowersNames(userName,100,i)
                    if(error2==0):
                        followers.extend(following)
                    else:
                        error2list.extend(['Count ',i,' and error ',error2])
                    i = i + 100
                else:
                    (following,error2)=self.getNewFollowersNames(userName,count-i,i)
                    if(error2==0):
                        followers.extend(following)
                    else:
                        error2list.extend(['Count- ',i,' and error ',error2])
                    break

                if(ii>10000):#temporary glass ceiling - need a timer
                    error2list.append('Too many iterations.')
                    break

            errFlag = error2list
            if(count != len(followers)):
                errFlag = 'Not all followers found after '+str(ii)+' requests.'

        else:
            errFlag = 1

        followers.reverse()
        #TODO: write to file
        return(followers,errFlag)

    def getAllSubscribers(self,userName):
        pass

    def getAlSubscribing(self,userName):
        pass

    def getAllFollowing(self,userName):
        followings = []
        (count,error1) = self.getFollowingCount(userName)
        if(error1==0):
            i=0
            ii=0
            error2list = []
            while(i<count):
                ii = ii + 1
                if(i+100<=count):
                    (following,error2)=self.getFollowingNames(userName,100,i)
                    if(error2==0):
                        followings.extend(following)
                    else:
                        error2list.extend(['Count ',i,' and error ',error2])
                    i = i + 100
                else:
                    (following,error2)=self.getFollowingNames(userName,count-i,i)
                    if(error2==0):
                        followings.extend(following)
                    else:
                        error2list.extend(['Count- ',i,' and error ',error2])
                    break

                if(ii>10000):#temporary glass ceiling - need a timer
                    error2list.append('Too many iterations.')
                    break

            errFlag = error2list
            if(count != len(followings)):
                errFlag = 'Not all followers found after '+str(ii)+' requests.'

        else:
            errFlag = 1

        followings.reverse()
        #TODO: write to file
        return(followings,errFlag)

    def getFollowingCount(self,userName):
        errFlag = 0

        try:
            try:
                url = 'https://api.twitch.tv/kraken/users/'+userName+'/follows/channels?limit=1'
            except TypeError:
                url = 'https://api.twitch.tv/kraken/users/'+str(userName)+'/follows/channels?limit=1'

            try:
                followingData = urlopen(url)
                followingData = followingData.read()
                followingData = followingData.decode()
                followings = loads(followingData)['_total']
                followings = int(followings)

            except TypeError:
                #currently broken
                followingData = urlopen(url)
                followingData = followingData.read()
                followingData = str(followingData)
                followings = int(followingData.split(':')[1].split(',')[0])

                errFlag = 2

        except:
            errFlag = 1
            followings = 'null'

        return(followings,errFlag)

    def getFollowingNames(self,userName,limit,offset):
        errFlag = 0
        followings = []

        try:
            int(limit)
            int(offset)
        except:
            followers = ['null']
            errFlag = -1
            return(followings,errFlag)

        if(limit == 0):
            followings = ['null']
            return(followings,errFlag)

        try:
            if(limit > 100 or offset < 0):
                errFlag = 1
                followings = ['null']

                return(followings,errFlag)
            else:
                url = 'https://api.twitch.tv/kraken/users/'
                url = url + str(userName) + '/follows/channels?direction=DESC&limit='
                url = url + str(limit)
                url = url + '&offset='
                url = url + str(offset)

                try:
                    followingData = urlopen(url)
                    followingData = followingData.read()

                    followingData = followingData.decode()
                    followingData = loads(followingData)

                    #switch to xrange?
                    for i in range(0, limit):
                        followings.append(followingData['follows'][i]['channel']['display_name'])

                except:
                    #currently broken
                    followingData = urlopen(url)
                    followingData = followingData.read()
                    followingData = str(followingData)

                    for i in range(0, limit):
                        followings.append(followingData.split(':')[15 + i*22])
                        followings[i] = followings[i].split(',')[0].strip('"')

                    errFlag = 3

        except:
            errFlag = 2
            followers = ['null']

        return(followings,errFlag)

    def updateAllFollowers(self,userName,filePath):
        pass

    def updateAllFollowing(self,userName,filePath):
        pass

    def updateAllSubscribers(self,userName,filePath):
        pass

    def updateAllSubscribing(self,userName,filePath):
        pass

    def findLiveStreamerFromFollowing(self,userName):
        #give preferrence to same gametitle
        pass


text:
import CategoryLogger from './CategoryLogger';
import DefaultLogger from './DefaultLogger';
import ILogger from './ILogger';

export default class Logger implements ILogger {
  public static instance: ILogger = new DefaultLogger();

  public static forCategory (category: string): ILogger {
    return new CategoryLogger(() => Logger.instance, category);
  }

  public static setInstance (logger: ILogger) {
    if (!logger) {
      throw new Error('Invalid argument: logger can not be empty');
    }
    Logger.instance = logger;
  }

  public debug (...params: any[]) {
    Logger.instance.debug(params);
  }

  public warn (...params: any[]) {
    Logger.instance.warn(params);
  }

  public error (...params: any[]) {
    Logger.instance.error(params);
  }

  public info (...params: any[]) {
    Logger.instance.info(params);
  }
}


text:
/*
 * ISP: MPI Dynamic Verification Tool
 *
 * File:        Envelope.hpp
 * Description: Implements the various envelopes received from profiled code
 * Contact:     isp-dev@cs.utah.edu
 */

#ifndef _ENVELOPE_HPP
#define _ENVELOPE_HPP

#include "name2id.hpp"
#include <iostream>
#include <vector>
#include <cassert>
#ifdef WIN32
#include <winsock2.h>
#endif
#define WILDCARD (-1)

class Envelope {
public:
    /*
     * The envelope contains all the possible parameters for a
     * function. Only those valid for a particular function must
     * be used. Use with care!
     */
    int                 id;
    int                 order_id;
    int                 issue_id;
    std::string         func;
    std::string         display_name;
    int                 func_id;
    int                 count;
    int                 index;
    int                 dest;
    bool                dest_wildcard;
    int                 src;
    bool                src_wildcard;
    int                 stag;
    std::string         comm;
    int					data_type; //CGD
    bool				typesMatch;//CGD
    std::vector<int>    comm_list;
    std::vector<int>    req_procs;

    int                 rtag;
    int                 nprocs;
    int                 comm_split_color;
    int                 comm_id;
    std::string         filename;
    int                 linenumber;
    unsigned int        ref;
/* == fprs begin == */
    bool in_exall;
/* == fprs end == */

/*  modifications of the multireceive FM encoding   */
  int cardinality;
  int corresponding_top_id;
  int corresponding_top_index;
  int corresponding_bottom_index;
  bool istop;
  bool isbottom;
  bool isMultiRecv;

    void ref_inc();
    void ref_dec();
    bool isshared();
    inline void Issued () {
        static int issue_number = 0;
        issue_id = ++issue_number;
    }
    void PrintLog();

    inline bool isSendType () {
        return (func_id == SSEND || func_id == SEND ||
				func_id == RSEND || func_id == ISEND);
    }

    inline bool isRecvType () {
        return (func_id == IRECV || func_id == RECV ||
                func_id == PROBE || func_id == IPROBE);
    }

  inline bool isRecvTypeOnly () {
    return (func_id == IRECV || func_id == RECV);
  }

    inline bool isCollectiveType () {
        return (func_id == BARRIER || func_id == BCAST || func_id == CART_CREATE
                || func_id == COMM_CREATE || func_id == COMM_DUP
                || func_id == COMM_SPLIT || func_id == COMM_FREE
                || func_id == ALLREDUCE || func_id == REDUCE
                || func_id == GATHER || func_id == SCATTER
                || func_id == GATHERV || func_id == SCATTERV
                || func_id == ALLGATHER || func_id == ALLGATHERV
                || func_id == ALLTOALL || func_id == ALLTOALLV
                || func_id == SCAN || func_id == REDUCE_SCATTER);
    }

  inline bool isBlockingType () {
    return (func_id == RECV || func_id == SSEND
	    || func_id == WAIT || func_id == PROBE || func_id == IPROBE
	    || func_id == FINALIZE || func_id == TEST
	    || func_id == WAITANY || func_id == TESTANY
	    || func_id == WAITALL || func_id == TESTALL || isCollectiveType());
    }

    inline bool isWaitorTestType () {
        return (func_id == WAIT || func_id == TEST
                || func_id == WAITANY || func_id == TESTANY
                || func_id == WAITALL || func_id == TESTALL
                );
    }

    bool        operator==(Envelope &);
    bool        operator!=(Envelope &);
    friend std::ostream &operator<< (std::ostream &os, Envelope &e);
    Envelope();
    Envelope(const Envelope &e);
};

/* == fprs begin == */
Envelope *CreateEnvelope (char *buffer, int id, int order_id, bool to_expl);
// Envelope *CreateEnvelope (char *buffer, int id, int order_id);
/* == fprs end == */
std::ostream &operator<< (std::ostream *os, Envelope &e);

#endif


text:
static NSString *const TyphoonDefinitionGlobalNamespace = @"TyphoonDefinitionGlobalNamespace";

@interface TyphoonDefinitionNamespace ()

@property (strong, nonatomic, readwrite) NSString *key;

@end

@implementation TyphoonDefinitionNamespace

+ (instancetype)globalNamespace {
    return [self namespaceWithKey:TyphoonDefinitionGlobalNamespace];
}

+ (instancetype)namespaceWithKey:(NSString *)key {
    return [[[self class] alloc] initWithKey:key];
}

- (instancetype)initWithKey:(NSString *)key {
    self = [super init];
    if (self) {
        _key = key;
    }
    return self;
}

- (BOOL)isGlobalNamespace {
    return [self.key isEqualToString:TyphoonDefinitionGlobalNamespace];
}

- (NSUInteger)hash
{
    return [self.key hash];
}

- (BOOL)isEqual:(id)other
{
    if (other == self) {
        return YES;
    }
    if (!other || ![[other class] isEqual:[self class]]) {
        return NO;
    }

    return [self.key isEqualToString:((TyphoonDefinitionNamespace *)other).key];
}

@end


text:
package com.lockit.widget;

import android.content.Context;
import android.support.annotation.Keep;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lockit.R;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EViewGroup;
import org.androidannotations.annotations.ViewById;

@EViewGroup(R.layout.four_pin_view)
public class FourPinView extends LinearLayout {

    @ViewById(R.id.pin1)
    View pin1;

    @ViewById(R.id.pin2)
    View pin2;

    @ViewById(R.id.pin3)
    View pin3;

    @ViewById(R.id.pin4)
    View pin4;

    @ViewById(R.id.prompt)
    TextView prompt;

    @ViewById(R.id.pin_view)
    View pinView;

    View[] pin = new View[4];
    private Context context;

    public FourPinView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
    }

    @AfterViews
    void init() {
        pin[0] = pin1;
        pin[1] = pin2;
        pin[2] = pin3;
        pin[3] = pin4;
    }

    public void addPin() {
        for (int i = 0; i < 4; i++)
            if (!pin[i].isSelected()) {
                pin[i].setSelected(true);
                pin[i].startAnimation(AnimationUtils.loadAnimation(context, R.anim.pin_enter));
                break;
            }
    }

    public void removePin() {
        for (int i = 3; i > -1; i--)
            if (pin[i].isSelected()) {
                pin[i].setSelected(false);
                pin[i].startAnimation(AnimationUtils.loadAnimation(context, R.anim.pin_remove));
                break;
            }
    }

    public void reset() {
        for (View view : pin) {
            view.setSelected(false);
            view.setEnabled(true);
        }
    }

    public void error() {
        for (View view : pin)
            view.setEnabled(false);
        pinView.startAnimation(AnimationUtils.loadAnimation(context, R.anim.pin_error));
    }
}