text:
def warn(*args, **kwargs):
    pass
import warnings
warnings.warn = warn

import numpy as np
import os
import time
import pickle
import datetime
from datetime import timedelta
from optparse import OptionParser
from sklearn.model_selection import cross_val_score, train_test_split
from multiprocessing.dummy import Pool as ThreadPool

import model
import model.feature_util
import model.sentiment_analysis
import model.topic_extractor
import math
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from model.linear_regression_model import LinearRegressionModel
from model.regression_model import RegressionModel
from model.MLPRegressionModel import MLPRegressionModel
from model.keras_lstm_regression_model import LSTMRegressionModel
from preprocess_text.load_corpora import load_corpora
from preprocess_text.setup_corpus import setup_corpus
from util.config import Config, Paths, RegressionModels
from preprocess_text.document import Document

current_milli_time = lambda: int(round(time.time() * 1000))
plt.style.use("ggplot")

def doc_to_text(doc, max_sentences=-1):
    sentences = ""
    num_sentences = 1
    for sent in doc.sents:
        if max_sentences > 0 and num_sentences > max_sentences:
            break

        sentences += str(sent).strip()
        num_sentences += 1

    return sentences

def corpus_to_day_features(date, corpus_for_day, output):
    print("Starting build for date: " + str(date))
    topic_extraction_cache_filename = "_".join([str(date), Config.CORPUS_NAME, Config.TOPIC_EXTRACTION_METHOD.name])
    one_hot_topic_extraction_cache_filename = "_".join([str(date), Config.CORPUS_NAME, Config.SENTIMENT_ANALYSIS_METHOD.name, "ONE_HOT"])
    sentiment_analysis_cache_filename = "_".join([str(date), Config.CORPUS_NAME, Config.SENTIMENT_ANALYSIS_METHOD.name])
    one_hot_sentiment_analysis_cache_filename = "_".join([str(date), Config.CORPUS_NAME, Config.SENTIMENT_ANALYSIS_METHOD.name, "ONE_HOT"]) # gives the sentiment to the most relevant topic per doc

    topic_extraction_cache_filename = os.path.join(Config.FEATURE_CACHE_DIR, topic_extraction_cache_filename)
    sentiment_analysis_cache_filename = os.path.join(Config.FEATURE_CACHE_DIR, sentiment_analysis_cache_filename)
    one_hot_topic_extraction_cache_filename = os.path.join(Config.FEATURE_CACHE_DIR, one_hot_topic_extraction_cache_filename)
    one_hot_sentiment_analysis_cache_filename = os.path.join(Config.FEATURE_CACHE_DIR, one_hot_sentiment_analysis_cache_filename)

    topics_precomputed = os.path.exists(topic_extraction_cache_filename)
    one_hot_topics_precomputed = os.path.exists(one_hot_topic_extraction_cache_filename)
    sentiments_precomputed = os.path.exists(sentiment_analysis_cache_filename)
    one_hot_sentiments_precomputed = os.path.exists(one_hot_sentiment_analysis_cache_filename)

    day_feature_vector = [0.0] * (2 * Config.NUM_TOPICS) # features are topic labels plus sentiment for each topic
    day_sentiments = [0.0] * (Config.NUM_TOPICS)
    one_hot_day_sentiments = [0.0] * (Config.NUM_TOPICS)
    day_topics = [0.0] * (Config.NUM_TOPICS)
    one_hot_day_topics = [0.0] * (Config.NUM_TOPICS)

    if topics_precomputed and not Config.OVERWRITE:
        #print("Loading topics from cache...")
        day_topics = pickle.load(open(topic_extraction_cache_filename, "rb"))

    if sentiments_precomputed and not Config.OVERWRITE:
        #print("Loading sentiments from cache...")
        day_sentiments = pickle.load(open(sentiment_analysis_cache_filename, "rb"))

    if one_hot_topics_precomputed and not Config.OVERWRITE:
        one_hot_day_topics = pickle.load(open(one_hot_topic_extraction_cache_filename, "rb"))

    if one_hot_sentiments_precomputed and not Config.OVERWRITE:
        one_hot_day_sentiments = pickle.load(open(one_hot_sentiment_analysis_cache_filename, "rb"))

    if not topics_precomputed or not sentiments_precomputed or Config.OVERWRITE:
        doc_num = 0
        for doc in corpus_for_day:
            doc_num += 1
            doc_topic = []
            doc_sentiment = []
            identifying_topic = -1 #which index is the topic which the article identifies with the most
            print("Computing doc # " + str(doc_num))
            if not topics_precomputed or Config.OVERWRITE:
                doc_topic = Config.TOPIC_EXTRACTION_METHOD.value(doc_to_text(doc, max_sentences=Config.MAX_SENTENCES))
                max_topic_val = -1.0
                for i in range(len(doc_topic)):
                    day_topics[i] += doc_topic[i]
                    if doc_topic[i] > max_topic_val and doc_topic[i] > 0.0:
                        indentifying_topic = i
                        max_topic_val = doc_topic[i]
                one_hot_day_topics[identifying_topic] += 1.0

            if not sentiments_precomputed or Config.OVERWRITE:
                doc_sentiment = Config.SENTIMENT_ANALYSIS_METHOD.value(doc)
                for i in range(len(day_sentiments)):
                    day_sentiments[i] += doc_sentiment * 1.0 * doc_topic[i]
                one_hot_day_sentiments[identifying_topic] += doc_sentiment * 1.0
            print("Finished doc #" + str(doc_num))
    if not topics_precomputed or Config.OVERWRITE:
        for i in range(len(day_topics)):
            day_topics[i] = day_topics[i] / len(corpus_for_day)

        pickle.dump(day_topics, open(topic_extraction_cache_filename, "wb"))

    if not sentiments_precomputed or Config.OVERWRITE:
        for i in range(len(day_sentiments)):
            day_sentiments[i] = day_sentiments[i] / len(corpus_for_day)

        pickle.dump(day_sentiments, open(sentiment_analysis_cache_filename, "wb"))

    if not one_hot_topics_precomputed or Config.OVERWRITE:
        for i in range(len(one_hot_day_topics)):
            one_hot_day_topics[i] = one_hot_day_topics[i] / len(corpus_for_day)

        pickle.dump(one_hot_day_topics, open(one_hot_topic_extraction_cache_filename, "wb"))

    if not one_hot_sentiments_precomputed or Config.OVERWRITE:
        for i in range(len(one_hot_day_sentiments)):
            one_hot_day_sentiments[i] = one_hot_day_sentiments[i] / len(corpus_for_day)

        pickle.dump(one_hot_day_sentiments, open(one_hot_sentiment_analysis_cache_filename, "wb"))

    for i in range(Config.NUM_TOPICS):
        day_feature_vector[2 * i] = day_topics[i]
        day_feature_vector[2 * i + 1] = day_sentiments[i]

    output[date] = day_feature_vector
    print("Finished date: " + str(date))

# run topic extraction/sentiment analysis on the corpora
# to build feature vectors per day
# we expect corpora to be a map of {datetime: corpus}
def corpora_to_day_features(corpora):
    output = {}
    for date, corpus_for_day in corpora.items():
        corpus_to_day_features(date, corpus_for_day, output)
    """threadpool = ThreadPool(4)
    arg_list = [(item[0], item[1], output) for item in corpora.items()]
    threadpool.starmap(corpus_to_day_features, arg_list)
    threadpool.close()
    threadpool.join()"""
    return output

def init_corpora():
    print("Loading daily approval ratings...")
    approval_ratings = model.feature_util.get_approval_poll_data()
    print("done.")

    print("Loading corpus of political articles...")
    num_articles = 100
    corpus_name = Config.CORPUS_NAME
    article_corpora = load_corpora(corpus_name, "/opt/nlp_shared/corpora/{}/".format(Config.CORPUS_SUBDIR), Config.CORPUS_YEARS)
    print("done.")

    return (approval_ratings, article_corpora)

# takes the features for individual days and does a running average for
# a shifting range of days (specified in config)
def combine_day_ranges(features_by_day, approval_ratings):
    output = {}
    for date, features in features_by_day.items():
        range_features = [0.0] * (2 * Config.NUM_TOPICS)
        days_with_data = 0 # count how many days in this range actually provided us data
        # TODO: this might be biased since days with different # of articles are weighted the same
        for i in range(0, Config.DAY_RANGE):
            days_away = timedelta(days=i)
            target_day = date - days_away
            curr_day_features = features_by_day.get(target_day)
            if curr_day_features is not None:
                days_with_data += 1
                for i in range(len(curr_day_features)):
                    range_features[i] += curr_day_features[i]
        for i in range(len(range_features)):
            range_features[i] = range_features[i] / days_with_data

        '''prev_label = approval_ratings.get(date - timedelta(days=1)) # get yesterday's labels
        if prev_label is not None:
            range_features.append(prev_label[0])
            range_features.append(prev_label[1])
        else:
            # no information so just provide a 50/50 guess...
            range_features.append(50.0)
            range_features.append(50.0)'''

        output[date] = range_features
    return output

def multid_combine_day_ranges(features_by_day):
    output = {}
    for date, features in features_by_day.items():
        ranged_features = []
        for i in range(0, Config.DAY_RANGE):
            days_away = timedelta(days=i)
            target_day = date - days_away
            curr_day_features = features_by_day.get(target_day)
            if curr_day_features is not None:
                ranged_features.insert(0, curr_day_features)
            else:
                # if we're missing a day, put in a default -1.0 value vector
                ranged_features.insert(0, ([-1.0] * (2 * Config.NUM_TOPICS)))
        output[date] = ranged_features
    return output

def match_features_to_labels(features_by_range, approval_ratings):
        X = []
        Y = []
        # match up inputs (range features) w/ output label
        for date, features in sorted(features_by_range.items(), key=lambda pair: pair[0]):
            print(date)
            actual_date = date + timedelta(days=Config.POLL_DELAY)
            approval_label = approval_ratings.get(actual_date.date()) # approval label should be 'poll_lag' days into the future
            if approval_label is not None:
                X.append(features)
                Y.append(approval_label[:-1])  # remove count of number of polls contributing to daily rating
            else:
                pass #print("UNABLE TO FIND APPROVAL RATINGS FOR DAY {}".format(str(actual_date.date())))
        return (X, Y)

def split_data(X, Y):
    print("Length of data samples: {}".format(len(X)))
    print("Length of labels: {}".format(len(Y)))
    np_X = np.array(X)
    np_Y = np.array(Y)
    first_split = Config.TRAINING_PARTITION
    second_split = first_split + Config.TEST_PARTITION
    first_split = int(first_split * len(np_X))
    second_split = int(second_split * len(np_X))
    train_X, test_X, val_X = np.split(np_X, [first_split, second_split])
    train_Y, test_Y, val_Y = np.split(np_Y, [first_split, second_split])
    return ([train_X, test_X, val_X], [train_Y, test_Y, val_Y])

# print the given message to console
# and write it to file
def pw(output_file, message):
    output_file.write(message + "\n")
    print(message)

if __name__ == '__main__':
    # add command-line flags
    # NOTE: Set hyper-parameters in util/Config.py
    parser = OptionParser()
    parser.add_option("-s", "--save", dest="save", action="store_true", help="save the model to disk with a default name")
    parser.add_option("-l", "--load", dest="load_file", help="load the model from the given file", metavar="MODEL_FILE")
    parser.add_option("-p", "--plot", dest="plot_results", action="store_true", help="plot the eval results")
    parser.add_option("-d", "--dump_predictions", dest="dump_predictions", action="store_true", help="print feature vectors and prediction vectors for test set")
    parser.add_option("-e", "--evaluate", dest="evaluate", action="store_true", help="run k-fold cross validation on the data")
    parser.add_option("-m", "--model", dest="model_type", help="run with the given model type", metavar="MODEL_TYPE")
    (options, args) = parser.parse_args()

    # load various corpora and labels
    approval_ratings, political_article_corpora = init_corpora()

    print(len(political_article_corpora.keys()))
    features_by_day = corpora_to_day_features(political_article_corpora)
    print("Number of days of data: " + str(len(features_by_day.items())))
    features_by_range = combine_day_ranges(features_by_day, approval_ratings)
    X, Y = match_features_to_labels(features_by_range, approval_ratings)

    print("Number of feature vectors (ideally this is # days - moving_range_size + 1): " + str(len(X)))
    X_train = []
    X_test = []
    X_val = []
    Y_train = []
    Y_test = []
    Y_val = []

    if not Config.TRAIN_TEST_CONSECUTIVE:
        X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=Config.TRAINING_PARTITION)
    else:
        X_data, Y_data = split_data(X, Y)
        X_train, X_test, X_val = X_data
        Y_train, Y_test, Y_val = Y_data

    # setup model and configurations
    model = None
    model_type = ""
    # train new model (only if no model is loaded)
    if options.model_type is None or options.model_type == RegressionModels.LINEAR_REGRESSION.value:
        model_type = "Linear Regression"
        if not options.evaluate:
            model = LinearRegressionModel([X, Y]) # when not evaluating, use entire data
        else:
            model = LinearRegressionModel([X_train, Y_train])
    elif options.model_type == RegressionModels.MLP.value:
        model_type = "MLP Regression"
        if not options.evaluate:
            model = MLPRegressionModel([X, Y]) # when not evaluating, use entire data
        else:
            model = MLPRegressionModel([X_train, Y_train])
    elif options.model_type == RegressionModels.LSTM.value:
        # we need to re-match our data since LSTM expects sequential data per day
        ranged_features = multid_combine_day_ranges(features_by_day)
        X, Y = match_features_to_labels(ranged_features, approval_ratings)
        X_data, Y_data = split_data(X, Y)
        X_train, X_test, X_val = X_data
        Y_train, Y_test, Y_val = Y_data
        model_type = "LSTM Regression"
        lstm_file = "lstm_models/LSTM_EPOCH_195"
        if not options.evaluate:
            model = LSTMRegressionModel([X, Y], [X, Y], saved_model=lstm_file)
        else:
            model = LSTMRegressionModel(train_data=[X_train, Y_train], test_data=[X_test, Y_test], saved_model=lstm_file)
    model_name = "TEMP_MODEL_" + str(datetime.datetime.now()).replace(" ", "_")
    if options.load_file is not None:
        model = RegressionModel.load(options.load_file)
        model_name = options.load_file
    elif options.model_type != RegressionModels.LSTM.value:
        print("Training model...")
        model.train()
        print("Done.")
        model_name = "TEMP_MODEL_" + str(datetime.datetime.now()).replace(" ", "_")
    if options.save:
        model_name = "TEMP_MODEL_" + str(datetime.datetime.now()).replace(" ", "_")
        model.save(model_name)

    if options.evaluate:
        eval_file = open(Paths.EVAL_RESULTS_PATH.value + model_name + ".txt", 'w')
        pw(eval_file, "BEGIN MODEL ANALYSIS FOR: " + model_name + " of type " + model_type)
        pw(eval_file, "================================================")
        pw(eval_file, "")
        pw(eval_file, "")
        pw(eval_file, "")

        MSE_approval = 0.0
        MSE_disapproval = 0.0

        total_diff_approval = 0.0
        total_diff_disapproval = 0.0

        first_approval_group_count = 0
        second_approval_group_count = 0
        third_approval_group_count = 0
        fourth_approval_group_count = 0
        fifth_approval_group_count = 0

        first_disapproval_group_count = 0
        second_disapproval_group_count = 0
        third_disapproval_group_count = 0
        fourth_disapproval_group_count = 0
        fifth_disapproval_group_count = 0

        approval_over_count = 0
        approval_under_count = 0
        disapproval_over_count = 0
        disapproval_under_count = 0

        # keep track of outliers: tuples of the form (feature_vector, label, prediction)
        approval_outliers = []
        disapproval_outliers = []
        X_test = X_val
        Y_test = Y_val
        for i in range(len(X_train)):
            prediction = model.predict([X_train[i]])[0]
            diff_approval_signed = prediction[0] - Y_train[i][0]
            diff_disapproval_signed = prediction[1] - Y_train[i][1]
            diff_approval = math.fabs(diff_approval_signed)
            diff_disapproval = math.fabs(diff_disapproval_signed)

            percent_diff_approval_signed = diff_approval / Y_train[i][0]
            percent_diff_disapproval_signed = diff_disapproval / Y_train[i][1]
            percent_diff_approval = math.fabs(percent_diff_approval_signed)
            percent_diff_disapproval = math.fabs(percent_diff_disapproval_signed)

            MSE_approval += math.pow(diff_approval, 2)
            MSE_disapproval += math.pow(diff_disapproval, 2)

            total_diff_approval += diff_approval
            total_diff_disapproval += diff_disapproval

            # count which 'percentiile' results fall in
            if percent_diff_approval < Config.FIRST_CUTOFF:
                first_approval_group_count += 1
            if percent_diff_approval < Config.SECOND_CUTOFF:
                second_approval_group_count += 1
            if percent_diff_approval < Config.THIRD_CUTOFF:
                third_approval_group_count += 1
            if percent_diff_approval < Config.FOURTH_CUTOFF:
                fourth_approval_group_count += 1
            if percent_diff_approval < Config.FIFTH_CUTOFF:
                fifth_approval_group_count += 1

            # count which 'percentiile' results fall in
            if percent_diff_disapproval < Config.FIRST_CUTOFF:
                first_disapproval_group_count += 1
            if percent_diff_disapproval < Config.SECOND_CUTOFF:
                second_disapproval_group_count += 1
            if percent_diff_disapproval < Config.THIRD_CUTOFF:
                third_disapproval_group_count += 1
            if percent_diff_disapproval < Config.FOURTH_CUTOFF:
                fourth_disapproval_group_count += 1
            if percent_diff_disapproval < Config.FIFTH_CUTOFF:
                fifth_disapproval_group_count += 1

            # count over/understimates
            if diff_approval > Config.LENIENCY:
                if diff_approval_signed > 0:
                    approval_over_count += 1
                else:
                    approval_under_count += 1
            if diff_disapproval > Config.LENIENCY:
                if diff_disapproval_signed > 0:
                    disapproval_over_count += 1
                else:
                    disapproval_under_count += 1

            # handle outliers
            if diff_approval >= Config.OUTLIER_THRESHOLD_HARD:
                approval_outliers.append((X_train[i], Y_train[i], prediction[0]))
            if diff_disapproval >= Config.OUTLIER_THRESHOLD_HARD:
                disapproval_outliers.append((X_train[i], Y_train[i], prediction[1]))

            #TODO: Check trend matching (does the directionality/magnitude change correlate with the actual labels)
            # This might be difficult given random partitioning

        RMSE_approval = math.sqrt(MSE_approval / len(Y_train))
        RMSE_disapproval = math.sqrt(MSE_disapproval / len(Y_train))

        avg_diff_approval = total_diff_approval / len(Y_train)
        avg_diff_disapproval = total_diff_disapproval / len(Y_train)

        # print out results:
        pw(eval_file, "Evaluation results on {} points of Training Data".format(len(X_train)))
        pw(eval_file, "==================================================")
        pw(eval_file, "Root Mean Squared Error (Approval): " + str(RMSE_approval))
        pw(eval_file, "Root Mean Squared Error (Disapproval): " + str(RMSE_disapproval))
        pw(eval_file, "")
        pw(eval_file, "Average distance (Approval): " + str(avg_diff_approval))
        pw(eval_file, "Average distance (Disapproval): " + str(avg_diff_disapproval))
        pw(eval_file, "")
        pw(eval_file, "# of approval data points within " + str(Config.FIRST_CUTOFF * 100) + "% of actual: " + str(first_approval_group_count))
        pw(eval_file, "# of approval data points within " + str(Config.SECOND_CUTOFF * 100) + "% of actual: " + str(second_approval_group_count))
        pw(eval_file, "# of approval data points within " + str(Config.THIRD_CUTOFF * 100) + "% of actual: " + str(third_approval_group_count))
        pw(eval_file, "# of approval data points within " + str(Config.FOURTH_CUTOFF * 100) + "% of actual: " + str(fourth_approval_group_count))
        pw(eval_file, "# of approval data points within " + str(Config.FIFTH_CUTOFF * 100) + "% of actual: " + str(fifth_approval_group_count))
        pw(eval_file, "")
        pw(eval_file, "# of disapproval data points within " + str(Config.FIRST_CUTOFF * 100) + "% of actual: " + str(first_disapproval_group_count))
        pw(eval_file, "# of disapproval data points within " + str(Config.SECOND_CUTOFF * 100) + "% of actual: " + str(second_disapproval_group_count))
        pw(eval_file, "# of disapproval data points within " + str(Config.THIRD_CUTOFF * 100) + "% of actual: " + str(third_disapproval_group_count))
        pw(eval_file, "# of disapproval data points within " + str(Config.FOURTH_CUTOFF * 100) + "% of actual: " + str(fourth_disapproval_group_count))
        pw(eval_file, "# of disapproval data points within " + str(Config.FIFTH_CUTOFF * 100) + "% of actual: " + str(fifth_disapproval_group_count))
        pw(eval_file, "")
        pw(eval_file, "# of approval over-estimates: " + str(approval_over_count))
        pw(eval_file, "# of approval under-estimates: " + str(approval_under_count))
        pw(eval_file, "Ratio of over to under (Approval): " + str(approval_over_count * 1.0 / approval_under_count))
        pw(eval_file, "# of disapproval over-estimates: " + str(disapproval_over_count))
        pw(eval_file, "# of disapproval under-estimates: " + str(disapproval_under_count))
        pw(eval_file, "Ratio of over to under (Disapproval): " + str(disapproval_over_count * 1.0 / disapproval_under_count))
        pw(eval_file, "")
        pw(eval_file, "# of Outliers (Approval): " + str(len(approval_outliers)))
        pw(eval_file, "---------------------------------------------------")
        for i in range(len(approval_outliers)):
            features, actual, predicted  = approval_outliers[i]
            pw(eval_file, "Outlier " + str(i) + ": " + str(features) + " => " + str(predicted) + "(when actual is " + str(actual) + ")")
        pw(eval_file, "")
        pw(eval_file, "# of Outliers (Disapproval): " + str(len(approval_outliers)))
        pw(eval_file, "---------------------------------------------------")
        for i in range(len(disapproval_outliers)):
            features, actual, predicted  = disapproval_outliers[i]
            pw(eval_file, "Outlier " + str(i) + ": " + str(features) + " => " + str(predicted) + "(when actual is " + str(actual) + ")")

        MSE_approval = 0.0
        MSE_disapproval = 0.0

        total_diff_approval = 0.0
        total_diff_disapproval = 0.0

        first_approval_group_count = 0
        second_approval_group_count = 0
        third_approval_group_count = 0
        fourth_approval_group_count = 0
        fifth_approval_group_count = 0

        first_disapproval_group_count = 0
        second_disapproval_group_count = 0
        third_disapproval_group_count = 0
        fourth_disapproval_group_count = 0
        fifth_disapproval_group_count = 0

        approval_over_count = 0
        approval_under_count = 0
        disapproval_over_count = 0
        disapproval_under_count = 0

        # keep track of outliers: tuples of the form (feature_vector, label, prediction)
        approval_outliers = []
        disapproval_outliers = []

        for i in range(len(X_test)):
            prediction = model.predict([X_test[i]])[0]
            diff_approval_signed = prediction[0] - Y_test[i][0]
            diff_disapproval_signed = prediction[1] - Y_test[i][1]
            diff_approval = math.fabs(diff_approval_signed)
            diff_disapproval = math.fabs(diff_disapproval_signed)

            percent_diff_approval_signed = diff_approval / Y_test[i][0]
            percent_diff_disapproval_signed = diff_disapproval / Y_test[i][1]
            percent_diff_approval = math.fabs(percent_diff_approval_signed)
            percent_diff_disapproval = math.fabs(percent_diff_disapproval_signed)

            MSE_approval += math.pow(diff_approval, 2)
            MSE_disapproval += math.pow(diff_disapproval, 2)

            total_diff_approval += diff_approval
            total_diff_disapproval += diff_disapproval

            # count which 'percentiile' results fall in
            if percent_diff_approval < Config.FIRST_CUTOFF:
                first_approval_group_count += 1
            if percent_diff_approval < Config.SECOND_CUTOFF:
                second_approval_group_count += 1
            if percent_diff_approval < Config.THIRD_CUTOFF:
                third_approval_group_count += 1
            if percent_diff_approval < Config.FOURTH_CUTOFF:
                fourth_approval_group_count += 1
            if percent_diff_approval < Config.FIFTH_CUTOFF:
                fifth_approval_group_count += 1

            # count which 'percentiile' results fall in
            if percent_diff_disapproval < Config.FIRST_CUTOFF:
                first_disapproval_group_count += 1
            if percent_diff_disapproval < Config.SECOND_CUTOFF:
                second_disapproval_group_count += 1
            if percent_diff_disapproval < Config.THIRD_CUTOFF:
                third_disapproval_group_count += 1
            if percent_diff_disapproval < Config.FOURTH_CUTOFF:
                fourth_disapproval_group_count += 1
            if percent_diff_disapproval < Config.FIFTH_CUTOFF:
                fifth_disapproval_group_count += 1

            # count over/understimates
            if diff_approval > Config.LENIENCY:
                if diff_approval_signed > 0:
                    approval_over_count += 1
                else:
                    approval_under_count += 1
            if diff_disapproval > Config.LENIENCY:
                if diff_disapproval_signed > 0:
                    disapproval_over_count += 1
                else:
                    disapproval_under_count += 1

            # handle outliers
            if diff_approval >= Config.OUTLIER_THRESHOLD_HARD:
                approval_outliers.append((X_test[i], Y_test[i], prediction[0]))
            if diff_disapproval >= Config.OUTLIER_THRESHOLD_HARD:
                disapproval_outliers.append((X_test[i], Y_test[i], prediction[1]))

            #TODO: Check trend matching (does the directionality/magnitude change correlate with the actual labels)
            # This might be difficult given random partitioning

        RMSE_approval = math.sqrt(MSE_approval / len(Y_test))
        RMSE_disapproval = math.sqrt(MSE_disapproval / len(Y_test))

        avg_diff_approval = total_diff_approval / len(Y_test)
        avg_diff_disapproval = total_diff_disapproval / len(Y_test)

        # print out results:
        pw(eval_file, "Evaluation results on {} points of Test Data".format(len(X_test)))
        pw(eval_file, "==================================================")
        pw(eval_file, "Root Mean Squared Error (Approval): " + str(RMSE_approval))
        pw(eval_file, "Root Mean Squared Error (Disapproval): " + str(RMSE_disapproval))
        pw(eval_file, "")
        pw(eval_file, "Average distance (Approval): " + str(avg_diff_approval))
        pw(eval_file, "Average distance (Disapproval): " + str(avg_diff_disapproval))
        pw(eval_file, "")
        pw(eval_file, "# of approval data points within " + str(Config.FIRST_CUTOFF * 100) + "% of actual: " + str(first_approval_group_count))
        pw(eval_file, "# of approval data points within " + str(Config.SECOND_CUTOFF * 100) + "% of actual: " + str(second_approval_group_count))
        pw(eval_file, "# of approval data points within " + str(Config.THIRD_CUTOFF * 100) + "% of actual: " + str(third_approval_group_count))
        pw(eval_file, "# of approval data points within " + str(Config.FOURTH_CUTOFF * 100) + "% of actual: " + str(fourth_approval_group_count))
        pw(eval_file, "# of approval data points within " + str(Config.FIFTH_CUTOFF * 100) + "% of actual: " + str(fifth_approval_group_count))
        pw(eval_file, "")
        pw(eval_file, "# of disapproval data points within " + str(Config.FIRST_CUTOFF * 100) + "% of actual: " + str(first_disapproval_group_count))
        pw(eval_file, "# of disapproval data points within " + str(Config.SECOND_CUTOFF * 100) + "% of actual: " + str(second_disapproval_group_count))
        pw(eval_file, "# of disapproval data points within " + str(Config.THIRD_CUTOFF * 100) + "% of actual: " + str(third_disapproval_group_count))
        pw(eval_file, "# of disapproval data points within " + str(Config.FOURTH_CUTOFF * 100) + "% of actual: " + str(fourth_disapproval_group_count))
        pw(eval_file, "# of disapproval data points within " + str(Config.FIFTH_CUTOFF * 100) + "% of actual: " + str(fifth_disapproval_group_count))
        pw(eval_file, "")
        pw(eval_file, "# of approval over-estimates: " + str(approval_over_count))
        pw(eval_file, "# of approval under-estimates: " + str(approval_under_count))
        pw(eval_file, "Ratio of over to under (Approval): " + str(approval_over_count * 1.0 / approval_under_count))
        pw(eval_file, "# of disapproval over-estimates: " + str(disapproval_over_count))
        pw(eval_file, "# of disapproval under-estimates: " + str(disapproval_under_count))
        pw(eval_file, "Ratio of over to under (Disapproval): " + str(disapproval_over_count * 1.0 / disapproval_under_count))
        pw(eval_file, "")
        pw(eval_file, "# of Outliers (Approval): " + str(len(approval_outliers)))
        pw(eval_file, "---------------------------------------------------")
        for i in range(len(approval_outliers)):
            features, actual, predicted  = approval_outliers[i]
            pw(eval_file, "Outlier " + str(i) + ": " + str(features) + " => " + str(predicted) + "(when actual is " + str(actual) + ")")
        pw(eval_file, "")
        pw(eval_file, "# of Outliers (Disapproval): " + str(len(approval_outliers)))
        pw(eval_file, "---------------------------------------------------")
        for i in range(len(disapproval_outliers)):
            features, actual, predicted  = disapproval_outliers[i]
            pw(eval_file, "Outlier " + str(i) + ": " + str(features) + " => " + str(predicted) + "(when actual is " + str(actual) + ")")

        pw(eval_file, "")
        pw(eval_file, "")
        pw(eval_file, "========================================================")
        if options.model_type != RegressionModels.LSTM.value:
            pw(eval_file, "K-fold cross validation scores: ")
            k_fold_scores = cross_val_score(model.model, X, Y, n_jobs=-1, cv=4, scoring="neg_mean_squared_error")
            pw(eval_file, str(k_fold_scores))

        eval_file.close()

    # ------------------------ Plotting Results ----------------------------------------
    if options.plot_results:
        actual_approval = []
        actual_disapproval = []
        predict_approval = []
        predict_disapproval = []
        axis_vals = []

        for label in Y_test:
            actual_approval.append(label[0])
            actual_disapproval.append(label[1])

        for i in range(len(X_test)):
            prediction = model.predict([X_test[i]])[0]
            if options.dump_predictions:
                print("Predicting day " + str(i) + " given: " + str(X_test[i]))
                print("Output: " + str(prediction))
            predict_approval.append(prediction[0])
            predict_disapproval.append(prediction[1])
            if options.plot_results:
                axis_vals.append(i)
                plt.figure(1)

        # red is actual, blue is predicted
        print("RED VALUES ARE ACTUAL - BLUE VALUES ARE PREDICTED") # just a nice console reminder
        plt.subplot(211)
        approval_actual, = plt.plot(axis_vals, actual_approval, 'ro', markersize=4)
        approval_predicted, = plt.plot(axis_vals, predict_approval, 'bo', markersize=4)
        plt.legend([approval_actual, approval_predicted], ["Actual", "Predicted"], loc=2, borderaxespad=0.)
        plt.ylabel('Approval percentage')
        axes = plt.gca()
        axes.set_ylim([20, 70])

        plt.subplot(212)
        disapproval_actual, = plt.plot(axis_vals, actual_disapproval, 'ro', markersize=4)
        disapproval_predicted, = plt.plot(axis_vals, predict_disapproval, 'bo', markersize=4)
        plt.legend([disapproval_actual, approval_predicted], ["Actual", "Predicted"], loc=2, borderaxespad=0.)
        plt.ylabel('Disapproval percentage')
        axes = plt.gca()
        axes.set_ylim([20, 70])

        plt.show()
        config_params = [
            "CORPUS_NAME",
            "POLL_DELAY",
            "DAY_RANGE",
            "SENTIMENT_ANALYSIS_METHOD",
            "TOPIC_EXTRACTION_METHOD",
            "NUM_TOPICS",
            "REGRESSION_MODEL",
            "NUM_LAYERS",
            "YEARS"
        ]
        plt.savefig(os.path.join(Config.PLOT_DIR, (Config.dump_config(config_params) + ".png")))
        pickle.dump(k_fold_scores, open(os.path.join(Config.PLOT_DIR, Config.dump_config(config_params) + "_k_fold_scores_negmse.txt"), "wb"))


text:
INSERT INTO Affiliations (
    document_id,
    course_id
) VALUES (
    $1::TEXT,
    $2::INTEGER
)
RETURNING *;

redpajama_set_name: RedPajamaGithub


text:
var towserHubInit = function () {
    var term = towserTermInit();

    var hub = $.connection.towserHub;

    hub.client.write = function (data) {
        term.write(data);
    }

    hub.client.error = function (data) { console.error(data); }
    hub.client.stop = function () { console.info("Stopped"); }
    hub.client.dcs = function (data) { console.error("DCS " + data); }
    hub.client.osc = function (data) { console.info("OSC " + data); }
    hub.client.pm = function (data) { console.info("PM " + data); }
    hub.client.apc = function (data) { console.info("APC " + data); }

    $.connection.hub.start()
        .done(function () {
            hub.server.init();
            console.log('Now connected, connection id=' + $.connection.hub.id);
        })
        .fail(function () {
            console.log('Could not connect!');
        });

    // receive from terminal
    term.oninput = function (data) { hub.server.keyPress(data); }

    // stop terminal
    term.onstop = function () { $.connection.hub.stop(); }
}


text:
package org.apache.hadoop.hbase.util;

import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;

/**
 * A basic {@link ByteRange} implementation.
 */
@InterfaceAudience.Public
@InterfaceStability.Evolving
public class SimpleByteRange implements ByteRange {

  private static final int UNSET_HASH_VALUE = -1;

  // Note to maintainers: Do not make these final, as the intention is to
  // reuse objects of this class

  /**
   * The array containing the bytes in this range. It will be >= length.
   */
  protected byte[] bytes;

  /**
   * The index of the first byte in this range. {@code ByteRange.get(0)} will
   * return bytes[offset].
   */
  protected int offset;

  /**
   * The number of bytes in the range.  Offset + length must be <= bytes.length
   */
  protected int length;

  /**
   * Variable for lazy-caching the hashCode of this range. Useful for
   * frequently used ranges, long-lived ranges, or long ranges.
   */
  private int hash = UNSET_HASH_VALUE;

  /**
   * Create a new {@code ByteRange} lacking a backing array and with an
   * undefined viewport.
   */
  public SimpleByteRange() {
    unset();
  }

  /**
   * Create a new {@code ByteRange} over a new backing array of size
   * {@code capacity}. The range's offset and length are 0 and {@code capacity},
   * respectively.
   * @param capacity the size of the backing array.
   */
  public SimpleByteRange(int capacity) {
    this(new byte[capacity]);
  }

  /**
   * Create a new {@code ByteRange} over the provided {@code bytes}.
   * @param bytes The array to wrap.
   */
  public SimpleByteRange(byte[] bytes) {
    set(bytes);
  }

  /**
   * Create a new {@code ByteRange} over the provided {@code bytes}.
   * @param bytes The array to wrap.
   * @param offset The offset into {@code bytes} considered the beginning
   *          of this range.
   * @param length The length of this range.
   */
  public SimpleByteRange(byte[] bytes, int offset, int length) {
    set(bytes, offset, length);
  }

  //
  // methods for managing the backing array and range viewport
  //

  @Override
  public byte[] getBytes() {
    return bytes;
  }

  @Override
  public ByteRange unset() {
    clearHashCache();
    this.bytes = null;
    this.offset = 0;
    this.length = 0;
    return this;
  }

  @Override
  public ByteRange set(int capacity) {
    return set(new byte[capacity]);
  }

  @Override
  public ByteRange set(byte[] bytes) {
    if (null == bytes) return unset();
    clearHashCache();
    this.bytes = bytes;
    this.offset = 0;
    this.length = bytes.length;
    return this;
  }

  @Override
  public ByteRange set(byte[] bytes, int offset, int length) {
    if (null == bytes) return unset();
    clearHashCache();
    this.bytes = bytes;
    this.offset = offset;
    this.length = length;
    return this;
  }

  @Override
  public int getOffset() {
    return offset;
  }

  @Override
  public ByteRange setOffset(int offset) {
    clearHashCache();
    this.offset = offset;
    return this;
  }

  @Override
  public int getLength() {
    return length;
  }

  @Override
  public ByteRange setLength(int length) {
    clearHashCache();
    this.length = length;
    return this;
  }

  @Override
  public boolean isEmpty() {
    return isEmpty(this);
  }

  /**
   * @return true when {@code range} is of zero length, false otherwise.
   */
  public static boolean isEmpty(ByteRange range) {
    return range == null || range.getLength() == 0;
  }

  //
  // methods for retrieving data
  //

  @Override
  public byte get(int index) {
    return bytes[offset + index];
  }

  @Override
  public short getShort(int index) {
    int offset = this.offset + index;
    short n = 0;
    n ^= bytes[offset] & 0xFF;
    n <<= 8;
    n ^= bytes[offset + 1] & 0xFF;
    return n;
  }

  @Override
  public int getInt(int index) {
    int offset = this.offset + index;
    int n = 0;
    for (int i = offset; i < (offset + Bytes.SIZEOF_INT); i++) {
      n <<= 8;
      n ^= bytes[i] & 0xFF;
    }
    return n;
  }

  @Override
  public long getLong(int index) {
    int offset = this.offset + index;
    long l = 0;
    for (int i = offset; i < offset + Bytes.SIZEOF_LONG; i++) {
      l <<= 8;
      l ^= bytes[i] & 0xFF;
    }
    return l;
  }

  // Copied from com.google.protobuf.CodedInputStream
  @Override
  public long getVLong(int index) {
    int shift = 0;
    long result = 0;
    while (shift < 64) {
      final byte b = get(index++);
      result |= (long) (b & 0x7F) << shift;
      if ((b & 0x80) == 0) {
        break;
      }
      shift += 7;
    }
    return result;
  }

  public static int getVLongSize(long val) {
    int rPos = 0;
    while ((val & ~0x7F) != 0) {
      val >>>= 7;
      rPos++;
    }
    return rPos + 1;
  }

  @Override
  public ByteRange get(int index, byte[] dst) {
    if (0 == dst.length) return this;
    return get(index, dst, 0, dst.length);
  }

  @Override
  public ByteRange get(int index, byte[] dst, int offset, int length) {
    if (0 == length) return this;
    System.arraycopy(this.bytes, this.offset + index, dst, offset, length);
    return this;
  }

  @Override
  public ByteRange put(int index, byte val) {
    bytes[offset + index] = val;
    clearHashCache();
    return this;
  }

  @Override
  public ByteRange putShort(int index, short val) {
    // This writing is same as BB's putShort. When byte[] is wrapped in a BB and call putShort(),
    // one can get the same result.
    bytes[offset + index + 1] = (byte) val;
    val >>= 8;
    bytes[offset + index] = (byte) val;
    clearHashCache();
    return this;
  }

  @Override
  public ByteRange putInt(int index, int val) {
    // This writing is same as BB's putInt. When byte[] is wrapped in a BB and call getInt(), one
    // can get the same result.
    for (int i = Bytes.SIZEOF_INT - 1; i > 0; i--) {
      bytes[offset + index + i] = (byte) val;
      val >>>= 8;
    }
    bytes[offset + index] = (byte) val;
    clearHashCache();
    return this;
  }

  @Override
  public ByteRange putLong(int index, long val) {
    // This writing is same as BB's putLong. When byte[] is wrapped in a BB and call putLong(), one
    // can get the same result.
    for (int i = Bytes.SIZEOF_LONG - 1; i > 0; i--) {
      bytes[offset + index + i] = (byte) val;
      val >>>= 8;
    }
    bytes[offset + index] = (byte) val;
    clearHashCache();
    return this;
  }

  // Copied from com.google.protobuf.CodedOutputStream
  @Override
  public int putVLong(int index, long val) {
    int rPos = 0;
    while (true) {
      if ((val & ~0x7F) == 0) {
        bytes[offset + index + rPos] = (byte) val;
        break;
      } else {
        bytes[offset + index + rPos] = (byte) ((val & 0x7F) | 0x80);
        val >>>= 7;
      }
      rPos++;
    }
    clearHashCache();
    return rPos + 1;
  }

  @Override
  public ByteRange put(int index, byte[] val) {
    if (0 == val.length) return this;
    return put(index, val, 0, val.length);
  }

  @Override
  public ByteRange put(int index, byte[] val, int offset, int length) {
    if (0 == length) return this;
    System.arraycopy(val, offset, this.bytes, this.offset + index, length);
    clearHashCache();
    return this;
  }

  //
  // methods for duplicating the current instance
  //

  @Override
  public byte[] deepCopyToNewArray() {
    byte[] result = new byte[length];
    System.arraycopy(bytes, offset, result, 0, length);
    return result;
  }

  @Override
  public ByteRange deepCopy() {
    SimpleByteRange clone = new SimpleByteRange(deepCopyToNewArray());
    if (isHashCached()) {
      clone.hash = hash;
    }
    return clone;
  }

  @Override
  public void deepCopyTo(byte[] destination, int destinationOffset) {
    System.arraycopy(bytes, offset, destination, destinationOffset, length);
  }

  @Override
  public void deepCopySubRangeTo(int innerOffset, int copyLength, byte[] destination,
      int destinationOffset) {
    System.arraycopy(bytes, offset + innerOffset, destination, destinationOffset, copyLength);
  }

  @Override
  public ByteRange shallowCopy() {
    SimpleByteRange clone = new SimpleByteRange(bytes, offset, length);
    if (isHashCached()) {
      clone.hash = hash;
    }
    return clone;
  }

  @Override
  public ByteRange shallowCopySubRange(int innerOffset, int copyLength) {
    SimpleByteRange clone = new SimpleByteRange(bytes, offset + innerOffset, copyLength);
    if (isHashCached()) {
      clone.hash = hash;
    }
    return clone;
  }

  //
  // methods used for comparison
  //

  @Override
  public boolean equals(Object thatObject) {
    if (thatObject == null){
      return false;
    }
    if (this == thatObject) {
      return true;
    }
    if (hashCode() != thatObject.hashCode()) {
      return false;
    }
    if (!(thatObject instanceof SimpleByteRange)) {
      return false;
    }
    SimpleByteRange that = (SimpleByteRange) thatObject;
    return Bytes.equals(bytes, offset, length, that.bytes, that.offset, that.length);
  }

  @Override
  public int hashCode() {
    if (isHashCached()) {// hash is already calculated and cached
      return hash;
    }
    if (this.isEmpty()) {// return 0 for empty ByteRange
      hash = 0;
      return hash;
    }
    int off = offset;
    hash = 0;
    for (int i = 0; i < length; i++) {
      hash = 31 * hash + bytes[off++];
    }
    return hash;
  }

  private boolean isHashCached() {
    return hash != UNSET_HASH_VALUE;
  }

  protected void clearHashCache() {
    hash = UNSET_HASH_VALUE;
  }

  /**
   * Bitwise comparison of each byte in the array.  Unsigned comparison, not
   * paying attention to java's signed bytes.
   */
  @Override
  public int compareTo(ByteRange other) {
    return Bytes.compareTo(bytes, offset, length, other.getBytes(), other.getOffset(),
      other.getLength());
  }

  @Override
  public String toString() {
    return Bytes.toStringBinary(bytes, offset, length);
  }
}


text:
<?php
/**
 * DO NOT EDIT THIS FILE!
 *
 * This file was automatically generated from external sources.
 *
 * Any manual change here will be lost the next time the SDK
 * is updated. You've been warned!
 */

namespace DTS\eBaySDK\MerchantData\Types;

/**
 *
 * @property \DTS\eBaySDK\MerchantData\Types\PickupOptionsType[] $PickupOptions
 */
class PickupDetailsType extends \DTS\eBaySDK\Types\BaseType
{
    /**
     * @var array Properties belonging to objects of this class.
     */
    private static $propertyTypes = [
        'PickupOptions' => [
            'type' => 'DTS\eBaySDK\MerchantData\Types\PickupOptionsType',
            'repeatable' => true,
            'attribute' => false,
            'elementName' => 'PickupOptions'
        ]
    ];

    /**
     * @param array $values Optional properties and values to assign to the object.
     */
    public function __construct(array $values = [])
    {
        list($parentValues, $childValues) = self::getParentValues(self::$propertyTypes, $values);

        parent::__construct($parentValues);

        if (!array_key_exists(__CLASS__, self::$properties)) {
            self::$properties[__CLASS__] = array_merge(self::$properties[get_parent_class()], self::$propertyTypes);
        }

        if (!array_key_exists(__CLASS__, self::$xmlNamespaces)) {
            self::$xmlNamespaces[__CLASS__] = 'xmlns="urn:ebay:apis:eBLBaseComponents"';
        }

        $this->setValues(__CLASS__, $childValues);
    }
}


text:
require_relative 'base_service'

##
# Branch can be deleted either by DeleteBranchService
# or by GitPushService.
#
class AfterBranchDeleteService < BaseService
  attr_reader :branch_name

  def execute(branch_name)
    @branch_name = branch_name

    stop_environments
  end

  private

  def stop_environments
    Ci::StopEnvironmentsService
      .new(project, current_user)
      .execute(branch_name)
  end
end


text:
import {Compose} from './compose';
import {If} from './if';
import {With} from './with';
import {Repeat} from './repeat';
import {Show} from './show';
import {SanitizeHTMLValueConverter} from './sanitize-html';
import {Replaceable} from './replaceable';
import {Focus} from './focus';
import {CompileSpy} from './compile-spy';
import {ViewSpy} from './view-spy';
import {ViewEngine} from 'aurelia-templating';
import {_createDynamicElement} from './dynamic-element';
import {_createCSSResource} from './css-resource';
import {FEATURE, DOM} from 'aurelia-pal';
import {HTMLSanitizer} from './html-sanitizer';
import {OneTimeBindingBehavior, OneWayBindingBehavior, TwoWayBindingBehavior} from './binding-mode-behaviors';
import {ThrottleBindingBehavior} from './throttle-binding-behavior';
import {DebounceBindingBehavior} from './debounce-binding-behavior';
import {SignalBindingBehavior} from './signal-binding-behavior';
import {BindingSignaler} from './binding-signaler';
import {UpdateTriggerBindingBehavior} from './update-trigger-binding-behavior';

function configure(config) {
  if (FEATURE.shadowDOM) {
    DOM.injectStyles('body /deep/ .aurelia-hide { display:none !important; }');
  } else {
    DOM.injectStyles('.aurelia-hide { display:none !important; }');
  }

  config.globalResources(
    './compose',
    './if',
    './with',
    './repeat',
    './show',
    './replaceable',
    './sanitize-html',
    './focus',
    './compile-spy',
    './view-spy',
    './binding-mode-behaviors',
    './throttle-binding-behavior',
    './debounce-binding-behavior',
    './signal-binding-behavior',
    './update-trigger-binding-behavior'
  );

  let viewEngine = config.container.get(ViewEngine);
  let loader = config.aurelia.loader;

  viewEngine.addResourcePlugin('.html', {
    'fetch': function(address) {
      return loader.loadTemplate(address).then(registryEntry => {
        let bindable = registryEntry.template.getAttribute('bindable');
        let elementName = address.replace('.html', '');
        let index = elementName.lastIndexOf('/');

        if (index !== 0) {
          elementName = elementName.substring(index + 1);
        }

        if (bindable) {
          bindable = bindable.split(',').map(x => x.trim());
          registryEntry.template.removeAttribute('bindable');
        } else {
          bindable = [];
        }

        return { [elementName]: _createDynamicElement(elementName, address, bindable) };
      });
    }
  });

  viewEngine.addResourcePlugin('.css', {
    'fetch': function(address) {
      return { [address]: _createCSSResource(address) };
    }
  });
}

export {
  Compose,
  If,
  With,
  Repeat,
  Show,
  HTMLSanitizer,
  SanitizeHTMLValueConverter,
  Replaceable,
  Focus,
  CompileSpy,
  ViewSpy,
  configure,
  OneTimeBindingBehavior,
  OneWayBindingBehavior,
  TwoWayBindingBehavior,
  ThrottleBindingBehavior,
  DebounceBindingBehavior,
  SignalBindingBehavior,
  BindingSignaler,
  UpdateTriggerBindingBehavior
};


text:
layout: default
title: Impressum
---

# Impressum

Das **Global Azure Bootcamp Austria** ist eine Veranstaltung des Coding Club Linz e.V., Birkenweg 16, A-4060 Leonding. Sie erreichen uns unter [info@coderdojo-linz.org](mailto:info@coderdojo-linz.org).


text:
(function(window, angular, ones, io){
    /*
     * @app productAttribute
     * @author laofahai@TEam Swift
     * @link http://ng-erp.com
     * */
    'use strict';
    ones.global_module

        .service('ProductAttribute.ProductAttributeAPI', [
            'ones.dataApiFactory',
            'ones.form_fields_factory',
            function(dataAPI, form_fields) {
                var self = this;

                this.resource = dataAPI.getResourceInstance({
                    uri: 'productAttribute/productAttribute',
                    extra_methods: ['api_get', 'api_query']
                });

                this.config = {
                    app: 'productAttribute',
                    module: 'productAttribute',
                    table: 'product_attribute',
                    fields: {
                        widget: {
                            widget: 'select',
                            data_source: [],
                            value: 'text',
                            get_display: function(value) {
                                return get_data_source_display(this.data_source, value);
                            }
                        },
                        data_type: {
                            widget: 'select',
                            data_source: DATA_TYPES_DATASOURCE,
                            value: 'string',
                            get_display: function(value) {
                                return get_data_source_display(this.data_source, value);
                            }
                        }
                    },
                    filters: {
                        widget: {
                            type: "link"
                        }
                    },
                    extra_selected_actions: [
                        {
                            label: _('productAttribute.View Product Attribute'),
                            icon: 'eye',
                            auth_node: "productAttribute.productAttributeContent.get",
                            action: function(evt, selected, item) {

                            }
                        }
                    ]
                };

                // 支持的输入控件
                angular.forEach(form_fields.widgets, function(widget) {
                    self.config.fields.widget.data_source.push({
                        value: widget,
                        label: _(widget+'.WIDGETS.'+camelCaseSpace(widget)+' Widget')
                    });
                });

                this.get_attributes = function() {
                    return this.resource.api_query().$promise;
                };

                /*
                * 将产品属性字段赋予模型字段配置
                * @param object model 模型对象实例
                * */
                this.assign_attributes = function(model, callback) {
                    this.get_attributes().then(function(attrs) {

                        model.config.bill_fields = model.config.bill_fields || [];
                        model.config.list_display = model.config.list_display || [];

                        angular.forEach(attrs, function(attr) {
                            if(!attr.alias || model.config.bill_fields.indexOf(attr.alias) >= 0) {
                                return false;
                            }
                            model.config.fields[attr.alias] = {
                                auto_query: true,
                                label: attr.name,
                                widget: attr.widget,
                                editable_required: 'product_id',
                                data_source: 'ProductAttribute.ProductAttributeContentAPI',
                                field: attr.alias,
                                field_model: attr.alias,
                                field_label_model: attr.alias + '__label__',
                                'ng-model': 'bill_rows[$parent.$index].' + attr.alias,
                                data_source_query_param: {
                                    _mf: 'product_attribute_id',
                                    _mv: attr.id
                                },
                                dynamic_add_opts: {
                                    addable: true
                                },
                                data_source_query_with: 'product_id' // 根据product_id查询
                            };

                            model.config.bill_fields.splice(
                                model.config.bill_fields.indexOf('product_id') + 1,
                                0,
                                attr.alias
                            );
                            model.config.list_display.splice(
                                model.config.list_display.indexOf('product_id') + 1,
                                0,
                                attr.alias
                            );
                        });

                        if(typeof callback === 'function') {
                            callback();
                        }
                    });
                };

            }
        ])

        .service('ProductAttribute.ProductAttributeContentAPI', [
            'ones.dataApiFactory',
            function(dataAPI) {
                var self = this;

                this.resource = dataAPI.getResourceInstance({
                    uri: 'productAttribute/productAttributeContent',
                    extra_methods: ['api_get', 'api_query']
                });

                this.config = {
                    app: 'productAttribute',
                    module: 'productAttributeContent',
                    table: 'product_attribute_content',
                    label_field: 'content',
                    fields: {
                        product_attribute_id: {
                            widget: 'select',
                            label: _('productAttribute.Product Attribute'),
                            data_source: 'ProductAttribute.ProductAttributeAPI',
                            get_display: function(value, item) {
                                return item.product_attribute_name;
                            }
                        },
                        product_id: {
                            widget: "select3",
                            data_source: "Product.ProductAPI",
                            group_tpl: FORM_FIELDS_TPL.select3_group_tpl,
                            label: _('product.Product')
                        },
                        product_name: {
                            label: _('product.Product'),
                            addable: false,
                            editable: false,
                            search_able: true
                        }
                    },
                    filters: {
                        product_attribute_id: {
                            type: "link"
                        }
                    },
                    addable: false
                };

            }
        ])

    ;

})(window, window.angular, window.ones, window.io);


text:
use warnings;
use strict;

sub usage()
{
  print STDERR "Usage: consensusAllFamilies family-dir\n" .
               "note: cons from EMBOSS is required in path\n";
  exit;
}

if ( @ARGV < 1 || $ARGV[0] eq "-h" )
{
  &usage();
}

sub main ()
{
  # open a family file
  my $familyDir = $ARGV[0];
  opendir (FAMILIES,"$familyDir");

  # create a directory for results.
  chop $familyDir if (substr($familyDir, -1) eq "/");
  my $resultsDir = $familyDir . "-consensus";
  mkdir "$resultsDir", 0755 or die "Could not create directory";

  # get all the family names
  #my @files = grep (/^[^\.]*\.faa/,readdir(FAMILIES));
  # pjh Feb 2015: generalize and accept either .faa or .fasta
  my @files = grep (/^[^\.]*\.fa/,readdir(FAMILIES));
  #print STDERR "$_\n" foreach (@files);

  foreach my $file (@files) {
    # get the consensus sequence
    system("cons $familyDir/$file $resultsDir/$file");
  }

  closedir FAMILIES;

  # ta da!
}

&main();


text:
<?php
/**
 * Piwik - free/libre analytics platform
 *
 * @link http://piwik.org
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 *
 */
namespace Piwik\AssetManager;

class UIAssetCatalogSorter
{
    /**
     * @var string[]
     */
    private $priorityOrder;

    /**
     * @param string[] $priorityOrder
     */
    function __construct($priorityOrder)
    {
        $this->priorityOrder = $priorityOrder;
    }

    /**
     * @param UIAssetCatalog $uiAssetCatalog
     * @return UIAssetCatalog
     */
    public function sortUIAssetCatalog($uiAssetCatalog)
    {
        $sortedCatalog = new UIAssetCatalog($this);
        foreach ($this->priorityOrder as $filePattern) {

            $assetsMatchingPattern = array_filter($uiAssetCatalog->getAssets(), function($uiAsset) use ($filePattern)  {
                return preg_match('~^' . $filePattern . '~', $uiAsset->getRelativeLocation());
            });

            foreach($assetsMatchingPattern as $assetMatchingPattern) {
                $sortedCatalog->addUIAsset($assetMatchingPattern);
            }
        }

        $this->addUnmatchedAssets($uiAssetCatalog, $sortedCatalog);

        return $sortedCatalog;
    }

    /**
     * @param UIAssetCatalog $uiAssetCatalog
     * @param UIAssetCatalog $sortedCatalog
     */
    private function addUnmatchedAssets($uiAssetCatalog, $sortedCatalog)
    {
        foreach ($uiAssetCatalog->getAssets() as $uiAsset) {
            $sortedCatalog->addUIAsset($uiAsset);
        }
    }
}


text:
> Role models are important.

> -- Officer Alex J. Murphy / RoboCop

**RuboCop** is a Ruby static code analyzer (a.k.a. linter) and code
formatter. Out of the box it will enforce many of the guidelines
outlined in the community [Ruby Style
Guide](https://github.com/rubocop-hq/ruby-style-guide).

Apart from reporting problems in your code, RuboCop can also
automatically fix some of the problems for you.

See ["Basic Usage"](basic_usage.md) to get yourself familiar with RuboCop's
capabilities.

RuboCop is an extremely flexible tool and most aspects of its behavior
can be tweaked via various [configuration
options](https://github.com/rubocop-hq/rubocop/blob/master/config/default.yml).


text:
<?php

declare(strict_types=1);

use PHPUnit\Framework\TestCase;

class SessionTest extends TestCase
{
}


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

namespace LitJson
{
	internal class OrderedDictionaryEnumerator : IDictionaryEnumerator, IEnumerator
	{
		private IEnumerator<KeyValuePair<string, JsonData>> list_enumerator;

		public object Current
		{
			get
			{
				return this.Entry;
			}
		}

		public DictionaryEntry Entry
		{
			get
			{
				KeyValuePair<string, JsonData> current = this.list_enumerator.Current;
				return new DictionaryEntry(current.Key, current.Value);
			}
		}

		public object Key
		{
			get
			{
				KeyValuePair<string, JsonData> current = this.list_enumerator.Current;
				return current.Key;
			}
		}

		public object Value
		{
			get
			{
				KeyValuePair<string, JsonData> current = this.list_enumerator.Current;
				return current.Value;
			}
		}

		public OrderedDictionaryEnumerator(IEnumerator<KeyValuePair<string, JsonData>> enumerator)
		{
			this.list_enumerator = enumerator;
		}

		public bool MoveNext()
		{
			return this.list_enumerator.MoveNext();
		}

		public void Reset()
		{
			this.list_enumerator.Reset();
		}
	}
}


text:
class MockECR(object):
  @property
  def aws_account_id(self):
    return '12345678'

  @property
  def registry(self):
    return []

  @property
  def project_repo(self):
    return 'nginxdemos'

  def project_repo_exists(self):
    return True

  def create_project_repo(self):
    return True

  def get_login(self):
    return ''

  def get_image_by_tag(self, tag):
    return 'latest'

  @property
  def images(self):
    return []

  def tag_exists(self, tag):
    return True

  def find_git_sha1_image_tag(self, tag):
    return 'latest'

  def retag(self, tag, new_tag):
    pass


text:
/**
 * $Id$
 */

#include <string>
using std::string;
#include <stdexcept>
using std::runtime_error;

#include <cppunit/extensions/HelperMacros.h>

#include "par_t.h"
#include "recap_t.h"

class TestTagest
: public CppUnit::TestFixture
{
public:
TestTagest() {;}
TestTagest(const TestTagest&);
virtual ~TestTagest() {;}

public:
CPPUNIT_TEST_SUITE(TestTagest);
CPPUNIT_TEST(testOrderingCollapseCohorts);
CPPUNIT_TEST(testGetParFileVersion);
CPPUNIT_TEST(testPathFileParser);
CPPUNIT_TEST_SUITE_END();
public:
void setUp() {
        ifstream ifs("file_nam.tmp");
        if (!ifs) {
                cerr << "Cannot open file_nam.tmp in main()" << endl;
                return;
        }
        ifs >> filename;
        ifs.close();
}
void tearDown() {
}
public:
void testOrderingCollapseCohorts() {
	typedef par_t<d3_array,dmatrix,dvector,double> Param;
	Param::createInstance(filename.c_str());
	CPPUNIT_ASSERT(Param::instance != 0);

	Param& param = *Param::instance;
	for (int release = 1; release < param.nrelease; release++) {
		CPPUNIT_ASSERT(param.get_tr_cohort(release) < param.get_tr_cohort(release + 1));
	}
	recaptype_vector* recaps = recaptype_vector::createInstance(filename.c_str(), param);
	CPPUNIT_ASSERT(recaptype_vector::instance != 0);

	param.collapse_cohorts(*recaps, recaps->getTotalRecords());
	for (int release = 1; release < param.nrelease; release++) {
		if (param.get_tr_cohort(release) > param.get_tr_cohort(release + 1)) {
			CPPUNIT_ASSERT(param.get_tr_cohort(release) < param.get_tr_cohort(release + 1));
		}
	}

	Param::deleteInstance();
	CPPUNIT_ASSERT(Param::instance == 0);

	recaptype_vector::deleteInstance();
	CPPUNIT_ASSERT(recaptype_vector::instance == 0);
}
void testGetParFileVersion() {
	typedef par_t<d3_array,dmatrix,dvector,double> Param;
	Param::createInstance(filename.c_str());
	CPPUNIT_ASSERT(Param::instance != 0);

	std::string parfile = filename + ".par";
        cifstream cifs(parfile.c_str());
	CPPUNIT_ASSERT(cifs.is_open() == true);
        adstring signature = cifs.signature();
	CPPUNIT_ASSERT(signature.length() > 0);
        cifs.close();
	Param& param = *Param::instance;
	CPPUNIT_ASSERT(param.getParFileVersion() == signature);

	Param::deleteInstance();
	CPPUNIT_ASSERT(Param::instance == 0);
}
void testPathFileParser() {
	adstring input("/home/maguro/johnoel/25/test/benchmark/v20r/ssap/6/skj10.par");
	PathFileParser parser(input);
	CPPUNIT_ASSERT(input(1, 51) == parser.getPath());
	CPPUNIT_ASSERT(input(52, 56) == parser.getRoot());
	CPPUNIT_ASSERT(input(1, 56) == parser.getPathRoot());
}
private:
string filename;
};

CPPUNIT_TEST_SUITE_REGISTRATION(TestTagest);


text:
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using System;
using Microsoft.Azure.WebJobs.Host.Executors;
using Xunit;

namespace Microsoft.Azure.WebJobs.Host.UnitTests.Executors
{
    public class FunctionResultTests
    {
        [Fact]
        public void Constructor_Boolean()
        {
            FunctionResult result = new FunctionResult(true);
            Assert.True(result.Succeeded);
            Assert.Null(result.Exception);

            result = new FunctionResult(false);
            Assert.False(result.Succeeded);
            Assert.Null(result.Exception);
        }

        [Fact]
        public void Constructor_Exception()
        {
            Exception exception = new Exception("Kaboom!");
            FunctionResult result = new FunctionResult(exception);
            Assert.False(result.Succeeded);
            Assert.Same(exception, result.Exception);
        }

        [Fact]
        public void Constructor_BooleanAndException()
        {
            Exception exception = new Exception("Kaboom!");
            FunctionResult result = new FunctionResult(true, exception);
            Assert.True(result.Succeeded);
            Assert.Same(exception, result.Exception);

            result = new FunctionResult(false, exception);
            Assert.False(result.Succeeded);
            Assert.Same(exception, result.Exception);
        }
    }
}


text:
============
Release 0.96
============

Hive Changes
------------

* Add support for tables partitioned by ``DATE``.


text:
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
    <string name="app_name">RxTwitch_MVP_Dagger</string>
    <string name="action_settings">Settings</string>
    <string name="video">Video</string>
    <string name="audio">Audio</string>
    <string name="text">text</string>
    <string name="logging">logging</string>
    <string name="retry">retry</string>

    <string name="error_drm_not_supported">Protected content not supported on API levels below 18</string>

    <string name="error_drm_unsupported_scheme">This device does not support the required DRM scheme</string>

    <string name="error_drm_unknown">An unknown DRM error occurred</string>

    <string name="error_no_decoder">This device does not provide a decoder for <xliff:g id="mime_type">%1$s</xliff:g></string>

    <string name="error_no_secure_decoder">This device does not provide a secure decoder for <xliff:g id="mime_type">%1$s</xliff:g></string>

    <string name="error_querying_decoders">Unable to query device decoders</string>

    <string name="error_instantiating_decoder">Unable to instantiate decoder <xliff:g id="decoder_name">%1$s</xliff:g></string>

    <string name="storage_permission_denied">Permission to access storage was denied</string>
    <string name="enable_background_audio">Play in background</string>

    <string name="logging_normal">Normal</string>

    <string name="logging_verbose">Verbose</string>
    <string name="off">[off]</string>
    <string name="live_end">live end!</string>
    <string name="connect_error1">无法获取数据</string>
    <string name="connect_error2">请连接网络后重试</string>
    <string name="refresh">刷新</string>

    <string name="following">Following</string>
    <string name="block">Blocking</string>
    <string name="chat">Chat</string>
    <string name="language">Language</string>
    <string name="updated_time">Updated Time</string>
    <string name="games">Games</string>
    <string name="profile">Profile</string>
    <string name="cancel">Cancel</string>
    <string name="edit_hint">search games,streams,and users…</string>
    <string name="no_internet">网路连接错误!</string>
    <string name="refresh_failed">刷新失败,请稍后重试!</string>
    <string name="error_update_time_toast">这是人类第一台Android手机诞生的时间。</string>
    <string name="error_update_time">2008.9.28</string>

    <string name="search_checkbox">pres_search_checkbox</string>
    <string name="checkbox_stream">stream</string>
    <string name="checkbox_game">game</string>
    <string name="checkbox_user">user</string>
    <string name="checkbox_block_game">Block Game</string>
    <string name="checkbox_block_user">Block User</string>
    <string name="checkbox_block_stream">Block Stream</string>
    <string name="choose_search_checkbox">请选择搜索选项!</string>

    <string name="following_error"> 网络错误,请稍后重试!</string>
    <string name="enter_keywords">请输入关键词</string>
    <string name="input_msg">input message, please.</string>
    <string name="coming_soon">coming soon</string>

    <!--toolbar checkbox-->
    <string name="search_game">Game</string>
    <string name="search_stream">Stream</string>
    <string name="search_user">User</string>

    <!--share-->
    <string name="choose_app">Share</string>
    <string name="share_channel">Watch %s with me on Twitch! \r</string>
    <string name="share_app">Watch game with me on Twitch! \r</string>
    <string name="timer">Timer</string>

    <string name="load_channel_error">Can not load data!</string>
    <string name="action_following">following</string>

    <!--settings-->
    <string name="settings">Settings</string>
    <string name="settings_network">Network</string>
    <string name="settings_wifi">仅在WIFI下观看视频</string>

    <string name="settings_check_version">检查更新</string>
    <string name="settings_version">v1.0</string>

    <string name="settings_clear_cache">清除缓存</string>
    <string name="settings_cache">0.0KB</string>
    <string name="settings_suggestion">问题反馈</string>
    <string name="settings_ue_improvement">用户体验改进计划</string>
    <string name="settings_share">分享此应用</string>
    <string name="settings_about_dev">关于开发者</string>
    <string name="settings_chat_text_size">聊天字号</string>

    <string name="settings_about">About me</string>

    <!--suggestion-->
    <string name="suggestion">Suggestions</string>
    <string name="suggestion_submit">Submit</string>
    <string name="suggestion_desc_hint">请详细描述您遇到的问题(不超过 1000 字)</string>
    <string name="suggestion_email_hint">电子邮箱(选填)</string>
    <string name="suggestion_feed_back">反馈图片</string>

    <!--only wifi dialog-->
    <string name="only_wifi_text">监测到您在使用手机流量,继续观看会大量消耗的手机流量,是否继续观看?</string>

    <string name="cancel_suggestion_text">要舍弃未提交的反馈吗?</string>

    <string name="no_search_results">No Search Results</string>
    <string name="no_games_followed">No Game Followed</string>
    <string name="no_streams_followed">No Stream Followed</string>
    <string name="no_channels_followed">No Channel Followed</string>

    <string name="toast_followed">Followed</string>
    <string name="toast_unfollowed">Unfollowed</string>
    <string name="toast_unfollow_error">取消关注失败,请连接网络!</string>
    <string name="toast_follow_error">关注失败,请连接网络!</string>

    <!--notifications-->

    <!--logout-->
    <string name="logout_confirm">确定退出登录?</string>
    <string name="logout">Logout</string>
    <string name="ok">OK</string>

</resources>


text:
#include "MiscSubclassDriver.h"

//
// Static (possibly build generated) Bios Vendor data.
//
MISC_SMBIOS_TABLE_DATA(EFI_MISC_PORT_INTERNAL_CONNECTOR_DESIGNATOR_DATA, MiscPortInternalConnectorDesignator) = {
  STRING_TOKEN(STR_MISC_PORT_INTERNAL_CONNECTOR_DESIGNATOR),  // PortInternalConnectorDesignator
  STRING_TOKEN(STR_MISC_PORT_EXTERNAL_CONNECTOR_DESIGNATOR),  // PortExternalConnectorDesignator
  EfiPortConnectorTypeOther,  // PortInternalConnectorType
  EfiPortConnectorTypeOther,  // PortExternalConnectorType
  EfiPortTypeNone,            // PortType
  0                           // PortPath
};

//
// Static (possibly build generated) Bios Vendor data.
//
MISC_SMBIOS_TABLE_DATA(EFI_MISC_PORT_INTERNAL_CONNECTOR_DESIGNATOR_DATA, MiscPortKeyboard) = {
  STRING_TOKEN (STR_MISC_PORT_INTERNAL_KEYBOARD),   // PortInternalConnectorDesignator
  STRING_TOKEN (STR_MISC_PORT_EXTERNAL_KEYBOARD),   // PortExternalConnectorDesignator
  EfiPortConnectorTypeNone, // PortInternalConnectorType
  EfiPortConnectorTypePS2,  // PortExternalConnectorType
  EfiPortTypeKeyboard,      // PortType
  // mPs2KbyboardDevicePath                          // PortPath
  //
  0
};

MISC_SMBIOS_TABLE_DATA(EFI_MISC_PORT_INTERNAL_CONNECTOR_DESIGNATOR_DATA, MiscPortMouse) = {
  STRING_TOKEN (STR_MISC_PORT_INTERNAL_MOUSE),      // PortInternalConnectorDesignator
  STRING_TOKEN (STR_MISC_PORT_EXTERNAL_MOUSE),      // PortExternalConnectorDesignator
  EfiPortConnectorTypeNone, // PortInternalConnectorType
  EfiPortConnectorTypePS2,  // PortExternalConnectorType
  EfiPortTypeMouse,         // PortType
  // mPs2MouseDevicePath                // PortPath
  //
  0
};

MISC_SMBIOS_TABLE_DATA(EFI_MISC_PORT_INTERNAL_CONNECTOR_DESIGNATOR_DATA, MiscPortCom1) = {
  STRING_TOKEN(STR_MISC_PORT_INTERNAL_COM1),
  STRING_TOKEN(STR_MISC_PORT_EXTERNAL_COM1),
  EfiPortConnectorTypeNone,
  EfiPortConnectorTypeDB9Female,
  EfiPortTypeSerial16550ACompatible,
  0
};

MISC_SMBIOS_TABLE_DATA(EFI_MISC_PORT_INTERNAL_CONNECTOR_DESIGNATOR_DATA, MiscPortCom2) = {
  STRING_TOKEN(STR_MISC_PORT_INTERNAL_COM2),
  STRING_TOKEN(STR_MISC_PORT_EXTERNAL_COM2),
  EfiPortConnectorTypeNone,
  EfiPortConnectorTypeDB9Female,
  EfiPortTypeSerial16550ACompatible,
  0
};

MISC_SMBIOS_TABLE_DATA(EFI_MISC_PORT_INTERNAL_CONNECTOR_DESIGNATOR_DATA, MiscPortExtensionPower) = {
  STRING_TOKEN(STR_MISC_PORT_INTERNAL_EXTENSION_POWER),
  STRING_TOKEN(STR_MISC_PORT_EXTERNAL_EXTENSION_POWER),
  EfiPortConnectorTypeOther,
  EfiPortConnectorTypeNone,
  EfiPortTypeOther,
  0
};

MISC_SMBIOS_TABLE_DATA(EFI_MISC_PORT_INTERNAL_CONNECTOR_DESIGNATOR_DATA, MiscPortFloppy) = {
  STRING_TOKEN(STR_MISC_PORT_INTERNAL_FLOPPY),
  STRING_TOKEN(STR_MISC_PORT_EXTERNAL_FLOPPY),
  EfiPortConnectorTypeOnboardFloppy,
  EfiPortConnectorTypeNone,
  EfiPortTypeOther,
  0
};

/* eof - MiscPortInternalConnectorDesignatorData.c */


text:
package com.vtence.molecule;

import com.vtence.molecule.lib.matchers.Matcher;
import com.vtence.molecule.middlewares.FilterMap;
import com.vtence.molecule.middlewares.Router;
import com.vtence.molecule.routing.RouteBuilder;
import com.vtence.molecule.servers.SimpleServer;

import javax.net.ssl.SSLContext;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.security.GeneralSecurityException;

import static com.vtence.molecule.lib.KeyStoreType.DEFAULT;
import static com.vtence.molecule.lib.SecureProtocol.TLS;

public class WebServer {

    public static final String LOCAL_ADDRESS = "0.0.0.0";
    public static final int DEFAULT_PORT = 8080;

    private final Server server;
    private final MiddlewareStack stack;

    private SSLContext ssl;

    public static WebServer create() {
        return create(DEFAULT_PORT);
    }

    public static WebServer create(int port) {
        return create(LOCAL_ADDRESS, port);
    }

    public static WebServer create(String host, int port) {
        return new WebServer(new SimpleServer(host, port));
    }

    public WebServer(Server server) {
        this.server = server;
        this.stack = new MiddlewareStack();
    }

    public WebServer enableSSL(File keyStore, String storePassword, String keyPassword) throws GeneralSecurityException, IOException {
        return enableSSL(TLS.initialize(DEFAULT.loadKeys(keyStore, storePassword, keyPassword)));
    }

    public WebServer enableSSL(SSLContext context) {
        this.ssl = context;
        return this;
    }

    public WebServer failureReporter(FailureReporter reporter) {
        server.reportErrorsTo(reporter);
        return this;
    }

    public WebServer add(Middleware middleware) {
        stack.use(middleware);
        return this;
    }

    public WebServer filter(String path, Middleware filter) {
        stack.use(new FilterMap().map(path, filter));
        return this;
    }

    public WebServer filter(Matcher<? super Request> requestMatcher, Middleware filter) {
        stack.use(new FilterMap().map(requestMatcher, filter));
        return this;
    }

    public Server start(RouteBuilder routes) throws IOException {
        return start(Router.draw(routes));
    }

    public Server start(Application application) throws IOException {
        server.run(stack.run(application), ssl);
        return server;
    }

    public void stop() throws IOException {
        server.shutdown();
    }

    public URI uri() {
        return URI.create((ssl != null ? "https://" : "http://") + server.host() + ":" + server.port());
    }
}


text:
<?php
/*
	Verify User Authentication
*/
session_start();

// Get credentials
require_once __DIR__.'/db.php';

// Workaround to getting AngularJS post data as $_REQUEST does not work
$params = json_decode(file_get_contents('php://input'),true);

$username = $params['username'];
$password = $params['password'];

try {
	$dbh = new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", $mysql_username, $mysql_password);
	$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	$stmt = $dbh->prepare("SELECT user_id FROM dummy_users WHERE username = :username AND password_hash = md5(concat(password_salt,:password))");
	$stmt->bindParam(':username', $username, PDO::PARAM_STR);
	$stmt->bindParam(':password', $password, PDO::PARAM_STR, 40);

	$stmt->execute();

	$user_id = $stmt->fetchColumn();

	if ($user_id == false) {
		// Login Failed
		die('{"success": false, "error": "Login Failed, Try Again"}');
	}
	else {
		$_SESSION['user_id'] = $user_id;
	}
}
catch(Exception $e) {
	// DB Failed
	die('{"success": false, "message": "'.$e.'"}');
}

// Return success
die('{"success": true, "user_id": '.$user_id.'}');
?>


text:
import React, { useState } from 'react';

import { Box, CheckBox } from 'grommet';

const SimpleCheckBox = ({ checked: checkedProp, ...rest }) => {
  const [checked, setChecked] = useState(!!checkedProp);
  const onChange = (event) => setChecked(event.target.checked);

  return (
    <Box gap="small" align="center" pad="large">
      <CheckBox {...rest} checked={checked} onChange={onChange} />
    </Box>
  );
};

export const Simple = () => (
  <>
    <SimpleCheckBox label="Reversed Checkbox" reverse />
    <SimpleCheckBox label="Disabled Checkbox" checked disabled />
  </>
);

export default {
  title: 'Input/CheckBox/Simple',
};


text:
{- Copyright (C) 2014 Calvin Beck

   Permission is hereby granted, free of charge, to any person
   obtaining a copy of this software and associated documentation files
   (the "Software"), to deal in the Software without restriction,
   including without limitation the rights to use, copy, modify, merge,
   publish, distribute, sublicense, and/or sell copies of the Software,
   and to permit persons to whom the Software is furnished to do so,
   subject to the following conditions:

   The above copyright notice and this permission notice shall be
   included in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
   NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
   BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
   ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
   CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
   SOFTWARE.
-}

import SurvivalPlot.Parser

import Data.Attoparsec.Text hiding (take)
import qualified Data.Text.IO as T
import qualified Data.Foldable as F

import Graphics.Rendering.Chart.Easy
import Graphics.Rendering.Chart.Backend.Cairo

import System.Directory
import System.Directory.Tree
import System.Environment
import System.FilePath

-- | Plots for one set of iterations.
-- | SurvivalPlot model-dir distribution-dir
-- | distribution directory contains iteration 1, 2, and 3 (as does the model directory)
-- | We assume that the distribution directory has the same structure as the model directory
-- | and that the file extension of the distributions is ".out"
main :: IO ()
main = do (plotDir:errorName:intervalDir:args) <- getArgs

          let distributionDirs = map snd . filter (\(n,_) -> n `mod` 2 == 0) $ zip [0..] args
          let names = map snd . filter (\(n,_) -> n `mod` 2 == 1) $ zip [0..] args

          putStrLn "Getting averages..."
          tests <- getTestAvgs distributionDirs

          putStrLn "Plotting errors..."
          createDirectoryIfMissing True plotDir
          plotErrors names tests (joinPath [plotDir, errorName])

          putStrLn "Plotting all curves..."
          plotAllCurves intervalDir distributionDirs plotDir

          putStrLn "Done!"

plotAllCurves intervalDir dataDirs plotDir =
  do readDir <- readDirectoryWith return intervalDir
     let intervalFiles = F.toList $ dirTree readDir
     sequence_ [plotIntervalFile inter dir plotDir | inter <- intervalFiles, dir <- dataDirs]

plotIntervalFile intervalFile dataDir plotDir =
  do intervalData <- T.readFile intervalFile
     let intervals = takeRight intervalFile $ parseOnly parseIntervals intervalData

     dataData <- T.readFile dataFile
     let (curves, _) = takeRight dataFile $ parseOnly parseDistributions dataData

     plotCurves intervals curves plotFile
  where dataFile = joinPath (dataDir : dirs ++ [(replaceExtension (takeFileName intervalFile) "out")])
        plotFile = joinPath (plotDir : dirs ++ [(replaceExtension (takeFileName intervalFile) "pdf")])
        (_:_:dirs) = splitDirectories (dropFileName intervalFile)

takeRight _ (Right a) = a
takeRight file _ = error ("Could not parse file: " ++ file)

getTestAvgs :: [FilePath] -> IO [TestInfo]
getTestAvgs allDirs = mapM getTestAvg allDirs

getTestAvg :: FilePath -> IO TestInfo
getTestAvg dir = do readDir <- readDirectoryWith return dir
                    let files = F.toList $ dirTree readDir

                    distData <- mapM T.readFile files
                    let infos = map (\(f, d) -> snd . takeRight f $ parseOnly parseDistributions d) (zip files distData)

                    return (avgTestInfo infos)

plotCurves intervals curves fileName =
  do createDirectoryIfMissing True (takeDirectory fileName)
     toFile (fo_format .~ PDF $ def) fileName $
       do layout_title .= "Survival Curves"
          mapM_ (\curve -> plot (line "" [(zip intervals (map constrain . curvePoints $ curve))])) (take 10 curves)
  where constrain n = if n > 1
                         then 1
                         else if n < 0
                                 then 0
                                 else n

plotErrors names tests fileName =
  do createDirectoryIfMissing True (takeDirectory fileName)
     toFile (fo_format .~ PDF $ def) fileName $
       do layout_title .= "Average Losses"
          layout_x_axis . laxis_generate .= autoIndexAxis names
          plot $ fmap plotBars $ bars ["L2-log"] (addIndexes indexes)
  where indexes = map ((: []) . (!! 4) . testLosses) tests

testLosses :: TestInfo -> [Double]
testLosses (TestInfo _ l1 l2 rae l1Log l2Log logLikely) = [l1, l2, rae, l1Log, l2Log, logLikely]

lossesToTest :: Double -> [Double] -> TestInfo
lossesToTest c [l1, l2, rae, l1Log, l2Log, logLikely] = TestInfo c l1 l2 rae l1Log l2Log logLikely

-- | From a list of TestInfo data create a new one with the average of all losses.
avgTestInfo :: [TestInfo] -> TestInfo
avgTestInfo tests = (foldl infoSum (TestInfo 0 0 0 0 0 0 0) tests) `infoDiv` (fromIntegral $ length tests)
  where infoSum t1 t2 = lossesToTest (concordance t1) (zipWith (+) (testLosses t1) (testLosses t2))
        infoDiv t1 s = lossesToTest (concordance t1) (zipWith (/) (testLosses t1) (repeat s))


text:
package com.opengamma.engine.function.dsl.properties;

import com.opengamma.engine.value.ValueProperties;

public class WithoutAny extends ValuePropertiesModifier {

  public WithoutAny(final String propertyName) {
    super(propertyName);
  }

  @Override
  public ValueProperties.Builder modify(final ValueProperties.Builder builder) {
    return builder.withoutAny(getPropertyName());
  }

}


text:
namespace extensions {

namespace {

// Return the menu label for a global error.
base::string16 GetMenuItemLabel(const Extension* extension) {
  if (!extension)
    return base::string16();

  int id = -1;
  if (extension->is_app())
    id = IDS_EXTENSION_EXTERNAL_INSTALL_ALERT_APP;
  else if (extension->is_theme())
    id = IDS_EXTENSION_EXTERNAL_INSTALL_ALERT_THEME;
  else
    id = IDS_EXTENSION_EXTERNAL_INSTALL_ALERT_EXTENSION;

  return l10n_util::GetStringFUTF16(id, base::UTF8ToUTF16(extension->name()));
}

// A global error that spawns a dialog when the menu item is clicked.
class ExternalInstallMenuAlert : public GlobalError {
 public:
  explicit ExternalInstallMenuAlert(ExternalInstallError* error);
  virtual ~ExternalInstallMenuAlert();

 private:
  // GlobalError implementation.
  virtual Severity GetSeverity() OVERRIDE;
  virtual bool HasMenuItem() OVERRIDE;
  virtual int MenuItemCommandID() OVERRIDE;
  virtual base::string16 MenuItemLabel() OVERRIDE;
  virtual void ExecuteMenuItem(Browser* browser) OVERRIDE;
  virtual bool HasBubbleView() OVERRIDE;
  virtual bool HasShownBubbleView() OVERRIDE;
  virtual void ShowBubbleView(Browser* browser) OVERRIDE;
  virtual GlobalErrorBubbleViewBase* GetBubbleView() OVERRIDE;

  // The owning ExternalInstallError.
  ExternalInstallError* error_;

  DISALLOW_COPY_AND_ASSIGN(ExternalInstallMenuAlert);
};

// A global error that spawns a bubble when the menu item is clicked.
class ExternalInstallBubbleAlert : public GlobalErrorWithStandardBubble {
 public:
  explicit ExternalInstallBubbleAlert(ExternalInstallError* error,
                                      ExtensionInstallPrompt::Prompt* prompt);
  virtual ~ExternalInstallBubbleAlert();

 private:
  // GlobalError implementation.
  virtual Severity GetSeverity() OVERRIDE;
  virtual bool HasMenuItem() OVERRIDE;
  virtual int MenuItemCommandID() OVERRIDE;
  virtual base::string16 MenuItemLabel() OVERRIDE;
  virtual void ExecuteMenuItem(Browser* browser) OVERRIDE;

  // GlobalErrorWithStandardBubble implementation.
  virtual gfx::Image GetBubbleViewIcon() OVERRIDE;
  virtual base::string16 GetBubbleViewTitle() OVERRIDE;
  virtual std::vector<base::string16> GetBubbleViewMessages() OVERRIDE;
  virtual base::string16 GetBubbleViewAcceptButtonLabel() OVERRIDE;
  virtual base::string16 GetBubbleViewCancelButtonLabel() OVERRIDE;
  virtual void OnBubbleViewDidClose(Browser* browser) OVERRIDE;
  virtual void BubbleViewAcceptButtonPressed(Browser* browser) OVERRIDE;
  virtual void BubbleViewCancelButtonPressed(Browser* browser) OVERRIDE;

  // The owning ExternalInstallError.
  ExternalInstallError* error_;

  // The Prompt with all information, which we then use to populate the bubble.
  ExtensionInstallPrompt::Prompt* prompt_;

  DISALLOW_COPY_AND_ASSIGN(ExternalInstallBubbleAlert);
};

////////////////////////////////////////////////////////////////////////////////
// ExternalInstallMenuAlert

ExternalInstallMenuAlert::ExternalInstallMenuAlert(ExternalInstallError* error)
    : error_(error) {
}

ExternalInstallMenuAlert::~ExternalInstallMenuAlert() {
}

GlobalError::Severity ExternalInstallMenuAlert::GetSeverity() {
  return SEVERITY_LOW;
}

bool ExternalInstallMenuAlert::HasMenuItem() {
  return true;
}

int ExternalInstallMenuAlert::MenuItemCommandID() {
  return IDC_EXTERNAL_EXTENSION_ALERT;
}

base::string16 ExternalInstallMenuAlert::MenuItemLabel() {
  return GetMenuItemLabel(error_->GetExtension());
}

void ExternalInstallMenuAlert::ExecuteMenuItem(Browser* browser) {
  error_->ShowDialog(browser);
}

bool ExternalInstallMenuAlert::HasBubbleView() {
  return false;
}

bool ExternalInstallMenuAlert::HasShownBubbleView() {
  NOTREACHED();
  return true;
}

void ExternalInstallMenuAlert::ShowBubbleView(Browser* browser) {
  NOTREACHED();
}

GlobalErrorBubbleViewBase* ExternalInstallMenuAlert::GetBubbleView() {
  return NULL;
}

////////////////////////////////////////////////////////////////////////////////
// ExternalInstallBubbleAlert

ExternalInstallBubbleAlert::ExternalInstallBubbleAlert(
    ExternalInstallError* error,
    ExtensionInstallPrompt::Prompt* prompt)
    : error_(error), prompt_(prompt) {
  DCHECK(error_);
  DCHECK(prompt_);
}

ExternalInstallBubbleAlert::~ExternalInstallBubbleAlert() {
}

GlobalError::Severity ExternalInstallBubbleAlert::GetSeverity() {
  return SEVERITY_LOW;
}

bool ExternalInstallBubbleAlert::HasMenuItem() {
  return true;
}

int ExternalInstallBubbleAlert::MenuItemCommandID() {
  return IDC_EXTERNAL_EXTENSION_ALERT;
}

base::string16 ExternalInstallBubbleAlert::MenuItemLabel() {
  return GetMenuItemLabel(error_->GetExtension());
}

void ExternalInstallBubbleAlert::ExecuteMenuItem(Browser* browser) {
  ShowBubbleView(browser);
}

gfx::Image ExternalInstallBubbleAlert::GetBubbleViewIcon() {
  if (prompt_->icon().IsEmpty())
    return GlobalErrorWithStandardBubble::GetBubbleViewIcon();
  // Scale icon to a reasonable size.
  return gfx::Image(gfx::ImageSkiaOperations::CreateResizedImage(
      *prompt_->icon().ToImageSkia(),
      skia::ImageOperations::RESIZE_BEST,
      gfx::Size(extension_misc::EXTENSION_ICON_SMALL,
                extension_misc::EXTENSION_ICON_SMALL)));
}

base::string16 ExternalInstallBubbleAlert::GetBubbleViewTitle() {
  return prompt_->GetDialogTitle();
}

std::vector<base::string16>
ExternalInstallBubbleAlert::GetBubbleViewMessages() {
  std::vector<base::string16> messages;
  messages.push_back(prompt_->GetHeading());
  if (prompt_->GetPermissionCount()) {
    messages.push_back(prompt_->GetPermissionsHeading());
    for (size_t i = 0; i < prompt_->GetPermissionCount(); ++i) {
      messages.push_back(l10n_util::GetStringFUTF16(
          IDS_EXTENSION_PERMISSION_LINE, prompt_->GetPermission(i)));
    }
  }
  // TODO(yoz): OAuth issue advice?
  return messages;
}

base::string16 ExternalInstallBubbleAlert::GetBubbleViewAcceptButtonLabel() {
  return prompt_->GetAcceptButtonLabel();
}

base::string16 ExternalInstallBubbleAlert::GetBubbleViewCancelButtonLabel() {
  return prompt_->GetAbortButtonLabel();
}

void ExternalInstallBubbleAlert::OnBubbleViewDidClose(Browser* browser) {
}

void ExternalInstallBubbleAlert::BubbleViewAcceptButtonPressed(
    Browser* browser) {
  error_->InstallUIProceed();
}

void ExternalInstallBubbleAlert::BubbleViewCancelButtonPressed(
    Browser* browser) {
  error_->InstallUIAbort(true);
}

}  // namespace

////////////////////////////////////////////////////////////////////////////////
// ExternalInstallError

ExternalInstallError::ExternalInstallError(
    content::BrowserContext* browser_context,
    const std::string& extension_id,
    AlertType alert_type,
    ExternalInstallManager* manager)
    : browser_context_(browser_context),
      extension_id_(extension_id),
      alert_type_(alert_type),
      manager_(manager),
      error_service_(GlobalErrorServiceFactory::GetForProfile(
          Profile::FromBrowserContext(browser_context_))),
      weak_factory_(this) {
  prompt_ = new ExtensionInstallPrompt::Prompt(
      ExtensionInstallPrompt::EXTERNAL_INSTALL_PROMPT);

  webstore_data_fetcher_.reset(new WebstoreDataFetcher(
      this, browser_context_->GetRequestContext(), GURL(), extension_id_));
  webstore_data_fetcher_->Start();
}

ExternalInstallError::~ExternalInstallError() {
  if (global_error_.get())
    error_service_->RemoveGlobalError(global_error_.get());
}

void ExternalInstallError::InstallUIProceed() {
  const Extension* extension = GetExtension();
  if (extension) {
    ExtensionSystem::Get(browser_context_)
        ->extension_service()
        ->GrantPermissionsAndEnableExtension(extension);
    // Since the manager listens for the extension to be loaded, this will
    // remove the error...
  } else {
    // ... Otherwise we have to do it explicitly.
    manager_->RemoveExternalInstallError();
  }
}

void ExternalInstallError::InstallUIAbort(bool user_initiated) {
  if (user_initiated && GetExtension()) {
    ExtensionSystem::Get(browser_context_)
        ->extension_service()
        ->UninstallExtension(
            extension_id_,
            ExtensionService::UNINSTALL_REASON_INSTALL_CANCELED,
            NULL);  // Ignore error.
    // Since the manager listens for the extension to be removed, this will
    // remove the error...
  } else {
    // ... Otherwise we have to do it explicitly.
    manager_->RemoveExternalInstallError();
  }
}

void ExternalInstallError::ShowDialog(Browser* browser) {
  DCHECK(install_ui_.get());
  DCHECK(prompt_.get());
  DCHECK(browser);
  content::WebContents* web_contents = NULL;
#if !defined(OS_ANDROID)
  web_contents = browser->tab_strip_model()->GetActiveWebContents();
#endif
  ExtensionInstallPrompt::ShowParams params(web_contents);
  ExtensionInstallPrompt::GetDefaultShowDialogCallback().Run(
      params, this, prompt_);
}

const Extension* ExternalInstallError::GetExtension() const {
  return ExtensionRegistry::Get(browser_context_)
      ->GetExtensionById(extension_id_, ExtensionRegistry::EVERYTHING);
}

void ExternalInstallError::OnWebstoreRequestFailure() {
  OnFetchComplete();
}

void ExternalInstallError::OnWebstoreResponseParseSuccess(
    scoped_ptr<base::DictionaryValue> webstore_data) {
  std::string localized_user_count;
  double average_rating;
  int rating_count;
  if (!webstore_data->GetString(kUsersKey, &localized_user_count) ||
      !webstore_data->GetDouble(kAverageRatingKey, &average_rating) ||
      !webstore_data->GetInteger(kRatingCountKey, &rating_count)) {
    // If we don't get a valid webstore response, short circuit, and continue
    // to show a prompt without webstore data.
    OnFetchComplete();
    return;
  }

  bool show_user_count = true;
  webstore_data->GetBoolean(kShowUserCountKey, &show_user_count);

  prompt_->SetWebstoreData(
      localized_user_count, show_user_count, average_rating, rating_count);
  OnFetchComplete();
}

void ExternalInstallError::OnWebstoreResponseParseFailure(
    const std::string& error) {
  OnFetchComplete();
}

void ExternalInstallError::OnFetchComplete() {
  // Create a new ExtensionInstallPrompt. We pass in NULL for the UI
  // components because we display at a later point, and don't want
  // to pass ones which may be invalidated.
  install_ui_.reset(
      new ExtensionInstallPrompt(Profile::FromBrowserContext(browser_context_),
                                 NULL,    // NULL native window.
                                 NULL));  // NULL navigator.

  install_ui_->ConfirmExternalInstall(
      this,
      GetExtension(),
      base::Bind(&ExternalInstallError::OnDialogReady,
                 weak_factory_.GetWeakPtr()),
      prompt_);
}

void ExternalInstallError::OnDialogReady(
    const ExtensionInstallPrompt::ShowParams& show_params,
    ExtensionInstallPrompt::Delegate* prompt_delegate,
    scoped_refptr<ExtensionInstallPrompt::Prompt> prompt) {
  DCHECK_EQ(this, prompt_delegate);
  prompt_ = prompt;

  if (alert_type_ == BUBBLE_ALERT) {
    global_error_.reset(new ExternalInstallBubbleAlert(this, prompt_));
    error_service_->AddGlobalError(global_error_.get());

    Browser* browser = NULL;
#if !defined(OS_ANDROID)
    browser =
        chrome::FindTabbedBrowser(Profile::FromBrowserContext(browser_context_),
                                  true,
                                  chrome::GetActiveDesktop());
#endif  // !defined(OS_ANDROID)
    if (browser)
      global_error_->ShowBubbleView(browser);
  } else {
    DCHECK(alert_type_ == MENU_ALERT);
    global_error_.reset(new ExternalInstallMenuAlert(this));
    error_service_->AddGlobalError(global_error_.get());
  }
}

}  // namespace extensions