<commit_before>/**
 * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * WSO2 Inc. licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

define(['log', 'jquery', 'lodash', 'attribute', 'storeAnnotation', 'handlebar', 'annotationObject', 'annotationElement',
    'constants'],
    function (log, $, _, Attribute, StoreAnnotation, Handlebars, AnnotationObject, AnnotationElement, Constants) {

        /**
         * @class TableForm Creates a forms to collect data from a table
         * @constructor
         * @param {Object} options Rendering options for the view
         */
        var TableForm = function (options) {
            if (options !== undefined) {
                this.configurationData = options.configurationData;
                this.application = options.application;
                this.formUtils = options.formUtils;
                this.consoleListManager = options.application.outputController;
                var currentTabId = this.application.tabController.activeTab.cid;
                this.designViewContainer = $('#design-container-' + currentTabId);
                this.toggleViewButton = $('#toggle-view-button-' + currentTabId);
            }
        };

        /**
         * @function generate properties form for a table
         * @param element selected element(table)
         * @param formConsole Console which holds the form
         * @param formContainer Container which holds the form
         */
        TableForm.prototype.generatePropertiesForm = function (element, formConsole, formContainer) {
            var self = this;
            var id = $(element).parent().attr('id');
            var clickedElement = self.configurationData.getSiddhiAppConfig().getTable(id);

            var propertyDiv = $('

 Table Configuration

 ' +
                '

 Name:
 <input type="text" id="tableName" ' +
                'class = "clearfix name">  ' +
                '

' + self.formUtils.buildFormButtons() + '
 ' +
                '

  ' +
                '

 ' +
                '
' +
                '

');

            formContainer.append(propertyDiv);
            self.formUtils.popUpSelectedElement(id);
            self.designViewContainer.addClass('disableContainer');
            self.toggleViewButton.addClass('disableContainer');

            var predefinedStores = _.orderBy(this.configurationData.rawExtensions["store"], ['name'], ['asc']);
            self.formUtils.addDefaultStoreType(predefinedStores);
            var predefinedTableAnnotations = self.configurationData.application.config.primary_index_annotations;
            var customizedStoreOptions = [];
            var storeOptions = [];
            var storeOptionsWithValues = [];

            self.formUtils.addEventListenersForOptionsDiv(Constants.STORE);

            var name = clickedElement.getName();
            if (!name) {
                var attributes = [{ name: "" }];
                self.formUtils.renderAttributeTemplate(attributes)

            } else {
                $('#tableName').val(name);
                var savedAttributes = clickedElement.getAttributeList();
                self.formUtils.renderAttributeTemplate(savedAttributes)
                self.formUtils.selectTypesOfSavedAttributes(savedAttributes);
            }
            var savedAnnotations = clickedElement.getAnnotationList();
            var savedAnnotationObjects = clickedElement.getAnnotationListObjects();
            var userAnnotations = [];
            var tableAnnotations = JSON.parse(JSON.stringify(predefinedTableAnnotations));
            if (savedAnnotations && savedAnnotations.length != 0) {
                userAnnotations = self.formUtils.getUserAnnotations(savedAnnotationObjects, tableAnnotations);
                self.formUtils.mapPrimaryIndexAnnotationValues(tableAnnotations, savedAnnotationObjects)
            }

            //render the predefined table annotation form template
            self.formUtils.renderPrimaryIndexAnnotations(tableAnnotations, 'define-predefined-annotations');

            self.formUtils.renderAnnotationTemplate("define-user-annotations", userAnnotations);
            $('#define-user-annotations').find('h4').html('Customized Annotations');

            //render the template to  generate the store types
            self.formUtils.renderTypeSelectionTemplate(Constants.STORE, predefinedStores)

            $('#define-rdbms-type').on('change', '[name=radioOpt]', function () {
                var dataStoreOptions = self.formUtils.getRdbmsOptions(storeOptionsWithValues);
                self.formUtils.renderOptions(dataStoreOptions, customizedStoreOptions, Constants.STORE)
            });

            //onchange of the store type select box
            $('#define-store').on('change', '#store-type', function () {
                if (this.value === Constants.DEFAULT_STORE_TYPE) {
                    $('#define-predefined-annotations').hide();
                    $('#store-options-div').empty();
                    $('#define-rdbms-type').hide();
                } else {
                    $('#define-predefined-annotations').show();
                    storeOptions = self.formUtils.getSelectedTypeParameters(this.value, predefinedStores);
                    if (clickedElement.getStore() && savedStoreType === this.value) {
                        customizedStoreOptions = self.formUtils.getCustomizedStoreOptions(storeOptions, savedStoreOptions);
                        storeOptionsWithValues = self.formUtils.mapUserStoreOptionValues(storeOptions, savedStoreOptions);
                        self.formUtils.checkForRdbmsStoreType(this.value, storeOptionsWithValues, customizedStoreOptions);
                    } else {
                        storeOptionsWithValues = self.formUtils.createObjectWithValues(storeOptions);
                        customizedStoreOptions = [];
                        self.formUtils.checkForRdbmsStoreType(this.value, storeOptionsWithValues, customizedStoreOptions);
                    }
                }
            });

            if (clickedElement.getStore()) {
                //if table object is already edited
                var savedStoreAnnotation = clickedElement.getStore();
                var savedStoreType = savedStoreAnnotation.getType().toLowerCase();
                storeOptions = self.formUtils.getSelectedTypeParameters(savedStoreType, predefinedStores);
                var savedStoreAnnotationOptions = savedStoreAnnotation.getOptions();
                var savedStoreOptions = [];
                for (var key in savedStoreAnnotationOptions) {
                    if (savedStoreAnnotationOptions.hasOwnProperty(key)) {
                        savedStoreOptions.push({
                            key: key,
                            value: savedStoreAnnotationOptions[key]
                        });
                    }
                }
                $('#define-store #store-type').val(savedStoreType);
                customizedStoreOptions = self.formUtils.getCustomizedStoreOptions(storeOptions, savedStoreOptions);
                storeOptionsWithValues = self.formUtils.mapUserStoreOptionValues(storeOptions, savedStoreOptions);
                self.formUtils.checkForRdbmsStoreType(savedStoreType, storeOptionsWithValues, customizedStoreOptions);
            } else {
                //if table form is freshly opened [ new table object]
                $('#define-store #store-type').val(Constants.DEFAULT_STORE_TYPE);
                $('#define-predefined-annotations').hide();
            }

            // 'Submit' button action
            var submitButtonElement = $(formContainer).find('#btn-submit')[0];
            submitButtonElement.addEventListener('click', function () {

                //clear the error classes
                $('.error-message').text("");
                $('#tableNameErrorMessage').text("");
                $('.required-input-field').removeClass('required-input-field');
                var isErrorOccurred = false;

                var tableName = $('#tableName').val().trim();
                // to check if table name is empty
                if (tableName == "") {
                    self.formUtils.addErrorClass("#tableName");
                    $('#tableNameErrorMessage').text("Table name is required.");
                    isErrorOccurred = true;
                    return;
                }
                var previouslySavedName = clickedElement.getName();
                if (!previouslySavedName) {
                    previouslySavedName = "";
                }
                if (previouslySavedName !== tableName) {
                    var isTableNameUsed = self.formUtils.isDefinitionElementNameUsed(tableName);
                    if (isTableNameUsed) {
                        self.formUtils.addErrorClass("#tableName");
                        $('#tableNameErrorMessage').text("Table name is already used.");
                        isErrorOccurred = true;
                        return;
                    }
                    if (self.formUtils.validateAttributeOrElementName("#tableName", Constants.TABLE, tableName)) {
                        isErrorOccurred = true;
                        return;
                    }
                }

                //store annotation
                var selectedStoreType = $('#define-store #store-type').val();
                if (selectedStoreType !== Constants.DEFAULT_STORE_TYPE) {
                    if (self.formUtils.validateOptions(storeOptions, Constants.STORE)) {
                        isErrorOccurred = true;
                        return;
                    }
                    if (self.formUtils.validateCustomizedOptions(Constants.STORE)) {
                        isErrorOccurred = true;
                        return;
                    }
                    if (self.formUtils.validatePrimaryIndexAnnotations()) {
                        isErrorOccurred = true;
                        return;
                    }
                }

                var attributeNameList = [];
                if (self.formUtils.validateAttributes(attributeNameList)) {
                    isErrorOccurred = true;
                    return;
                }
                if (attributeNameList.length == 0) {
                    self.formUtils.addErrorClass($('.attribute:eq(0)').find('.attr-name'));
                    $('.attribute:eq(0)').find('.error-message').text("Minimum one attribute is required.");
                    isErrorOccurred = true;
                    return;
                }

                if (!isErrorOccurred) {
                    var annotationList = [];
                    var annotationObjectList = [];
                    //clear the annotation list
                    clickedElement.clearAnnotationList();
                    clickedElement.clearAnnotationListObjects();

                    if (previouslySavedName !== tableName) {
                        // update selected table model
                        clickedElement.setName(tableName);
                        // update connection related to the element if the name is changed
                        self.formUtils.updateConnectionsAfterDefinitionElementNameChange(id);

                        var textNode = $('#' + id).find('.tableNameNode');
                        textNode.html(tableName);
                    }

                    if (selectedStoreType !== Constants.DEFAULT_STORE_TYPE) {
                        var optionsMap = {};
                        self.formUtils.buildStoreAndAnnotationOptions(optionsMap, Constants.STORE);
                        self.formUtils.buildCustomizedStoreOption(optionsMap);
                        var storeAnnotationOptions = {};
                        _.set(storeAnnotationOptions, 'type', selectedStoreType);
                        _.set(storeAnnotationOptions, 'options', optionsMap);
                        var storeAnnotation = new StoreAnnotation(storeAnnotationOptions);
                        clickedElement.setStore(storeAnnotation);

                        self.formUtils.buildPrimaryIndexAnnotations(annotationList, annotationObjectList);
                    } else {
                        clickedElement.setStore(undefined);
                    }

                    var annotationNodes = $('#annotation-div').jstree(true)._model.data['#'].children;
                    self.formUtils.buildAnnotation(annotationNodes, annotationList, annotationObjectList)
                    //add the annotations to the clicked element
                    _.forEach(annotationList, function (annotation) {
                        clickedElement.addAnnotation(annotation);
                    });
                    _.forEach(annotationObjectList, function (annotation) {
                        clickedElement.addAnnotationObject(annotation);
                    });

                    //clear the saved attributes
                    clickedElement.clearAttributeList()
                    //add the attributes
                    $('.attribute .attr-content').each(function () {
                        var nameValue = $(this).find('.attr-name').val().trim();
                        var typeValue = $(this).find('.attr-type').val();
                        if (nameValue != "") {
                            var attributeObject = new Attribute({ name: nameValue, type: typeValue });
                            clickedElement.addAttribute(attributeObject);
                        }
                    });

                    $('#' + id).removeClass('incomplete-element');
                    //Send table element to the backend and generate tooltip
                    var tableToolTip = self.formUtils.getTooltip(clickedElement, Constants.TABLE);
                    $('#' + id).prop('title', tableToolTip);

                    // set the isDesignViewContentChanged to true
                    self.configurationData.setIsDesignViewContentChanged(true);
                    // close the form window
                    self.consoleListManager.removeFormConsole(formConsole);
                    self.designViewContainer.removeClass('disableContainer');
                    self.toggleViewButton.removeClass('disableContainer');
                }
            });

            // 'Cancel' button action
            var cancelButtonElement = $(formContainer).find('#btn-cancel')[0];
            cancelButtonElement.addEventListener('click', function () {
                self.designViewContainer.removeClass('disableContainer');
                self.toggleViewButton.removeClass('disableContainer');
                // close the form window
                self.consoleListManager.removeFormConsole(formConsole);
            });
        };

        return TableForm;
    });

<commit_msg>Prevents modifying the original array<commit_after>/**
 * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * WSO2 Inc. licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

define(['log', 'jquery', 'lodash', 'attribute', 'storeAnnotation', 'handlebar', 'annotationObject', 'annotationElement',
    'constants'],
    function (log, $, _, Attribute, StoreAnnotation, Handlebars, AnnotationObject, AnnotationElement, Constants) {

        /**
         * @class TableForm Creates a forms to collect data from a table
         * @constructor
         * @param {Object} options Rendering options for the view
         */
        var TableForm = function (options) {
            if (options !== undefined) {
                this.configurationData = options.configurationData;
                this.application = options.application;
                this.formUtils = options.formUtils;
                this.consoleListManager = options.application.outputController;
                var currentTabId = this.application.tabController.activeTab.cid;
                this.designViewContainer = $('#design-container-' + currentTabId);
                this.toggleViewButton = $('#toggle-view-button-' + currentTabId);
            }
        };

        /**
         * @function generate properties form for a table
         * @param element selected element(table)
         * @param formConsole Console which holds the form
         * @param formContainer Container which holds the form
         */
        TableForm.prototype.generatePropertiesForm = function (element, formConsole, formContainer) {
            var self = this;
            var id = $(element).parent().attr('id');
            var clickedElement = self.configurationData.getSiddhiAppConfig().getTable(id);

            var propertyDiv = $('

 Table Configuration

 ' +
                '

 Name:
 <input type="text" id="tableName" ' +
                'class = "clearfix name">  ' +
                '

' + self.formUtils.buildFormButtons() + '
 ' +
                '

  ' +
                '

 ' +
                '
' +
                '

');

            formContainer.append(propertyDiv);
            self.formUtils.popUpSelectedElement(id);
            self.designViewContainer.addClass('disableContainer');
            self.toggleViewButton.addClass('disableContainer');

            var predefinedStores =  _.orderBy(JSON.parse(JSON.stringify(this.configurationData.rawExtensions["store"]),
            ['name'], ['asc']));
            self.formUtils.addCustomizedType(predefinedStores, Constants.DEFAULT_STORE_TYPE);
            var predefinedTableAnnotations = self.configurationData.application.config.primary_index_annotations;
            var customizedStoreOptions = [];
            var storeOptions = [];
            var storeOptionsWithValues = [];

            self.formUtils.addEventListenersForOptionsDiv(Constants.STORE);

            var name = clickedElement.getName();
            if (!name) {
                var attributes = [{ name: "" }];
                self.formUtils.renderAttributeTemplate(attributes)

            } else {
                $('#tableName').val(name);
                var savedAttributes = clickedElement.getAttributeList();
                self.formUtils.renderAttributeTemplate(savedAttributes)
                self.formUtils.selectTypesOfSavedAttributes(savedAttributes);
            }
            var savedAnnotations = clickedElement.getAnnotationList();
            var savedAnnotationObjects = clickedElement.getAnnotationListObjects();
            var userAnnotations = [];
            var tableAnnotations = JSON.parse(JSON.stringify(predefinedTableAnnotations));
            if (savedAnnotations && savedAnnotations.length != 0) {
                userAnnotations = self.formUtils.getUserAnnotations(savedAnnotationObjects, tableAnnotations);
                self.formUtils.mapPrimaryIndexAnnotationValues(tableAnnotations, savedAnnotationObjects)
            }

            //render the predefined table annotation form template
            self.formUtils.renderPrimaryIndexAnnotations(tableAnnotations, 'define-predefined-annotations');

            self.formUtils.renderAnnotationTemplate("define-user-annotations", userAnnotations);
            $('#define-user-annotations').find('h4').html('Customized Annotations');

            //render the template to  generate the store types
            self.formUtils.renderTypeSelectionTemplate(Constants.STORE, predefinedStores)

            $('#define-rdbms-type').on('change', '[name=radioOpt]', function () {
                var dataStoreOptions = self.formUtils.getRdbmsOptions(storeOptionsWithValues);
                self.formUtils.renderOptions(dataStoreOptions, customizedStoreOptions, Constants.STORE)
            });

            //onchange of the store type select box
            $('#define-store').on('change', '#store-type', function () {
                if (this.value === Constants.DEFAULT_STORE_TYPE) {
                    $('#define-predefined-annotations').hide();
                    $('#store-options-div').empty();
                    $('#define-rdbms-type').hide();
                } else {
                    $('#define-predefined-annotations').show();
                    storeOptions = self.formUtils.getSelectedTypeParameters(this.value, predefinedStores);
                    if (clickedElement.getStore() && savedStoreType === this.value) {
                        customizedStoreOptions = self.formUtils.getCustomizedStoreOptions(storeOptions, savedStoreOptions);
                        storeOptionsWithValues = self.formUtils.mapUserStoreOptionValues(storeOptions, savedStoreOptions);
                        self.formUtils.checkForRdbmsStoreType(this.value, storeOptionsWithValues, customizedStoreOptions);
                    } else {
                        storeOptionsWithValues = self.formUtils.createObjectWithValues(storeOptions);
                        customizedStoreOptions = [];
                        self.formUtils.checkForRdbmsStoreType(this.value, storeOptionsWithValues, customizedStoreOptions);
                    }
                }
            });

            if (clickedElement.getStore()) {
                //if table object is already edited
                var savedStoreAnnotation = clickedElement.getStore();
                var savedStoreType = savedStoreAnnotation.getType().toLowerCase();
                storeOptions = self.formUtils.getSelectedTypeParameters(savedStoreType, predefinedStores);
                var savedStoreAnnotationOptions = savedStoreAnnotation.getOptions();
                var savedStoreOptions = [];
                for (var key in savedStoreAnnotationOptions) {
                    if (savedStoreAnnotationOptions.hasOwnProperty(key)) {
                        savedStoreOptions.push({
                            key: key,
                            value: savedStoreAnnotationOptions[key]
                        });
                    }
                }
                $('#define-store #store-type').val(savedStoreType);
                customizedStoreOptions = self.formUtils.getCustomizedStoreOptions(storeOptions, savedStoreOptions);
                storeOptionsWithValues = self.formUtils.mapUserStoreOptionValues(storeOptions, savedStoreOptions);
                self.formUtils.checkForRdbmsStoreType(savedStoreType, storeOptionsWithValues, customizedStoreOptions);
            } else {
                //if table form is freshly opened [ new table object]
                $('#define-store #store-type').val(Constants.DEFAULT_STORE_TYPE);
                $('#define-predefined-annotations').hide();
            }

            // 'Submit' button action
            var submitButtonElement = $(formContainer).find('#btn-submit')[0];
            submitButtonElement.addEventListener('click', function () {

                //clear the error classes
                $('.error-message').text("");
                $('#tableNameErrorMessage').text("");
                $('.required-input-field').removeClass('required-input-field');
                var isErrorOccurred = false;

                var tableName = $('#tableName').val().trim();
                // to check if table name is empty
                if (tableName == "") {
                    self.formUtils.addErrorClass("#tableName");
                    $('#tableNameErrorMessage').text("Table name is required.");
                    isErrorOccurred = true;
                    return;
                }
                var previouslySavedName = clickedElement.getName();
                if (!previouslySavedName) {
                    previouslySavedName = "";
                }
                if (previouslySavedName !== tableName) {
                    var isTableNameUsed = self.formUtils.isDefinitionElementNameUsed(tableName);
                    if (isTableNameUsed) {
                        self.formUtils.addErrorClass("#tableName");
                        $('#tableNameErrorMessage').text("Table name is already used.");
                        isErrorOccurred = true;
                        return;
                    }
                    if (self.formUtils.validateAttributeOrElementName("#tableName", Constants.TABLE, tableName)) {
                        isErrorOccurred = true;
                        return;
                    }
                }

                //store annotation
                var selectedStoreType = $('#define-store #store-type').val();
                if (selectedStoreType !== Constants.DEFAULT_STORE_TYPE) {
                    if (self.formUtils.validateOptions(storeOptions, Constants.STORE)) {
                        isErrorOccurred = true;
                        return;
                    }
                    if (self.formUtils.validateCustomizedOptions(Constants.STORE)) {
                        isErrorOccurred = true;
                        return;
                    }
                    if (self.formUtils.validatePrimaryIndexAnnotations()) {
                        isErrorOccurred = true;
                        return;
                    }
                }

                var attributeNameList = [];
                if (self.formUtils.validateAttributes(attributeNameList)) {
                    isErrorOccurred = true;
                    return;
                }
                if (attributeNameList.length == 0) {
                    self.formUtils.addErrorClass($('.attribute:eq(0)').find('.attr-name'));
                    $('.attribute:eq(0)').find('.error-message').text("Minimum one attribute is required.");
                    isErrorOccurred = true;
                    return;
                }

                if (!isErrorOccurred) {
                    var annotationList = [];
                    var annotationObjectList = [];
                    //clear the annotation list
                    clickedElement.clearAnnotationList();
                    clickedElement.clearAnnotationListObjects();

                    if (previouslySavedName !== tableName) {
                        // update selected table model
                        clickedElement.setName(tableName);
                        // update connection related to the element if the name is changed
                        self.formUtils.updateConnectionsAfterDefinitionElementNameChange(id);

                        var textNode = $('#' + id).find('.tableNameNode');
                        textNode.html(tableName);
                    }

                    if (selectedStoreType !== Constants.DEFAULT_STORE_TYPE) {
                        var optionsMap = {};
                        self.formUtils.buildStoreAndAnnotationOptions(optionsMap, Constants.STORE);
                        self.formUtils.buildCustomizedStoreOption(optionsMap);
                        var storeAnnotationOptions = {};
                        _.set(storeAnnotationOptions, 'type', selectedStoreType);
                        _.set(storeAnnotationOptions, 'options', optionsMap);
                        var storeAnnotation = new StoreAnnotation(storeAnnotationOptions);
                        clickedElement.setStore(storeAnnotation);

                        self.formUtils.buildPrimaryIndexAnnotations(annotationList, annotationObjectList);
                    } else {
                        clickedElement.setStore(undefined);
                    }

                    var annotationNodes = $('#annotation-div').jstree(true)._model.data['#'].children;
                    self.formUtils.buildAnnotation(annotationNodes, annotationList, annotationObjectList)
                    //add the annotations to the clicked element
                    _.forEach(annotationList, function (annotation) {
                        clickedElement.addAnnotation(annotation);
                    });
                    _.forEach(annotationObjectList, function (annotation) {
                        clickedElement.addAnnotationObject(annotation);
                    });

                    //clear the saved attributes
                    clickedElement.clearAttributeList()
                    //add the attributes
                    $('.attribute .attr-content').each(function () {
                        var nameValue = $(this).find('.attr-name').val().trim();
                        var typeValue = $(this).find('.attr-type').val();
                        if (nameValue != "") {
                            var attributeObject = new Attribute({ name: nameValue, type: typeValue });
                            clickedElement.addAttribute(attributeObject);
                        }
                    });

                    $('#' + id).removeClass('incomplete-element');
                    //Send table element to the backend and generate tooltip
                    var tableToolTip = self.formUtils.getTooltip(clickedElement, Constants.TABLE);
                    $('#' + id).prop('title', tableToolTip);

                    // set the isDesignViewContentChanged to true
                    self.configurationData.setIsDesignViewContentChanged(true);
                    // close the form window
                    self.consoleListManager.removeFormConsole(formConsole);
                    self.designViewContainer.removeClass('disableContainer');
                    self.toggleViewButton.removeClass('disableContainer');
                }
            });

            // 'Cancel' button action
            var cancelButtonElement = $(formContainer).find('#btn-cancel')[0];
            cancelButtonElement.addEventListener('click', function () {
                self.designViewContainer.removeClass('disableContainer');
                self.toggleViewButton.removeClass('disableContainer');
                // close the form window
                self.consoleListManager.removeFormConsole(formConsole);
            });
        };

        return TableForm;
    });

<|endoftext|>


<commit_before>var http = require('http'),
	url = require('url'),
	fs = require('fs'),
	mime = require('mime').lookup,
	jsmin = require('jsmin').jsmin,
	qs = require('querystring');

function readDirRecursive(dir) {
	if (fs.statSync(dir).isDirectory()) {
		var body = '',
			dataType = '',
			alpha = [];
		fs.readdirSync(dir).forEach(function(v, k) {
			alpha.push(v)
		});
		alpha.sort().forEach(function(v, k) {
			if (fs.statSync(dir + '/' + v).isFile()) {
				dataType = mime(dir + '/' + v);
				body += fs.readFileSync(dir + '/' + v, 'utf8');
				console.log(v +':'+ k);
			}
			else if (fs.statSync(dir + '/' + v).isDirectory()) {
				readDirRecursive(dir + '/' + v).body;
			}
		});
		return {
			body : body,
			dataType : dataType
		};
	}
}

var core = {
	list : [/* data from chain.cache */],
	server : http.createServer(function(req, res) {
		for (var i in core.list) {
			if (url.parse(req.url).pathname === core.list[i].route && req.method === core.list[i].method) {
				if (typeof core.list[i].end !== 'function') {
					if (core.list[i].header) {
						core.list[i].header.server = 'Node.js Frank';
						res.writeHead(core.list[i].statusCode, core.list[i].header);
					}
					else {
						res.writeHead(core.list[i].statusCode, {'Content-Type':core.list[i].dataType, Server:'Node.js Frank', 'Content-Length':core.list[i].end.length});
						res.write(core.list[i].end);
						res.end();
					}
				}
				else {
					core.list[i].end(req, res);
				}
			}
			else {
				if (core.list[i].route.toLowerCase() === 'not found' || core.list[i].route.toLowerCase() === 'not found') {
					if (typeof core.list[i].end !== 'function') {
						res.writeHead(404, {'Content-Type':core.list[i].dataType, Server:'Node.js Frank', 'Content-Length':core.list[i].end.length});
						res.write(core.list[i].end);
						res.end();
					}
					else {
						core.list[i].end(req, res);
					}
				}
			}
		}
	})
};

var chain = {
	cache : {
		// route
		// statusCode
		// method
		// header
		// dataType
		// end
	},
	first : {
		request : function(route, method, statusCode) {
			chain.cache = {};
			chain.cache.route = route;
			chain.cache.method = method;
			chain.cache.statusCode = statusCode;
			return chain.second;
		}
	},
	second : {
		then : function(cb) {
			if (typeof cb !== 'function') {
				throw new Error('argument must be a function');
			}
			chain.cache.end = cb;
			return chain.fourth;
		},
		header : function(head) {
			if (typeof head !== 'object') {
				throw new Error('argument must be an object');
			}
			chain.cache.header = head;
			return {
				write : chain.second.write,
				send : chain.second.send
			};
		},
		write : function(str, dataType) {
			if (typeof str !== 'string') {
				throw new Error('argument must be a string');
			}
			chain.cache.dataType = dataType || 'text/plain';
			chain.cache.end = str;
			if (/javascript/.test(dataType)) {
				return {
					minify : chain.third.jsmin,
					end : chain.fourth.run
				};
			}
			else {
				return chain.fourth;
			}
		},
		send : function(file, dataType) {
			if (fs.statSync(file).isFile()) {
				chain.cache.end = fs.readFileSync(file, 'utf8');
				chain.cache.dataType = dataType || mime(file);
				if (chain.cache.dataType.match(/javascript/)) {
					return {
						minify : chain.third.jsmin,
						end : chain.fourth.end
					};
				}
			}
			return chain.fourth;
		},
		sendDir : function(dir, type) {
			chain.cache.dataType = type || readDirRecursive(dir).dataType;
			chain.cache.end = readDirRecursive(dir).body;

			if (chain.cache.dataType.match(/javascript/)) {
				return {
					minify : chain.third.jsmin,
					end : chain.fourth.end
				};
			}
			else {
				return chain.fourth;
			}
		}
	},
	third : {
		jsmin : function(level) {
			chain.cache.end = jsmin(chain.cache.end, level);
			return chain.fourth;
		}
	},
	fourth : {
		end : function() {
			core.list.push(chain.cache);
		}
	}
};

var api = {
	get : function(route, statusCode) {
		if (!statusCode) {
			statusCode = 200;
		}
		return chain.first.request(route, 'GET', statusCode);
	},
	post : function(route, statusCode) {
		if (!statusCode) {
			statusCode = 200;
		}
		return chain.first.request(route, 'POST', statusCode);
	},
	server : core.server,
	run : function(port) {
		console.log("\nFrank is singin' at http://localhost:"+port+"\n");

		if (typeof port !== 'number') {
			port = 8888;
		}
		return core.server.listen(port);
	}
};

module.exports = api;
<commit_msg>removed console.log from sendDir method<commit_after>var http = require('http'),
	url = require('url'),
	fs = require('fs'),
	mime = require('mime').lookup,
	jsmin = require('jsmin').jsmin,
	qs = require('querystring');

function readDirRecursive(dir) {
	if (fs.statSync(dir).isDirectory()) {
		var body = '',
			dataType = '',
			alpha = [];
		fs.readdirSync(dir).forEach(function(v, k) {
			alpha.push(v)
		});
		alpha.sort().forEach(function(v, k) {
			if (fs.statSync(dir + '/' + v).isFile()) {
				dataType = mime(dir + '/' + v);
				body += fs.readFileSync(dir + '/' + v, 'utf8');
			}
			else if (fs.statSync(dir + '/' + v).isDirectory()) {
				readDirRecursive(dir + '/' + v).body;
			}
		});
		return {
			body : body,
			dataType : dataType
		};
	}
}

var core = {
	list : [/* data from chain.cache */],
	server : http.createServer(function(req, res) {
		for (var i in core.list) {
			if (url.parse(req.url).pathname === core.list[i].route && req.method === core.list[i].method) {
				if (typeof core.list[i].end !== 'function') {
					if (core.list[i].header) {
						core.list[i].header.server = 'Node.js Frank';
						res.writeHead(core.list[i].statusCode, core.list[i].header);
					}
					else {
						res.writeHead(core.list[i].statusCode, {'Content-Type':core.list[i].dataType, Server:'Node.js Frank', 'Content-Length':core.list[i].end.length});
						res.write(core.list[i].end);
						res.end();
					}
				}
				else {
					core.list[i].end(req, res);
				}
			}
			else {
				if (core.list[i].route.toLowerCase() === 'not found' || core.list[i].route.toLowerCase() === 'not found') {
					if (typeof core.list[i].end !== 'function') {
						res.writeHead(404, {'Content-Type':core.list[i].dataType, Server:'Node.js Frank', 'Content-Length':core.list[i].end.length});
						res.write(core.list[i].end);
						res.end();
					}
					else {
						core.list[i].end(req, res);
					}
				}
			}
		}
	})
};

var chain = {
	cache : {
		// route
		// statusCode
		// method
		// header
		// dataType
		// end
	},
	first : {
		request : function(route, method, statusCode) {
			chain.cache = {};
			chain.cache.route = route;
			chain.cache.method = method;
			chain.cache.statusCode = statusCode;
			return chain.second;
		}
	},
	second : {
		then : function(cb) {
			if (typeof cb !== 'function') {
				throw new Error('argument must be a function');
			}
			chain.cache.end = cb;
			return chain.fourth;
		},
		header : function(head) {
			if (typeof head !== 'object') {
				throw new Error('argument must be an object');
			}
			chain.cache.header = head;
			return {
				write : chain.second.write,
				send : chain.second.send
			};
		},
		write : function(str, dataType) {
			if (typeof str !== 'string') {
				throw new Error('argument must be a string');
			}
			chain.cache.dataType = dataType || 'text/plain';
			chain.cache.end = str;
			if (/javascript/.test(dataType)) {
				return {
					minify : chain.third.jsmin,
					end : chain.fourth.run
				};
			}
			else {
				return chain.fourth;
			}
		},
		send : function(file, dataType) {
			if (fs.statSync(file).isFile()) {
				chain.cache.end = fs.readFileSync(file, 'utf8');
				chain.cache.dataType = dataType || mime(file);
				if (chain.cache.dataType.match(/javascript/)) {
					return {
						minify : chain.third.jsmin,
						end : chain.fourth.end
					};
				}
			}
			return chain.fourth;
		},
		sendDir : function(dir, type) {
			chain.cache.dataType = type || readDirRecursive(dir).dataType;
			chain.cache.end = readDirRecursive(dir).body;

			if (chain.cache.dataType.match(/javascript/)) {
				return {
					minify : chain.third.jsmin,
					end : chain.fourth.end
				};
			}
			else {
				return chain.fourth;
			}
		}
	},
	third : {
		jsmin : function(level) {
			chain.cache.end = jsmin(chain.cache.end, level);
			return chain.fourth;
		}
	},
	fourth : {
		end : function() {
			core.list.push(chain.cache);
		}
	}
};

var api = {
	get : function(route, statusCode) {
		if (!statusCode) {
			statusCode = 200;
		}
		return chain.first.request(route, 'GET', statusCode);
	},
	post : function(route, statusCode) {
		if (!statusCode) {
			statusCode = 200;
		}
		return chain.first.request(route, 'POST', statusCode);
	},
	server : core.server,
	run : function(port) {
		console.log("\nFrank is singin' at http://localhost:"+port+"\n");

		if (typeof port !== 'number') {
			port = 8888;
		}
		return core.server.listen(port);
	}
};

module.exports = api;
<|endoftext|>


<commit_before>import React from 'react';

import promisifyEventListeners from '../utils/promisifyEventListeners';

const childrenToMap = (children) => {
    const childrenArray = React.Children.toArray(children);
    const keyedArray = childrenArray.map((child) => [child.key, child]);
    return new Map(keyedArray);
};

const compareChildren = (children1, children2) => {
    const keys1 = Array.from(children1.keys());
    const keys2 = Array.from(children2.keys());

    return keys1 === keys2;
};

class SharedElementTransitionGroup extends React.Component {
    constructor(props) {
        super();

        this.state = {
            outgoingShow: true,
            incomingShow: false,
            children: childrenToMap(props.children),
            transitionPending: false,
        };
        this.outgoingSharedElements;
        this.incomingSharedElements;
    }

    getSharedElements = () => {
        if (this.outgoingSharedElements && this.incomingSharedElements) return {outgoingSharedElements: this.outgoingSharedElements, incomingSharedElements: this.incomingSharedElements};

        this.outgoingSharedElements = [];
        this.incomingSharedElements = [];

        const outgoingMarkedEls = this.outgoingRef.querySelectorAll('[id]');
        const incomingMarkedEls = this.incomingRef.querySelectorAll('[id]');

        const outgoingSet = new Set(Array.from(outgoingMarkedEls).map((el) => el.id));
        const incomingSet = new Set(Array.from(incomingMarkedEls).map((el) => el.id));

        for (let element of outgoingMarkedEls) {
            if (incomingSet.has(element.id)) {
                this.outgoingSharedElements.push(element);
            }
        }
        for (let element of incomingMarkedEls) {
            if (outgoingSet.has(element.id)) {
                this.incomingSharedElements.push(element);
            }
        }

        return {outgoingSharedElements: this.outgoingSharedElements, incomingSharedElements: this.incomingSharedElements};
    }

    getSharedDimens = () => {
        const initialDimensArr = this.outgoingSharedElements.map((element) => element.getBoundingClientRect());
        const finalDimensArr = this.incomingSharedElements.map((element) => element.getBoundingClientRect());

        return {initialDimensArr, finalDimensArr};
    };

    componentWillReceiveProps(nextProps) {
        const prevChildren = this.state.children;
        const newChildren = childrenToMap(nextProps.children);

        const allChildren = new Map([...prevChildren, ...newChildren]);

        allChildren.forEach((value, key) => {
            const outgoing = prevChildren.has(key);
            const incoming = newChildren.has(key);

            if (outgoing) {
                allChildren.set(key, React.cloneElement(
                    value,
                    {
                        exit: () => {
                            this.exit(key);
                        },
                        innerRef: (ref) => {
                            this.outgoingRef = ref;
                        },
                        outgoing: true,
                    }
                ));
            } else if (incoming) {
                allChildren.set(key, React.cloneElement(
                    value,
                    {
                        innerRef: (ref) => {
                            this.incomingRef = ref;
                        },
                        incoming: true,
                    }
                ));
            }
        });

        this.setState((prevState) => ({
            ...prevState,
            children: allChildren,
            transitionPending: true,
        }));
    }

    createElementsForTransition(outgoingSharedElements, initialDimensArr) {
        const newElements = [];
        outgoingSharedElements.forEach((sharedEl, idx) => {
            const element = sharedEl.cloneNode();
            element.style.position = 'absolute';
            element.style.top = initialDimensArr[idx].top;
            element.style.left = initialDimensArr[idx].left;
            element.style.height = initialDimensArr[idx].height;
            element.style.width = initialDimensArr[idx].width;
            element.style.transformOrigin = '0 0';
            element.style.transition = 'transform 300ms ease-in-out';
            newElements.push(element);
        });

        return newElements;
    }

    componentDidUpdate(prevProps, prevState) {
        if (!this.state.transitionPending) return;
        if (compareChildren(this.state.children, prevState.children)) return;
        if (!this.incomingRef && !this.outgoingRef) return;

        this.setState((state) => ({
            transitionPending: false,
        }));

        const {outgoingSharedElements} = this.getSharedElements();
        const {initialDimensArr, finalDimensArr} = this.getSharedDimens();
        const allChildren = this.state.children;

        const newElements = this.createElementsForTransition(outgoingSharedElements, initialDimensArr);
        const promisifiedTransitionEnd = promisifyEventListeners(newElements, 'transitionend');
        Promise.all(promisifiedTransitionEnd)
        .then((events) => {
            this.incomingRef.addEventListener('transitionend', () => {
                events.forEach((event) => {
                    event.target.remove();
                });
                for (let [key, value] of allChildren.entries()) {
                    let changedChildren = new Map();
                    let element;
                    if (value.props.incoming) {
                        element = React.cloneElement(value, {ref: undefined, incoming: undefined});
                        changedChildren.set(key, element);
                    }
                    this.outgoingRef = undefined;
                    this.incomingRef = undefined;
                    this.outgoingSharedElements = undefined;
                    this.incomingSharedElements = undefined;
                    this.setState((prevState) => ({
                        ...prevState,
                        children: changedChildren,
                        incomingShow: false,
                        outgoingShow: false,
                    }));
                }
            });
            this.setState((prevState) => ({
                ...prevState,
                incomingShow: true,
            }));
        });

        const invert = [];

        newElements.forEach((element, idx) => {
            document.body.appendChild(element);
            invert[idx] = {};
            invert[idx].sx = finalDimensArr[idx].width / initialDimensArr[idx].width;
            invert[idx].sy = finalDimensArr[idx].height / initialDimensArr[idx].height;
            invert[idx].x = finalDimensArr[idx].left - initialDimensArr[idx].left;
            invert[idx].y = finalDimensArr[idx].top - initialDimensArr[idx].top;
        });

        requestAnimationFrame(() => {
            requestAnimationFrame(() => {
                this.outgoingRef.addEventListener('transitionend', () => {
                    newElements.forEach((element, idx) => {
                        element.style.transform = `translate(${invert[idx].x}px, ${invert[idx].y}px) scale(${invert[idx].sx}, ${invert[idx].sy})`;
                    });
                });
                this.setState((prevState) => ({
                    ...prevState,
                    outgoingShow: false,
                }));
            });
        });
    }

    exit = (key) => {
        this.setState((prevState) => ({
            ...prevState,
            children: prevState.children.delete(key),
        }));
    };

    render() {
        const outgoingStyles = {
            position: 'absolute',
            transition: 'opacity 300ms ease-out',
            opacity: this.state.outgoingShow ? 1 : 0,
        };
        const incomingStyles = {
            position: 'absolute',
            transition: 'opacity 300ms ease-out',
            opacity: this.state.incomingShow ? 1 : 0,
        };
        const normalStyles = {
            position: 'absolute',
        };
        const containerStyles = {
            position: 'relative',
        };

        return (

                {Array.from(this.state.children.values()).map((child) => {
                    if (child.props.outgoing) {
                        return React.cloneElement(child, {style: outgoingStyles});
                    } else if (child.props.incoming) {
                        return React.cloneElement(child, {style: incomingStyles});
                    } else {
                        return React.cloneElement(child, {style: normalStyles});
                    }
                })}

        );
    }
}

export default SharedElementTransitionGroup;
<commit_msg>Use absolute position instead of visual viewport<commit_after>import React from 'react';

import promisifyEventListeners from '../utils/promisifyEventListeners';

const childrenToMap = (children) => {
    const childrenArray = React.Children.toArray(children);
    const keyedArray = childrenArray.map((child) => [child.key, child]);
    return new Map(keyedArray);
};

const compareChildren = (children1, children2) => {
    const keys1 = Array.from(children1.keys());
    const keys2 = Array.from(children2.keys());

    return keys1 === keys2;
};

class SharedElementTransitionGroup extends React.Component {
    constructor(props) {
        super();

        this.state = {
            outgoingShow: true,
            incomingShow: false,
            children: childrenToMap(props.children),
            transitionPending: false,
        };
        this.outgoingSharedElements;
        this.incomingSharedElements;
    }

    getSharedElements = () => {
        if (this.outgoingSharedElements && this.incomingSharedElements) return {outgoingSharedElements: this.outgoingSharedElements, incomingSharedElements: this.incomingSharedElements};

        this.outgoingSharedElements = [];
        this.incomingSharedElements = [];

        const outgoingMarkedEls = this.outgoingRef.querySelectorAll('[id]');
        const incomingMarkedEls = this.incomingRef.querySelectorAll('[id]');

        const outgoingSet = new Set(Array.from(outgoingMarkedEls).map((el) => el.id));
        const incomingSet = new Set(Array.from(incomingMarkedEls).map((el) => el.id));

        for (let element of outgoingMarkedEls) {
            if (incomingSet.has(element.id)) {
                this.outgoingSharedElements.push(element);
            }
        }
        for (let element of incomingMarkedEls) {
            if (outgoingSet.has(element.id)) {
                this.incomingSharedElements.push(element);
            }
        }

        return {outgoingSharedElements: this.outgoingSharedElements, incomingSharedElements: this.incomingSharedElements};
    }

    getSharedDimens = () => {
        const initialDimensArr = this.outgoingSharedElements.map((element) => element.getBoundingClientRect());
        const finalDimensArr = this.incomingSharedElements.map((element) => element.getBoundingClientRect());

        return {initialDimensArr, finalDimensArr};
    };

    componentWillReceiveProps(nextProps) {
        const prevChildren = this.state.children;
        const newChildren = childrenToMap(nextProps.children);

        const allChildren = new Map([...prevChildren, ...newChildren]);

        allChildren.forEach((value, key) => {
            const outgoing = prevChildren.has(key);
            const incoming = newChildren.has(key);

            if (outgoing) {
                allChildren.set(key, React.cloneElement(
                    value,
                    {
                        exit: () => {
                            this.exit(key);
                        },
                        innerRef: (ref) => {
                            this.outgoingRef = ref;
                        },
                        outgoing: true,
                    }
                ));
            } else if (incoming) {
                allChildren.set(key, React.cloneElement(
                    value,
                    {
                        innerRef: (ref) => {
                            this.incomingRef = ref;
                        },
                        incoming: true,
                    }
                ));
            }
        });

        this.setState((prevState) => ({
            ...prevState,
            children: allChildren,
            transitionPending: true,
        }));
    }

    createElementsForTransition(outgoingSharedElements, initialDimensArr) {
        const newElements = [];
        outgoingSharedElements.forEach((sharedEl, idx) => {
            const element = sharedEl.cloneNode();
            element.style.position = 'absolute';
            element.style.top = initialDimensArr[idx].top + window.scrollY;
            element.style.left = initialDimensArr[idx].left + window.scrollX;
            element.style.height = initialDimensArr[idx].height;
            element.style.width = initialDimensArr[idx].width;
            element.style.transformOrigin = '0 0';
            element.style.transition = 'transform 300ms ease-in-out';
            newElements.push(element);
        });

        return newElements;
    }

    componentDidUpdate(prevProps, prevState) {
        if (!this.state.transitionPending) return;
        if (compareChildren(this.state.children, prevState.children)) return;
        if (!this.incomingRef && !this.outgoingRef) return;

        this.setState((state) => ({
            transitionPending: false,
        }));

        const {outgoingSharedElements} = this.getSharedElements();
        const {initialDimensArr, finalDimensArr} = this.getSharedDimens();
        const allChildren = this.state.children;

        const newElements = this.createElementsForTransition(outgoingSharedElements, initialDimensArr);
        const promisifiedTransitionEnd = promisifyEventListeners(newElements, 'transitionend');
        Promise.all(promisifiedTransitionEnd)
        .then((events) => {
            this.incomingRef.addEventListener('transitionend', () => {
                events.forEach((event) => {
                    event.target.remove();
                });
                for (let [key, value] of allChildren.entries()) {
                    let changedChildren = new Map();
                    let element;
                    if (value.props.incoming) {
                        element = React.cloneElement(value, {ref: undefined, incoming: undefined});
                        changedChildren.set(key, element);
                    }
                    this.outgoingRef = undefined;
                    this.incomingRef = undefined;
                    this.outgoingSharedElements = undefined;
                    this.incomingSharedElements = undefined;
                    this.setState((prevState) => ({
                        ...prevState,
                        children: changedChildren,
                        incomingShow: false,
                        outgoingShow: false,
                    }));
                }
            });
            this.setState((prevState) => ({
                ...prevState,
                incomingShow: true,
            }));
        });

        const invert = [];

        newElements.forEach((element, idx) => {
            document.body.appendChild(element);
            invert[idx] = {};
            invert[idx].sx = finalDimensArr[idx].width / initialDimensArr[idx].width;
            invert[idx].sy = finalDimensArr[idx].height / initialDimensArr[idx].height;
            invert[idx].x = finalDimensArr[idx].left - initialDimensArr[idx].left;
            invert[idx].y = finalDimensArr[idx].top - initialDimensArr[idx].top;
        });

        requestAnimationFrame(() => {
            requestAnimationFrame(() => {
                this.outgoingRef.addEventListener('transitionend', () => {
                    newElements.forEach((element, idx) => {
                        element.style.transform = `translate(${invert[idx].x}px, ${invert[idx].y}px) scale(${invert[idx].sx}, ${invert[idx].sy})`;
                    });
                });
                this.setState((prevState) => ({
                    ...prevState,
                    outgoingShow: false,
                }));
            });
        });
    }

    exit = (key) => {
        this.setState((prevState) => ({
            ...prevState,
            children: prevState.children.delete(key),
        }));
    };

    render() {
        const outgoingStyles = {
            position: 'absolute',
            transition: 'opacity 300ms ease-out',
            opacity: this.state.outgoingShow ? 1 : 0,
        };
        const incomingStyles = {
            position: 'absolute',
            transition: 'opacity 300ms ease-out',
            opacity: this.state.incomingShow ? 1 : 0,
        };
        const normalStyles = {
            position: 'absolute',
        };
        const containerStyles = {
            position: 'relative',
        };

        return (

                {Array.from(this.state.children.values()).map((child) => {
                    if (child.props.outgoing) {
                        return React.cloneElement(child, {style: outgoingStyles});
                    } else if (child.props.incoming) {
                        return React.cloneElement(child, {style: incomingStyles});
                    } else {
                        return React.cloneElement(child, {style: normalStyles});
                    }
                })}

        );
    }
}

export default SharedElementTransitionGroup;
<|endoftext|>


<commit_before>quail.languageChangesAreIdentified = function() {
	var currentLanguage = quail.components.language.getDocumentLanguage(true);
	var text, regularExpression, matches, $element;

	var noCharactersMatch = function($element, language, matches, regularExpression) {
		var $children = $element.find('[lang=' + language + ']');
		var childMatches;
		if($children.length === 0) {
			return true;
		}
		matches = matches.length;
		$children.each(function() {
			childMatches = quail.getTextContents($(this)).match(regularExpression);
			if(childMatches) {
				matches -= childMatches.length;
			}
		});
		return matches > 0;
	};

	quail.html.find(quail.textSelector).each(function() {
		$element = $(this);
		if($element.attr('lang')) {
			currentLanguage = $element.attr('lang').trim().toLowerCase().split('-')[0];
		}
		text = quail.getTextContents($element);

		$.each(quail.components.language.scriptSingletons, function(code, regularExpression) {
			if(code === currentLanguage) {
				return;
			}
			matches = text.match(regularExpression);
			if(matches && matches.length && noCharactersMatch($element, code, matches, regularExpression)) {
				quail.testFails('languageChangesAreIdentified', $element, { language : code });
			}
		});
		$.each(quail.components.language.scripts, function(code, script) {
			if(script.languages.indexOf(currentLanguage) !== -1) {
				return;
			}
			matches = text.match(script.regularExpression);
			if(matches && matches.length && noCharactersMatch($element, code, matches, regularExpression)) {
				quail.testFails('languageChangesAreIdentified', $element, { language : code });
			}
		});

	});
};<commit_msg>Fixed detecting current language of element.<commit_after>quail.languageChangesAreIdentified = function() {
	var currentLanguage = quail.components.language.getDocumentLanguage(true);
	var text, regularExpression, matches, $element;

	var noCharactersMatch = function($element, language, matches, regularExpression) {
		var $children = $element.find('[lang=' + language + ']');
		var childMatches;
		if($children.length === 0) {
			return true;
		}
		matches = matches.length;
		$children.each(function() {
			childMatches = quail.getTextContents($(this)).match(regularExpression);
			if(childMatches) {
				matches -= childMatches.length;
			}
		});
		return matches > 0;
	};

	var findCurrentLanguage = function($element) {
		if($element.attr('lang')) {
			return $element.attr('lang').trim().toLowerCase().split('-')[0];
		}
		if($element.parents('[lang]').length) {
			return $element.parents('[lang]:first').attr('lang').trim().toLowerCase().split('-')[0];
		}
		return quail.components.language.getDocumentLanguage(true);
	};

	quail.html.find(quail.textSelector).each(function() {
		$element = $(this);
		currentLanguage = findCurrentLanguage($element);
		text = quail.getTextContents($element);

		$.each(quail.components.language.scriptSingletons, function(code, regularExpression) {
			if(code === currentLanguage) {
				return;
			}
			matches = text.match(regularExpression);
			if(matches && matches.length && noCharactersMatch($element, code, matches, regularExpression)) {
				quail.testFails('languageChangesAreIdentified', $element, { language : code });
			}
		});
		$.each(quail.components.language.scripts, function(code, script) {
			if(script.languages.indexOf(currentLanguage) !== -1) {
				return;
			}
			matches = text.match(script.regularExpression);
			if(matches && matches.length && noCharactersMatch($element, code, matches, regularExpression)) {
				console.log(matches);
				console.log(code);
				quail.testFails('languageChangesAreIdentified', $element, { language : code });
			}
		});

	});
};<|endoftext|>


<commit_before>/*global describe, it, after*/
/*
 * mochify.js
 *
 * Copyright (c) 2014 Maximilian Antoni <mail@maxantoni.de>
 *
 * @license MIT
 */
'use strict';

var assert = require('assert');
var args   = require('../lib/args');
var run    = require('./fixture/run');

describe('args', function () {

  it('sets defaults', function () {
    var opts = args([]);

    assert.equal(opts.watch, false);
    assert.equal(opts.cover, false);
    assert.equal(opts.node, false);
    assert.equal(opts.wd, false);
    assert.equal(opts.reporter, 'dot');
    assert.equal(opts.timeout, 2000);
    assert.equal(opts.port, 0);
    assert.equal(opts.yields, 0);
  });

  it('parses --reporter', function () {
    var opts = args(['--reporter', 'tap']);

    assert.equal(opts.reporter, 'tap');
  });

  it('parses -R', function () {
    var opts = args(['-R', 'tap']);

    assert.equal(opts.reporter, 'tap');
  });

  it('parses --timeout', function () {
    var opts = args(['--timeout', '3000']);

    assert.equal(opts.timeout, 3000);
  });

  it('parses -t', function () {
    var opts = args(['-t', '3000']);

    assert.equal(opts.timeout, 3000);
  });

  it('parses --ui', function () {
    var opts = args(['--ui', 'TDD']);

    assert.equal(opts.ui, 'TDD');
  });

  it('parses -U', function () {
    var opts = args(['-U', 'TDD']);

    assert.equal(opts.ui, 'TDD');
  });

  it('parses --watch', function () {
    var opts = args(['--watch']);

    assert(opts.watch);
  });

  it('parses -w', function () {
    var opts = args(['-w']);

    assert(opts.watch);
  });

  it('parses --node', function () {
    var opts = args(['--node']);

    assert(opts.node);
  });

  it('parses --wd', function () {
    var opts = args(['--wd']);

    assert(opts.wd);
  });

  it('parses --port', function () {
    var opts = args(['--port', '8765']);

    assert.equal(opts.port, 8765);
  });

  it('parses --yields', function () {
    var opts = args(['--yields', '123']);

    assert.equal(opts.yields, 123);
  });

  it('parses -y', function () {
    var opts = args(['-y', '123']);

    assert.equal(opts.yields, 123);
  });

  it('parses --phantomjs', function () {
    var opts = args(['--phantomjs', '/foo/bar']);

    assert.equal(opts.phantomjs, '/foo/bar');
  });

  it('quits with usage', function (done) {
    run('passes', ['--unknown'], function (code, stdout) {
      assert.equal(code, 1);
      assert.equal(stdout, 'Unknown argument: --unknown\n'
                   + 'Run `mochify --help` for usage.\n\n');
      done();
    });
  });

  it('requires single glob to match', function (done) {
    run('passes', ['./unknown/*'], function (code, stdout) {
      assert.equal(code, 1);
      assert.equal(stdout, 'Error: Nothing found for "./unknown/*".\n\n');
      done();
    });
  });

  it('requires multiple globs to match', function (done) {
    run('passes', ['./thing-a/*', './thing-b/*'], function (code, stdout) {
      assert.equal(code, 1);
      assert.equal(stdout,
          'Error: Nothing found for "./thing-a/*" or "./thing-b/*".\n\n');
      done();
    });
  });

  it('fails with meaningful message if file is missing', function (done) {
    run('passes', ['./unknown-file.js'], function (code, stdout) {
      assert.equal(code, 1);
      assert(stdout.indexOf('./unknown-file.js') !== -1);
      done();
    });
  });

  it('fails with meaningful message for defaults', function (done) {
    run('.', [], function (code, stdout) {
      assert.equal(code, 1);
      assert.equal(stdout, 'Error: Nothing found for "./test/*.js".\n\n');
      done();
    });
  });

});
<commit_msg>Add args test for --debug<commit_after>/*global describe, it, after*/
/*
 * mochify.js
 *
 * Copyright (c) 2014 Maximilian Antoni <mail@maxantoni.de>
 *
 * @license MIT
 */
'use strict';

var assert = require('assert');
var args   = require('../lib/args');
var run    = require('./fixture/run');

describe('args', function () {

  it('sets defaults', function () {
    var opts = args([]);

    assert.equal(opts.watch, false);
    assert.equal(opts.cover, false);
    assert.equal(opts.node, false);
    assert.equal(opts.wd, false);
    assert.equal(opts.reporter, 'dot');
    assert.equal(opts.timeout, 2000);
    assert.equal(opts.port, 0);
    assert.equal(opts.yields, 0);
  });

  it('parses --reporter', function () {
    var opts = args(['--reporter', 'tap']);

    assert.equal(opts.reporter, 'tap');
  });

  it('parses -R', function () {
    var opts = args(['-R', 'tap']);

    assert.equal(opts.reporter, 'tap');
  });

  it('parses --timeout', function () {
    var opts = args(['--timeout', '3000']);

    assert.equal(opts.timeout, 3000);
  });

  it('parses -t', function () {
    var opts = args(['-t', '3000']);

    assert.equal(opts.timeout, 3000);
  });

  it('parses --ui', function () {
    var opts = args(['--ui', 'TDD']);

    assert.equal(opts.ui, 'TDD');
  });

  it('parses -U', function () {
    var opts = args(['-U', 'TDD']);

    assert.equal(opts.ui, 'TDD');
  });

  it('parses --watch', function () {
    var opts = args(['--watch']);

    assert(opts.watch);
  });

  it('parses -w', function () {
    var opts = args(['-w']);

    assert(opts.watch);
  });

  it('parses --node', function () {
    var opts = args(['--node']);

    assert(opts.node);
  });

  it('parses --wd', function () {
    var opts = args(['--wd']);

    assert(opts.wd);
  });

  it('parses --port', function () {
    var opts = args(['--port', '8765']);

    assert.equal(opts.port, 8765);
  });

  it('parses --yields', function () {
    var opts = args(['--yields', '123']);

    assert.equal(opts.yields, 123);
  });

  it('parses -y', function () {
    var opts = args(['-y', '123']);

    assert.equal(opts.yields, 123);
  });

  it('parses --phantomjs', function () {
    var opts = args(['--phantomjs', '/foo/bar']);

    assert.equal(opts.phantomjs, '/foo/bar');
  });

  it('parses --debug', function () {
    var opts = args(['--debug']);

    assert(opts.debug);
  });

  it('quits with usage', function (done) {
    run('passes', ['--unknown'], function (code, stdout) {
      assert.equal(code, 1);
      assert.equal(stdout, 'Unknown argument: --unknown\n'
                   + 'Run `mochify --help` for usage.\n\n');
      done();
    });
  });

  it('requires single glob to match', function (done) {
    run('passes', ['./unknown/*'], function (code, stdout) {
      assert.equal(code, 1);
      assert.equal(stdout, 'Error: Nothing found for "./unknown/*".\n\n');
      done();
    });
  });

  it('requires multiple globs to match', function (done) {
    run('passes', ['./thing-a/*', './thing-b/*'], function (code, stdout) {
      assert.equal(code, 1);
      assert.equal(stdout,
          'Error: Nothing found for "./thing-a/*" or "./thing-b/*".\n\n');
      done();
    });
  });

  it('fails with meaningful message if file is missing', function (done) {
    run('passes', ['./unknown-file.js'], function (code, stdout) {
      assert.equal(code, 1);
      assert(stdout.indexOf('./unknown-file.js') !== -1);
      done();
    });
  });

  it('fails with meaningful message for defaults', function (done) {
    run('.', [], function (code, stdout) {
      assert.equal(code, 1);
      assert.equal(stdout, 'Error: Nothing found for "./test/*.js".\n\n');
      done();
    });
  });

});
<|endoftext|>


<commit_before>const _ = require('lodash');

const {conform} = require('./conform');
const exercise = require('./exercise');
const isValid = require('./isValid');
const {invalidString, isFunction} = require('./utils');

function fspec(options) {
    const alwaysTrue = () => true;
    const {args: argsSpec, ret, fn: funcSpec = alwaysTrue} = options;

    return {
        conform: f => {
            if (isFunction(f)) {
                // TODO: Overlap with test/check.js!!!
                const samples = exercise(argsSpec, 10);

                const validReturnValue = ([, returnValue]) => isValid(ret, returnValue);
                const validateFunction = ([args, returnValue]) => funcSpec({ret: returnValue, args: conform(argsSpec, args)});

                const results = _.map(samples, ([args]) => [args, f(...args)]);

                const pass = _.every(results, sample => validReturnValue(sample) && validateFunction(sample));

                return pass ? f : invalidString;
            } else {
                return invalidString;
            }
        }
    }
}

module.exports = fspec;
<commit_msg>Fix build error<commit_after>const _ = require('lodash');

const {conform} = require('./conform');
const exercise = require('./exercise');
const isValid = require('./isValid');
const {invalidString, isFunction} = require('./utils');

function fspec(options) {
    const alwaysTrue = () => true;
//    const {args: argsSpec, ret, fn: funcSpec = alwaysTrue} = options;
    const {args: argsSpec, ret, fn} = options;

    const funcSpec = fn ? fn : alwaysTrue;

    return {
        conform: f => {
            if (isFunction(f)) {
                // TODO: Overlap with test/check.js!!!
                const samples = exercise(argsSpec, 10);

                const validReturnValue = ([, returnValue]) => isValid(ret, returnValue);
                const validateFunction = ([args, returnValue]) => funcSpec({ret: returnValue, args: conform(argsSpec, args)});

                const results = _.map(samples, ([args]) => [args, f(...args)]);

                const pass = _.every(results, sample => validReturnValue(sample) && validateFunction(sample));

                return pass ? f : invalidString;
            } else {
                return invalidString;
            }
        }
    };
}

module.exports = fspec;
<|endoftext|>


<commit_before>var procstreams = require('procstreams');
var http = require('http');
var express = require('express');
var app = express();
var config = require('./config.json');
var path = require('path');
var bodyParser = require('body-parser');

app.use(bodyParser());
// 設定、啟動server
app.set('views', path.join(__dirname, 'views'));
//app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');

app.use(express.static(path.join(__dirname, 'public')));

config.targets.forEach(function (target) {
    var run = function (req, res) {
        var version = req.body.version;

        var isEMPTY = /^\s*$/i;
        if (isEMPTY.test(version)) {
            res.end("version number is required.");
            return;
        }

        var isHEAD = /^\s*head\s*$/i;
        if (target.requireVersion && (isHEAD.test(version))) {
            res.end("version number is required.");
            return;
        }

        var log = 'Update ' + target.name + ":";
        var opt = { cwd: target.path };
        log += "\n    at: " + new Date().toLocaleString();
        log += "\n    options: " + JSON.stringify(opt);
        var keeplocal = [].concat(target.keeplocal || []);
        if (keeplocal.length > 0)
            log += "\n    keeplocal: " + JSON.stringify(keeplocal);
        log += "\n";

        var cmdstream = null;
        var haserr = false;
        function command(cmd, logresult) {
            if (logresult !== false)
                logresult = true;
            if (cmdstream == null)
                cmdstream = procstreams(cmd, null, opt);
            else
                cmdstream = cmdstream.and(cmd, null, opt);

            cmdstream.data(function (err, stdout, stderr) {
                if (logresult) {
                    log += '\n' + cmd;
                    if (err)
                        log += "\n!" + JSON.stringify(err) + "";
                    if (stderr)
                        log += "\n*" + stderr + "";
                    if (stdout)
                        log += "\n>" + (stdout || "");
                    if (!stdout && !err && !stderr) {
                        log += "\n>no result.";
                    }
                    if (!log.match(/\n$/))
                        log += "\n";
                }

                console.log(cmd);
                if (err)
                    console.log("!" + JSON.stringify(err));
                if (stderr)
                    console.log("*" + stderr);
                console.log(">" + stdout); // prints number of lines in the file lines.txt

                if (err) {
                    haserr = true;
                    setTimeout(function () {
                        res.end(log);
                        if (target.mail) {
                            var nodemailer = require('nodemailer');
                            var transporter = nodemailer.createTransport(target.mail.smtpTransportOptions);
                            var mailOptions = {
                                from: target.mail.from, // sender address
                                to: target.mail.to, // list of receivers
                                subject: target.name + " updated failed!!!" , // Subject line
                                text: log // plaintext body
                            };
                            transporter.sendMail(mailOptions, function (error, info) {
                                if (error) {
                                    console.log('Mail error: ' + error);
                                } else {
                                    console.log('Mail sent: ' + info.response);
                                }
                            });
                        }
                    }, 800);
                }
            })
        }
        command('rm -rf ' + __dirname + '/__keeplocal');
        command('mkdir ' + __dirname + '/__keeplocal');
        keeplocal.forEach(function (file, index) {
            command('/bin/cp -f ' + file + ' ' + __dirname + '/__keeplocal/l' + index + '.l');
        });

        if (version && isHEAD.test(version)) {
            command('git reset --hard');
            command('git pull');
        }
        else {
            command('git fetch');
            command('git show ' + version);
            command('git checkout -f ' + version);
        }

        keeplocal.forEach(function (file, index) {
            command('mv ' + file + ' ' + __dirname + '/__keeplocal/del' + index + '.l');
            command('mv ' + __dirname + '/__keeplocal/l' + index + '.l ' + file);
        });

        if (target.writeTag) {

            function pad2(n) {  // always returns a string
                return (n < 10 ? '0' : '') + n;
            }
            function pad3(n) {  // always returns a string
                return (n < 10 ? '00' : (n < 100 ? '0' : '')) + n;
            }

            var time = new Date();
            var deployT = time.getFullYear() + "." +
                pad2(time.getMonth() + 1) + "." +
                pad2(time.getDate()) + "-" +
                pad2(time.getHours()) + "." +
                pad2(time.getMinutes()) + "." +
                pad2(time.getSeconds()) + "." +
                pad3(time.getMilliseconds());
            var deployM = time.getFullYear() + "/" +
                pad2(time.getMonth() + 1) + "/" +
                pad2(time.getDate()) + " " +
                pad2(time.getHours()) + ":" +
                pad2(time.getMinutes()) + ":" +
                pad2(time.getSeconds());
            command("git tag -a " + deployT + " -m'" + deployM + "'", false);
            command('git push --tags', false);
        }
        cmdstream.on('exit', function () {
            setTimeout(function () {
                if (!haserr) {
                    res.end(log);
                    if (target.mail) {
                        var nodemailer = require('nodemailer');
                        var transporter = nodemailer.createTransport(target.mail.smtpTransportOptions);
                        var mailOptions = {
                            from: target.mail.from, // sender address
                            to: target.mail.to, // list of receivers
                            subject: target.name + " updated." , // Subject line
                            text: log // plaintext body
                        };
                        transporter.sendMail(mailOptions, function (error, info) {
                            if (error) {
                                console.log('Mail error: ' + error);
                            } else {
                                console.log('Mail sent: ' + info.response);
                            }
                            if (target.finalCommand) {
                                console.log('finalCommand: ' + target.finalCommand);
                                command(target.finalCommand, false);
                            }
                        });
                    } else {
                        if (target.finalCommand) {
                            console.log('finalCommand: ' + target.finalCommand);
                            command(target.finalCommand, false);
                        }
                    }
                }
            }, 1000);
        });
    };
    app.post('/' + target.name, run);
    app.get('/' + target.name, function (req, res) {
        res.render('root', { name: target.name });
    });
});
http.createServer(app).listen(config.port, function () {
    console.log('Express server listening on port ' + config.port);
});
<commit_msg>強化更新到最新版功能的指令<commit_after>var procstreams = require('procstreams');
var http = require('http');
var express = require('express');
var app = express();
var config = require('./config.json');
var path = require('path');
var bodyParser = require('body-parser');

app.use(bodyParser());
// 設定、啟動server
app.set('views', path.join(__dirname, 'views'));
//app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');

app.use(express.static(path.join(__dirname, 'public')));

config.targets.forEach(function (target) {
    var run = function (req, res) {
        var version = req.body.version;

        var isEMPTY = /^\s*$/i;
        if (isEMPTY.test(version)) {
            res.end("version number is required.");
            return;
        }

        var isHEAD = /^\s*head\s*$/i;
        if (target.requireVersion && (isHEAD.test(version))) {
            res.end("version number is required.");
            return;
        }

        var log = 'Update ' + target.name + ":";
        var opt = { cwd: target.path };
        log += "\n    at: " + new Date().toLocaleString();
        log += "\n    options: " + JSON.stringify(opt);
        var keeplocal = [].concat(target.keeplocal || []);
        if (keeplocal.length > 0)
            log += "\n    keeplocal: " + JSON.stringify(keeplocal);
        log += "\n";

        var cmdstream = null;
        var haserr = false;
        function command(cmd, logresult) {
            if (logresult !== false)
                logresult = true;
            if (cmdstream == null)
                cmdstream = procstreams(cmd, null, opt);
            else
                cmdstream = cmdstream.and(cmd, null, opt);

            cmdstream.data(function (err, stdout, stderr) {
                if (logresult) {
                    log += '\n' + cmd;
                    if (err)
                        log += "\n!" + JSON.stringify(err) + "";
                    if (stderr)
                        log += "\n*" + stderr + "";
                    if (stdout)
                        log += "\n>" + (stdout || "");
                    if (!stdout && !err && !stderr) {
                        log += "\n>no result.";
                    }
                    if (!log.match(/\n$/))
                        log += "\n";
                }

                console.log(cmd);
                if (err)
                    console.log("!" + JSON.stringify(err));
                if (stderr)
                    console.log("*" + stderr);
                console.log(">" + stdout); // prints number of lines in the file lines.txt

                if (err) {
                    haserr = true;
                    setTimeout(function () {
                        res.end(log);
                        if (target.mail) {
                            var nodemailer = require('nodemailer');
                            var transporter = nodemailer.createTransport(target.mail.smtpTransportOptions);
                            var mailOptions = {
                                from: target.mail.from, // sender address
                                to: target.mail.to, // list of receivers
                                subject: target.name + " updated failed!!!" , // Subject line
                                text: log // plaintext body
                            };
                            transporter.sendMail(mailOptions, function (error, info) {
                                if (error) {
                                    console.log('Mail error: ' + error);
                                } else {
                                    console.log('Mail sent: ' + info.response);
                                }
                            });
                        }
                    }, 800);
                }
            })
        }
        command('rm -rf ' + __dirname + '/__keeplocal');
        command('mkdir ' + __dirname + '/__keeplocal');
        keeplocal.forEach(function (file, index) {
            command('/bin/cp -f ' + file + ' ' + __dirname + '/__keeplocal/l' + index + '.l');
        });

        if (version && isHEAD.test(version)) {
            command('git reset --hard HEAD');
            command('git pull --rebase');
        }
        else {
            command('git fetch');
            command('git show ' + version);
            command('git checkout -f ' + version);
        }

        keeplocal.forEach(function (file, index) {
            command('mv ' + file + ' ' + __dirname + '/__keeplocal/del' + index + '.l');
            command('mv ' + __dirname + '/__keeplocal/l' + index + '.l ' + file);
        });

        if (target.writeTag) {

            function pad2(n) {  // always returns a string
                return (n < 10 ? '0' : '') + n;
            }
            function pad3(n) {  // always returns a string
                return (n < 10 ? '00' : (n < 100 ? '0' : '')) + n;
            }

            var time = new Date();
            var deployT = time.getFullYear() + "." +
                pad2(time.getMonth() + 1) + "." +
                pad2(time.getDate()) + "-" +
                pad2(time.getHours()) + "." +
                pad2(time.getMinutes()) + "." +
                pad2(time.getSeconds()) + "." +
                pad3(time.getMilliseconds());
            var deployM = time.getFullYear() + "/" +
                pad2(time.getMonth() + 1) + "/" +
                pad2(time.getDate()) + " " +
                pad2(time.getHours()) + ":" +
                pad2(time.getMinutes()) + ":" +
                pad2(time.getSeconds());
            command("git tag -a " + deployT + " -m'" + deployM + "'", false);
            command('git push --tags', false);
        }
        cmdstream.on('exit', function () {
            setTimeout(function () {
                if (!haserr) {
                    res.end(log);
                    if (target.mail) {
                        var nodemailer = require('nodemailer');
                        var transporter = nodemailer.createTransport(target.mail.smtpTransportOptions);
                        var mailOptions = {
                            from: target.mail.from, // sender address
                            to: target.mail.to, // list of receivers
                            subject: target.name + " updated." , // Subject line
                            text: log // plaintext body
                        };
                        transporter.sendMail(mailOptions, function (error, info) {
                            if (error) {
                                console.log('Mail error: ' + error);
                            } else {
                                console.log('Mail sent: ' + info.response);
                            }
                            if (target.finalCommand) {
                                console.log('finalCommand: ' + target.finalCommand);
                                command(target.finalCommand, false);
                            }
                        });
                    } else {
                        if (target.finalCommand) {
                            console.log('finalCommand: ' + target.finalCommand);
                            command(target.finalCommand, false);
                        }
                    }
                }
            }, 1000);
        });
    };
    app.post('/' + target.name, run);
    app.get('/' + target.name, function (req, res) {
        res.render('root', { name: target.name });
    });
});
http.createServer(app).listen(config.port, function () {
    console.log('Express server listening on port ' + config.port);
});
<|endoftext|>