text:
'use strict';

const batch    = require('batch-stream');
const Mongoose = require('mongoose');
const stream   = require('stream');
const { pipeline } = require('stream/promises');
const progress = require('./utils').progress;
const Schema   = Mongoose.Schema;

const BATCH_SIZE = 10000;

module.exports = async function (N) {
  await N.models.users.Vote.aggregate([
    { $match: { type: N.shared.content_type.FORUM_POST } },
    {
      $project: {
        for: '$for',
        votes_hb: '$value',
        votes: { $cond: { if: { $eq: [ '$hb', true ] }, then: 0, else: '$value' } }
      }
    },
    {
      $group: {
        _id: '$for',
        votes: { $sum: '$votes' },
        votes_hb: { $sum: '$votes_hb' }
      }
    },
    { $out: 'vbconvert.post_vote_recount_tmp' }
  ]).allowDiskUse(true);

  let schema = new Schema({
    votes:    Number,
    votes_hb: Number
  }, {
    versionKey: false
  });

  let AggregationResult = Mongoose.model('PostVoteRecount', schema, 'vbconvert.post_vote_recount_tmp');

  async function process_chunk(chunk) {
    let bulk = N.models.forum.Post.collection.initializeUnorderedBulkOp();

    for (let result of chunk) {
      bulk.find({ _id: result._id })
          .update({ $set: {
            votes:    result.votes,
            votes_hb: result.votes_hb
          } });
    }

    if (bulk.length > 0) await bulk.execute();
  }

  let count = await AggregationResult.estimatedDocumentCount();
  let bar = progress(' post vote recount :current/:total :percent', count);

  await pipeline(
    AggregationResult.find()
        .sort('_id')
        .lean(true)
        .cursor(),

    batch({ size: BATCH_SIZE }),

    new stream.Writable({
      objectMode: true,
      highWaterMark: 2, // buffer 2 chunks at most
      write(chunk, __, callback) {
        process_chunk(chunk)
          .then(() => {
            bar.tick(chunk.length);
            callback();
          }, err => { callback(err); });
      }
    })
  );

  bar.terminate();

  await AggregationResult.collection.drop();

  N.logger.info('Post vote recount finished');
};


text:
import sys
import pandas as pd
import operator
import re

class LibSvm_Utilities(object):
    @staticmethod
    def write_libsvm_file_from_vectors_list(list_of_vectors, classes_list, output_file_libsvm):
        with open(output_file_libsvm, "w") as libsvm_file:
            for row_idx in range(0, len(list_of_vectors)):
                row_class=classes_list[row_idx]
                libsvm_file.write('{:d}'.format(row_class))
                for f_idx in range(0,len(list_of_vectors[row_idx])):
                    libsvm_file.write('\t{:d}:{:f}'.format(f_idx+1, list_of_vectors[row_idx][f_idx]))
                libsvm_file.write('\n')

    @staticmethod
    def write_libsvm_file_from_sparsefeatures_list(list_of_sparse, classes_list, feat_dict, output_file_libsvm):
        feat_dict_sorted_tupl = sorted(feat_dict.iteritems(), key=lambda (k,v): (v,k))
        #feat_dict_sorted = {}
        #for k,v in feat_dict_sorted_tupl:
        #    feat_dict_sorted[k]=v

        print feat_dict_sorted_tupl
        with open(output_file_libsvm, "w") as libsvm_file:
            for row_idx in range(0, len(list_of_sparse)):
                row_class=classes_list[row_idx]
                libsvm_file.write('{:d}'.format(row_class))

                for key, val in feat_dict_sorted_tupl:
                    if key in list_of_sparse[row_idx]:
                        #print "Row:%s;Key:%s"%(row_idx, key)
                        #print list_of_sparse[row_idx][key]
                        libsvm_file.write('\t%d:%f'%(int(val), list_of_sparse[row_idx][key]))

                libsvm_file.write('\n')

    @staticmethod
    def write_libsvm_file_from_intkey_floatval_sparsefeatures_tuple_list(list_of_sparse, classes_list, output_file_libsvm, filter_includekeys=None, sort_features=False):
        with open(output_file_libsvm, "w") as libsvm_file:
            #print filter_includekeys
            for row_idx in range(0, len(list_of_sparse)):
                row_class=classes_list[row_idx]
                libsvm_file.write('{:d}'.format(row_class))
                #print list_of_sparse[row_idx]

                if sort_features:
                    feat_sorted_tupl = sorted(list_of_sparse[row_idx], key=lambda tup: tup[0])
                else:
                    feat_sorted_tupl = list_of_sparse[row_idx]

                if not filter_includekeys is None:
                    feat_sorted_tupl = [(x,y) for (x,y) in feat_sorted_tupl if x in filter_includekeys]

                #print feat_sorted_tupl
                for key, val in feat_sorted_tupl:
                    libsvm_file.write('\t%d:%f'%(key, val))

                libsvm_file.write('\n')

    @staticmethod
    def read_libsvm_features_into_intkey_floatval_sparsefeatures_dict_list(input_file_libsvm):
        data_dict_list=[]
        classes_list=[]

        with open(input_file_libsvm,'r') as libsvm_file:
            for line in libsvm_file:
                items =  re.split('\s', line.strip())
                classes_list.append(int(items[0]))
                values_dict = {}
                for i in range(1,len(items)):
                    item_kv = items[i].split(':')
                    values_dict[int(item_kv[0])] = float(item_kv[1])

                data_dict_list.append(values_dict)

        return classes_list, data_dict_list

    @staticmethod
    def read_libsvm_features_into_intkey_floatval_sparsefeatures_tuple_list(input_file_libsvm):
        data_dict_list=[]
        classes_list=[]

        with open(input_file_libsvm,'r') as libsvm_file:
            for line in libsvm_file:
                items =  re.split('\s', line.strip())
                classes_list.append(int(items[0]))
                values_dict = []
                for i in range(1,len(items)):
                    item_kv = items[i].split(':')
                    values_dict.append((int(item_kv[0]),float(item_kv[1])))

                data_dict_list.append(values_dict)

        return classes_list, data_dict_list

    @staticmethod
    def read_libsvm_predictions_file(libsvm_predictions_file, autoremove_headers=True):
        res_data = []
        with open(libsvm_predictions_file, "r") as f:
            for line in f:
                if(line.startswith("labels")):
                    continue
                res_data.append(line.replace("\n","").split(" "))

        return res_data

if __name__ == '__main__':
    sample_data = [[0.4, 0.5, 0.23, -0.14], \
    [0.33, 0.67, -0.36, -0.44], \
    [0.56, 0.5, -0.86, -0.54]]

    sample_data1 = [[0.2, 0.1, 0.123, -0.45], \
    [0.133, 0.47, -0.23, -0.11], \
    [0.16, 0.9, -0.36, -0.44]]

    classes = [0,1,0]
    output_file="text.libsvm"

    #combine arrays into feature vectors
    sample_data_export=[]
    for i in range(0, len(sample_data)):
        data_row = sample_data[i]+sample_data1[i]
        sample_data_export.append(data_row)

    #calculate similarity
    from scipy import spatial
    similarities=[]
    for i in range(0, len(sample_data)):
        similarity =1 - spatial.distance.cosine(sample_data[i],sample_data1[i])
        similarities.append(similarity)

    print "Similarities:"
    print similarities
    #export to livsvm format
    import time
    start = time.time()
    LibSvm_Utilities.write_libsvm_file_from_vectors_list(sample_data_export, classes, output_file)
    end = time.time()
    print("Done! Execution time: %s s"%(end - start))

redpajama_set_name: RedPajamaGithub


text:
class ProveUru::PersonalData
  attr_accessor :title, :forename, :middlename, :surname, :gender, :dob, :email

  def to_prove_hash
    {
      "Title" => self.title,
      "Forename" => self.forename,
      "MiddleName" => self.middlename,
      "Surname" => self.surname,
      "Gender" => self.gender.blank? ? "Unknown" : self.gender,
      "DOBDay" => self.dob.blank? ? "" : self.dob.day,
      "DOBMonth" => self.dob.blank? ? "" : self.dob.month,
      "DOBYear" => self.dob.blank? ? "" : self.dob.year,
      "Email" => self.email
    }
  end

end
# <Title>string</Title>
#  <Forename>string</Forename>
#  <MiddleName>string</MiddleName>
#  <Surname>string</Surname>
#  <Gender>Unspecified or Unknown or Male or Female</Gender>
#  <DOBDay>int</DOBDay>
#  <DOBMonth>int</DOBMonth>
#  <DOBYear>int</DOBYear>
#  <Email>string</Email>


text:
set -uo pipefail; f=bazel_tools/tools/bash/runfiles/runfiles.bash
source "${RUNFILES_DIR:-/dev/null}/$f" 2>/dev/null || \
  source "$(grep -sm1 "^$f " "${RUNFILES_MANIFEST_FILE:-/dev/null}" | cut -f2- -d' ')" 2>/dev/null || \
  source "$0.runfiles/$f" 2>/dev/null || \
  source "$(grep -sm1 "^$f " "$0.runfiles_manifest" | cut -f2- -d' ')" 2>/dev/null || \
  source "$(grep -sm1 "^$f " "$0.exe.runfiles_manifest" | cut -f2- -d' ')" 2>/dev/null || \
  { echo>&2 "ERROR: cannot find $f"; exit 1; }; f=; set -e
# --- end runfiles.bash initialization v2 ---

set -euox pipefail

classes_file=$(rlocation rules_jvm_external/tests/integration/kt_jvm_export/classes.txt)

if grep -q DependencyKt.class "$classes_file"; then
  echo "Unexpectedly found dependency class in jar"
  exit 1
fi

if ! grep -q MainKt.class "$classes_file"; then
  echo "Missing main class from jar"
  exit 1
fi


text:
module B
  def bar() 3 end
end

module A

  include B
  module_function :bar
end

A::bar + 4


text:
export default function () {
  this.filter("cssfmt", (data) => {
    try {
      return require("cssfmt").process(data.toString())
     } catch (e) { throw e }
  })
}


text:
package elements

//
//type Template struct {
//	Base
//}


text:
import os
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp import template

class MainHandler(webapp.RequestHandler):
    def get(self, preso_dir):
      base_dir = os.path.dirname(__file__)
      if os.path.isdir(os.path.join(base_dir, preso_dir)):
        template_values = { 'base_dir': self.request.path_url }
        path = os.path.join(base_dir, preso_dir, 'index.html')
        self.response.out.write(template.render(path, template_values))

def main():
    application = webapp.WSGIApplication([('/(.*)', MainHandler)], debug=False)
    util.run_wsgi_app(application)

if __name__ == '__main__':
    main()


text:
require 'concurrent-edge'

def do_stuff
  :stuff
end

Concurrent.use_simple_logger Logger::DEBUG


text:
module BreezeGrid {

    export class BreezeGrid<T> implements BreezeGridMethods<T> {

        public columns: KnockoutObservableArray<Column<T>>;

        public sortColumn = ko.observable<Column<T>>(null);
        public sortDesc = ko.observable(false);
        public totalCount = ko.observable(0);

        public rows = ko.observableArray<T>();

        public loading = ko.observable(true);
        public templates: { [index: string]: string; };

        public dataProvider: DataProvider;

        constructor(public options: GridOptions<T>) {

            initKoNumericExtender();

            //initialize plugins
            (options.plugins || []).forEach(p => {

                var plugin: BreezeGridPlugin<T> = typeof (p) == 'function' ? new p() : p;
                var original: BreezeGridMethods<T> = {};
                this.initPlugin(plugin, original);
                plugin.init(this, original);

            });

            options.columns.forEach(this.initColumn);

            this.sortColumn(options.columns[0]);

            this.columns = ko.observableArray(options.columns);

            this.templates = <any> this.getDefaultTemplates();

            this.dataProvider = options.dataProvider;

        }

        private initPlugin<T>(plugin: BreezeGridPlugin<T>, original: BreezeGridMethods<T>) {
            for (var p in plugin) {

                if (typeof (plugin[p]) == 'function') {
                    if (typeof (this[p]) == 'function') {
                        original[p] = this[p].bind(this);
                    }
                    this[p] = plugin[p].bind(plugin);
                }
            }

        }

        public initColumn(col: Column<T>) {

            if (!col.field && col.fieldName) {
                col.field = function(row) {
                    return row[this.fieldName];
                }
            } else if (col.field && !col.fieldName) {
                col.fieldName = BreezeGrid.getExpression(col.field);
            }

            if (typeof (col.width) == 'undefined') {
                col.width = null;
            }
            else if (typeof(col.width) == 'number') {
                col.width = <any>(col.width + 'px');
            }

            if (typeof (col.sortable) == 'undefined') {
                col.sortable = true;
            }

            if (!col.sortExpression) {
                col.sortExpression = col.fieldName;
            }

            if (!col.headerText) {
                col.headerText = col.fieldName;
            }
            if (col.viewTemplate) {
                //if (typeof (col.viewTemplate) == 'function') {
                  //  col.viewTemplate = new col.viewTemplate();
                //} else {
                    //col.viewTemplate = col.viewTemplate;
                //}
            } else {
                col.viewTemplate = ViewBuilder.Default;
            }

        }

        private static getExpression(func): string {

            var expr = func.toString();

            var myregexp = /return .*\.(\w+);?/;
            var match = myregexp.exec(expr);
            if (match != null) {
                return match[1];
            }
            return null;
        }

        public performSort(column: Column<T>) {
            if (this.sortColumn() == column)
                this.sortDesc(!this.sortDesc());
            else {
                this.sortColumn(column);
                this.sortDesc(false);
            }

            this.search();

        }

        public getCurrentView(column: Column<T>, row: T) {

            var value = ko.utils.unwrapObservable(column.field(row));
            var displayValue = column.formatter ? column.formatter(value, row) : value;

            var viewTemplate = column.viewTemplate;
            return viewTemplate(column, displayValue, row);
        }

        public search() {

            this.loading(true);

            var options = this.getQueryOptions();

            this.dataProvider.executeQuery(options, data => {

                this.searchComplete(data);

                this.rows(<any[]>data.results);

                this.setTotalCount(data);

                this.loading(false);

            });

        }

        public setTotalCount(data: breeze.QueryResult) {
            this.totalCount(data.results.length);
        }

        public getQueryOptions() {

            return {
                sortDesc: this.sortDesc(),
                sortColumn: this.sortColumn().sortExpression

            };
        }

        public searchComplete(data) {

        }

        public getDefaultTemplates() {

            return {
                headerRowTemplate: '',

                headerCellTemplate:
                "	",
                sortableHeaderCellTemplate:
                "	",

                footerRowTemplate: '' +
                '

' +
                '	',
                footerTemplate:
                '
' +
                ' ' +
                'Records' +
                '
'

            };
        }

        public getRowTemplate() {

            var rowbindings = '';

            if (this.options.rowCssClass) {
                rowbindings = "attr: {'class': $parent.options.rowCssClass($data) }, ";
            }

            if (this.options.rowBindings) {
                rowbindings += this.options.rowBindings;
            }

            var rowTemplate = '
' +
                '	' +
                '
';

            return rowTemplate;
        }

        public headerCellTemplateName(column: Column<T>) {

            return (column.sortable ? 'sortableHeaderCellTemplate' : 'headerCellTemplate');
        }

        public initBindings(element: JQuery) {

        }
    }

    export interface BreezeGridMethods<T> {

        //overridable methods
        getCurrentView? (column: Column<T>, row: T);
        getDefaultTemplates? ();
        initBindings? (element: JQuery)
        getQueryOptions? (): QueryOptions;
        searchComplete? (data: breeze.QueryResult);
        initColumn? (col: Column<T>);
        setTotalCount? (data: breeze.QueryResult);
        getRowTemplate?: ()=>string;
    }

    export interface SelectOptions {
        options: any;
        optionsText?: string;
        optionsValue?: string;
        optionsCaption?: string;
    }

    export interface Column<TEntity> {

        field?: (entity: TEntity) => any;
        fieldName?: string;
        headerText?: string;
        cssClass?: (row?: TEntity)=> string;
        width?: number;
        sortable?: boolean;
        formatter?: (value: any, row?: TEntity) => string;
        editor?: any;
        sortExpression?: string;
        viewTemplate?: (col: Column<TEntity>, value, row: TEntity)=>any;
        //viewTemplateInstance?: Views.View<TEntity>;
    }

    export interface DataProvider {
        executeQuery(options: QueryOptions, callback: breeze.ExecuteQuerySuccessCallback): Q.Promise<breeze.QueryResult>;
        createEntity();
        saveChanges(row, saveOptions?: breeze.SaveOptions): Q.Promise<breeze.SaveResult>;

    }

    export class BreezeDataProvider implements DataProvider {

        constructor(public manager: breeze.EntityManager, public query: breeze.EntityQuery, private entityTypeName: string) {

        }

        public executeQuery(options: QueryOptions, callback: breeze.ExecuteQuerySuccessCallback) {

            var q = this.query;

            q = options.sortDesc ? q.orderByDesc(options.sortColumn) : q.orderBy(options.sortColumn);

            if (options.includeTotalCount)
                q = q.inlineCount();

            if (typeof (options.currentPage) != 'undefined') {
                var skip = (options.currentPage - 1) * options.pageSize;
                q = q.skip(skip).take(options.pageSize);
            }

            return this.manager.executeQuery(q, callback);

        }

        public createEntity() {
            return this.manager.createEntity(this.entityTypeName);
        }
        public saveChanges(row) {
            return this.manager.saveChanges(row);
        }

    }

    export interface GridOptions<TEntity> {

        dataProvider: DataProvider;
        plugins?: any[];
        columns: Column<TEntity>[];
        rowCssClass?: (row?: TEntity) => string;
        rowBindings?: string;
        tableCssClass?: string;
    }

    export interface QueryOptions {
        sortColumn: string;
        sortDesc: boolean;
        currentPage?: number;
        pageSize?: number;
        includeTotalCount?: boolean;
    }

    export class ViewBuilder<TEntity> {

        static Default<TEntity>(col: Column<TEntity>, value, row: TEntity) {
            return {
                div: {
                    text: value,
                    attr:
                    {
                        title: value
                    },
                    style: {
                        width: col.width
                    }
                }
            }
        }

        public Default(col: Column<TEntity>, value, row: TEntity) {
            return ViewBuilder.Default(col, value, row);
        }

        public ExtendDefault(builder: (row: TEntity) => any) {
            return (col: Column<TEntity>, value, row: TEntity) => {
                var result = ViewBuilder.Default(col, value, row);
                return extendDeep(result, builder(row));

            };
        }

        public Hyperlink(hrefBuilder: (row: TEntity) => string) {

            return (col: Column<TEntity>, value, row: TEntity) => {
                return {
                    a: {
                        text: value,
                        attr:
                        {
                            href: hrefBuilder(row),
                            title: value
                        },
                        style: {
                            width: col.width
                        }
                    }
                };
            };
        }

    }

    function extendDeep(target, source) {
        if (source) {
            for (var prop in source) {
                if (source.hasOwnProperty(prop)) {

                    if (typeof (source[prop]) == 'object') {
                        extendDeep(target[prop], source[prop]);
                    } else {
                        target[prop] = source[prop];
                    }
                }
            }
        }
        return target;
    }

    export module Editors {
        export interface Editor {
            getTemplate(col: Column<any>, row);
        }

        export class Text implements Editor {

            public getTemplate(col: Column<any>, row) {
                return {
                    input: {
                        value: col.field(row),
                        attr: { type: 'text', 'class': 'form-control' },
                        //style: { width: col.width + 'px' },

                    }
                }
            }
        }

        export class Checkbox implements Editor {
            public getTemplate(col: Column<any>, row) {
                return {
                    input: {
                        checked: col.field(row),
                        attr: { type: 'checkbox' },
                    }
                }
            }
        }

        export class Select implements Editor {

            constructor(private valueGetter: (row) => any, private options: SelectOptions) {

            }
            public getTemplate(col: Column<any>, row) {

                var result = <any> {
                    select: {
                        attr: { 'class': 'form-control' },
                        value: this.valueGetter(row)
                    }
                };
                ko.utils.extend(result.select, this.options);
                return result;

            }

        }

        export class MultiSelect implements Editor {

            constructor(private valueGetter: (row) => any, private options: SelectOptions) {

            }
            public getTemplate(col: Column<any>, row) {

                var selectedOptions = this.valueGetter(row);

                if (ko.isObservable(selectedOptions)) {

                    var computedOptions = ko.computed({
                        read: function () {
                            return selectedOptions().split(', ');
                        },
                        write: function (value: string[]) {

                            selectedOptions(value.join(', '));
                        },
                    });

                    var result = <any> {
                        select: {
                            attr: { 'class': 'form-control', multiple: 'multiple' },
                            selectedOptions: computedOptions

                        }
                    };
                    ko.utils.extend(result.select, this.options);
                    return result;

                }

            }

        }

    }

    export interface BreezeGridPlugin<T> extends BreezeGridMethods<T> {
        init(grid: BreezeGrid<T>, original: BreezeGridMethods<T>) : void;

    }

    function initKoNumericExtender() {

        if (!ko.extenders['numeric']) {
            //from http://knockoutjs.com/documentation/extenders.html

            ko.extenders['numeric'] = function(target, precision) {
                //create a writeable computed observable to intercept writes to our observable
                var result = ko.computed({
                    read: target, //always return the original observables value
                    write: function(newValue: number) {
                        var current = target(),
                            roundingMultiplier = Math.pow(10, precision),
                            newValueAsNum = isNaN(newValue) ? 0 : parseFloat(<any>+newValue),
                            valueToWrite = Math.round(newValueAsNum * roundingMultiplier) / roundingMultiplier;

                        //only write if it changed
                        if (valueToWrite !== current) {
                            target(valueToWrite);
                        } else {
                            //if the rounded value is the same, but a different value was written, force a notification for the current field
                            if (newValueAsNum !== current) {
                                target.notifySubscribers(valueToWrite);
                            }
                        }
                    }
                }).extend({ notify: 'always' });

                //initialize with current value to make sure it is rounded appropriately
                result(target());

                //return the new computed observable
                return result;
            };
        }
    }

}


text:
namespace device {
class BluetoothAdapter;
}

namespace metrics {
class ChromeUserMetricsExtension;
}

class PrefRegistrySimple;
class PrefService;

// Performs ChromeOS specific metrics logging.
class ChromeOSMetricsProvider : public metrics::MetricsProvider {
 public:
  ChromeOSMetricsProvider();
  virtual ~ChromeOSMetricsProvider();

  static void RegisterPrefs(PrefRegistrySimple* registry);

  // Records a crash.
  static void LogCrash(const std::string& crash_type);

  // Loads hardware class information. When this task is complete, |callback|
  // is run.
  void InitTaskGetHardwareClass(const base::Closure& callback);

  // metrics::MetricsProvider:
  virtual void OnDidCreateMetricsLog() OVERRIDE;
  virtual void ProvideSystemProfileMetrics(
      metrics::SystemProfileProto* system_profile_proto) OVERRIDE;
  virtual void ProvideStabilityMetrics(
      metrics::SystemProfileProto* system_profile_proto) OVERRIDE;
  virtual void ProvideGeneralMetrics(
      metrics::ChromeUserMetricsExtension* uma_proto) OVERRIDE;

 private:
  // Called on the FILE thread to load hardware class information.
  void InitTaskGetHardwareClassOnFileThread();

  // Update the number of users logged into a multi-profile session.
  // If the number of users change while the log is open, the call invalidates
  // the user count value.
  void UpdateMultiProfileUserCount(
      metrics::SystemProfileProto* system_profile_proto);

  // Sets the Bluetooth Adapter instance used for the WriteBluetoothProto()
  // call.
  void SetBluetoothAdapter(scoped_refptr<device::BluetoothAdapter> adapter);

  // Writes info about paired Bluetooth devices on this system.
  void WriteBluetoothProto(metrics::SystemProfileProto* system_profile_proto);

  metrics::PerfProvider perf_provider_;

  // Bluetooth Adapter instance for collecting information about paired devices.
  scoped_refptr<device::BluetoothAdapter> adapter_;

  // Whether the user count was registered at the last log initialization.
  bool registered_user_count_at_log_initialization_;

  // The user count at the time that a log was last initialized. Contains a
  // valid value only if |registered_user_count_at_log_initialization_| is
  // true.
  uint64 user_count_at_log_initialization_;

  // Hardware class (e.g., hardware qualification ID). This class identifies
  // the configured system components such as CPU, WiFi adapter, etc.
  std::string hardware_class_;

  base::WeakPtrFactory<ChromeOSMetricsProvider> weak_ptr_factory_;

  DISALLOW_COPY_AND_ASSIGN(ChromeOSMetricsProvider);
};

#endif  // CHROME_BROWSER_METRICS_CHROMEOS_METRICS_PROVIDER_H_


text: Tests for user agent string template


text:
package org.drools.compiler.integrationtests;

import java.util.ArrayList;
import java.util.List;
import org.drools.compiler.Cheesery;
import org.drools.compiler.Child;
import org.drools.compiler.CommonTestMethodBase;
import org.drools.compiler.MockPersistentSet;
import org.drools.compiler.ObjectWithSet;
import org.junit.Test;
import org.kie.api.KieBase;
import org.kie.api.runtime.KieSession;

import static org.junit.Assert.assertEquals;

public class ShadowProxyTest extends CommonTestMethodBase {

    @Test
    public void testShadowProxyInHierarchies() throws Exception {
        final KieBase kbase = SerializationHelper.serializeObject(loadKnowledgeBase("test_ShadowProxyInHierarchies.drl"));
        final KieSession ksession = createKnowledgeSession(kbase);
        try {
            ksession.insert(new Child("gp"));
            ksession.fireAllRules();
        } finally {
            ksession.dispose();
        }
    }

    @Test
    public void testShadowProxyOnCollections() throws Exception {
        final KieBase kbase = SerializationHelper.serializeObject(loadKnowledgeBase("test_ShadowProxyOnCollections.drl"));
        final KieSession ksession = createKnowledgeSession(kbase);
        try {
            final List results = new ArrayList();
            ksession.setGlobal("results", results);

            final Cheesery cheesery = new Cheesery();
            ksession.insert(cheesery);

            ksession.fireAllRules();
            assertEquals(1, results.size());
            assertEquals(1, cheesery.getCheeses().size());
            assertEquals(results.get(0), cheesery.getCheeses().get(0));
        } finally {
            ksession.dispose();
        }
    }

    @Test
    public void testShadowProxyOnCollections2() throws Exception {
        final KieBase kbase = SerializationHelper.serializeObject(loadKnowledgeBase("test_ShadowProxyOnCollections2.drl"));
        final KieSession ksession = createKnowledgeSession(kbase);
        try {
            final List results = new ArrayList();
            ksession.setGlobal("results", results);

            final List list = new ArrayList();
            list.add("example1");
            list.add("example2");

            final MockPersistentSet mockPersistentSet = new MockPersistentSet(false);
            mockPersistentSet.addAll(list);
            final ObjectWithSet objectWithSet = new ObjectWithSet();
            objectWithSet.setSet(mockPersistentSet);

            ksession.insert(objectWithSet);

            ksession.fireAllRules();

            assertEquals(1, results.size());
            assertEquals("show", objectWithSet.getMessage());
        } finally {
            ksession.dispose();
        }
    }
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.facebook.presto.hive.parquet.reader;

import com.facebook.presto.hive.parquet.ParquetCodecFactory.BytesDecompressor;
import com.google.common.primitives.Ints;
import parquet.column.page.DataPage;
import parquet.column.page.DataPageV1;
import parquet.column.page.DataPageV2;
import parquet.column.page.DictionaryPage;
import parquet.column.page.PageReader;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

class ParquetColumnChunkPageReader
        implements PageReader
{
    private final BytesDecompressor decompressor;
    private final long valueCount;
    private final List<DataPage> compressedPages;
    private final DictionaryPage compressedDictionaryPage;

    public ParquetColumnChunkPageReader(BytesDecompressor decompressor,
            List<DataPage> compressedPages,
            DictionaryPage compressedDictionaryPage)
    {
        this.decompressor = decompressor;
        this.compressedPages = new LinkedList<>(compressedPages);
        this.compressedDictionaryPage = compressedDictionaryPage;
        int count = 0;
        for (DataPage page : compressedPages) {
            count += page.getValueCount();
        }
        this.valueCount = count;
    }

    @Override
    public long getTotalValueCount()
    {
        return valueCount;
    }

    @Override
    public DataPage readPage()
    {
        if (compressedPages.isEmpty()) {
            return null;
        }
        DataPage compressedPage = compressedPages.remove(0);
        try {
            if (compressedPage instanceof DataPageV1) {
                DataPageV1 dataPageV1 = (DataPageV1) compressedPage;
                return new DataPageV1(
                        decompressor.decompress(dataPageV1.getBytes(), dataPageV1.getUncompressedSize()),
                        dataPageV1.getValueCount(),
                        dataPageV1.getUncompressedSize(),
                        dataPageV1.getStatistics(),
                        dataPageV1.getRlEncoding(),
                        dataPageV1.getDlEncoding(),
                        dataPageV1.getValueEncoding());
            }
            else {
                DataPageV2 dataPageV2 = (DataPageV2) compressedPage;
                if (!dataPageV2.isCompressed()) {
                    return dataPageV2;
                }
                int uncompressedSize = Ints.checkedCast(dataPageV2.getUncompressedSize() - dataPageV2.getDefinitionLevels().size() - dataPageV2.getRepetitionLevels().size());
                return DataPageV2.uncompressed(
                        dataPageV2.getRowCount(),
                        dataPageV2.getNullCount(),
                        dataPageV2.getValueCount(),
                        dataPageV2.getRepetitionLevels(),
                        dataPageV2.getDefinitionLevels(),
                        dataPageV2.getDataEncoding(),
                        decompressor.decompress(dataPageV2.getData(), uncompressedSize),
                        dataPageV2.getStatistics());
            }
        }
        catch (IOException e) {
            throw new RuntimeException("Could not decompress page", e);
        }
    }

    @Override
    public DictionaryPage readDictionaryPage()
    {
        if (compressedDictionaryPage == null) {
            return null;
        }
        try {
            return new DictionaryPage(
                    decompressor.decompress(compressedDictionaryPage.getBytes(), compressedDictionaryPage.getUncompressedSize()),
                    compressedDictionaryPage.getDictionarySize(),
                    compressedDictionaryPage.getEncoding());
        }
        catch (IOException e) {
            throw new RuntimeException("Error reading dictionary page", e);
        }
    }
}


text:
[Traefik](http://traefik.io/) is a modern HTTP reverse proxy and load balancer made to deploy
microservices with ease.

__DISCLAIMER:__ While this chart has been well-tested, testers have encountered occasional issues
with the Traefik software itself. Be advised that your mileage may vary.

## Introduction

This chart bootstraps Traefik as a Kubernetes ingress controller with optional support for SSL and
Let's Encrypt.

__NOTE:__ Operators will typically wish to install this component into the `kube-system` namespace
where that namespace's default service account will ensure adequate privileges to watch `Ingress`
resources _cluster-wide_.

## Prerequisites

- Kubernetes 1.4+ with Beta APIs enabled
- You are deploying the chart to a cluster with a cloud provider capable of provisioning an
external load balancer (e.g. AWS or GKE)
- You control DNS for the domain(s) you intend to route through Traefik
- __Suggested:__ PV provisioner support in the underlying infrastructure

## Installing the Chart

To install the chart with the release name `my-release`:

```bash
$ helm install stable/traefik --name my-release --namespace kube-system
```

After installing the chart, create DNS records for applicable domains to direct inbound traffic to
the load balancer. You can use the commands below to find the load balancer's IP/hostname:

__NOTE:__ It may take a few minutes for this to become available.

You can watch the status by running:

```bash
$ kubectl get svc my-release-traefik --namespace kube-system -w
```

Once `EXTERNAL-IP` is no longer `<pending>`:

```bash
$ kubectl describe service my-release-traefik -n kube-system | grep Ingress | awk '{print $3}'
```

__NOTE:__ If ACME support is enabled, it is only _after_ this step is complete that Traefik will be
able to successfully use the ACME protocol to obtain certificates from Let's Encrypt.

## Uninstalling the Chart

To uninstall/delete the `my-release` deployment:

```bash
$ helm delete my-release
```

The command removes all the Kubernetes components associated with the chart and deletes the
release.

## Configuration

The following tables lists the configurable parameters of the Traefik chart and their default values.

| Parameter                       | Description                                                          | Default                                   |
| ------------------------------- | -------------------------------------------------------------------- | ----------------------------------------- |
| `imageTag`                      | The version of the official Traefik image to use                     | `v1.1.2`                                  |
| `serviceType`                   | A valid Kubernetes service type                                      | `LoadBalancer`                            |
| `cpuRequest`                    | Initial share of CPU requested per Traefik pod                       | `100m`                                    |
| `memoryRequest`                 | Initial share of memory requested per Traefik pod                    | `20Mi`                                    |
| `cpuLimit`                      | CPU limit per Traefik pod                                            | `200m`                                    |
| `memoryLimit`                   | Memory limit per Traefik pod                                         | `30Mi`                                    |
| `ssl.enabled`                   | Whether to enable HTTPS                                              | `false`                                   |
| `ssl.enforced`                  | Whether to redirect HTTP requests to HTTPS                           | `false`                                   |
| `ssl.defaultCert`               | Base64 encoded default certficate                                    | A self-signed certificate                 |
| `ssl.defaultKey`                | Base64 encoded private key for the certificate above                 | The private key for the certificate above |
| `acme.enabled`                  | Whether to use Let's Encrypt to obtain certificates                  | `false`                                   |
| `acme.email`                    | Email address to be used in certificates obtained from Let's Encrypt | `admin@example.com`                       |
| `acme.staging`                  | Whether to get certs from Let's Encrypt's staging environment        | `true`                                    |
| `acme.persistence.enabled`      | Create a volume to store ACME certs (if ACME is enabled)             | `true`                                    |
| `acme.persistence.storageClass` | Type of `StorageClass` to request-- will be cluster-specific         | `nil` (uses alpha storage class annotation) |
| `acme.persistence.accessMode`   | `ReadWriteOnce` or `ReadOnly`                                        | `ReadWriteOnce`                           |
| `acme.persistence.size`         | Minimum size of the volume requested                                 | `1Gi`                                     |
| `dashboard.enabled`             | Whether to enable the Traefik dashboard                              | `false`                                   |
| `dashboard.domain`              | Domain for the Traefik dashboard                                     | `traefik.example.com`                     |
| `dashboard.ingress.annotations` | Annotations for the Traefik dashboard Ingress definition, specified as a map | None                              |
| `service.annotations`           | Annotations for the Traefik Service definition, specified as a map   | None                                      |
| `service.labels`                | Additional labels for the Traefik Service definition, specified as a map | None                                  |
| `gzip.enabled`                  | Whether to use gzip compression                                      | `true`                                    |
| `kubernetes.namespaces`         | List of Kubernetes namespaces to watch                               | All namespaces                            |
| `kubernetes.labelSelector`      | Valid Kubernetes ingress label selector to watch (e.g `realm=public`)| No label filter                           |

Specify each parameter using the `--set key=value[,key=value]` argument to `helm install`. For example:

```bash
$ helm install --name my-release --namespace kube-system --set dashboard.enabled=true,dashboard.domain=traefik.example.com stable/traefik
```

The above command enables the Traefik dashboard on the domain `traefik.example.com`.

Alternatively, a YAML file that specifies the values for the parameters can be provided while
installing the chart. For example:

```bash
$ helm install --name my-release --namespace kube-system --values values.yaml stable/traefik
```


text:
package org.apache.parquet.bytes;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;

/**
 * Tests the deprecated behavior of instantiating ByteBufferInputStream directly
 */
@RunWith(Parameterized.class)
public class TestDeprecatedBufferInputStream extends TestByteBufferInputStreams {
  @Parameter(0)
  public ByteBuffer data;
  @Parameter(1)
  public Integer offset;

  @Parameters
  public static List<Object[]> parameters() {
    return Arrays.asList(
        new Object[] { TestSingleBufferInputStream.DATA, null },
        new Object[] { TestSingleBufferInputStream.DATA, 0 },
        new Object[] { ByteBuffer.wrap(new byte[] { -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
            15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34 }), 4 },
        new Object[] { ByteBuffer.wrap(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
            19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, -1, -1, -1 }), 0 },
        new Object[] { ByteBuffer.wrap(new byte[] { -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
            16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, -1, -1 }), 3 });
  }

  @Override
  protected ByteBufferInputStream newStream() {
    if (offset == null) {
      return new ByteBufferInputStream(data);
    } else {
      return new ByteBufferInputStream(data, offset, DATA_LENGTH);
    }
  }

  @Override
  protected void checkOriginalData() {
    Assert.assertEquals("Position should not change", 0, data.position());
    Assert.assertEquals("Limit should not change",
        data.array().length, data.limit());
  }

  @Test
  public void testSliceData() throws Exception {
    ByteBufferInputStream stream = newStream();
    int length = stream.available();

    List<ByteBuffer> buffers = new ArrayList<>();
    // slice the stream into 3 8-byte buffers and 1 2-byte buffer
    while (stream.available() > 0) {
      int bytesToSlice = Math.min(stream.available(), 8);
      buffers.add(stream.slice(bytesToSlice));
    }

    Assert.assertEquals("Position should be at end", length, stream.position());
    Assert.assertEquals("Should produce 5 buffers", 5, buffers.size());

    int i = 0;

    ByteBuffer one = buffers.get(0);
    Assert.assertSame("Should use the same backing array",
        one.array(), data.array());
    Assert.assertEquals(8, one.remaining());
    Assert.assertEquals(0, one.position());
    Assert.assertEquals(8, one.limit());
    for (; i < 8; i += 1) {
      Assert.assertEquals("Should produce correct values", i, one.get());
    }

    ByteBuffer two = buffers.get(1);
    Assert.assertSame("Should use the same backing array",
        two.array(), data.array());
    Assert.assertEquals(8, two.remaining());
    Assert.assertEquals(8, two.position());
    Assert.assertEquals(16, two.limit());
    for (; i < 16; i += 1) {
      Assert.assertEquals("Should produce correct values", i, two.get());
    }

    // three is a copy of part of the 4th buffer
    ByteBuffer three = buffers.get(2);
    Assert.assertSame("Should use the same backing array",
        three.array(), data.array());
    Assert.assertEquals(8, three.remaining());
    Assert.assertEquals(16, three.position());
    Assert.assertEquals(24, three.limit());
    for (; i < 24; i += 1) {
      Assert.assertEquals("Should produce correct values", i, three.get());
    }

    // four should be a copy of the next 8 bytes
    ByteBuffer four = buffers.get(3);
    Assert.assertSame("Should use the same backing array",
        four.array(), data.array());
    Assert.assertEquals(8, four.remaining());
    Assert.assertEquals(24, four.position());
    Assert.assertEquals(32, four.limit());
    for (; i < 32; i += 1) {
      Assert.assertEquals("Should produce correct values", i, four.get());
    }

    // five should be a copy of the next 8 bytes
    ByteBuffer five = buffers.get(4);
    Assert.assertSame("Should use the same backing array",
        five.array(), data.array());
    Assert.assertEquals(3, five.remaining());
    Assert.assertEquals(32, five.position());
    Assert.assertEquals(35, five.limit());
    for (; i < 35; i += 1) {
      Assert.assertEquals("Should produce correct values", i, five.get());
    }
  }

  @Test
  public void testWholeSliceBuffersData() throws Exception {
    ByteBufferInputStream stream = newStream();

    List<ByteBuffer> buffers = stream.sliceBuffers(stream.available());
    Assert.assertEquals("Should return duplicates of all non-empty buffers",
        Collections.singletonList(TestSingleBufferInputStream.DATA), buffers);
  }
}


text:
 #include <Arduino.h>
#else
 #include <WProgram.h>
 #include <pins_arduino.h>
#endif

class LPD8806 {

 public:

  LPD8806(uint16_t n, uint8_t dpin, uint8_t cpin); // Configurable pins
  LPD8806(uint16_t n); // Use SPI hardware; specific pins only
  LPD8806(void); // Empty constructor; init pins & strip length later
  void
    begin(void),
    show(void),
    setPixelColor(uint16_t n, uint8_t r, uint8_t g, uint8_t b),
    setPixelColor(uint16_t n, uint32_t c),
    updatePins(uint8_t dpin, uint8_t cpin), // Change pins, configurable
    updatePins(void),                       // Change pins, hardware SPI
    updateLength(uint16_t n);               // Change strip length
  uint16_t
    numPixels(void);
  uint32_t
    Color(byte, byte, byte),
    getPixelColor(uint16_t n);

 private:

  uint16_t
    numLEDs,    // Number of RGB LEDs in strip
    numBytes;   // Size of 'pixels' buffer below
  uint8_t
    *pixels,    // Holds LED color values (3 bytes each) + latch
    clkpin    , datapin,     // Clock & data pin numbers
    clkpinmask, datapinmask; // Clock & data PORT bitmasks
  volatile uint8_t
    *clkport  , *dataport;   // Clock & data PORT registers
  void
    startBitbang(void),
    startSPI(void);
  boolean
    hardwareSPI, // If 'true', using hardware SPI
    begun;       // If 'true', begin() method was previously invoked
};
#endif


text:
use cql_bindgen::CassIterator as _CassIterator;
use cql_bindgen::cass_iterator_free;
use cql_bindgen::cass_iterator_next;
use cql_bindgen::cass_iterator_get_column;
use cql_bindgen::CassRow as _CassRow;
use cql_bindgen::cass_row_get_column;
use cql_bindgen::cass_row_get_column_by_name;
use cql_bindgen::cass_iterator_from_row;
use cql_bindgen::CASS_ERROR_LIB_INDEX_OUT_OF_BOUNDS;

use std::fmt::Debug;
use std::fmt::Display;
use std::fmt::Formatter;
use std::fmt;
use std::ffi::CString;
use std::iter::IntoIterator;
use std::iter;

use cql_ffi::value::CassValue;
use cql_ffi::error::CassError;
use cql_ffi::column::CassColumn;

pub struct CassRow(pub *const _CassRow);

impl Debug for CassRow {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        for column in self {
            //println!("foo:{:?}",column);
            try!(write!(f, "{:?}\t", CassValue::new(column.0)));
        }
        Ok(())
    }
}

impl Display for CassRow {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        for column in self {
            try!(write!(f, "{}\t", CassValue::new(column.0)));
        }
        Ok(())
    }
}

impl CassRow {
    pub fn get_column(&self, index: u64) -> Result<CassColumn, CassError> {
        unsafe {
            let col = cass_row_get_column(self.0, index);
            match col.is_null() {
                true => Err(CassError::build(CASS_ERROR_LIB_INDEX_OUT_OF_BOUNDS)),
                false => Ok(CassColumn(col)),
            }
        }
    }

    pub fn get_column_by_name<S>(&self, name: S) -> CassColumn
        where S: Into<String>
    {
        unsafe {
            let name = CString::new(name.into()).unwrap();
            println!("name: {:?}", name);
            println!("self: {:?}", self);
        //unimplemented!();
            CassColumn(cass_row_get_column_by_name(self.0, name.as_ptr()))
        }
    }
}

pub struct RowIterator(pub *mut _CassIterator);

impl Drop for RowIterator {
    fn drop(&mut self) {
        unsafe {
            cass_iterator_free(self.0)
        }
    }
}

impl iter::Iterator for RowIterator {

    type Item = CassColumn;

    fn next(&mut self) -> Option<<Self as Iterator>::Item> {
        unsafe {
            match cass_iterator_next(self.0) {
                0 => None,
                _ => Some(CassColumn(cass_iterator_get_column(self.0))),
            }
        }
    }
}

impl<'a> Iterator for &'a RowIterator {

    type Item = CassColumn;

    fn next(&mut self) -> Option<<Self as Iterator>::Item> {
        unsafe {
            match cass_iterator_next(self.0) {
                0 => None,
                _ => Some(CassColumn(cass_iterator_get_column(self.0))),
            }
        }
    }
}

impl Display for RowIterator {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        for item in self {
            try!(write!(f, "{}\t", CassValue::new(item.0)));
        }
        Ok(())
    }
}

impl IntoIterator for CassRow {

    type Item = CassColumn;
    type IntoIter = RowIterator;

    fn into_iter(self) -> Self::IntoIter {
        unsafe {
            RowIterator(cass_iterator_from_row(self.0))
        }
    }
}

impl<'a> IntoIterator for &'a CassRow {
    type Item = CassColumn;
    type IntoIter = RowIterator;
    fn into_iter(self) -> Self::IntoIter {
        unsafe {
            RowIterator(cass_iterator_from_row(self.0))
        }
    }
}


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

  <xi:include href="master.html" />

  <meta content="text/html; charset=UTF-8" http-equiv="content-type" py:replace="''"/>
  <title>A ${code} Error has Occurred </title>

Error ${code}

${XML(message)}


text:
namespace JoinRpg.Dal.Impl.Migrations
{
  using System.Data.Entity.Migrations;

    public partial class CanApproveClaims : DbMigration
    {
        public override void Up()
        {
            AddColumn("dbo.ProjectAcls", "CanApproveClaims", c => c.Boolean(nullable: false, defaultValue:true));
        }

        public override void Down()
        {
            DropColumn("dbo.ProjectAcls", "CanApproveClaims");
        }
    }
}


text:
using Nucleo.Presentation;
using Nucleo.Presentation;
using Nucleo.Presentation.Caching;
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TypeMock.ArrangeActAssert;

namespace Nucleo.Presentation
{
	[TestClass]
	public class PresenterCacheOptionsTest
	{
		[TestMethod]
		public void GettingAndSettingPropertiesWorksOK()
		{
			//Arrange
			var options = new PresenterCacheOptions();
			var ctx = Isolate.Fake.Instance<IPresenterContextCache>();

			//Act
			options.ContextCache = ctx;

			//Assert
			Assert.AreEqual(ctx, options.ContextCache);

			Isolate.CleanUp();
		}
	}
}


text:
module Dis
  module Model
    # = Dis Model Data
    #
    # Facilitates communication between the model and the storage,
    # and holds any newly assigned data before the record is saved.
    class Data
      def initialize(record, raw = nil)
        @record = record
        @raw = raw
      end

      # Returns true if two Data objects represent the same data.
      def ==(other)
        # TODO: This can be made faster by
        # comparing hashes for stored objects.
        other.read == read
      end

      # Returns true if data exists either in memory or in storage.
      def any?
        raw? || stored?
      end

      # Returns the data as a binary string.
      def read
        @read ||= read_from(closest)
      end

      # Will be true if data has been explicitely set.
      #
      #   Dis::Model::Data.new(record).changed? # => false
      #   Dis::Model::Data.new(record, new_file).changed? # => true
      def changed?
        raw?
      end

      # Returns the length of the data.
      def content_length
        if raw? && raw.respond_to?(:length)
          raw.length
        else
          read.try(&:length).to_i
        end
      end

      # Expires a data object from the storage if it's no longer being used
      # by existing records. This is triggered from callbacks on the record
      # whenever they are changed or destroyed.
      def expire(hash)
        unless @record.class.where(
          @record.class.dis_attributes[:content_hash] => hash
        ).any?
          Dis::Storage.delete(storage_type, hash)
        end
      end

      # Stores the data. Returns a hash of the content for reference.
      def store!
        raise Dis::Errors::NoDataError unless raw?

        Dis::Storage.store(storage_type, raw)
      end

      # Writes the data to a temporary file.
      def tempfile
        unless @tempfile
          @tempfile = Tempfile.new(binmode: true)
          @tempfile.write(@read || read_from(closest))
          @tempfile.open
        end
        @tempfile
      end

      private

      def closest
        if raw?
          raw
        elsif stored?
          stored
        end
      end

      def content_hash
        @record[@record.class.dis_attributes[:content_hash]]
      end

      def raw?
        raw ? true : false
      end

      def read_from(object)
        return nil unless object

        if object.respond_to?(:body)
          object.body
        elsif object.respond_to?(:read)
          rewind_and_read(object)
        else
          object
        end
      end

      def rewind_and_read(object)
        object.rewind
        response = object.read
        object.rewind
        response
      end

      def storage_type
        @record.class.dis_type
      end

      def stored?
        content_hash.present? &&
          (@record.dis_stored? ||
           Dis::Storage.exists?(storage_type, content_hash))
      end

      def stored
        Dis::Storage.get(storage_type, content_hash)
      end

      attr_reader :raw
    end
  end
end


text:
Build servers to test Influent and Fluentd.

## Terraform

### Requirements

* GCP
* High CPU quota
  * a sender node uses 32 cpus
  * a reciver node uses 64 cpus

### Configuration

Edit [google.tf](https://github.com/okumin/influent-benchmark/tree/master/terraform/providers/google/google.tf).

## Ansible

### Requirements

* CentOS 7

### Setup

#### Receiver node

```
sudo yum -y install git
git clone https://github.com/okumin/influent-benchmark.git ~/influent-benchmark
~/influent-benchmark/setup_receiver.sh
source ~/.bash_profile
cd ~/influent
sbt compile
```

#### Sender node

```
RECEIVER_HOST=influent-receiver001 # host name or ip address of the target
sudo yum -y install git
git clone https://github.com/okumin/influent-benchmark.git ~/influent-benchmark
~/influent-benchmark/setup_sender.sh ${RECEIVER_HOST}
source ~/.bash_profile
```

### Benchmark

#### 1. Start the receiver

When testing Fluentd,

* version: 0.12 or 0.14

```
~/influent-benchmark/start_fluentd.sh {version} {parallelism}
```

When testing Influent,

```
~/influent-benchmark/start_influent.sh {test branch} {parallelism}
```

#### 2. Start benchmark

* version: 0.12 or 0.14
* mode: at-most-once or at-least-once
* message/sec: message per sec

```
~/influent-benchmark/run_benchmark.sh {version} {mode} {message/sec}
```


text:
<?php

namespace HXPHP\System\Storage\Session;

class Session implements \HXPHP\System\Storage\StorageInterface
{
	/**
	 * Prefixo das sessões
	 */
	const PREFIX = 'hxphp_storage_session';

	/**
	 * Método que cria uma sessão
	 * @param string $name  Nome da sessão
	 * @param string $value Conteúdo da sessão
     * @param int $timeout  Tempo de expiração da sessão
	 */
	public function set($name, $value, $timeout = null)
	{
		$_SESSION[self::PREFIX][$name] = $value;

        if ($timeout && is_int($timeout)) {
            $_SESSION[self::PREFIX][$name.'_created_at'] = time();
            $_SESSION[self::PREFIX][$name.'_timeout'] = $timeout;
        }

		return $this;
	}

	/**
	 * Método que seleciona uma sessão
	 * @param  string $name Nome da sessão
	 * @return string       Conteúdo da sessão
	 */
	public function get($name)
	{
		if ($this->exists($name)) {
            if (!$this->hasExpired($name))
                return $_SESSION[self::PREFIX][$name];
            else
                return false;
        }

		return null;
	}

	/**
	 * Verifica a existência da sessão
	 * @param  string  $name Nome da sessão
	 * @return boolean       Status do processo
	 */
	public function exists($name)
	{
		return isset($_SESSION[self::PREFIX][$name]);
	}

    /**
    * Verifica se uma sessão já expirou
    * @param string $name   Nome da sessão
    * @return boolean       Sessão expirada ou não
    */
    public function hasExpired($name)
    {
        if (!$this->exists($name.'_timeout'))
            return false;

        if (!$this->exists($name.'_created_at'))
            throw new \LogicException('A sessão < '.$name.'_created_at > não existe.');

        if ($this->get($name.'_created_at') + $this->get($name.'_timeout') < time())
            return true;
    }

    /**
    * Quantidade de tempo restante para o timeout de uma sessão
    * @param string $name   Nome da sessão
    * @return date          Quantidade de tempo restante para o timeout
    */
    public function getTimeLeftOf($name)
    {
        if ($this->hasExpired($name))
            return 0;

        return ($this->get($name.'_created_at') + $this->get($name.'_timeout')) - time();
    }

	/**
	 * Exclui uma sessão
	 * @param  string $name Nome da sessão
	 */
	public function clear($name)
	{
		if ($this->exists($name))
			unset($_SESSION[self::PREFIX][$name]);
	}
}


text:
/*
 * Observer.java
 *
 * Created on July 14, 2004, 3:06 PM
 */

package com.seekerr.simulator.robot.graphics.collision;

/**
 *
 * @author  Wesley Kerr
 */
public class Observer implements Runnable {

    public int width = 15;
    public int height = 15;

    public boolean exit = false;
    public boolean reset = false;

    private Calculator c;
    private Viewer viewer;

    private static Observer observer = null;

    public Object lock = new Object();

    /** Creates a new instance of Observer */
    private Observer() {
    }

    public static Observer inst() {
        if (observer == null) {
            observer = new Observer();
        }

        return observer;
    }

    public void init() {
        c = new Calculator();
        c.globalAx = 4;
        c.globalAy = 9;
        c.globalAvx = 1;
        c.globalAvy = -3;

        c.globalBx = 7;
        c.globalBy = 6;
        c.globalBvx = -2;
        c.globalBvy = 4;

        //c.globalAx = 4;
        //c.globalAy = 4;
        //c.globalAvx = 1;
        //c.globalAvy = -1;

        //c.globalBx = 7;
        //c.globalBy = 1;
        //c.globalBvx = -1;
        //c.globalBvy = 1;
        c.calculate();
    }

    public void loadNewValues() {
        viewer.loadNewValues();
    }

    public void setValues(double ax, double ay, double avx, double avy,
                          double bx, double by, double bvx, double bvy) {
        c.globalAx = ax;
        c.globalAy = ay;
        c.globalAvx = avx;
        c.globalAvy = avy;

        c.globalBx = bx;
        c.globalBy = by;
        c.globalBvx = bvx;
        c.globalBvy = bvy;
        c.calculate();
        viewer.update();
    }

    public void createDisplay() {
        viewer = new Viewer();
    }

    public Calculator getCalculator() {
        return c;
    }

    public void update() {
        viewer.update();
    }

    public void run() {
        while (!exit) {
            viewer.update();
            doWait();
            continue;
        }
        dispose();
    }

    private void doWait() {
        synchronized (lock) {
            try {
                lock.wait();
            } catch (Exception e) {
                System.err.println("Error - " + e.getMessage());
                System.exit(-1);
            }
        }
    }

    public void dispose() {
        viewer.dispose();
        System.exit(0);
    }

    public static void main(String[] args) {
        Observer.inst().init();
        Observer.inst().createDisplay();
        Observer.inst().run();
    }
}


text:
test:
	python -m pytest jupyterworkflow


text:
module PolymorphicConstraints
  module ConnectionAdapters
    module BaseAdapter
      include PolymorphicConstraints::Utils::SqlString
      include PolymorphicConstraints::Utils::PolymorphicModelFinder

      def supports_polymorphic_constraints?
        true
      end

      def add_polymorphic_constraints(relation, associated_table, options = {})
        polymorphic_models = options.fetch(:polymorphic_models) { get_polymorphic_models(relation) }

        statements = []
        statements << drop_constraints(relation)
        statements << generate_upsert_constraints(relation, associated_table, polymorphic_models)
        statements << generate_delete_constraints(relation, associated_table, polymorphic_models)

        statements.flatten.each { |statement| execute statement }
      end

      def remove_polymorphic_constraints(relation)
        statements = []
        statements << drop_constraints(relation)
        statements.flatten.each { |statement| execute statement }
      end

      alias_method :update_polymorphic_constraints, :add_polymorphic_constraints
    end
  end
end


text:
using System.Threading.Tasks;

namespace Kentico.Kontent.Delivery.Abstractions
{
    /// <summary>
    /// Represents a feed that can be used to retrieve strongly typed content items from Kentico Kontent Delivery API in smaller batches.
    /// </summary>
    /// <typeparam name="T">The type of content items in the feed.</typeparam>
    public interface IDeliveryItemsFeed<T>
    {
        /// <summary>
        /// Indicates whether there are more batches to fetch.
        /// </summary>
        bool HasMoreResults { get; }

        /// <summary>
        /// Retrieves the next feed batch if available.
        /// </summary>
        /// <returns>Instance of <see cref="IDeliveryItemsFeedResponse{T}"/> class that contains a list of strongly typed content items.</returns>
        Task<IDeliveryItemsFeedResponse<T>> FetchNextBatchAsync();
    }
}


text:
export default function div () {
  const div = document.createElement('div')
  div.id = 'root'
  document.body.appendChild(div)

  return div
}


text:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="tokenbase_before_load_active_cards">
        <observer name="authnetcim_loaded_cards" instance="ParadoxLabs\Authnetcim\Observer\ConvertLegacyStoredDataObserver" />
    </event>
    <event name="tokenbase_before_load_payment_info">
        <observer name="authnetcim_loaded_cards" instance="ParadoxLabs\Authnetcim\Observer\ConvertLegacyStoredDataObserver" />
    </event>
    <event name="payment_method_assign_data_authnetcim">
        <observer name="authnetcim_assign_data" instance="ParadoxLabs\TokenBase\Observer\PaymentMethodAssignDataObserver" />
        <observer name="authnetcim_acceptjs_assign_data" instance="ParadoxLabs\Authnetcim\Observer\PaymentMethodAssignAcceptjsDataObserver" />
    </event>
    <event name="payment_method_assign_data_authnetcim_ach">
        <observer name="authnetcim_assign_data" instance="ParadoxLabs\TokenBase\Observer\PaymentMethodAssignDataObserver" />
        <observer name="authnetcim_ach_assign_data" instance="ParadoxLabs\TokenBase\Observer\PaymentMethodAssignAchDataObserver" />
    </event>
    <event name="sales_model_service_quote_submit_failure">
        <observer name="authnetcim_failure_clear_acceptjs" instance="ParadoxLabs\Authnetcim\Observer\CheckoutFailureClearAcceptjsObserver" />
        <observer name="authnetcim_failure_clear_profileid" instance="ParadoxLabs\Authnetcim\Observer\CheckoutFailureClearProfileIdObserver" />
    </event>
</config>


text:
/// <reference path="jqwidgets.d.ts" />
import { Component, Input, Output, EventEmitter, ElementRef, forwardRef, OnChanges, SimpleChanges, ChangeDetectionStrategy } from '@angular/core';
declare let JQXLite: any;

@Component({
    selector: 'jqxNotification',
    template: '
<ng-content></ng-content>
'
})

export class jqxNotificationComponent implements OnChanges
{
   @Input('appendContainer') attrAppendContainer: any;
   @Input('autoOpen') attrAutoOpen: any;
   @Input('animationOpenDelay') attrAnimationOpenDelay: any;
   @Input('animationCloseDelay') attrAnimationCloseDelay: any;
   @Input('autoClose') attrAutoClose: any;
   @Input('autoCloseDelay') attrAutoCloseDelay: any;
   @Input('blink') attrBlink: any;
   @Input('browserBoundsOffset') attrBrowserBoundsOffset: any;
   @Input('closeOnClick') attrCloseOnClick: any;
   @Input('disabled') attrDisabled: any;
   @Input('hoverOpacity') attrHoverOpacity: any;
   @Input('icon') attrIcon: any;
   @Input('notificationOffset') attrNotificationOffset: any;
   @Input('opacity') attrOpacity: any;
   @Input('position') attrPosition: any;
   @Input('rtl') attrRtl: any;
   @Input('showCloseButton') attrShowCloseButton: any;
   @Input('template') attrTemplate: any;
   @Input('theme') attrTheme: any;
   @Input('width') attrWidth: any;
   @Input('height') attrHeight: any;

   @Input('auto-create') autoCreate: boolean = true;

   properties: string[] = ['appendContainer','autoOpen','animationOpenDelay','animationCloseDelay','autoClose','autoCloseDelay','blink','browserBoundsOffset','closeOnClick','disabled','height','hoverOpacity','icon','notificationOffset','opacity','position','rtl','showCloseButton','template','theme','width'];
   host: any;
   elementRef: ElementRef;
   widgetObject:  jqwidgets.jqxNotification;

   constructor(containerElement: ElementRef) {
      this.elementRef = containerElement;
   }

   ngOnInit() {
      if (this.autoCreate) {
         this.createComponent();
      }
   };

   ngOnChanges(changes: SimpleChanges) {
      if (this.host) {
         for (let i = 0; i < this.properties.length; i++) {
            let attrName = 'attr' + this.properties[i].substring(0, 1).toUpperCase() + this.properties[i].substring(1);
            let areEqual: boolean;

            if (this[attrName] !== undefined) {
               if (typeof this[attrName] === 'object') {
                  if (this[attrName] instanceof Array) {
                     areEqual = this.arraysEqual(this[attrName], this.host.jqxNotification(this.properties[i]));
                  }
                  if (areEqual) {
                     return false;
                  }

                  this.host.jqxNotification(this.properties[i], this[attrName]);
                  continue;
               }

               if (this[attrName] !== this.host.jqxNotification(this.properties[i])) {
                  this.host.jqxNotification(this.properties[i], this[attrName]);
               }
            }
         }
      }
   }

   arraysEqual(attrValue: any, hostValue: any): boolean {
      if (attrValue.length != hostValue.length) {
         return false;
      }
      for (let i = 0; i < attrValue.length; i++) {
         if (attrValue[i] !== hostValue[i]) {
            return false;
         }
      }
      return true;
   }

   manageAttributes(): any {
      let options = {};
      for (let i = 0; i < this.properties.length; i++) {
         let attrName = 'attr' + this.properties[i].substring(0, 1).toUpperCase() + this.properties[i].substring(1);
         if (this[attrName] !== undefined) {
            options[this.properties[i]] = this[attrName];
         }
      }
      return options;
   }

   moveClasses(parentEl: HTMLElement, childEl: HTMLElement): void {
      let classes: any = parentEl.classList;
      childEl.classList.add(...classes);
      parentEl.className = '';
   }

   moveStyles(parentEl: HTMLElement, childEl: HTMLElement): void {
      let style = parentEl.style.cssText;
      childEl.style.cssText = style
      parentEl.style.cssText = '';
   }

   createComponent(options?: any): void {
      if (options) {
         JQXLite.extend(options, this.manageAttributes());
      }
      else {
        options = this.manageAttributes();
      }
      this.host = JQXLite(this.elementRef.nativeElement.firstChild);

      this.moveClasses(this.elementRef.nativeElement, this.host[0]);
      this.moveStyles(this.elementRef.nativeElement, this.host[0]);

      this.__wireEvents__();
      this.widgetObject = jqwidgets.createInstance(this.host, 'jqxNotification', options);

      this.__updateRect__();
   }

   createWidget(options?: any): void {
        this.createComponent(options);
   }

   __updateRect__() : void {
      this.host.css({ width: this.attrWidth, height: this.attrHeight });
   }

   setOptions(options: any) : void {
      this.host.jqxNotification('setOptions', options);
   }

   // jqxNotificationComponent properties
   appendContainer(arg?: string) : any {
      if (arg !== undefined) {
          this.host.jqxNotification('appendContainer', arg);
      } else {
          return this.host.jqxNotification('appendContainer');
      }
   }

   autoOpen(arg?: boolean) : any {
      if (arg !== undefined) {
          this.host.jqxNotification('autoOpen', arg);
      } else {
          return this.host.jqxNotification('autoOpen');
      }
   }

   animationOpenDelay(arg?: number) : any {
      if (arg !== undefined) {
          this.host.jqxNotification('animationOpenDelay', arg);
      } else {
          return this.host.jqxNotification('animationOpenDelay');
      }
   }

   animationCloseDelay(arg?: number) : any {
      if (arg !== undefined) {
          this.host.jqxNotification('animationCloseDelay', arg);
      } else {
          return this.host.jqxNotification('animationCloseDelay');
      }
   }

   autoClose(arg?: boolean) : any {
      if (arg !== undefined) {
          this.host.jqxNotification('autoClose', arg);
      } else {
          return this.host.jqxNotification('autoClose');
      }
   }

   autoCloseDelay(arg?: String | Number) : any {
      if (arg !== undefined) {
          this.host.jqxNotification('autoCloseDelay', arg);
      } else {
          return this.host.jqxNotification('autoCloseDelay');
      }
   }

   blink(arg?: boolean) : any {
      if (arg !== undefined) {
          this.host.jqxNotification('blink', arg);
      } else {
          return this.host.jqxNotification('blink');
      }
   }

   browserBoundsOffset(arg?: number) : any {
      if (arg !== undefined) {
          this.host.jqxNotification('browserBoundsOffset', arg);
      } else {
          return this.host.jqxNotification('browserBoundsOffset');
      }
   }

   closeOnClick(arg?: boolean) : any {
      if (arg !== undefined) {
          this.host.jqxNotification('closeOnClick', arg);
      } else {
          return this.host.jqxNotification('closeOnClick');
      }
   }

   disabled(arg?: boolean) : any {
      if (arg !== undefined) {
          this.host.jqxNotification('disabled', arg);
      } else {
          return this.host.jqxNotification('disabled');
      }
   }

   height(arg?: String | Number) : any {
      if (arg !== undefined) {
          this.host.jqxNotification('height', arg);
      } else {
          return this.host.jqxNotification('height');
      }
   }

   hoverOpacity(arg?: number) : any {
      if (arg !== undefined) {
          this.host.jqxNotification('hoverOpacity', arg);
      } else {
          return this.host.jqxNotification('hoverOpacity');
      }
   }

   icon(arg?: jqwidgets.NotificationIcon) : any {
      if (arg !== undefined) {
          this.host.jqxNotification('icon', arg);
      } else {
          return this.host.jqxNotification('icon');
      }
   }

   notificationOffset(arg?: number) : any {
      if (arg !== undefined) {
          this.host.jqxNotification('notificationOffset', arg);
      } else {
          return this.host.jqxNotification('notificationOffset');
      }
   }

   opacity(arg?: number) : any {
      if (arg !== undefined) {
          this.host.jqxNotification('opacity', arg);
      } else {
          return this.host.jqxNotification('opacity');
      }
   }

   position(arg?: string) : any {
      if (arg !== undefined) {
          this.host.jqxNotification('position', arg);
      } else {
          return this.host.jqxNotification('position');
      }
   }

   rtl(arg?: boolean) : any {
      if (arg !== undefined) {
          this.host.jqxNotification('rtl', arg);
      } else {
          return this.host.jqxNotification('rtl');
      }
   }

   showCloseButton(arg?: boolean) : any {
      if (arg !== undefined) {
          this.host.jqxNotification('showCloseButton', arg);
      } else {
          return this.host.jqxNotification('showCloseButton');
      }
   }

   template(arg?: string) : any {
      if (arg !== undefined) {
          this.host.jqxNotification('template', arg);
      } else {
          return this.host.jqxNotification('template');
      }
   }

   theme(arg?: string) : any {
      if (arg !== undefined) {
          this.host.jqxNotification('theme', arg);
      } else {
          return this.host.jqxNotification('theme');
      }
   }

   width(arg?: String | Number) : any {
      if (arg !== undefined) {
          this.host.jqxNotification('width', arg);
      } else {
          return this.host.jqxNotification('width');
      }
   }

   // jqxNotificationComponent functions
   closeAll(): void {
      this.host.jqxNotification('closeAll');
   }

   closeLast(): void {
      this.host.jqxNotification('closeLast');
   }

   destroy(): void {
      this.host.jqxNotification('destroy');
   }

   open(): void {
      this.host.jqxNotification('open');
   }

   refresh(): void {
      this.host.jqxNotification('refresh');
   }

   render(): void {
      this.host.jqxNotification('render');
   }

   // jqxNotificationComponent events
   @Output() onClose = new EventEmitter();
   @Output() onClick = new EventEmitter();
   @Output() onOpen = new EventEmitter();

   __wireEvents__(): void {
      this.host.on('close', (eventData: any) => { this.onClose.emit(eventData); });
      this.host.on('click', (eventData: any) => { this.onClick.emit(eventData); });
      this.host.on('open', (eventData: any) => { this.onOpen.emit(eventData); });
   }

} //jqxNotificationComponent


text:
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>

<link href="doc-style.css" type="text/css" rel="StyleSheet">

		Local Properties

Managed Object Types	Data Object Types	All Properties	All Methods

Data Object - DvsSingleIpPort

Extends

DvsIpPort

Since

vSphere API 5.5

Data Object
                  Description

         This class defines a Single Port

Properties

	          Name

	          Type

	          Description

portNumber	xsd:int

         The IP port number.

						Properties inherited from DvsIpPort

None

						Properties inherited from NegatableExpression

negate

						Properties inherited from DynamicData

dynamicProperty, dynamicType

Show WSDL type definition

<textarea cols="20" rows="10" name="wsdl-textarea" wrap="off" readonly="1" id="wsdl-textarea">         <complexType xmlns="http://www.w3.org/2001/XMLSchema" xmlns:vim25="urn:vim25" name="DvsSingleIpPort">
            <complexContent>
               <extension base="vim25:DvsIpPort">
                  <sequence>
                     <element name="portNumber" type="xsd:int"/>
                  </sequence>
               </extension>
            </complexContent>
         </complexType></textarea>

Top of page		Local Properties

Managed Object Types	Data Object Types	All Properties	All Methods


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Can. J. Bot. 61(1): 42 (1983)

#### Original name
Phacidium symplocinum P. Syd., 1911

### Remarks
null


text:
using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Security.Principal;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class SiteMaster : MasterPage
{
    private const string AntiXsrfTokenKey = "__AntiXsrfToken";
    private const string AntiXsrfUserNameKey = "__AntiXsrfUserName";
    private string _antiXsrfTokenValue;

    protected void Page_Init(object sender, EventArgs e)
    {
        // 以下代码可帮助防御 XSRF 攻击
        var requestCookie = Request.Cookies[AntiXsrfTokenKey];
        Guid requestCookieGuidValue;
        if (requestCookie != null && Guid.TryParse(requestCookie.Value, out requestCookieGuidValue))
        {
            // 使用 Cookie 中的 Anti-XSRF 令牌
            _antiXsrfTokenValue = requestCookie.Value;
            Page.ViewStateUserKey = _antiXsrfTokenValue;
        }
        else
        {
            // 生成新的 Anti-XSRF 令牌并保存到 Cookie
            _antiXsrfTokenValue = Guid.NewGuid().ToString("N");
            Page.ViewStateUserKey = _antiXsrfTokenValue;

            var responseCookie = new HttpCookie(AntiXsrfTokenKey)
            {
                HttpOnly = true,
                Value = _antiXsrfTokenValue
            };
            if (FormsAuthentication.RequireSSL && Request.IsSecureConnection)
            {
                responseCookie.Secure = true;
            }
            Response.Cookies.Set(responseCookie);
        }

        Page.PreLoad += master_Page_PreLoad;
    }

    protected void master_Page_PreLoad(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            // 设置 Anti-XSRF 令牌
            ViewState[AntiXsrfTokenKey] = Page.ViewStateUserKey;
            ViewState[AntiXsrfUserNameKey] = Context.User.Identity.Name ?? String.Empty;
        }
        else
        {
            // 验证 Anti-XSRF 令牌
            if ((string)ViewState[AntiXsrfTokenKey] != _antiXsrfTokenValue
                || (string)ViewState[AntiXsrfUserNameKey] != (Context.User.Identity.Name ?? String.Empty))
            {
                throw new InvalidOperationException("Anti-XSRF 令牌验证失败。");
            }
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void Unnamed_LoggingOut(object sender, LoginCancelEventArgs e)
    {
        Context.GetOwinContext().Authentication.SignOut();
    }
}


text:
layout: post
title: How to Let Go of Something That You Love
date: 2013-07-02 05:25
author: Kevin Olega
comments: true
categories: [Confidence and Moving Forward]
---
We sometimes suffer when reality does not turn out the way we want it to be.

As a result, we want to change reality or move to a different one if possible. A lot of times we only get what we have and because we want a different one we become really unhappy.

We have a future that we imagine happening but the reality is different (and often) the opposite of things that we want to be.

In a lot of cases we end up getting what we aim for. We just don't get it the exact same way that we wanted it to be.

When I was younger and didn't have people skills, I read and studied about talking to people and I eventually got good at it. The reality was I made a lot of really embarrassing mistakes learning how to.

Five years ago or so, I set a goal list to get a bunch of gadgets and some experiences like being a minimalist, a traveler, a blogger, an author, and a whole bunch of things. It took me a couple of years longer but what's interesting is that I was able to achieve the goals I set. It took longer and it took a different method for me to achieve than originally planned but I got it. The reality was that my plan failed. Almost all my plans failed. I gave up, and some time later I received an opportunity, grabbed it, got something and realized that what I got was what I set before.

What's the point here? If you learn to be content with what you have, you enjoy your life more because your vision does not clash with reality. There is less emotional issues with things you are working on and the work gets done.

When minimal changes had a bunch of drama posts a couple of years ago, I was depressed because of a failed relationship that I couldn't let go of. I tried everything to change that. I wrote a book, built a wedding photobook, became a pick up artist, started a charity, learned to cook, lost weight, tried to take care of my body better and I still ended up depressed. I would go out on a date with someone totally awesome and while I'm with that person drown myself with the illusion that I can get the past back. I was rarely present, whether in a hang out, or a date or wherever I was.

I tried to take care of myself better and stumbled upon the serotonin study which led me to drink probiotics everyday. Since then negative thoughts leave my head after five seconds. Most of them were self inflicted.

My values were somehow bring me back to remind me of what I want to let go of.
1. I never give up on someone.
2. I will end up forgiving the people I love.
3. If Naruto can turn Zabuza, Neji, Gaara, Tsunade and Nagato into allies/friends then so can I. (Naruto is a Japanese comicbook series about never giving up and friendship told through ninjas with awesome powers.)

After a hang out didn't push through, I got to hang out with a new friend. We went to CJ, my other close friend who was moving to Canada. It was out last hangout together and I ended up buying an iPhone (interestingly the specific model I wanted a few years ago).

CJ taught us something that day which is the main point of this post.

Not being together with someone doesn't mean that you stopped loving them. Its okay to still love something you won't have but accept the reality that you won't have that (again).

I thought about it for a few days and realized that it was true.

I loved martial arts, Star Wars, a bunch of games and other hobbies which I no longer practiced because my priorities have changed. I have a bunch of friends that were really close to me but I don't see them anymore but if they ever needed any help, I'd be there in a heartbeat.

Other than the fact that letting go and moving on doesn't mean the end of the world I thought about what I can do to get better at it.

If there were steps to applying this to real life here's what I think they would be:
1. Accept that you love something a lot.
2. Accept that that for specific reasons you will no longer be spending time with it (or a lot of time with it.)
3. Accept that you won't be not because you are abandoning it but for reasons you can't control.
4. Accept that it's totally fine. You are not defeated by the challenge or reality. It's just so.
5. Find something awesome to appreciate or work on.

I've used it to move on and let go of a few things and has worked so far. I want to name it "Illusion cancel technique" or "Mind control release technique" but that's just so geeky. Anyways let me know how things work for you.

I'll be back to regular blogging. Check out my other blogs too.

Whenever people say "Let it go" it's too simple but hard to execute so here are some additional learnings that might support you with letting go.
1. We have no control of reality. We only influence a small part of it. We can't control other people's thoughts just the same as we can't control the weather so we just learn to live with it and move on with life.
2. 90% of what we get in life are blessings and 10% are learning experiences.
3. Whenever we don't get what we want, God has something at least 10 times more awesome waiting for us instead.

Here's a status I recently posted:

If you don't get what you want, don't ever think God will give you something you won't like. Over time, I realized that each blessing from God is ten times more awesome than whatever wish that I didn't get.


text:
import simtk.unit as units

from intermol.decorators import accepts_compatible_units
from intermol.forces.abstract_bond_type import AbstractBondType

class HarmonicPotentialBondType(AbstractBondType):
    __slots__ = ['length', 'k', 'order', 'c']

    @accepts_compatible_units(None, None,
                              length=units.nanometers,
                              k=units.kilojoules_per_mole * units.nanometers ** (-2),
                              order=None,
                              c=None)
    def __init__(self, bondingtype1, bondingtype2,
                 length=0.0 * units.nanometers,
                 k=0.0 * units.kilojoules_per_mole * units.nanometers ** (-2),
                 order=1, c=False):
        AbstractBondType.__init__(self, bondingtype1, bondingtype2, order, c)
        self.length = length
        self.k = k

class HarmonicPotentialBond(HarmonicPotentialBondType):
    """
    stub documentation
    """
    def __init__(self, atom1, atom2, bondingtype1=None, bondingtype2=None,
                 length=0.0 * units.nanometers,
                 k=0.0 * units.kilojoules_per_mole * units.nanometers ** (-2),
                 order=1, c=False):
        self.atom1 = atom1
        self.atom2 = atom2
        HarmonicPotentialBondType.__init__(self, bondingtype1, bondingtype2,
                length=length,
                k=k,
                order=order, c=c)


text:
angular-express-token-authentication
=======================
_______________________

Installation
-------

```sh
npm install
npm start
```

Test
---
####server
```sh
npm test
```
####client
```sh
./node_modules/karma/bin/karma start ./test/client/karma.conf.js
```
Demo
----
http://angular-express-token-auth.herokuapp.com


text:
require 'digest'
class User < ActiveRecord::Base
    validates_length_of :username, :in => 3..15
    validates_uniqueness_of :username
    validates_length_of :password, :in => 6..200
    validates_confirmation_of :password
    validates_length_of :email, :in => 5..200, :allow_nil => true, :allow_blank => true # TODO email format validation?
    validates_uniqueness_of :email, :allow_nil => true
    validates_length_of :student_number, :in => 4..100, :allow_nil => true, :allow_blank => true
    validates_uniqueness_of :student_number, :allow_nil => true

    attr_accessor :password_confirmation

    has_many :registrations
    has_many :exercise_groups, :through => :registrations
    has_many :friendships
    has_many :friends, :through => :friendships
    has_many :courses_completeds
    has_many :completed_courses, :through => :courses_completeds, :source =>
        :course
    has_many :courses_faileds
    has_many :failed_courses, :through => :courses_faileds, :source =>
        :course
    has_many :likes
    has_many :liked_feeds, :through => :likes, :source => :newsfeed

    after_create :update_newsfeed

    def self.with_email_in_exercise_groups
        find(:all, :conditions => "email IS NOT NULL").find_all{ |u|
            not u.exercise_groups.empty?
        }
    end

    def before_save
        self.username.downcase!

        if self.salt == nil
            self.salt = random_numbers(5)
            self.password = Digest::MD5.hexdigest(self.salt + self.password)
        else
            self.password = Digest::MD5.hexdigest(salt + self.password)
        end
    end

    def password_matches?(password_to_match)
        self.password == Digest::MD5.hexdigest(self.salt + password_to_match)
    end

    private

    def random_numbers(n)
        numbers = ("0".."9").to_a
        newrand = ""
        1.upto(n) { |i| newrand << numbers[rand(numbers.size - 1)] }
        return newrand
    end

    def update_newsfeed
        Newsfeed.user_registered(self)
    end
end


text:
package match

import (
	"bytes"
	"fmt"
	"regexp"
	"testing"
)

type testContent struct {
	name  string
	lines [][]byte
}

type benchRunner struct {
	title string
	f     func(*testing.B)
}

var allContents = []testContent{
	mixedContent,
	logContent,
	logContent2,
	logContentLevel,
}

var mixedContent = makeContent("mixed", `Lorem ipsum dolor sit amet,
PATTERN consectetur adipiscing elit. Nam vitae turpis augue.
 Quisque euismod erat tortor, posuere auctor elit fermentum vel. Proin in odio

23-08-2016 eleifend, maximus turpis non, lacinia ligula. Nullam vel pharetra quam, id egestas

massa. Sed a vestibulum libero. Sed tellus lorem, imperdiet non nisl ac,
 aliquet placerat magna. Sed PATTERN in bibendum eros. Curabitur ut pretium neque. Sed
23-08-2016 egestas elit et leo consectetur, nec dignissim arcu ultricies. Sed molestie tempor

erat, a maximus sapien rutrum ut. Curabitur congue condimentum dignissim.
 Mauris hendrerit, velit nec accumsan egestas, augue justo tincidunt risus,

a facilisis nulla augue PATTERN eu metus. Duis vel neque sit amet nunc elementum viverra
eu ut ligula. Mauris et libero lacus.`)

var logContent = makeContent("simple_log", `23-08-2016 15:10:01 - Lorem ipsum dolor sit amet,
23-08-2016 15:10:02 - PATTERN consectetur adipiscing elit. Nam vitae turpis augue.
23-08-2016 15:10:03 -  Quisque euismod erat tortor, posuere auctor elit fermentum vel. Proin in odio
23-08-2016 15:10:05 - 23-08-2016 eleifend, maximus turpis non, lacinia ligula. Nullam vel pharetra quam, id egestas
23-08-2016 15:10:07 - massa. Sed a vestibulum libero. Sed tellus lorem, imperdiet non nisl ac,
23-08-2016 15:10:08 -  aliquet placerat magna. Sed PATTERN in bibendum eros. Curabitur ut pretium neque. Sed
23-08-2016 15:10:09 - 23-08-2016 egestas elit et leo consectetur, nec dignissim arcu ultricies. Sed molestie tempor
23-08-2016 15:10:11 - erat, a maximus sapien rutrum ut. Curabitur congue condimentum dignissim.
23-08-2016 15:10:12 -  Mauris hendrerit, velit nec accumsan egestas, augue justo tincidunt risus,
23-08-2016 15:10:14 - a facilisis nulla augue PATTERN eu metus. Duis vel neque sit amet nunc elementum viverra
eu ut ligula. Mauris et libero lacus.
`)

var logContent2 = makeContent("simple_log2", `2016-08-23 15:10:01 - DEBUG - Lorem ipsum dolor sit amet,
2016-08-23 15:10:02 - INFO - PATTERN consectetur adipiscing elit. Nam vitae turpis augue.
2016-08-23 15:10:03 -  DEBUG - Quisque euismod erat tortor, posuere auctor elit fermentum vel. Proin in odio
2016-08-23 15:10:05 - ERROR - 23-08-2016 eleifend, maximus turpis non, lacinia ligula. Nullam vel pharetra quam, id egestas
2016-08-23 15:10:07 - WARN - massa. Sed a vestibulum libero. Sed tellus lorem, imperdiet non nisl ac,
2016-08-23 15:10:08 - CRIT - aliquet placerat magna. Sed PATTERN in bibendum eros. Curabitur ut pretium neque. Sed
2016-08-23 15:10:09 - DEBUG - 23-08-2016 egestas elit et leo consectetur, nec dignissim arcu ultricies. Sed molestie tempor
2016-08-23 15:10:11 - ERROR - erat, a maximus sapien rutrum ut. Curabitur congue condimentum dignissim.
2016-08-23 15:10:12 - INFO - Mauris hendrerit, velit nec accumsan egestas, augue justo tincidunt risus,
2016-08-23 15:10:14 - INFO - a facilisis nulla augue PATTERN eu metus. Duis vel neque sit amet nunc elementum viverra eu ut ligula. Mauris et libero lacus.
`)

var logContentLevel = makeContent("simple_log_with_level", `DEBUG - 2016-08-23 15:10:01 - Lorem ipsum dolor sit amet,
INFO - 2016-08-23 15:10:02 - PATTERN consectetur adipiscing elit. Nam vitae turpis augue.
DEBUG - 2016-08-23 15:10:03 -  Quisque euismod erat tortor, posuere auctor elit fermentum vel. Proin in odio
ERROR - 2016-08-23 15:10:05 - 23-08-2016 eleifend, maximus turpis non, lacinia ligula. Nullam vel pharetra quam, id egestas
WARN - 2016-08-23 15:10:07 - massa. Sed a vestibulum libero. Sed tellus lorem, imperdiet non nisl ac,
CRIT - 2016-08-23 15:10:08 -  aliquet placerat magna. Sed PATTERN in bibendum eros. Curabitur ut pretium neque. Sed
DEBUG - 2016-08-23 15:10:09 - 23-08-2016 egestas elit et leo consectetur, nec dignissim arcu ultricies. Sed molestie tempor
ERROR -2016-08-23 15:10:11 - erat, a maximus sapien rutrum ut. Curabitur congue condimentum dignissim.
DEBUG - 2016-08-23 15:10:12 -  Mauris hendrerit, velit nec accumsan egestas, augue justo tincidunt risus,
INFO - 2016-08-23 15:10:14 - a facilisis nulla augue PATTERN eu metus. Duis vel neque sit amet nunc elementum viverra
eu ut ligula. Mauris et libero lacus.
`)

func BenchmarkPatterns(b *testing.B) {
	patterns := []struct {
		title string
		regex string
	}{
		{"match any 1", `^.*$`},
		{"match any 2", `.*`},
		{"startsWith 'PATTERN'", `^PATTERN`},
		{"startsWith ' '", `^ `},
		{"startsWithDate", `^\d{2}-\d{2}-\d{4}`},
		{"startsWithDate2", `^\d{4}-\d{2}-\d{2}`},
		{"startsWithDate3", `^\d\d\d\d-\d\d-\d\d`},
		{"startsWithDate4", `^20\d{2}-\d{2}-\d{2}`},
		{"startsWithDateAndSpace", `^\d{4}-\d{2}-\d{2} `},
		{"startsWithLevel", `^(DEBUG|INFO|WARN|ERR|CRIT)`},
		{"hasLevel", `(DEBUG|INFO|WARN|ERR|CRIT)`},
		{"contains 'PATTERN'", `PATTERN`},
		{"contains 'PATTERN' with '.*", `.*PATTERN.*`},
		{"empty line", `^$`},
		{"empty line with optional whitespace", `^\s*$`},
	}

	runTitle := func(matcher, name, content string) string {
		return fmt.Sprintf("Name=%v, Matcher=%v, Content=%v", name, matcher, content)
	}

	for i, pattern := range patterns {
		b.Logf("benchmark (%v): %v", i, pattern.title)

		regex := regexp.MustCompile(pattern.regex)
		matcher := MustCompile(pattern.regex)

		b.Logf("regex: %v", regex)
		b.Logf("matcher: %v", matcher)

		for _, content := range allContents {
			title := runTitle("Regex", pattern.title, content.name)
			runner := makeRunner(title, content.lines, regex.Match)
			b.Run(runner.title, runner.f)

			title = runTitle("Match", pattern.title, content.name)
			runner = makeRunner(title, content.lines, matcher.Match)
			b.Run(runner.title, runner.f)
		}
	}
}

func makeRunner(title string, content [][]byte, m func([]byte) bool) benchRunner {
	return benchRunner{
		title,
		func(b *testing.B) {
			for i := 0; i < b.N; i++ {
				for _, line := range content {
					m(line)
				}
			}
		},
	}
}

func makeContent(name, s string) testContent {
	return testContent{
		name,
		bytes.Split([]byte(s), []byte("\n")),
	}
}


text:
A special interest group for bringing Kubernetes support to Windows.

## Meetings
* Bi-weekly: Tuesday 12:30 PM EST (9:30 AM PST)
* Zoom link: [https://zoom.us/my/sigwindows](https://zoom.us/my/sigwindows)
* To get an invite to the meeting, first join the Google group https://groups.google.com/forum/#!forum/kubernetes-sig-windows, and also ask the SIG Lead for the current invitation

## History
* Recorded Meetings Playlist on Youtube: https://www.youtube.com/playlist?list=PL69nYSiGNLP2OH9InCcNkWNu2bl-gmIU4&jct=LZ9EIvD4DGrhr2h4r0ItaBmco7gTgw
* Meeting Notes: https://docs.google.com/document/d/1Tjxzjjuy4SQsFSUVXZbvqVb64hjNAG5CQX8bK7Yda9w/edit#heading=h.kbz22d1yc431

## Get Involved
* Find us on Slack at https://kubernetes.slack.com/messages/sig-windows
* Find us on Google groups https://groups.google.com/forum/#!forum/kubernetes-sig-windows
* Slack History is archived at http://kubernetes.slackarchive.io/sig-windows/
* **Give it a try** as demonstrated at Google Cloud Next '17 https://github.com/apprenda/kubernetes-ovn-heterogeneous-cluster


text:
TOP=../../..
DIRNAME=java/basic_version/cstr

ALL_DIRS = est
BUILD_DIRS = awt est util testPrograms
NEED_JAVA = true

FILES = Makefile

ALL =  .sub_directories

-include ../../../Makefile.version
include $(TOP)/config/common_make_rules


text:
/*
 * Filename: yolov2.hpp
 *
 * Description:
 * This network is used to detecting objects from an image, it will return
 * its coordinate, label and confidence.
 *
 * Please refer to document "xilinx_XILINX_AI_SDK_user_guide.pdf" for more
 * details of these APIs.
 */
#pragma once
#include <vitis/ai/proto/dpu_model_param.pb.h>
#include <vitis/ai/library/tensor.hpp>

namespace vitis {
namespace ai {

/**
 * @struct YOLOv2Result
 * @brie Struct of the result returned by the yolov2 network.
 */
struct YOLOv2Result {
  /**
   * @struct BoundingBox
   * @brief  Struct of an object coordinate ,confidence and classification.
   */
  struct BoundingBox {
    /// classification.
    int label;
    /// confidence, the range from 0 to 1.
    float score;
    /// x-coordinate, x is normalized relative to the input image cols, its
    /// value range from 0 to 1.
    float x;
    /// y-coordinate, y is normalized relative to the input image rows, its
    /// value range from 0 to 1.
    float y;
    /// width, width is normalized relative to the input image cols, its value
    /// from 0 to 1.
    float width;
    /// height, height is normalized relative to the input image rows, its value
    /// range from 0 to 1.
    float height;
  };
  /// Width of input image.
  int width;
  /// Height of input image.
  int height;
  /// All objects.
  std::vector<BoundingBox> bboxes;
};
/**
 * @brief The post-processing function of the yolov2 network.
 * @param input_tensors A vector of all input-tensors in the network.
 *   Usage: input_tensors[input_tensor_index].
 * @param output_tensors A vector of all output-tensors in the network.
 *  Usage: output_tensors[output_index].
 * @param config The dpu model configuration information.
 * @param w The width of origin image.
 * @param h The height of origin image.
 * @return the result of the yolov2 network.
 */

YOLOv2Result yolov2_post_process(
    const std::vector<vitis::ai::library::InputTensor>& input_tensors,
    const std::vector<vitis::ai::library::OutputTensor>& output_tensors,
    const vitis::ai::proto::DpuModelParam& config, const int w, const int h);

std::vector<YOLOv2Result> yolov2_post_process(
    const std::vector<vitis::ai::library::InputTensor>& input_tensors,
    const std::vector<vitis::ai::library::OutputTensor>& output_tensors,
    const vitis::ai::proto::DpuModelParam& config, const std::vector<int> &w,
    const std::vector<int> &h);

}  // namespace ai
}  // namespace vitis


text:
@if(Session::has('message'))

                <button type='button' class='close' data-dismiss='alert' aria-label='close'>
                    ×
                </button>
                {{Session::get('message')}}

            @endif