text:
define(['jquery', 'log', './constants', './simulator-rest-client', 'lodash', './open-siddhi-apps',
    /* void libs */'bootstrap', 'theme_wso2', 'jquery_ui', 'jquery_validate', 'jquery_timepicker', './templates'],
    function ($, log, constants,Simulator, _, OpenSiddhiApps) {

    "use strict";   // JS strict mode

    var self = {};

    self.init = function (config) {

        self.singleEventConfigCount = 1;
        self.siddhiAppDetailsMap = {};
        self.singleEventForm = $('#single-event-form').find('form').clone();
        self.$singleEventConfigTabContent = $("#single-event-config-tab-content");
        self.$singleEventConfigs = $("#single-event-configs");
        self.$addSingleEventForm = $('#add-single-event-form');
        self.FAULTY = 'FAULTY';
        self.STOP = 'STOP';
        self.RUN = 'RUN';
        self.DEBUG = 'DEBUG';
        self.app = _.get(config, 'application');
        self.baseUrl = config.application.config.baseUrl;
        self.workspace = self.app.workspaceManager;
        self.SiddhiAppStatus = "Siddhi App Status : ";
        self.startAndSendLabel = "Start and Send";
        self.sendLabel = "Send";
        var consoleListManager = self.app.outputController;
        self.console = consoleListManager.getGlobalConsole();

        // add methods to validate int/long and double/float
        $.validator.addMethod("validateIntOrLong", function (value, element) {
            return this
                    .optional(element) || /^[-+]?[0-9]+$/.test(value);
        }, "Please provide a valid numerical value.");

        $.validator.addMethod("validateFloatOrDouble", function (value, element) {
            return this
                    .optional(element) || /^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?$/.test(value);
        }, "Please provide a valid numerical value.");

        // add the first single event form and disable the delete button
        self.addSingleEventConfigForm(null, self.$addSingleEventForm);
        $('li[data-uuid="1"] button[name="delete"]')
            .prop('disabled', true)
            .hide();

        // add a single event form
        self.$addSingleEventForm.on('click', function (e) {
            self.addSingleEventConfigForm(e, this);
        });

        // When siddhi app name selected changes refresh the form
        self.$singleEventConfigTabContent.on('change', 'select[name="single-event-siddhi-app-name"]', function () {
            var $element = $(this);
            var $form = $element.closest('form[data-form-type="single"]');
            var uuid = $form.data('uuid');
            var siddhiAppName = $element.val();
            var $siddhiAppMode = $form.find('div[data-name="siddhi-app-name-mode"]');
            var $streamNameSelect = $form.find('select[name="stream-name"]');
            var $timestamp = $form.find('input[name="sim-timestamp"]');
            var $attributes = $form.find('div[data-name="attributes"]');
            var $runDebugButtons = $form.find('div[data-name="run-debug-buttons"]');
            var $send = $form.find('button[type="submit"][name="send"]');
            var $singleEventForm = $element.closest(".single-event-form");
            var $nitificationBox = $singleEventForm.find(".alert");

            $streamNameSelect.empty();
            $timestamp.val('');

            // update the siddhi app status
            Simulator.retrieveSiddhiAppNames(
                function (data) {
                    self.createSiddhiAppMap(data);
                    $siddhiAppMode.html(self.SiddhiAppStatus + self.siddhiAppDetailsMap[siddhiAppName]);
                    self.removeSingleEventAttributeRules(uuid);
                    $attributes.empty();
                    $runDebugButtons.empty();
                    if (self.siddhiAppDetailsMap[siddhiAppName] === self.FAULTY) {
                        $streamNameSelect.prop('disabled', true);
                        $timestamp.prop('disabled', true);
                        $send.prop('disabled', true);
                    } else {
                        $streamNameSelect.prop('disabled', false);
                        $timestamp.prop('disabled', false);
                        $send.prop('disabled', false);
                        Simulator.retrieveStreamNames(
                            siddhiAppName,
                            function (data) {
                                self.refreshStreamList($streamNameSelect, data);
                                var firstOptionVal = $streamNameSelect.children().first().val();
                                $streamNameSelect.val(firstOptionVal).change();
                            },
                            function (data) {
                                log.info(data);
                            });
                        $nitificationBox.removeClass("hidden");
                        var $sendButton = $singleEventForm.find('button[name="send"]');
                        if (self.siddhiAppDetailsMap[siddhiAppName] === self.STOP) {
                            $nitificationBox.removeClass("alert-success");
                            $nitificationBox.addClass("alert-warning");
                            $runDebugButtons.html(self.createRunDebugButtons());
                            $sendButton.text(self.startAndSendLabel);
                            $form
                                .find('label[data-name="siddhi-app-start-msg"]')
                                .html('starting mode for siddhi app');
                        } else {
                            $nitificationBox.addClass("alert-success");
                            $nitificationBox.removeClass("alert-warning");
                            $sendButton.text("Send");
                        }
                    }
                },
                function (data) {
                    var message = {
                        "type" : "ERROR",
                        "message": data,
                    };
                    self.console.println(message);
                }
            );
        });

        // refresh attributes list when a stream is selected
        self.$singleEventConfigTabContent.on('change', 'select[name="stream-name"]', function () {
            var $form = $(this).closest('form[data-form-type="single"]');
            var uuid = $form.data('uuid');
            self.removeSingleEventAttributeRules(uuid);
            Simulator.retrieveStreamAttributes(
                $form
                    .find('select[name="single-event-siddhi-app-name"]')
                    .val(),
                $form
                    .find('select[name="stream-name"]')
                    .val(),
                function (data) {
                    self.refreshAttributesList(uuid, data);
                    self.addRulesForAttributes(uuid);
                },
                function (data) {
                    log.info(data);
                });
        });

        // remove a single event config tab and make the tab before it active
        self.$singleEventConfigs.on('click', 'button[name="delete"][data-form-type="single"]',
            function () {
                self.removeSingleEventForm(this);
                self.renameSingleEventConfigTabs();
            });

        // is isNull checkbox is checked disable txt input, else enable text input
        self.$singleEventConfigTabContent.on('click', 'input[data-input="null"]', function () {
            var $element = $(this);
            var $form = $element.closest('form[data-form-type="single"]');
            var attributeName = $element.data('attribute-name');
            var $inputField = $form.find('[data-element-type="attribute"][name="' + attributeName + '"]');
            if ($element.is(':checked')) {
                if ($inputField.is(':text')) {
                    $inputField
                        .val('')
                        .prop('disabled', true);
                } else {
                    $inputField
                        .prop('selectedIndex', -1)
                        .prop('disabled', true);
                }
                self.removeRuleOfAttribute($inputField);
            } else {
                $inputField
                    .prop('disabled', false);
                $('.parent-checkbox').prop("checked", false);
                self.addRuleForAttribute($inputField);
            }

        });

        // submit function of single event
        self.$singleEventConfigTabContent.on('submit', 'form[data-form-type="single"]', function (e) {
            e.preventDefault();
            var $form = $(this);
            var formValues = _.keyBy($form.serializeArray(), 'name');
            var formDataMap = {};
            var attributes = [];
            var i = 0;

            _.forEach(formValues, function (object, key) {
                if (key === 'single-event-siddhi-app-name' && object.value.length > 0) {
                    _.set(formDataMap, 'siddhiAppName', object.value);
                } else if (key === 'stream-name' && object.value.length > 0) {
                    _.set(formDataMap, 'streamName', object.value);
                } else if (key === 'sim-timestamp' && object.value.length > 0) {
                    _.set(formDataMap, 'timestamp', object.value);
                } else if (key.endsWith('-null')) {
                    attributes[i++] = null;
                } else if (key.endsWith('-attr')) {
                    attributes[i++] = object.value;
                }
            });

            if (!_.has(formDataMap, 'siddhiAppName')) {
                log.error("Siddhi app name is required for single event simulation.");
            }
            if (!_.has(formDataMap, 'streamName')) {
                log.error("Stream name is required for single event simulation.");
            }
            if (_.has(formDataMap, 'timestamp') && parseInt(_.get(formDataMap, 'timestamp')) < 0) {
                log.error("Timestamp value must be a positive integer for single event simulation.");
            }
            if (attributes.length === 0) {
                log.error("Attribute values are required for single event simulation.");
            }
            var started = true;
            if (self.siddhiAppDetailsMap[_.get(formDataMap, 'siddhiAppName')] == "STOP") {
                started = self.startInactiveSiddhiApp($form);
                log.info(_.get(formDataMap, 'siddhiAppName') + " is stopped");
            }

            if (started) {
                if (_.has(formDataMap, 'siddhiAppName')
                    && _.has(formDataMap, 'streamName')
                    && attributes.length > 0) {
                    _.set(formDataMap, 'data', attributes);
                    $form.loading('show');
                    Simulator.singleEvent(
                        JSON.stringify(formDataMap),
                        function (data) {
                            log.info(data);
                            setTimeout(function () {
                                $form.loading('hide');
                            }, 250)
                        },
                        function (data) {
                            log.error(data);
                            setTimeout(function () {
                                $form.loading('hide');
                            }, 250)
                        })
                }
            }
        });
    };

// add a datetimepicker to an element
    var myControl = {
        create: function (tp_inst, obj, unit, val, min, max, step) {
            $('<input class="ui-timepicker-input" value="' + val + '" style="width:50%">')
                .appendTo(obj)
                .spinner({
                    min: min,
                    max: max,
                    step: step,
                    change: function (e, ui) {
                        if (e.originalEvent !== undefined)
                            tp_inst._onTimeChange();
                        tp_inst._onSelectHandler();
                    },
                    spin: function (e, ui) { // spin events
                        tp_inst.control.value(tp_inst, obj, unit, ui.value);
                        tp_inst._onTimeChange();
                        tp_inst._onSelectHandler();
                    }
                });
            return obj;
        },
        options: function (tp_inst, obj, unit, opts, val) {
            if (typeof(opts) == 'string' && val !== undefined)
                return obj.find('.ui-timepicker-input').spinner(opts, val);
            return obj.find('.ui-timepicker-input').spinner(opts);
        },
        value: function (tp_inst, obj, unit, val) {
            if (val !== undefined)
                return obj.find('.ui-timepicker-input').spinner('value', val);
            return obj.find('.ui-timepicker-input').spinner('value');
        }
    };

    self.addDateTimePicker = function (uuid) {
        var $timestamp = $('form[data-form-type="single"][data-uuid="' + uuid + '"] input[name="sim-timestamp"]');
        $timestamp.datetimepicker({
            controlType: myControl,
            showSecond: true,
            showMillisec: true,
            dateFormat: 'yy-mm-dd',
            timeFormat: 'HH:mm:ss:l',
            showOn: 'button',
            buttonText: '' +
            '' +
            '' +
            '',
            onSelect: self.convertDateToUnix,
            onClose: self.closeTimestampPicker

        });
    };

// convert the date string in to unix timestamp onSelect
    self.convertDateToUnix = function () {
        var $element = $(this);
        var $form = $element.closest('form[data-form-type="single"]');
        if (self.siddhiAppDetailsMap[$form.find('select[name="single-event-siddhi-app-name"]').val()] !== self.FAULTY) {
            var date = $element.val();
            var patt = new RegExp("^((\\d)+||NaN)$");
            if(patt.test(date)){
                 return;
            }
            var dateParts = date.split(/[^0-9]/);
            var time=new Date(dateParts[0],dateParts[1]-1,dateParts[2],dateParts[3],dateParts[4],dateParts[5]).getTime()
                + parseInt(dateParts[6]) ;
            $element.val(time);
        } else {
            $element.val('');
        }
    };

// check whether the timestamp value is a unix timestamp onClose, if not convert date string into unix timestamp
    self.closeTimestampPicker = function () {
        var $element = $(this);
        var $form = $element.closest('form[data-form-type="single"]');
        if (self.siddhiAppDetailsMap[$form.find('select[name="single-event-siddhi-app-name"]').val()] !== self.FAULTY) {
            if ($element
                    .val()
                    .includes('-')) {
                var date = $element.val();
                var patt = new RegExp("^((\\d)+||NaN)$");
                if (patt.test(date)) {
                    return;
                }
                var dateParts = date.split(/[^0-9]/);
                var time = new Date(dateParts[0], dateParts[1] - 1, dateParts[2], dateParts[3],
                    dateParts[4], dateParts[5]).getTime()
                    + parseInt(dateParts[6]);
                $element.val(time);
            }
        } else {
            $element
                .val('');
        }
    };

    //create a new single event simulation config form
    self.addSingleEventConfigForm = function (e, ctx) {
        self.createSingleEventConfigForm(e, ctx);
        self.loadSiddhiAppNames(self.singleEventConfigCount);
        self.addSingleEventFormValidator(self.singleEventConfigCount);
        $('form[data-form-type="single"][data-uuid="' + self.singleEventConfigCount + '"] select[name="stream-name"]')
            .prop('disabled', true);
        self.singleEventConfigCount++;
        self.renameSingleEventConfigTabs();
    };

    // create a single event config form
    self.createSingleEventConfigForm = function (event, ctx) {
        // can't assign the ul to a variable since we need to get the count and count changes dynamically
        var nextTab = $('ul#single-event-config-tab li').size() - 1;
        $(ctx).siblings().removeClass("active");
        // create the tab
        $(self.createListItem(nextTab, self.singleEventConfigCount)).insertBefore($(ctx));
        $("#single-event-config-tab-content").find(".tab-pane").removeClass("active");
        var singleEvent = self.singleEventForm.clone();
        singleEvent.attr('data-uuid', self.singleEventConfigCount + '');
        // create the tab content
        $(self.createDivForSingleEventTabContent(self.singleEventConfigCount))
            .appendTo('#single-event-config-tab-content');
        // $(singleEvent).appendTo('#event-content-' + self.singleEventConfigCount);
        $('#event-content-' + self.singleEventConfigCount).append(singleEvent);
        self.addDateTimePicker(self.singleEventConfigCount);
    };

    // create a list item for the single event form tabs
    self.createListItem = function (nextTab, singleEventConfigCount) {
        var listItem =
            '
' +
            '   ' +
            '       S {{nextTab}}' +
            '       <button type="button" class="close" name="delete" data-form-type="single"' +
            '       aria-label="Close">' +
            '            ' +
            '       </button>' +
            '   ' +
            '
';
        var temp = listItem.replaceAll('{{dynamicId}}', singleEventConfigCount);
        return temp.replaceAll('{{nextTab}}', nextTab);
    };

    // create a div for the tab content of single
    self.createDivForSingleEventTabContent = function (singleEventConfigCount) {
        var div =
            '
' +
            '
' +
            '
' +
            '
';
        return div.replaceAll('{{dynamicId}}', singleEventConfigCount);
    };

// create jquery validators for single event forms
    self.addSingleEventFormValidator = function (uuid) {
        var $form = $('form[data-form-type="single"][data-uuid="' + uuid + '"]');
        $form.validate();
        $form.find('[name="single-event-siddhi-app-name"]').rules('add', {
            required: true,
            messages: {
                required: "Please select an siddhi app name."
            }
        });
        $form.find('[name="stream-name"]').rules('add', {
            required: true,
            messages: {
                required: "Please select a stream name."
            }
        });
        $form.find('[name="sim-timestamp"]').rules('add', {
            digits: true,
            messages: {
                digits: "Timestamp value must be a positive integer."
            }
        });
    };

// if the siddhi app is not on run or debug mode, append buttons to start siddhi app in either of the modes
    self.createRunDebugButtons = function () {
        var runDebugButtons =
            '
' +
            '' +
            '' +
            '
'+
            '
' +
                '<input id="run" name="run-debug" checked type="radio" value="run">' +
                'Run' +
                '<input id="debug" name="run-debug" type="radio" value="debug">' +
                'Debug' +
                '' +
            '
';
        return runDebugButtons;
    };

// refresh the run debug buttons of single event forms which have the same siddhi app name selected
    self.refreshRunDebugButtons = function (siddhiAppName) {
        $('form[data-form-type="single"]').each(function () {
            var $form = $(this);
            var uuid = $form.data('uuid');
            var thisSiddhiAppName = $form.find('select[name="single-event-siddhi-app-name"]').val();
            if (thisSiddhiAppName !== null && thisSiddhiAppName === siddhiAppName) {
                var mode = self.siddhiAppDetailsMap[siddhiAppName];
                $form
                    .find('div[data-name="siddhi-app-name-mode"]')
                    .html(self.SiddhiAppStatus + mode);
                $form
                    .find('label[data-name="siddhi-app-start-msg"]')
                    .html('Started siddhi app \'' +
                        siddhiAppName + '\' in \'' + mode + '\' mode.');
                self.disableRunDebugButtonSection($form);
                $form
                    .find('button[type="submit"][name="send"]')
                    .prop('disabled', false);
            }
        });
    };

// disable the run, debug and start buttons
    self.disableRunDebugButtonSection = function ($form) {
        $form.find('input[name="run-debug"]').each(function () {
            $(this)
                .prop('disabled', true)
        });
        $form
            .find('button[name="start"]')
            .prop('disabled', true);
    };

    //remove the tab from the single event tabs list and remove its tab content
    self.removeSingleEventForm = function (ctx) {
        var simulationName = $(ctx).parents("a").text();
        var x = $(ctx).parents("a").attr("href");
        var $current = $('#single-event-config-tab-content ' + x);
        if ("S 1" == simulationName.trim()) {
            $(ctx)
                .parents('li')
                .next()
                .addClass('active');
            $current
                .next()
                .addClass('active');
        } else {
            $(ctx)
                .parents('li')
                .prev()
                .addClass('active');
            $current
                .prev()
                .addClass('active');
        }
        $current
            .remove();
        $(ctx)
            .parents("li")
            .remove();
    };

    // rename the single event config tabs once a tab is deleted
    self.renameSingleEventConfigTabs = function () {
        var nextNum = 1;
        var $singleEventConfigTabs = $('#event-simulator #single-event-configs ul#single-event-config-tab li');
        var numOfTabs = $singleEventConfigTabs.size() - 1;
        $singleEventConfigTabs.each(function () {
            var $element = $(this);
            var uuid = $element.data('uuid');
            if (uuid !== undefined) {
                $element
                    .find('a')
                    .html(self.createSingleListItemText(nextNum, numOfTabs));
                nextNum++;
            }
        })
    };

    // create text element of the single event tab list element
    self.createSingleListItemText = function (nextNum, numOfTabs) {
        var listItemText;
        if (nextNum == 1 && numOfTabs == 1) {
            listItemText =
                'S {{nextNum}}' +
                '<button type="button" class="close" name="delete" data-form-type="single"' +
                '       aria-label="Close" disabled style="display: none;">' +
                '    ' +
                '</button>';
        } else {
            listItemText =
                'S {{nextNum}}' +
                '<button type="button" class="close" name="delete" data-form-type="single"' +
                '       aria-label="Close">' +
                '    ' +
                '</button>';
        }
        return listItemText.replaceAll('{{nextNum}}', nextNum);
    };

// load siddhi app names to form
    self.loadSiddhiAppNames = function (uuid) {
        var $siddhiAppSelect = $('form[data-uuid="' + uuid + '"] select[name="single-event-siddhi-app-name"]');
        var siddhiAppName = $siddhiAppSelect.val();
        Simulator.retrieveSiddhiAppNames(
            function (data) {
                self.createSiddhiAppMap(data);
                self.refreshSiddhiAppList($siddhiAppSelect, Object.keys(self.siddhiAppDetailsMap));
                self.selectSiddhiAppOptions($siddhiAppSelect, siddhiAppName);
            },
            function (data) {
                log.info(data);
            }
        );

    };

// create a map containing siddhi app name
    self.createSiddhiAppMap = function (data) {
        self.siddhiAppDetailsMap = {};
        for (var i = 0; i < data.length; i++) {
            self.siddhiAppDetailsMap[data[i]['siddhiAppName']] = data[i]['mode'];
        }
    };

// create the siddhi app name drop down
    self.refreshSiddhiAppList = function ($siddhiAppSelect, siddhiAppNames) {
        var initialOptionValue = "";
        if(siddhiAppNames.length == 0){
            initialOptionValue += '<option value = "-1" disabled>-- No saved Siddhi Apps available. --</option>';
        } else{
            initialOptionValue = '<option value = "-1" disabled>-- Please Select a Siddhi App --</option>';
        }

        var newSiddhiApps = self.generateOptions(siddhiAppNames,initialOptionValue);
        $siddhiAppSelect.html(newSiddhiApps);
        $siddhiAppSelect.find('option[value="-1"]').attr("selected",true);
    };

// select an option from the siddhi app name drop down
    self.selectSiddhiAppOptions = function ($siddhiAppSelect, siddhiAppName) {
        /*
         * if an siddhi app has been already selected when the siddhi app name list was refreshed,
         * check whether the siddhi app still exists in the workspace, if yes, make that siddhi app name the
         * selected value.
         * If the siddhi app no longer exists in the work space, set the selected option to -1 and refresh the form
         * */
        if (siddhiAppName in self.siddhiAppDetailsMap) {
            $siddhiAppSelect
                .val(siddhiAppName);
        } else {
            if (siddhiAppName !== null) {
                var $form = $siddhiAppSelect.closest('form[data-form-type="single"]');
                $form
                    .find('div[data-name="siddhi-app-name-mode"]')
                    .empty();
                $form
                    .find('select[name="stream-name"]')
                    .empty()
                    .prop('disabled', true);
                $form
                    .find('input[name="sim-timestamp"]')
                    .empty();
                $form
                    .find('div[data-name="attributes"]')
                    .empty();
                $form
                    .find('div[data-name="run-debug-buttons"]')
                    .empty();
            }
        }
    };

// create the stream name drop down
    self.refreshStreamList = function ($streamNameSelect, streamNames) {
        $streamNameSelect.children().first().remove();
        var initialOptionValue = '<option value = "-1" disabled>-- Please Select a Stream Name --</option>';
        var newStreamOptions = self.generateOptions(streamNames,initialOptionValue);
        $streamNameSelect.html(newStreamOptions);
        $streamNameSelect.find('option[value="-1"]').attr("selected",true);
    };

//    used to create options for available siddhi apps and streams
    self.generateOptions = function (dataArray,initialOptionValue) {
        dataArray.sort();
        var dataOption =
            '<option value = "{{dataName}}">' +
            '   {{dataName}}' +
            '</option>';
        var result = '';

        if(initialOptionValue !== undefined){
            result += initialOptionValue;
        }

        for (var i = 0; i < dataArray.length; i++) {
            result += dataOption.replaceAll('{{dataName}}', dataArray[i]);
        }
        return result;
    };

// create input fields for attributes
    self.refreshAttributesList = function (uuid, streamAttributes) {
        var newAttributesOption =
            '
 ' +
            '
' +
            '
' +
            '       ' +
            '           ' +
            '               Attributes *' +
            '            ' +
            '       	' +
            '       ' +
            '           ' +
            '            Is Null' +
            '           ' +
            '       	' +
            '       ' +
            '           <input type="checkbox" class="parent-checkbox" style="margin-bottom:7px" >' +
            '       	' +
            '
' +
            '
' +
            '
' +
            '
' +
            '
';

        var $attrSection = $(newAttributesOption);
        var $form = $('form[data-uuid="' + uuid + '"]');
        $attrSection
            .find('[data-name="attributes-body"]')
            .html(self.generateAttributes(streamAttributes, $form));
        var $attributesDiv = $('form[data-uuid="' + uuid + '"] div[data-name="attributes"]');
        $attributesDiv.html($attrSection);

        $form.removeData('validate');
        for (var i = 0; i < streamAttributes.length; i++) {
            if (streamAttributes[i]['type'] === 'BOOL') {
                $form.find('select[name="'+streamAttributes[i]['name']+'-attr"]').rules('add', {
                    required: true,
                    messages: {
                        required: "Please select a value."
                    }
                });
            } else {
                $form.find('input[name="'+streamAttributes[i]['name']+'-attr"]').rules('add', {
                    required: true,
                    messages: {
                        digits: "Please enter a value."
                    }
                });
            }
        }
        // if there are any boolean attributes set the selected option fo the drop down to -1
        $('select[data-input="bool"]').each(function () {
            $(this)
                .prop('selectedIndex', -1);
        });
        parentCheckboxEventListener();
    };

//add an eventlistener to parent checkbox for disabling all the attributes
    var parentCheckboxEventListener = function() {
        $(".form-group").on("click", ".parent-checkbox", function() {
            var checkStatus = $(this).is(":checked");
            var parent = $(this).parents(".form-group");
                parent.find(".attribtes-checkbox" && ".form-control").each(function() {
                    parent.find(".attributes-checkbox").prop("checked", checkStatus);
                    parent.find(".form-control").val("").prop("disabled", checkStatus);
                });
         });
    };

// create input fields for attributes
    self.generateAttributes = function (attributes, $form) {
        var booleanInput =
            '
' +
            '   ' +
            '       ' +
            '           {{attributeName}} ({{attributeType}})' +
            '      ' +
            '            <select class="form-control" data-element-type="attribute" name="{{attributeName}}-attr"' +
            '            data-type ="{{attributeType}}" data-input="bool">' +
            '               <option value="true">True</option> ' +
            '               <option value="false">False</option> ' +
            '           </select>' +
            '   	' +
            '   ' +
            '       <input type="checkbox" class="attributes-checkbox"  name="{{attributeName}}-null" data-attribute-name="{{attributeName}}-attr"' +
            '       data-input="null">' +
            '   	' +
            '
';

        var textInput =
            '
' +
            '   ' +
            '       ' +
            '           {{attributeName}} ({{attributeType}})' +
            '       ' +
            '           <input type="text" class="form-control" data-element-type="attribute"' +
            '           name="{{attributeName}}-attr" data-type ="{{attributeType}}">' +
            '   	' +
            '   ' +
            '       <input align="center" type="checkbox" class="attributes-checkbox" name="{{attributeName}}-null"' +
            '       data-attribute-name="{{attributeName}}-attr" data-input="null">' +
            '   	' +
            '
';

        var result = "";
        for (var i = 0; i < attributes.length; i++) {
            var temp;
            if (attributes[i]['type'] === 'BOOL') {
                temp = booleanInput.replaceAll('{{attributeName}}', attributes[i]['name']);
                result += temp.replaceAll('{{attributeType}}', attributes[i]['type'])
            } else {
                temp = textInput.replaceAll('{{attributeName}}', attributes[i]['name']);
                result += temp.replaceAll('{{attributeType}}', attributes[i]['type'])
            }
        }
        return result;
    };

// add rules for attribute
    self.addRulesForAttributes = function (uuid) {
        var $attributes = $('form[data-form-type="single"][data-uuid="' + uuid + '"] [data-element-type="attribute"]');
        $attributes.each(
            function () {
                self.addRuleForAttribute(this);
                var dataType = $(this).attr("data-type");
                $(this).keypress(function(e) {
                    var userInput = e.key;
                    if (!constants.ALLOWED_KEYS.includes(userInput)) {
                        var valid = self.onKeyPressValidate(dataType, userInput);
                        if (!valid) {
                            e.preventDefault();
                        }
                    }
                });
            }
        );
    };

//add onKeyPressValidate for an attribute based on the attribute type
    self.onKeyPressValidate = function(dataType, userInput) {
        var validDataType = true;
        if (constants.INT_LONG.includes(dataType)) {
            if (!userInput.match(constants.INT_LONG_REGEX_MATCH)) {
                validDataType = false;
            }
        } else if (constants.DOUBLE_FLOAT.includes(dataType)) {
            if (!userInput.match(constants.DOUBLE_FLOAT_REGEX_MATCH)) {
                validDataType = false;
            }
        }
        return validDataType;
    };

// add a validation rule for an attribute based on the attribute type
    self.addRuleForAttribute = function (ctx) {
        var type = $(ctx).data("type");
        switch (type) {
            case 'BOOL' :
                $(ctx).rules('add', {
                    required: true,
                    messages: {
                        required: "Please specify an attribute value."
                    }
                });
                break;
            case 'INT' :
            case 'LONG' :
                $(ctx).rules('add', {
                    required: true,
                    validateIntOrLong: true,
                    messages: {
                        required: "Please specify an attribute value."
                    }
                });
                break;
            case 'DOUBLE' :
            case 'FLOAT' :
                $(ctx).rules('add', {
                    required: true,
                    validateFloatOrDouble: true,
                    messages: {
                        required: "Please specify an attribute value."
                    }
                });
                break;
        }
    };

// remove rules used for previous attributes
    self.removeSingleEventAttributeRules = function (uuid) {
        var $attributes = $('form[data-form-type="single"][data-uuid="' + uuid + '"] [data-element-type="attribute"]');
        $attributes.each(
            function () {
                self.removeRuleOfAttribute(this);
            }
        );
    };

    // remove validation rule of an attribute
    self.removeRuleOfAttribute = function (ctx) {
        $(ctx).rules('remove');
    };

    // start inactive siddhi apps in run or debug mode
    self.startInactiveSiddhiApp = function ($form) {
        var uuid = $form.data('uuid');
        var siddhiAppName = $form.find('select[name="single-event-siddhi-app-name"]').val();
        var mode = $form.find('input[name="run-debug"]:checked').val();
        var tabController = self.app.tabController;
        var activeTab = tabController.getTabFromTitle(siddhiAppName);
        if (!activeTab) {
            OpenSiddhiApps.openFile(siddhiAppName);
            activeTab = tabController.getTabFromTitle(siddhiAppName);
        }
        tabController.setActiveTab(activeTab);
        var tab = self.app.tabController.getTabFromTitle(siddhiAppName);
        var launcher = tab.getSiddhiFileEditor().getLauncher();
        if(tab !== undefined){
            var started = false;
            if (mode === 'run') {
                started = launcher.runApplication(self.workspace, false);
                if (started) {
                    self.siddhiAppDetailsMap[siddhiAppName] = self.RUN;
                }
            } else if (mode === 'debug') {
                started = launcher.debugApplication(self.workspace, false);
                if (started) {
                    self.siddhiAppDetailsMap[siddhiAppName] = self.DEBUG;
                }
            }
            return started;
        }
    };

    self.changeSiddhiAppStatusInSingleSimulation = function (siddhiAppName, status) {
        var $singleEventConfigList = $("#single-event-configs").find("div[id^='event-content-parent-']");
        $singleEventConfigList.each(function () {
            var $singleEventConfig = $(this);
            var currentSiddhiAppName = $singleEventConfig.find("select[name='single-event-siddhi-app-name']").val();
            if (siddhiAppName == currentSiddhiAppName) {
                var $notificationBox = $singleEventConfig.find(".alert");
                self.siddhiAppDetailsMap[siddhiAppName] = status;
                $singleEventConfig.find('div[data-name="siddhi-app-name-mode"]').html(self.SiddhiAppStatus + status);
                if (status == "RUN" || status == "DEBUG") {
                    $notificationBox.addClass("alert-success");
                    $notificationBox.removeClass("alert-warning");
                    $notificationBox.removeClass("alert-danger");
                    $singleEventConfig.find('div[data-name="run-debug-buttons"]').empty();
                    $singleEventConfig.find('button[type="submit"][name="send"]').text(self.sendLabel);
                    $singleEventConfig.prop('disabled', false);
                } else if (status == "STOP") {
                    $notificationBox.removeClass("alert-success");
                    $notificationBox.removeClass("alert-danger");
                    $notificationBox.addClass("alert-warning");
                    $singleEventConfig.find('div[data-name="run-debug-buttons"]').html(self.createRunDebugButtons());
                    $singleEventConfig.find('button[type="submit"][name="send"]').text(self.startAndSendLabel);
                    $singleEventConfig.prop('disabled', false);
                } else {
                    $notificationBox.addClass("alert-danger");
                    $notificationBox.removeClass("alert-warning");
                    $notificationBox.removeClass("alert-success");
                    $singleEventConfig.find('div[data-name="run-debug-buttons"]').empty();
                    $singleEventConfig.prop('disabled', true);
                }
            }
        });
    };

    //This is on app save
    self.changeSiddhiAppsAndStreamOptionsInSingleSimulationOnSave = function (changedSiddhiAppName, noOfIterations) {
        if (0 !== noOfIterations) {
            noOfIterations--;
            Simulator.retrieveSiddhiAppNames(
                function (data) {
                    var valueFound = false;
                    if (0 < data.length) {
                        $('#createFeedSimulationNotification').hide();
                        self.app.eventSimulator.getFeedSimulator().enableCreateButtons(true);
                    }
                    for (var i = 0; i < data.length; i++) {
                        if (changedSiddhiAppName === data[i]['siddhiAppName']) {
                            valueFound = true;
                            var $singleEventConfigList = $("#single-event-configs")
                                .find("div[id^='event-content-parent-']");

                            if (1 === $singleEventConfigList.length) {
                                self.removeOrAddSiddhiStreamsOnAppSave($singleEventConfigList, changedSiddhiAppName);
                            } else {
                                $singleEventConfigList.each(function () {
                                    self.removeOrAddSiddhiStreamsOnAppSave($(this), changedSiddhiAppName);
                                });
                            }
                            if (self.FAULTY === data[i]['mode']) {
                                setTimeout(function(){
                                    self.changeSiddhiAppsAndStreamOptionsInSingleSimulationOnSave(
                                        changedSiddhiAppName, noOfIterations);
                                }, 1000);
                            }
                        }
                    }
                    //this means the saved app is not yet deployed
                    if (!valueFound) {
                        setTimeout(function(){
                            self.changeSiddhiAppsAndStreamOptionsInSingleSimulationOnSave(
                                changedSiddhiAppName, noOfIterations);
                        }, 1000);
                    } else {
                        var $singleEventConfigList = $("#single-event-configs")
                            .find("div[id^='event-content-parent-']");

                        if (1 === $singleEventConfigList.length) {
                            self.addSiddhiAppsOnAppSave($singleEventConfigList, changedSiddhiAppName);
                        } else {
                            $singleEventConfigList.each(function () {
                                self.addSiddhiAppsOnAppSave($(this), changedSiddhiAppName);
                            });
                        }
                    }
                },
                function (data) {
                    log.info(data);
                }
            );
        }
    };

    self.addSiddhiAppsOnAppSave = function ($singleEventConfig, changedSiddhiAppName) {
        var siddhiAppNames = $singleEventConfig.find("select[name='single-event-siddhi-app-name']");
        var valueFound = false;
        siddhiAppNames.find("option").each(function() {
            if ("-1" !== $(this).val()) {
                var option = $(this);
                if (changedSiddhiAppName === option.val()) {
                    valueFound = true;
                }
            }
        });
        if (!valueFound) {
            if (1 === siddhiAppNames.find("option").length) {
                siddhiAppNames.find("option").remove();
                siddhiAppNames.append($("<option value = \"-1\" disabled></option>").text("-- Please Select a Siddhi App --"));
                siddhiAppNames.find('option[value="-1"]').attr("selected",true);
            }
            siddhiAppNames.append($("<option></option>").attr("value", changedSiddhiAppName).text(changedSiddhiAppName));
        }
    };

    //This is on app delete
    self.changeSiddhiAppsAndStreamOptionsInSingleSimulationOnDelete = function (changedSiddhiAppName, noOfIterations) {
        if (0 !== noOfIterations) {
            noOfIterations--;
            Simulator.retrieveSiddhiAppNames(
                function (data) {
                    var valueFound = false;
                    if (0 === data.length) {
                        $('#createFeedSimulationNotification').show();
                        self.app.eventSimulator.getFeedSimulator().disableCreateButtons(false);
                    }
                    for (var i = 0; i < data.length; i++) {
                        if (changedSiddhiAppName.slice(0, -7) === data[i]['siddhiAppName']) {
                            valueFound = true;
                        }
                    }
                    //this means the saved app is not yet deleted
                    if (valueFound) {
                        setTimeout(function(){
                            self.changeSiddhiAppsAndStreamOptionsInSingleSimulationOnSave(
                                changedSiddhiAppName, noOfIterations);
                        }, 1000);
                    } else {
                        var $singleEventConfigList = $("#single-event-configs")
                            .find("div[id^='event-content-parent-']");
                        if (1 === $singleEventConfigList.length) {
                            self.removeSiddhiAppsOnAppDelete($singleEventConfigList, changedSiddhiAppName);
                        } else {
                            $singleEventConfigList.each(function () {
                                self.removeSiddhiAppsOnAppDelete($(this), changedSiddhiAppName);
                            });
                        }
                    }
                },
                function (data) {
                    log.info(data);
                }
            );

        }
    };

    self.removeSiddhiAppsOnAppDelete = function ($singleEventConfig, deletedSiddhiAppName) {
        var siddhiAppNames = $singleEventConfig.find("select[name='single-event-siddhi-app-name']");
        siddhiAppNames.find("option").each(function() {
            if ("-1" !== $(this).val()) {
                var option = $(this);
                if (deletedSiddhiAppName === option.val()) {
                    if (option.is(':selected')) {
                        option.parent().find('option[value=-1]').prop('selected', true);
                        option.closest('.single-event-form').find('div[data-name="attributes"]').html("");
                        option.remove();
                    } else {
                        option.remove();
                    }
                    if (1 === siddhiAppNames.find("option").length) {
                        siddhiAppNames.find("option").remove();
                        siddhiAppNames.append($("<option value = \"-1\" disabled></option>").text("-- No saved Siddhi Apps available. --"));
                        siddhiAppNames.find('option[value="-1"]').attr("selected",true);
                    }
                }
            }
        });
    };

    self.removeOrAddSiddhiStreamsOnAppSave = function ($singleEventConfig, changedSiddhiAppName) {
        var siddhiAppName = $singleEventConfig.find("select[name='single-event-siddhi-app-name']").val();
        var siddhiStreams = $singleEventConfig.find("select[name='stream-name']");
        if (changedSiddhiAppName === siddhiAppName) {
            Simulator.retrieveStreamNames(
                siddhiAppName,
                function (data) {
                    siddhiStreams.find("option").each(function() {
                        if ("-1" !== $(this).val()) {
                            var valueFound = false;
                            var option = $(this);
                            for (var i = 0; i < data.length; i++) {
                                if (data[i] === option.val()) {
                                    valueFound = true;
                                }
                            }
                            if (!valueFound) {
                                if (option.is(':selected')) {
                                    option.parent().find('option[value=-1]').prop('selected', true);
                                    option.closest('.single-event-form').find('div[data-name="attributes"]').html("");
                                    option.remove();
                                } else {
                                    option.remove();
                                }
                            }
                        }
                    });
                    for (var i = 0; i < data.length; i++) {
                        var valueFound = false;
                        siddhiStreams.find("option").each(function() {
                            if (data[i] === $(this).val()) {
                                valueFound = true;
                            }
                        });
                        if (!valueFound) {
                            siddhiStreams.append($("<option></option>").attr("value", data[i]).text(data[i]));
                        }
                    }
                },
                function (data) {
                    log.info(data);
                }
            );
        }
    };

    return self;
});


text:
namespace Microsoft.Azure.Management.DataLake.Store.Models
{
    using System;
    using System.Linq;
    using System.Collections.Generic;
    using Newtonsoft.Json;
    using Microsoft.Rest;
    using Microsoft.Rest.Serialization;
    using Microsoft.Rest.Azure;

    /// <summary>
    /// Data Lake Store filesystem exception based on the WebHDFS definition
    /// for RemoteExceptions.
    /// </summary>
    public partial class AdlsRemoteException
    {
        /// <summary>
        /// Initializes a new instance of the AdlsRemoteException class.
        /// </summary>
        public AdlsRemoteException() { }

        /// <summary>
        /// Initializes a new instance of the AdlsRemoteException class.
        /// </summary>
        /// <param name="javaClassName">the full class package name for the exception thrown, such as 'java.lang.IllegalArgumentException'.</param>
        /// <param name="message">the message associated with the exception that was thrown, such as 'Invalid value for webhdfs parameter "permission":...'.</param>
        public AdlsRemoteException(string javaClassName = default(string), string message = default(string))
        {
            JavaClassName = javaClassName;
            Message = message;
        }

        /// <summary>
        /// Gets the full class package name for the exception thrown, such as
        /// 'java.lang.IllegalArgumentException'.
        /// </summary>
        [JsonProperty(PropertyName = "javaClassName")]
        public string JavaClassName { get; private set; }

        /// <summary>
        /// Gets the message associated with the exception that was thrown,
        /// such as 'Invalid value for webhdfs parameter "permission":...'.
        /// </summary>
        [JsonProperty(PropertyName = "message")]
        public string Message { get; private set; }

    }
}

redpajama_set_name: RedPajamaGithub


text:
var gulp = require('gulp'),
  tsc = require('gulp-tsc'),
  typescript = require('gulp-typescript'),
  stylus = require('gulp-stylus'),
  rucksack = require('rucksack-css'),
  poststylus = require('poststylus'),
  sourcemaps = require('gulp-sourcemaps'),
  spawn = require('child_process').spawn;

const tsProject = typescript.createProject('tsconfig.json');

gulp.task('lite-server', function (cb) {
  var ls = spawn('npm', ['run', 'lite']);

  ls.stdout.on('data', function(data) {
    process.stdout.write('' + data);
  });

  ls.stderr.on('data', function(data) {
    process.stdout.write('' + data);
  });
});

gulp.task('stylus', function () {
  gulp.src('src/**/*.styl')
    .pipe(stylus({
      'include css': true,
      use: [
        poststylus(['rucksack-css'])
      ]
    }))
    .pipe(gulp.dest('src/'))
});

gulp.task('watch', function() {
  gulp.watch('src/**/*.styl', ['stylus']);
  gulp.watch('src/**/*.ts', ['compile']);
});

gulp.task('compile', function(){
  var tsResult = tsProject.src()
    .pipe(sourcemaps.init())
    .pipe(tsProject());
  return tsResult.js
    .pipe(sourcemaps.write())
    .pipe(gulp.dest(''));
});

gulp.task('default', ['compile', 'stylus', 'watch', 'lite-server']);


text:
* Type class constraints in functions

* Polymorphic application of functions (i.e. find natural transformations)

* Relations

* Imperative programs

## Small TODOs

* Hide output of background theories
  - Can we safely disable (or limit) completion with background
    theories?
  - Explore background theories up to a smaller size
  - Remember the set of terms and add to it

* Add QS1 feature of organising laws by defining function
  (i.e., "this is a law about BLAH")

* Improve handling of partial functions (see Heaps.hs)

* Make Type into an abstract type


text:
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifndef GMPTimerParent_h_
#define GMPTimerParent_h_

#include "mozilla/gmp/PGMPTimerParent.h"
#include "nsITimer.h"
#include "nsCOMPtr.h"
#include "nsClassHashtable.h"
#include "nsHashKeys.h"
#include "nsAutoPtr.h"
#include "mozilla/Monitor.h"
#include "nsIThread.h"

namespace mozilla {
namespace gmp {

class GMPTimerParent : public PGMPTimerParent {
public:
  NS_INLINE_DECL_REFCOUNTING(GMPTimerParent)
  explicit GMPTimerParent(nsIThread* aGMPThread);

  void Shutdown();

protected:
  virtual bool RecvSetTimer(const uint32_t& aTimerId,
                            const uint32_t& aTimeoutMs) override;
  virtual void ActorDestroy(ActorDestroyReason aWhy) override;

private:
  ~GMPTimerParent() {}

  static void GMPTimerExpired(nsITimer *aTimer, void *aClosure);

  struct Context {
    Context() {
      MOZ_COUNT_CTOR(Context);
    }
    ~Context() {
      MOZ_COUNT_DTOR(Context);
    }
    nsCOMPtr<nsITimer> mTimer;
    nsRefPtr<GMPTimerParent> mParent; // Note: live timers keep the GMPTimerParent alive.
    uint32_t mId;
  };

  static PLDHashOperator
  CancelTimers(nsPtrHashKey<Context>* aContext, void* aClosure);

  void TimerExpired(Context* aContext);

  nsTHashtable<nsPtrHashKey<Context>> mTimers;

  nsCOMPtr<nsIThread> mGMPThread;

  bool mIsOpen;
};

} // namespace gmp
} // namespace mozilla

#endif // GMPTimerParent_h_


text:
using CQRS.Messaging;
using System.Threading.Tasks;

namespace CQRS.InMemory.Messaging
{
    public interface IMessageBus
    {
        Task<IMessage> ReceiveAsync();
        Task SendAsync(IMessage m);
    }
}


text:
package main

import (
	"fmt"
	"os"

	"github.com/Smartling/api-sdk-go"
	"github.com/reconquest/hierr-go"
)

func doProjectsList(
	client *smartling.Client,
	config Config,
	args map[string]interface{},
) error {
	var (
		short = args["--short"].(bool)
	)

	projects, err := client.ListProjects(
		config.AccountID,
		smartling.ProjectsListRequest{},
	)
	if err != nil {
		return NewError(
			hierr.Errorf(err, "unable to list projects"),
			"",
		)
	}

	table := NewTableWriter(os.Stdout)

	for _, project := range projects.Items {
		if short {
			fmt.Fprintln(table, project.ProjectID)
		} else {
			fmt.Fprintf(
				table,
				"%s\t%s\t%s\n",
				project.ProjectID,
				project.ProjectName,
				project.SourceLocaleID,
			)
		}
	}

	err = RenderTable(table)
	if err != nil {
		return err
	}

	return nil
}


text:
package org.opensingular.form.view.list;

import org.opensingular.form.SInstance;

public class ButtonsMasterDetailConfig extends ButtonsConfig {

    public static final String VISUALIZAR_HINT = "Visualizar";
    public static final String EDITAR_HINT = "Editar";
    /**
     * The visible button rule visible will be used just in the edition, in the view mode will always be visible.
     */
    private ButtonAction viewButtonInEdition;

    private ButtonAction editButton;

    /**
     * Will overriding the edit button to be always visible.
     */
    public ButtonsMasterDetailConfig() {
        super();
        viewButtonInEdition = new ButtonAction(f -> false, VISUALIZAR_HINT, null);
        editButton = new ButtonAction(f -> true, EDITAR_HINT, null);
    }

    public ButtonAction getViewButtonInEdition() {
        return viewButtonInEdition;
    }

    public void setViewButtonInEdition(ButtonAction viewButtonInEdition) {
        this.viewButtonInEdition = viewButtonInEdition;
    }

    public boolean isViewEnabled(SInstance instance) {
        return viewButtonInEdition.isEnabled(instance);
    }

    public ButtonAction getEditButton() {
        return editButton;
    }

    public void setEditButton(ButtonAction editButton) {
        this.editButton = editButton;
    }

    /**
     * Verify is edit button is enabled by the instance of the row.
     *
     * @param instance The instance of the row.
     * @return True for enable, false for not.
     */
    public boolean isEditEnabled(SInstance instance) {
        return editButton.isEnabled(instance);
    }
}


text:
/**
 * \file serv.h
 *    \brief Functions prototypes for the server.
 * \author k.edeline
 * \version 0.1
 */

#ifndef UDPTUN_SERV_H
#define UDPTUN_SERV_H

#include "udptun.h"

/**
 * \fn void tun_serv(struct arguments *args)
 * \brief Runs the server.
 *
 * \param args A pointer to the server arguments.
 * \return
 */
void tun_serv(struct arguments *args);

#endif


text:
package slieb.closure.internal;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.HashMap;
import java.util.Map;

public class GlobalsConverter {

    @Nullable
    public Object convertValue(@Nullable final String stringValue) {
        if (stringValue == null || stringValue.equalsIgnoreCase("null")) {
            return null;
        }

        if (stringValue.equalsIgnoreCase("true")) {
            return true;
        }

        if (stringValue.equalsIgnoreCase("false")) {
            return false;
        }

        if (stringValue.startsWith("'") || stringValue.startsWith("\"")) {
            return stringValue.substring(1, stringValue.length() - 1);
        }

        return new Double(stringValue);
    }

    @Nonnull
    public Map<String, Object> convert(
            @Nonnull final Map<String, String> stringMap) {
        Map<String, Object> convertedMap = new HashMap<>();
        for (Map.Entry<String, String> entry : stringMap.entrySet()) {
            convertedMap.put(entry.getKey(), convertValue(entry.getValue()));
        }
        return convertedMap;
    }
}


text:
"Sometimes I feel like universal JS
is a far-off mirage in the desert
that just keeps turning into sand
when I get close to it." - Ryan Grove


text:
/*
	CVCardN.h

	Author:
	Description:	<describe the CVCardN class here>
*/

#ifndef CVCardN_H
#define CVCardN_H

#include <ostream>

#include "cdstring.h"

namespace vCard {

class CVCardN
{
public:
	CVCardN() {}
	CVCardN(const cdstring& fullname)
	{
		SetFullName(fullname);
	}
	CVCardN(const cdstring& first, const cdstring& last)
	{
		mItems[eFirst] = first;
		mItems[eLast] = last;
	}
	CVCardN(const CVCardN& copy)
		{ _copy_CVCardN(copy); }
	virtual ~CVCardN() {}

	CVCardN& operator=(const CVCardN& copy)
		{ if (this != &copy) _copy_CVCardN(copy); return *this; }

	const cdstring& GetFirst() const
		{ return mItems[eFirst]; }
	void SetFirst(const cdstring& first)
		{ mItems[eFirst] = first; }

	const cdstring& GetLast() const
		{ return mItems[eLast]; }
	void SetLast(const cdstring& last)
		{ mItems[eLast] = last; }

	const cdstring& GetMiddle() const
		{ return mItems[eMiddle]; }
	void SetMiddle(const cdstring& middle)
		{ mItems[eMiddle] = middle; }

	const cdstring& GetPrefix() const
		{ return mItems[ePrefix]; }
	void SetPrefix(const cdstring& prefix)
		{ mItems[ePrefix] = prefix; }

	const cdstring& GetSuffix() const
		{ return mItems[eSuffix]; }
	void SetSuffix(const cdstring& suffix)
		{ mItems[eSuffix] = suffix; }

	cdstring GetFullName(bool with_titles = false) const;
	void SetFullName(const cdstring& data);

	void Parse(const cdstring& data);
	void Generate(std::ostream& os) const;

	bool Search(const cdstring& pattern) const;

protected:
	enum
	{
		eLast = 0,
		eFirst,
		eMiddle,
		ePrefix,
		eSuffix,
		eMaxIndex
	};
	cdstring		mItems[eMaxIndex];

private:
	void _copy_CVCardN(const CVCardN& copy);

	void AppendFullNameItem(cdstring& result, const cdstring& item) const;

};

}	// namespace vCard

#endif	// CVCardN_H


text:
package gov.sandia.cognition.statistics.bayesian.conjugate;

import gov.sandia.cognition.statistics.distribution.UnivariateGaussian;
import java.util.ArrayList;

/**
 * Unit tests for UnivariateGaussianMeanBayesianEstimatorTest.
 *
 * @author krdixon
 */
public class UnivariateGaussianMeanBayesianEstimatorTest
    extends ConjugatePriorBayesianEstimatorTestHarness<Double,Double,UnivariateGaussian>
{

    /**
     * Tests for class UnivariateGaussianMeanBayesianEstimatorTest.
     * @param testName Name of the test.
     */
    public UnivariateGaussianMeanBayesianEstimatorTest(
        String testName)
    {
        super(testName);
    }

    /**
     * Tests the constructors of class UnivariateGaussianMeanBayesianEstimatorTest.
     */
    public void testConstructors()
    {
        System.out.println( "Constructors" );

        UnivariateGaussianMeanBayesianEstimator instance =
            new UnivariateGaussianMeanBayesianEstimator();
        assertEquals( UnivariateGaussianMeanBayesianEstimator.DEFAULT_KNOWN_VARIANCE, instance.getKnownVariance() );
        assertEquals( 0.0, instance.getInitialBelief().getMean() );
        assertEquals( 1.0, instance.getInitialBelief().getVariance() );

        double v = RANDOM.nextDouble();
        instance = new UnivariateGaussianMeanBayesianEstimator( v );
        assertEquals( v, instance.getKnownVariance() );
        assertEquals( 0.0, instance.getInitialBelief().getMean() );
        assertEquals( 1.0, instance.getInitialBelief().getVariance() );

        UnivariateGaussian u =
            new UnivariateGaussian( RANDOM.nextGaussian(), RANDOM.nextDouble() );
        instance = new UnivariateGaussianMeanBayesianEstimator( v, u );
        assertEquals( v, instance.getKnownVariance() );
        assertSame( u, instance.getInitialBelief() );

    }

    /**
     * Test of getKnownVariance method, of class UnivariateGaussianMeanBayesianEstimator.
     */
    public void testGetKnownVariance()
    {
        System.out.println("getKnownVariance");
        double variance = RANDOM.nextDouble();
        UnivariateGaussianMeanBayesianEstimator instance =
            new UnivariateGaussianMeanBayesianEstimator( variance );
        assertEquals( variance, instance.getKnownVariance() );
    }

    /**
     * Test of setKnownVariance method, of class UnivariateGaussianMeanBayesianEstimator.
     */
    public void testSetKnownVariance()
    {
        System.out.println("setKnownVariance");
        double knownVariance = RANDOM.nextDouble();
        UnivariateGaussianMeanBayesianEstimator instance =
            new UnivariateGaussianMeanBayesianEstimator( knownVariance );
        assertEquals( knownVariance, instance.getKnownVariance() );
        double v2 = knownVariance + 1.0;
        instance.setKnownVariance(v2);
        assertEquals( v2, instance.getKnownVariance() );

        try
        {
            instance.setKnownVariance(0.0);
            fail( "Known variance must be > 0.0" );
        }
        catch (Exception e)
        {
            System.out.println( "Good: " + e );
        }
    }

    @Override
    public UnivariateGaussianMeanBayesianEstimator createInstance()
    {
        return new UnivariateGaussianMeanBayesianEstimator();
    }

    @Override
    public UnivariateGaussian createConditionalDistribution()
    {
        return new UnivariateGaussian( RANDOM.nextGaussian(), RANDOM.nextDouble() );
    }

    @Override
    public void testKnownValues()
    {
        System.out.println( "Known values" );

        UnivariateGaussianMeanBayesianEstimator instance =
            new UnivariateGaussianMeanBayesianEstimator(
                4.0, new UnivariateGaussian( 30, 16 ) );

        ArrayList<Double> data = new ArrayList<Double>( 12 );
        for( int i = 0; i < 12; i++ )
        {
            data.add( 32.0 );
        }

        UnivariateGaussian result = instance.learn(data);
        assertEquals( 0.3265306, result.getVariance(), TOLERANCE );
        assertEquals( 31.959184, result.getMean(), TOLERANCE );

    }

}


text:
package org.springframework.web.servlet.view.tiles3;

import org.apache.tiles.request.render.Renderer;

import org.springframework.web.servlet.view.UrlBasedViewResolver;

/**
 * Convenience subclass of {@link UrlBasedViewResolver} that supports
 * {@link TilesView} (i.e. Tiles definitions) and custom subclasses of it.
 *
 * @author Nicolas Le Bas
 * @author Rossen Stoyanchev
 * @author Juergen Hoeller
 * @author Sebastien Deleuze
 * @since 3.2
 */
public class TilesViewResolver extends UrlBasedViewResolver {

	private Renderer renderer;

	private Boolean alwaysInclude;

	public TilesViewResolver() {
		setViewClass(requiredViewClass());
	}

	/**
	 * This resolver requires {@link TilesView}.
	 */
	@Override
	protected Class<?> requiredViewClass() {
		return TilesView.class;
	}

	/**
	 * Set the {@link Renderer} to use. If not specified, a default
	 * {@link org.apache.tiles.renderer.DefinitionRenderer} will be used.
	 * @see TilesView#setRenderer(Renderer)
	 */
	public void setRenderer(Renderer renderer) {
		this.renderer = renderer;
	}

	/**
	 * Specify whether to always include the view rather than forward to it.
	 * <p>Default is "false". Switch this flag on to enforce the use of a
	 * Servlet include, even if a forward would be possible.
	 * @since 4.1.2
	 * @see TilesView#setAlwaysInclude
	 */
	public void setAlwaysInclude(Boolean alwaysInclude) {
		this.alwaysInclude = alwaysInclude;
	}

	@Override
	protected TilesView buildView(String viewName) throws Exception {
		TilesView view = (TilesView) super.buildView(viewName);
		if (this.renderer != null) {
			view.setRenderer(this.renderer);
		}
		if (this.alwaysInclude != null) {
			view.setAlwaysInclude(this.alwaysInclude);
		}
		return view;
	}

}


text:
LuckyBlocks
===========
A remake of the popular Lucky Block mod for Minecraft using Bukkit. This aims to be a complete remake of the original mod, and maybe once I'm done with that I'll eventually add some of my own content too. I'd like to eventually add the luck system in, but that'll be a pain for a beginner like me.

Can I help?
===========
Yes. Everything helps - bug reporting/fixing, feature suggesting(!), feature adding(yay c:), ect. Please report bugs here on github.

Hey, I have a lucky blocks bukkit plugin too!
==========================================
Heck, if it's decent I'd be glad to switch my work to your mod instead of mine, or maybe you can switch. I didn't find any decent ones with a quick Google search (only one I found had 10 events or so).

WOW CAN I DOWNLOAD PLZ WHERE DOWNLOAD WOW
=========================================
You don't want this on your server yet. I'll have a proper build once you do.


text:
#pragma once
#include <aws/cloudsearch/CloudSearch_EXPORTS.h>
#include <aws/cloudsearch/model/DomainStatus.h>
#include <aws/cloudsearch/model/ResponseMetadata.h>
#include <utility>

namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;

namespace Utils
{
namespace Xml
{
  class XmlDocument;
} // namespace Xml
} // namespace Utils
namespace CloudSearch
{
namespace Model
{
  /**
   *
The result of a DeleteDomain request. Contains the status of a
   * newly deleted domain, or no status if the domain has already been completely
   * deleted.

See Also:
   AWS
   * API Reference

   */
  class AWS_CLOUDSEARCH_API DeleteDomainResult
  {
  public:
    DeleteDomainResult();
    DeleteDomainResult(const AmazonWebServiceResult<Aws::Utils::Xml::XmlDocument>& result);
    DeleteDomainResult& operator=(const AmazonWebServiceResult<Aws::Utils::Xml::XmlDocument>& result);

    inline const DomainStatus& GetDomainStatus() const{ return m_domainStatus; }

    inline void SetDomainStatus(const DomainStatus& value) { m_domainStatus = value; }

    inline void SetDomainStatus(DomainStatus&& value) { m_domainStatus = std::move(value); }

    inline DeleteDomainResult& WithDomainStatus(const DomainStatus& value) { SetDomainStatus(value); return *this;}

    inline DeleteDomainResult& WithDomainStatus(DomainStatus&& value) { SetDomainStatus(std::move(value)); return *this;}

    inline const ResponseMetadata& GetResponseMetadata() const{ return m_responseMetadata; }

    inline void SetResponseMetadata(const ResponseMetadata& value) { m_responseMetadata = value; }

    inline void SetResponseMetadata(ResponseMetadata&& value) { m_responseMetadata = std::move(value); }

    inline DeleteDomainResult& WithResponseMetadata(const ResponseMetadata& value) { SetResponseMetadata(value); return *this;}

    inline DeleteDomainResult& WithResponseMetadata(ResponseMetadata&& value) { SetResponseMetadata(std::move(value)); return *this;}

  private:
    DomainStatus m_domainStatus;
    ResponseMetadata m_responseMetadata;
  };

} // namespace Model
} // namespace CloudSearch
} // namespace Aws


text:
import { expect } from 'chai';
import { scale, unscale } from 'sound/common/utils';

describe('unscale(range, value)', ()=> {
	it('returns the value scaled in a 0..1 range', ()=>{
		const v = unscale({min: 500, max: 1000}, 750);
		expect(v).to.equal(.5);
	});
});

describe('scale(range, value)', ()=> {
	it('returns the value between 0 and 1 scaled back in given range', ()=>{
		const v = scale({min: 500, max: 1000}, .5);
		expect(v).to.equal(750);
	});
});


text:
import generate
import pprint

human_data = generate.load_json("genfiles/human.json")
human = generate.generate_entity(human_data)

pprint.pprint(human)


text:
from __future__ import with_statement
import os
import tornado.httpserver
import tornado.process

from core.application import Application
import core.db as db
from core.settings import Settings
from core.util import get_servlet_urlspec
from servlets.api import APIServlet
import ui_modules

api_application = tornado.web.Application(
    # Servlet dispatch rules
    [
        get_servlet_urlspec(APIServlet),
    ],
    # Server settings
    static_path = os.path.join(os.path.dirname(__file__), "static"),
    template_path = os.path.join(os.path.dirname(__file__), "templates"),
    gzip = True,
    login_url = "/login",
    cookie_secret = Settings['cookie_secret'],
    ui_modules = ui_modules,
    autoescape = None,
)

class PushManagerAPIApp(Application):
    name = "api"

    def start_services(self):
        # HTTP server (for api)
        sockets = tornado.netutil.bind_sockets(self.port, address=Settings['api_app']['servername'])
        tornado.process.fork_processes(Settings['tornado']['num_workers'])
        server = tornado.httpserver.HTTPServer(api_application)
        server.add_sockets(sockets)

if __name__ == '__main__':
    app = PushManagerAPIApp()
    db.init_db()
    app.run()


text:
package org.jbpm.workbench.cm.model;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import org.jboss.errai.common.client.api.annotations.Portable;
import org.jboss.errai.databinding.client.api.Bindable;

import static java.util.Optional.ofNullable;

@Bindable
@Portable
public class CaseInstanceSummary {

    private String caseId;
    private String description;
    private Integer status;
    private String containerId;
    private String owner;
    private Date startedAt;
    private Date completedAt;
    private String caseDefinitionId;
    private List<CaseRoleAssignmentSummary> roleAssignments = new ArrayList<>();
    private List<CaseStageSummary> stages = new ArrayList<>();

    public CaseInstanceSummary() {
    }

    public static Builder builder() {
        return new Builder();
    }

    public String getCaseId() {
        return caseId;
    }

    public void setCaseId(final String caseId) {
        this.caseId = caseId;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(final String description) {
        this.description = description;
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(final Integer status) {
        this.status = status;
    }

    public String getContainerId() {
        return containerId;
    }

    public void setContainerId(final String containerId) {
        this.containerId = containerId;
    }

    public String getOwner() {
        return owner;
    }

    public void setOwner(final String owner) {
        this.owner = owner;
    }

    public Date getStartedAt() {
        return startedAt;
    }

    public void setStartedAt(final Date startedAt) {
        this.startedAt = startedAt;
    }

    public Date getCompletedAt() {
        return completedAt;
    }

    public void setCompletedAt(final Date completedAt) {
        this.completedAt = completedAt;
    }

    public List<CaseRoleAssignmentSummary> getRoleAssignments() {
        return roleAssignments;
    }

    public void setRoleAssignments(final List<CaseRoleAssignmentSummary> roleAssignments) {
        this.roleAssignments = ofNullable(roleAssignments).orElse(new ArrayList<>());
    }

    public List<CaseStageSummary> getStages() {
        return stages;
    }

    public void setStages(final List<CaseStageSummary> stages) {
        this.stages = ofNullable(stages).orElse(new ArrayList<>());
    }

    public String getCaseDefinitionId() {
        return caseDefinitionId;
    }

    public void setCaseDefinitionId(final String caseDefinitionId) {
        this.caseDefinitionId = caseDefinitionId;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        CaseInstanceSummary that = (CaseInstanceSummary) o;
        return Objects.equals(caseId, that.caseId);
    }

    @Override
    @SuppressWarnings("PMD.AvoidMultipleUnaryOperators")
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((caseId == null) ? 0 : caseId.hashCode());
        result = ~~result;
        return result;
    }

    @Override
    public String toString() {
        return "CaseInstanceSummary{" +
                "caseId='" + caseId + '\'' +
                ", description='" + description + '\'' +
                ", status=" + status +
                ", containerId='" + containerId + '\'' +
                ", owner='" + owner + '\'' +
                ", startedAt=" + startedAt +
                ", completedAt=" + completedAt +
                ", caseDefinitionId='" + caseDefinitionId + '\'' +
                ", roleAssignments=" + roleAssignments + '\'' +
                ", stages=" + stages +
                '}';
    }

    public static class Builder {

        private CaseInstanceSummary caseInstance = new CaseInstanceSummary();

        public CaseInstanceSummary build() {
            return caseInstance;
        }

        public Builder caseId(final String caseId) {
            caseInstance.setCaseId(caseId);
            return this;
        }

        public Builder description(final String description) {
            caseInstance.setDescription(description);
            return this;
        }

        public Builder status(final Integer status) {
            caseInstance.setStatus(status);
            return this;
        }

        public Builder containerId(final String containerId) {
            caseInstance.setContainerId(containerId);
            return this;
        }

        public Builder owner(final String owner) {
            caseInstance.setOwner(owner);
            return this;
        }

        public Builder startedAt(final Date startedAt) {
            caseInstance.setStartedAt(startedAt);
            return this;
        }

        public Builder completedAt(final Date completedAt) {
            caseInstance.setCompletedAt(completedAt);
            return this;
        }

        public Builder caseDefinitionId(final String caseDefinitionId) {
            caseInstance.setCaseDefinitionId(caseDefinitionId);
            return this;
        }

        public Builder roleAssignments(final List<CaseRoleAssignmentSummary> roleAssignments) {
            caseInstance.setRoleAssignments(roleAssignments);
            return this;
        }

        public Builder stages(final List<CaseStageSummary> stages) {
            caseInstance.setStages(stages);
            return this;
        }

    }

}


text:
var http = require("http")
  , path = require("path")
  , mime = require("mime")
  , url = require("url")
  , fs = require("fs")
  , port = process.env.PORT || 8888
  , ip = process.env.IP || "0.0.0.0";

// compatibility with node 0.6
if (!fs.exists)
    fs.exists = path.exists;

var allowSave = process.argv.indexOf("--allow-save") != -1;

http.createServer(function(req, res) {
    var uri = url.parse(req.url).pathname
      , filename = path.join(process.cwd(), uri);

    if (req.method == "PUT") {
        if (!allowSave)
            return error(res, 404, "Saving not allowed pass --allow-save to enable");
        save(req, res, filename);
    }

    fs.exists(filename, function(exists) {
        if (!exists)
            return error(res, 404, "404 Not Found\n");

        if (fs.statSync(filename).isDirectory()) {
            var files = fs.readdirSync(filename);
            res.writeHead(200, {"Content-Type": "text/html"});

            files.push(".", "..");
            var html = files.map(function(name) {
                var href = uri + "/" + name;
                href = href.replace(/[\/\\]+/g, "/").replace(/\/$/g, "");
                if (fs.statSync(filename + "/" + name + "/").isDirectory())
                    href += "/";
                return "" + name + "
";
            });

            res._hasBody && res.write(html.join(""));
            res.end();
            return;
        }

        fs.readFile(filename, "binary", function(err, file) {
            if (err) {
                res.writeHead(500, { "Content-Type": "text/plain" });
                res.write(err + "\n");
                res.end();
                return;
            }

            var contentType = mime.lookup(filename) || "text/plain";
            res.writeHead(200, { "Content-Type": contentType });
            res.write(file, "binary");
            res.end();
        });
    });
}).listen(port, ip);

function error(res, status, message, error) {
    console.error(error || message);
    res.writeHead(status, { "Content-Type": "text/plain" });
    res.write(message);
    res.end();
}

function save(req, res, filePath) {
    var data = "";
    req.on("data", function(chunk) {
        data += chunk;
    });
    req.on("error", function() {
        error(res, 404, "Could't save file");
    });
    req.on("end", function() {
        try {
            fs.writeFileSync(filePath, data);
        }
        catch (e) {
            return error(res, 404, "Could't save file", e);
        }
        res.statusCode = 200;
        res.end("OK");
    });
}

function getLocalIps() {
    var os = require("os");

    var interfaces = os.networkInterfaces ? os.networkInterfaces() : {};
    var addresses = [];
    for (var k in interfaces) {
        for (var k2 in interfaces[k]) {
            var address = interfaces[k][k2];
            if (address.family === "IPv4" && !address.internal) {
                addresses.push(address.address);
            }
        }
    }
    return addresses;
}

console.log("http://" + (ip == "0.0.0.0" ? getLocalIps()[0] : ip) + ":" + port);


text:
<?php defined('BX_DOL') or die('hack attempt');

class BxGroupsInstaller extends BxBaseModProfileInstaller
{
    function __construct($aConfig)
    {
        parent::__construct($aConfig);
    }

    function enable($aParams)
    {
        $aResult = parent::enable($aParams);

        if($aResult['result'])
            BxDolPayments::getInstance()->updateDependentModules($this->_aConfig['name'], true);

        return $aResult;
    }

    function disable($aParams)
    {
        BxDolPayments::getInstance()->updateDependentModules($this->_aConfig['name'], false);

        return parent::disable($aParams);
    }
}

/** @} */


text:
namespace content {

namespace {

int kUserDataKey;  // Key value is not important.

class ServiceWorkerRequestInterceptor
    : public net::URLRequestInterceptor {
 public:
  explicit ServiceWorkerRequestInterceptor(ResourceContext* resource_context)
      : resource_context_(resource_context) {}
  ~ServiceWorkerRequestInterceptor() override {}
  net::URLRequestJob* MaybeInterceptRequest(
      net::URLRequest* request,
      net::NetworkDelegate* network_delegate) const override {
    ServiceWorkerRequestHandler* handler =
        ServiceWorkerRequestHandler::GetHandler(request);
    if (!handler)
      return NULL;
    return handler->MaybeCreateJob(
        request, network_delegate, resource_context_);
  }

 private:
  ResourceContext* resource_context_;
  DISALLOW_COPY_AND_ASSIGN(ServiceWorkerRequestInterceptor);
};

}  // namespace

void ServiceWorkerRequestHandler::InitializeHandler(
    net::URLRequest* request,
    ServiceWorkerContextWrapper* context_wrapper,
    storage::BlobStorageContext* blob_storage_context,
    int process_id,
    int provider_id,
    bool skip_service_worker,
    FetchRequestMode request_mode,
    FetchCredentialsMode credentials_mode,
    ResourceType resource_type,
    RequestContextType request_context_type,
    RequestContextFrameType frame_type,
    scoped_refptr<ResourceRequestBody> body) {
  if (!request->url().SchemeIsHTTPOrHTTPS())
    return;

  if (!context_wrapper || !context_wrapper->context() ||
      provider_id == kInvalidServiceWorkerProviderId) {
    return;
  }

  ServiceWorkerProviderHost* provider_host =
      context_wrapper->context()->GetProviderHost(process_id, provider_id);
  if (!provider_host || !provider_host->IsContextAlive())
    return;

  if (skip_service_worker) {
    if (ServiceWorkerUtils::IsMainResourceType(resource_type)) {
      provider_host->SetDocumentUrl(net::SimplifyUrlForRequest(request->url()));
      provider_host->SetTopmostFrameUrl(request->first_party_for_cookies());
      // A page load with skip_service_worker should be triggered by
      // shift-reload, so retain all live matching registrations.
      provider_host->AddAllMatchingRegistrations();
    }
    return;
  }

  scoped_ptr<ServiceWorkerRequestHandler> handler(
      provider_host->CreateRequestHandler(request_mode,
                                          credentials_mode,
                                          resource_type,
                                          request_context_type,
                                          frame_type,
                                          blob_storage_context->AsWeakPtr(),
                                          body));
  if (!handler)
    return;

  request->SetUserData(&kUserDataKey, handler.release());
}

ServiceWorkerRequestHandler* ServiceWorkerRequestHandler::GetHandler(
    net::URLRequest* request) {
  return static_cast<ServiceWorkerRequestHandler*>(
      request->GetUserData(&kUserDataKey));
}

scoped_ptr<net::URLRequestInterceptor>
ServiceWorkerRequestHandler::CreateInterceptor(
    ResourceContext* resource_context) {
  return scoped_ptr<net::URLRequestInterceptor>(
      new ServiceWorkerRequestInterceptor(resource_context));
}

bool ServiceWorkerRequestHandler::IsControlledByServiceWorker(
    net::URLRequest* request) {
  ServiceWorkerRequestHandler* handler = GetHandler(request);
  if (!handler || !handler->provider_host_)
    return false;
  return handler->provider_host_->associated_registration() ||
         handler->provider_host_->running_hosted_version();
}

void ServiceWorkerRequestHandler::PrepareForCrossSiteTransfer(
    int old_process_id) {
  if (!provider_host_ || !context_)
    return;
  old_process_id_ = old_process_id;
  old_provider_id_ = provider_host_->provider_id();
  host_for_cross_site_transfer_ =
      context_->TransferProviderHostOut(old_process_id,
                                        provider_host_->provider_id());
  DCHECK_EQ(provider_host_.get(), host_for_cross_site_transfer_.get());
}

void ServiceWorkerRequestHandler::CompleteCrossSiteTransfer(
    int new_process_id, int new_provider_id) {
  if (!host_for_cross_site_transfer_.get() || !context_)
    return;
  DCHECK_EQ(provider_host_.get(), host_for_cross_site_transfer_.get());
  context_->TransferProviderHostIn(
      new_process_id,
      new_provider_id,
      host_for_cross_site_transfer_.Pass());
  DCHECK_EQ(provider_host_->provider_id(), new_provider_id);
}

void ServiceWorkerRequestHandler::MaybeCompleteCrossSiteTransferInOldProcess(
    int old_process_id) {
  if (!host_for_cross_site_transfer_.get() || !context_ ||
      old_process_id_ != old_process_id) {
    return;
  }
  CompleteCrossSiteTransfer(old_process_id_, old_provider_id_);
}

ServiceWorkerRequestHandler::~ServiceWorkerRequestHandler() {
}

ServiceWorkerRequestHandler::ServiceWorkerRequestHandler(
    base::WeakPtr<ServiceWorkerContextCore> context,
    base::WeakPtr<ServiceWorkerProviderHost> provider_host,
    base::WeakPtr<storage::BlobStorageContext> blob_storage_context,
    ResourceType resource_type)
    : context_(context),
      provider_host_(provider_host),
      blob_storage_context_(blob_storage_context),
      resource_type_(resource_type),
      old_process_id_(0),
      old_provider_id_(kInvalidServiceWorkerProviderId) {
}

}  // namespace content


text:
package rx.swing.sources;

import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

import java.awt.Component;
import java.awt.Point;
import java.awt.event.*;

import javax.swing.JPanel;

import org.junit.Test;
import org.mockito.InOrder;
import org.mockito.Matchers;

import rx.Subscription;
import rx.functions.Action0;
import rx.functions.Action1;

public class MouseEventSourceTest {
    private Component comp = new JPanel();

    @Test
    public void testRelativeMouseMotion() throws Throwable {
        SwingTestHelper.create().runInEventDispatchThread(new Action0() {

            @Override
            public void call() {
                @SuppressWarnings("unchecked")
                Action1<Point> action = mock(Action1.class);
                @SuppressWarnings("unchecked")
                Action1<Throwable> error = mock(Action1.class);
                Action0 complete = mock(Action0.class);

                Subscription sub = MouseEventSource.fromRelativeMouseMotion(comp).subscribe(
                        action, error, complete);

                InOrder inOrder = inOrder(action);

                verify(action, never()).call(Matchers.<Point> any());
                verify(error, never()).call(Matchers.<Exception> any());
                verify(complete, never()).call();

                fireMouseMotionEvent(mouseEvent(0, 0, MouseEvent.MOUSE_MOVED));
                verify(action, never()).call(Matchers.<Point> any());

                fireMouseMotionEvent(mouseEvent(10, -5, MouseEvent.MOUSE_MOVED));
                inOrder.verify(action, times(1)).call(new Point(10, -5));

                fireMouseMotionEvent(mouseEvent(6, 10, MouseEvent.MOUSE_MOVED));
                inOrder.verify(action, times(1)).call(new Point(-4, 15));

                sub.unsubscribe();
                fireMouseMotionEvent(mouseEvent(0, 0, MouseEvent.MOUSE_MOVED));
                inOrder.verify(action, never()).call(Matchers.<Point> any());
                verify(error, never()).call(Matchers.<Exception> any());
                verify(complete, never()).call();
            }

        }).awaitTerminal();
    }

    @Test
    public void testMouseEvents() throws Throwable {
        SwingTestHelper.create().runInEventDispatchThread(new Action0() {

            @Override
            public void call() {
                @SuppressWarnings("unchecked")
                Action1<MouseEvent> action = mock(Action1.class);
                @SuppressWarnings("unchecked")
                Action1<Throwable> error = mock(Action1.class);
                Action0 complete = mock(Action0.class);

                Subscription sub = MouseEventSource.fromMouseEventsOf(comp)
                        .subscribe(action, error, complete);

                InOrder inOrder = inOrder(action);

                verify(action, never()).call(Matchers.<MouseEvent> any());
                verify(error, never()).call(Matchers.<Exception> any());
                verify(complete, never()).call();

                MouseEvent mouseEvent =
                        mouseEvent(0, 0, MouseEvent.MOUSE_CLICKED);
                fireMouseClickEvent(mouseEvent);
                inOrder.verify(action, times(1)).call(mouseEvent);

                mouseEvent = mouseEvent(300, 200, MouseEvent.MOUSE_CLICKED);
                fireMouseClickEvent(mouseEvent);
                inOrder.verify(action, times(1)).call(mouseEvent);

                mouseEvent = mouseEvent(0, 0,  MouseEvent.MOUSE_CLICKED);
                fireMouseClickEvent(mouseEvent);
                inOrder.verify(action, times(1)).call(mouseEvent);

                sub.unsubscribe();
                fireMouseClickEvent(mouseEvent(0, 0, MouseEvent.MOUSE_CLICKED));
                inOrder.verify(action, never()).call(Matchers.<MouseEvent> any());
                verify(error, never()).call(Matchers.<Exception> any());
                verify(complete, never()).call();
            }

        }).awaitTerminal();
    }

    @Test
    public void testMouseWheelEvents() throws Throwable {
        SwingTestHelper.create().runInEventDispatchThread(new Action0() {

            @Override
            public void call() {
                @SuppressWarnings("unchecked")
                Action1<MouseEvent> action = mock(Action1.class);
                @SuppressWarnings("unchecked")
                Action1<Throwable> error = mock(Action1.class);
                Action0 complete = mock(Action0.class);

                Subscription sub = MouseEventSource.fromMouseWheelEvents(comp)
                        .subscribe(action, error, complete);

                InOrder inOrder = inOrder(action);

                verify(action, never()).call(Matchers.<MouseEvent> any());
                verify(error, never()).call(Matchers.<Exception> any());
                verify(complete, never()).call();

                MouseWheelEvent mouseEvent = mouseWheelEvent(0);
                fireMouseWheelEvent(mouseEvent);
                inOrder.verify(action, times(1)).call(mouseEvent);

                mouseEvent = mouseWheelEvent(3);
                fireMouseWheelEvent(mouseEvent);
                inOrder.verify(action, times(1)).call(mouseEvent);

                mouseEvent = mouseWheelEvent(5);
                fireMouseWheelEvent(mouseEvent);
                inOrder.verify(action, times(1)).call(mouseEvent);

                mouseEvent = mouseWheelEvent(1);
                fireMouseWheelEvent(mouseEvent);
                inOrder.verify(action, times(1)).call(mouseEvent);

                sub.unsubscribe();
                fireMouseClickEvent(mouseEvent(0, 0,  MouseEvent.MOUSE_CLICKED));
                inOrder.verify(action, never()).call(Matchers.<MouseEvent> any());
                verify(error, never()).call(Matchers.<Exception> any());
                verify(complete, never()).call();
            }

        }).awaitTerminal();
    }

    private MouseEvent mouseEvent(int x, int y, int mouseEventType) {
        return new MouseEvent(comp, mouseEventType, 1L, 0, x, y, 0,
                false);
    }

    private void fireMouseMotionEvent(MouseEvent event) {
        for (MouseMotionListener listener : comp.getMouseMotionListeners()) {
            listener.mouseMoved(event);
        }
    }

    private void fireMouseClickEvent(MouseEvent event) {
        for (MouseListener listener : comp.getMouseListeners()) {
            listener.mouseClicked(event);
        }
    }

    private MouseWheelEvent mouseWheelEvent(int wheelRotationClicks) {
        int mouseEventType = MouseEvent.MOUSE_WHEEL;
        return new MouseWheelEvent(comp, mouseEventType, 1L, 0, 0, 0, 0,
                false, MouseWheelEvent.WHEEL_BLOCK_SCROLL, 0,
                wheelRotationClicks);
    }

    private void fireMouseWheelEvent(MouseWheelEvent event) {
        for (MouseWheelListener listener : comp.getMouseWheelListeners()) {
            listener.mouseWheelMoved(event);
        }
    }
}


text:
layout: postag
title: 'PRON'
shortdef: 'pronoun'
---

Besides the nominal inflectional features (Number, Case, Number[psor], Person[psor], Number[psed]), pronouns are marked for Number and Person and PronType. Reflexive pronouns bear the feature reflexive but no PronType.


text:
Requirements
============

* Arch Linux ARM for Raspberry Pi (ARMv6) http://archlinuxarm.org/platforms/armv6/raspberry-pi
* OpenCV 2.4 http://opencv.org/
* PiBits ServoBlaster (https://github.com/richardghirst/PiBits/tree/master/ServoBlaster)
* mmal (raspi userland tools)
* raspicam 0.0.5 http://sourceforge.net/projects/raspicam/

Install
=======

* install cmake
    * Arch linux: pacman -S cmake
* build/install opencv
    * Arch linux: pacman -S opencv
* build/install mmal
    * Arch linux: pacman -S raspberrypi-firmware-tools
* build servoblaster
    * cd <pibits dir>/ServoBlaster/user/
    * make
* build raspicam
    * cd <mechanical_eyes dir>/libs/raspicam-0.0.5/
    * mkdir build && cd build
    * cmake ..
    * make && make install
* build mechanical\_eyes
    * cd <mechanical_eyes dir>
    * mkdir build && cd build
    * cmake ..
    * make && make install

Run
===

* start servod from servoblaster directory
* start mechanical\_eyes


text:
<?php

namespace Resque\Helpers;

use Symfony\Component\Console\Formatter\OutputFormatterInterface;

/**
 * Catch output and store
 *
 * @author Michael Haynes <mike@mjphaynes.com>
 */
class CatchOutput extends \Symfony\Component\Console\Output\Output
{

    /**
     * @var string Stored output string
     */
    protected $written = '';

    /**
     * Constructor.
     *
     * @param int                           $verbosity The verbosity level (one of the VERBOSITY constants in OutputInterface)
     * @param bool                          $decorated Whether to decorate messages
     * @param OutputFormatterInterface|null $formatter Output formatter instance (null to use default OutputFormatter)
     */
    public function __construct(
        $verbosity = self::VERBOSITY_NORMAL,
        $decorated = true,
        OutputFormatterInterface $formatter = null
    ) {
        parent::__construct($verbosity, $decorated, $formatter);
    }

    /**
     * Writes a message to the output.
     *
     * @param string|array $messages The message as an array of lines or a single string
     * @param bool         $newline  Whether to add a newline
     * @param int          $type     The type of output (one of the OUTPUT constants)
     *
     * @throws \InvalidArgumentException When unknown output type is given
     */
    public function write($messages, $newline = false, $type = self::OUTPUT_RAW)
    {
        parent::write($messages, $newline, $type);
    }

    /**
     * Stores message in a local string
     *
     * @param string $message A message to write to the output
     * @param bool   $newline Whether to add a newline or not
     */
    protected function doWrite($message, $newline)
    {
        $this->written .= $message.($newline ? PHP_EOL : '');
    }

    /**
     * Returns written string so far
     *
     * @return string
     */
    public function written()
    {
        return $this->written;
    }
}


text:
package com.renarosantos.mybaseapplication.login.bo;

import android.support.annotation.NonNull;
import android.support.annotation.WorkerThread;

import com.renarosantos.mybaseapplication.remote.request.FacebookLoginRequest;
import com.renarosantos.mybaseapplication.remote.response.LoginResponse;
import com.renarosantos.mybaseapplication.user.dao.AppUserDAO;
import com.renarosantos.mybaseapplication.user.dao.FacebookUserCredentials;
import com.renarosantos.mybaseapplication.user.dao.LoggedUser;
import com.renarosantos.mybaseapplication.user.dao.UserPreferences;

/**
 * Created by renarosantos on 17/05/16.
 */
public class LoginBO {
    private final UserPreferences mUserPreferences;
    private final AppUserDAO mUserDAO;

    public LoginBO(@NonNull final AppUserDAO userDAO, @NonNull final UserPreferences userPreferences) {
        mUserDAO = userDAO;
        mUserPreferences = userPreferences;
    }

    @WorkerThread
    public LoggedUser login(String email, String password) {
        final LoginResponse result = mUserDAO.login(email, password);
        if (result != null && result.getStatus()) {
            final LoggedUser loggedUser = LoggedUser.from(result);
            mUserPreferences.setLoggedUser(loggedUser);
            return loggedUser;
        } else {
            return null;
        }
    }

    public LoggedUser getLoggedUser() {
        return mUserPreferences.getLoggedUser();
    }

    public LoggedUser loginWithFacebook() {
        final FacebookUserCredentials facebookUserCredentials = mUserPreferences.getFacebookUserCredentials();
        if (facebookUserCredentials != null) {
            final FacebookLoginRequest loginRequest =
                    new FacebookLoginRequest(facebookUserCredentials.token());
            final LoginResponse loginResponse = mUserDAO.loginWithFacebook(loginRequest);
            if (loginResponse != null && loginResponse.getStatus()) {
                final LoggedUser loggedUser = LoggedUser.from(loginResponse);
                mUserPreferences.setLoggedUser(loggedUser);
                return loggedUser;
            }
        } else {
            return null;
        }
        return null;
    }

}