<commit_before>/**
 * Pimcore
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.pimcore.org/license
 *
 * @copyright  Copyright (c) 2009-2014 pimcore GmbH (http://www.pimcore.org)
 * @license    http://www.pimcore.org/license     New BSD License
 */

pimcore.registerNS("pimcore.object.tags.href");
pimcore.object.tags.href = Class.create(pimcore.object.tags.abstract, {

    type: "href",
    dataChanged:false,

    initialize: function (data, fieldConfig) {

        this.data = {};

        if (data) {
            this.data = data;
        }
        this.fieldConfig = fieldConfig;

    },

    getGridColumnConfig:function (field) {
        var renderer = function (key, value, metaData, record) {
            this.applyPermissionStyle(key, value, metaData, record);

            if (record.data.inheritedFields[key] && record.data.inheritedFields[key].inherited == true) {
                metaData.css += " grid_value_inherited";
            }
            return value;

        }.bind(this, field.key);

        return {header:ts(field.label), sortable:false, dataIndex:field.key, renderer:renderer,
            editor:this.getGridColumnEditor(field)};
    },

    getLayoutEdit: function () {

        var href = {
            fieldLabel: this.fieldConfig.title,
            name: this.fieldConfig.name
        };

        if (this.data) {
            if (this.data.path) {
                href.value = this.data.path;
            }
        }

        if (this.fieldConfig.width) {
            href.width = this.fieldConfig.width;
        }
        href.enableKeyEvents = true;
        href.fieldCls = "pimcore_droptarget_input";
        this.component = new Ext.form.TextField(href);

        this.component.on("render", function (el) {

            // add drop zone
            new Ext.dd.DropZone(el.getEl(), {
                reference: this,
                ddGroup: "element",
                getTargetFromEvent: function(e) {
                    return this.reference.component.getEl();
                },

                onNodeOver : function(target, dd, e, data) {

                    var record = data.records[0];
                    var data = record.data;

                    if (this.dndAllowed(data)) {
                        return Ext.dd.DropZone.prototype.dropAllowed;
                    }
                    else {
                        return Ext.dd.DropZone.prototype.dropNotAllowed;
                    }

                }.bind(this),

                onNodeDrop : this.onNodeDrop.bind(this)
            });

            el.getEl().on("contextmenu", this.onContextMenu.bind(this));

        }.bind(this));

        // disable typing into the textfield
        this.component.on("keyup", function (element, event) {
            element.setValue(this.data.path);
        }.bind(this));

        var items = [this.component, {
            xtype: "button",
            iconCls: "pimcore_icon_edit",
            handler: this.openElement.bind(this)
        },{
            xtype: "button",
            iconCls: "pimcore_icon_delete",
            handler: this.empty.bind(this)
        },{
            xtype: "button",
            iconCls: "pimcore_icon_search",
            handler: this.openSearchEditor.bind(this)
        }];

        // add upload button when assets are allowed
        if (this.fieldConfig.assetsAllowed) {
            items.push({
                xtype: "button",
                iconCls: "pimcore_icon_upload_single",
                cls: "pimcore_inline_upload",
                handler: this.uploadDialog.bind(this)
            });
        }

        this.composite = Ext.create('Ext.form.FieldSet', {
            layout: 'hbox',
            items: items,
            itemCls: "object_field",
            border: false,
            style: {
                padding: 0
            }
        });

        return this.composite;
    },

    getLayoutShow: function () {

        var href = {
            fieldLabel: this.fieldConfig.title,
            name: this.fieldConfig.name,
            cls: "object_field"
        };

        if (this.data) {
            if (this.data.path) {
                href.value = this.data.path;
            }
        }

        if (this.fieldConfig.width) {
            href.width = this.fieldConfig.width;
        }
        href.disabled = true;

        this.component = new Ext.form.TextField(href);

        this.composite = Ext.create('Ext.form.FieldSet', {
            layout: 'hbox',
            items: [this.component, {
                xtype: "button",
                iconCls: "pimcore_icon_edit",
                handler: this.openElement.bind(this)
            }],
            itemCls: "object_field",
            border: false,
            style: {
                padding: 0
            }
        });

        return this.composite;

    },

    uploadDialog: function () {
        pimcore.helpers.assetSingleUploadDialog(this.fieldConfig.assetUploadPath, "path", function (res) {
            try {
                var data = Ext.decode(res.response.responseText);
                if(data["id"]) {
                    this.data.id = data["id"];
                    this.data.type = "asset";
                    this.data.subtype = data["type"];
                    this.dataChanged = true;

                    this.component.setValue(data["fullpath"]);
                }
            } catch (e) {
                console.log(e);
            }
        }.bind(this));
    },

    onNodeDrop: function (target, dd, e, data) {
        var record = data.records[0];
        var data = record.data;

        if (this.dndAllowed(data)) {
            this.data.id = data.id;
            this.data.type = data.elementType;
            this.data.subtype = data.type;
            this.dataChanged = true;
            this.component.setValue(data.path);

            return true;
        } else {
            return false;
        }
    },

    onContextMenu: function (e) {

        var menu = new Ext.menu.Menu();
        menu.add(new Ext.menu.Item({
            text: t('empty'),
            iconCls: "pimcore_icon_delete",
            handler: function (item) {
                item.parentMenu.destroy();

                this.empty();
            }.bind(this)
        }));

        menu.add(new Ext.menu.Item({
            text: t('open'),
            iconCls: "pimcore_icon_open",
            handler: function (item) {
                item.parentMenu.destroy();
                this.openElement();
            }.bind(this)
        }));

        menu.add(new Ext.menu.Item({
            text: t('search'),
            iconCls: "pimcore_icon_search",
            handler: function (item) {
                item.parentMenu.destroy();
                this.openSearchEditor();
            }.bind(this)
        }));

        // add upload button when assets are allowed
        if (this.fieldConfig.assetsAllowed) {
            menu.add(new Ext.menu.Item({
                text: t('upload'),
                cls: "pimcore_inline_upload",
                iconCls: "pimcore_icon_upload_single",
                handler: function (item) {
                    item.parentMenu.destroy();
                    this.uploadDialog();
                }.bind(this)
            }));
        }

        menu.showAt(e.getXY());

        e.stopEvent();
    },

    openSearchEditor: function () {
        var allowedTypes = [];
        var allowedSpecific = {};
        var allowedSubtypes = {};
        var i;

        if (this.fieldConfig.objectsAllowed) {
            allowedTypes.push("object");
            if (this.fieldConfig.classes != null && this.fieldConfig.classes.length > 0) {
                allowedSpecific.classes = [];
                allowedSubtypes.object = ["object"];
                for (i = 0; i < this.fieldConfig.classes.length; i++) {
                    allowedSpecific.classes.push(this.fieldConfig.classes[i].classes);
                }
            } else {
                allowedSubtypes.object = ["object","folder","variant"];
            }
        }
        if (this.fieldConfig.assetsAllowed) {
            allowedTypes.push("asset");
            if (this.fieldConfig.assetTypes != null && this.fieldConfig.assetTypes.length > 0) {
                allowedSubtypes.asset = [];
                for (i = 0; i < this.fieldConfig.assetTypes.length; i++) {
                    allowedSubtypes.asset.push(this.fieldConfig.assetTypes[i].assetTypes);
                }
            }
        }
        if (this.fieldConfig.documentsAllowed) {
            allowedTypes.push("document");
            if (this.fieldConfig.documentTypes != null && this.fieldConfig.documentTypes.length > 0) {
                allowedSubtypes.document = [];
                for (i = 0; i < this.fieldConfig.documentTypes.length; i++) {
                    allowedSubtypes.document.push(this.fieldConfig.documentTypes[i].documentTypes);
                }
            }
        }

        pimcore.helpers.itemselector(false, this.addDataFromSelector.bind(this), {
            type: allowedTypes,
            subtype: allowedSubtypes,
            specific: allowedSpecific
        });
    },

    addDataFromSelector: function (data) {
        this.data.id = data.id;
        this.data.type = data.type;
        this.data.subtype = data.subtype;
        this.dataChanged = true;

        this.component.setValue(data.fullpath);
    },

    openElement: function () {
        if(this.data.id && this.data.type && this.data.subtype) {
            pimcore.helpers.openElement(this.data.id, this.data.type, this.data.subtype);
        }
    },

    empty: function () {
        this.data = {};
        this.dataChanged=true;
        this.component.setValue("");
    },

    getValue: function () {
        return this.data;
    },

    getName: function () {
        return this.fieldConfig.name;
    },

    dndAllowed: function(data) {
        var type = data.elementType;
        var i;
        var subType;
        var isAllowed = false;
        if (type == "object" && this.fieldConfig.objectsAllowed) {

            var classname = data.className;

            isAllowed = false;
            if (this.fieldConfig.classes != null && this.fieldConfig.classes.length > 0) {
                for (i = 0; i < this.fieldConfig.classes.length; i++) {
                    if (this.fieldConfig.classes[i].classes == classname) {
                        isAllowed = true;
                        break;
                    }
                }
            } else {
                //no classes configured - allow all
                isAllowed = true;
            }

        } else if (type == "asset" && this.fieldConfig.assetsAllowed) {
            subType = data.type;
            isAllowed = false;
            if (this.fieldConfig.assetTypes != null && this.fieldConfig.assetTypes.length > 0) {
                for (i = 0; i < this.fieldConfig.assetTypes.length; i++) {
                    if (this.fieldConfig.assetTypes[i].assetTypes == subType) {
                        isAllowed = true;
                        break;
                    }
                }
            } else {
                //no asset types configured - allow all
                isAllowed = true;
            }

        } else if (type == "document" && this.fieldConfig.documentsAllowed) {
            subType = data.node.attributes.type;
            isAllowed = false;
            if (this.fieldConfig.documentTypes != null && this.fieldConfig.documentTypes.length > 0) {
                for (i = 0; i < this.fieldConfig.documentTypes.length; i++) {
                    if (this.fieldConfig.documentTypes[i].documentTypes == subType) {
                        isAllowed = true;
                        break;
                    }
                }
            } else {
                //no document types configured - allow all
                isAllowed = true;
            }
        }
        return isAllowed;
    },

    isInvalidMandatory: function () {
        if (this.data.id) {
            return false;
        }
        return true;
    }
});<commit_msg>href: use FieldContainer instead of FieldSet<commit_after>/**
 * Pimcore
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.pimcore.org/license
 *
 * @copyright  Copyright (c) 2009-2014 pimcore GmbH (http://www.pimcore.org)
 * @license    http://www.pimcore.org/license     New BSD License
 */

pimcore.registerNS("pimcore.object.tags.href");
pimcore.object.tags.href = Class.create(pimcore.object.tags.abstract, {

    type: "href",
    dataChanged:false,

    initialize: function (data, fieldConfig) {

        this.data = {};

        if (data) {
            this.data = data;
        }
        this.fieldConfig = fieldConfig;

    },

    getGridColumnConfig:function (field) {
        var renderer = function (key, value, metaData, record) {
            this.applyPermissionStyle(key, value, metaData, record);

            if (record.data.inheritedFields[key] && record.data.inheritedFields[key].inherited == true) {
                metaData.css += " grid_value_inherited";
            }
            return value;

        }.bind(this, field.key);

        return {header:ts(field.label), sortable:false, dataIndex:field.key, renderer:renderer,
            editor:this.getGridColumnEditor(field)};
    },

    getLayoutEdit: function () {

        var href = {
            name: this.fieldConfig.name
        };

        if (this.data) {
            if (this.data.path) {
                href.value = this.data.path;
            }
        }

        if (this.fieldConfig.width) {
            href.width = this.fieldConfig.width;
        }
        href.enableKeyEvents = true;
        href.fieldCls = "pimcore_droptarget_input";
        this.component = new Ext.form.TextField(href);

        this.component.on("render", function (el) {

            // add drop zone
            new Ext.dd.DropZone(el.getEl(), {
                reference: this,
                ddGroup: "element",
                getTargetFromEvent: function(e) {
                    return this.reference.component.getEl();
                },

                onNodeOver : function(target, dd, e, data) {

                    var record = data.records[0];
                    var data = record.data;

                    if (this.dndAllowed(data)) {
                        return Ext.dd.DropZone.prototype.dropAllowed;
                    }
                    else {
                        return Ext.dd.DropZone.prototype.dropNotAllowed;
                    }

                }.bind(this),

                onNodeDrop : this.onNodeDrop.bind(this)
            });

            el.getEl().on("contextmenu", this.onContextMenu.bind(this));

        }.bind(this));

        // disable typing into the textfield
        this.component.on("keyup", function (element, event) {
            element.setValue(this.data.path);
        }.bind(this));

        var items = [this.component, {
            xtype: "button",
            iconCls: "pimcore_icon_edit",
            handler: this.openElement.bind(this)
        },{
            xtype: "button",
            iconCls: "pimcore_icon_delete",
            handler: this.empty.bind(this)
        },{
            xtype: "button",
            iconCls: "pimcore_icon_search",
            handler: this.openSearchEditor.bind(this)
        }];

        // add upload button when assets are allowed
        if (this.fieldConfig.assetsAllowed) {
            items.push({
                xtype: "button",
                iconCls: "pimcore_icon_upload_single",
                cls: "pimcore_inline_upload",
                handler: this.uploadDialog.bind(this)
            });
        }

        this.composite = Ext.create('Ext.form.FieldContainer', {
            fieldLabel: this.fieldConfig.title,
            layout: 'hbox',
            items: items,
            itemCls: "object_field",
            border: false,
            style: {
                padding: 0
            }
        });

        return this.composite;
    },

    getLayoutShow: function () {

        var href = {
            fieldLabel: this.fieldConfig.title,
            name: this.fieldConfig.name,
            cls: "object_field"
        };

        if (this.data) {
            if (this.data.path) {
                href.value = this.data.path;
            }
        }

        if (this.fieldConfig.width) {
            href.width = this.fieldConfig.width;
        }
        href.disabled = true;

        this.component = new Ext.form.TextField(href);

        this.composite = Ext.create('Ext.form.FieldContainer', {
            layout: 'vbox',
            items: [this.component, {
                xtype: "button",
                iconCls: "pimcore_icon_edit",
                handler: this.openElement.bind(this)
            }],
            itemCls: "object_field",
            border: false,
            style: {
                padding: 0
            }
        });

        return this.composite;

    },

    uploadDialog: function () {
        pimcore.helpers.assetSingleUploadDialog(this.fieldConfig.assetUploadPath, "path", function (res) {
            try {
                var data = Ext.decode(res.response.responseText);
                if(data["id"]) {
                    this.data.id = data["id"];
                    this.data.type = "asset";
                    this.data.subtype = data["type"];
                    this.dataChanged = true;

                    this.component.setValue(data["fullpath"]);
                }
            } catch (e) {
                console.log(e);
            }
        }.bind(this));
    },

    onNodeDrop: function (target, dd, e, data) {
        var record = data.records[0];
        var data = record.data;

        if (this.dndAllowed(data)) {
            this.data.id = data.id;
            this.data.type = data.elementType;
            this.data.subtype = data.type;
            this.dataChanged = true;
            this.component.setValue(data.path);

            return true;
        } else {
            return false;
        }
    },

    onContextMenu: function (e) {

        var menu = new Ext.menu.Menu();
        menu.add(new Ext.menu.Item({
            text: t('empty'),
            iconCls: "pimcore_icon_delete",
            handler: function (item) {
                item.parentMenu.destroy();

                this.empty();
            }.bind(this)
        }));

        menu.add(new Ext.menu.Item({
            text: t('open'),
            iconCls: "pimcore_icon_open",
            handler: function (item) {
                item.parentMenu.destroy();
                this.openElement();
            }.bind(this)
        }));

        menu.add(new Ext.menu.Item({
            text: t('search'),
            iconCls: "pimcore_icon_search",
            handler: function (item) {
                item.parentMenu.destroy();
                this.openSearchEditor();
            }.bind(this)
        }));

        // add upload button when assets are allowed
        if (this.fieldConfig.assetsAllowed) {
            menu.add(new Ext.menu.Item({
                text: t('upload'),
                cls: "pimcore_inline_upload",
                iconCls: "pimcore_icon_upload_single",
                handler: function (item) {
                    item.parentMenu.destroy();
                    this.uploadDialog();
                }.bind(this)
            }));
        }

        menu.showAt(e.getXY());

        e.stopEvent();
    },

    openSearchEditor: function () {
        var allowedTypes = [];
        var allowedSpecific = {};
        var allowedSubtypes = {};
        var i;

        if (this.fieldConfig.objectsAllowed) {
            allowedTypes.push("object");
            if (this.fieldConfig.classes != null && this.fieldConfig.classes.length > 0) {
                allowedSpecific.classes = [];
                allowedSubtypes.object = ["object"];
                for (i = 0; i < this.fieldConfig.classes.length; i++) {
                    allowedSpecific.classes.push(this.fieldConfig.classes[i].classes);
                }
            } else {
                allowedSubtypes.object = ["object","folder","variant"];
            }
        }
        if (this.fieldConfig.assetsAllowed) {
            allowedTypes.push("asset");
            if (this.fieldConfig.assetTypes != null && this.fieldConfig.assetTypes.length > 0) {
                allowedSubtypes.asset = [];
                for (i = 0; i < this.fieldConfig.assetTypes.length; i++) {
                    allowedSubtypes.asset.push(this.fieldConfig.assetTypes[i].assetTypes);
                }
            }
        }
        if (this.fieldConfig.documentsAllowed) {
            allowedTypes.push("document");
            if (this.fieldConfig.documentTypes != null && this.fieldConfig.documentTypes.length > 0) {
                allowedSubtypes.document = [];
                for (i = 0; i < this.fieldConfig.documentTypes.length; i++) {
                    allowedSubtypes.document.push(this.fieldConfig.documentTypes[i].documentTypes);
                }
            }
        }

        pimcore.helpers.itemselector(false, this.addDataFromSelector.bind(this), {
            type: allowedTypes,
            subtype: allowedSubtypes,
            specific: allowedSpecific
        });
    },

    addDataFromSelector: function (data) {
        this.data.id = data.id;
        this.data.type = data.type;
        this.data.subtype = data.subtype;
        this.dataChanged = true;

        this.component.setValue(data.fullpath);
    },

    openElement: function () {
        if(this.data.id && this.data.type && this.data.subtype) {
            pimcore.helpers.openElement(this.data.id, this.data.type, this.data.subtype);
        }
    },

    empty: function () {
        this.data = {};
        this.dataChanged=true;
        this.component.setValue("");
    },

    getValue: function () {
        return this.data;
    },

    getName: function () {
        return this.fieldConfig.name;
    },

    dndAllowed: function(data) {
        var type = data.elementType;
        var i;
        var subType;
        var isAllowed = false;
        if (type == "object" && this.fieldConfig.objectsAllowed) {

            var classname = data.className;

            isAllowed = false;
            if (this.fieldConfig.classes != null && this.fieldConfig.classes.length > 0) {
                for (i = 0; i < this.fieldConfig.classes.length; i++) {
                    if (this.fieldConfig.classes[i].classes == classname) {
                        isAllowed = true;
                        break;
                    }
                }
            } else {
                //no classes configured - allow all
                isAllowed = true;
            }

        } else if (type == "asset" && this.fieldConfig.assetsAllowed) {
            subType = data.type;
            isAllowed = false;
            if (this.fieldConfig.assetTypes != null && this.fieldConfig.assetTypes.length > 0) {
                for (i = 0; i < this.fieldConfig.assetTypes.length; i++) {
                    if (this.fieldConfig.assetTypes[i].assetTypes == subType) {
                        isAllowed = true;
                        break;
                    }
                }
            } else {
                //no asset types configured - allow all
                isAllowed = true;
            }

        } else if (type == "document" && this.fieldConfig.documentsAllowed) {
            subType = data.node.attributes.type;
            isAllowed = false;
            if (this.fieldConfig.documentTypes != null && this.fieldConfig.documentTypes.length > 0) {
                for (i = 0; i < this.fieldConfig.documentTypes.length; i++) {
                    if (this.fieldConfig.documentTypes[i].documentTypes == subType) {
                        isAllowed = true;
                        break;
                    }
                }
            } else {
                //no document types configured - allow all
                isAllowed = true;
            }
        }
        return isAllowed;
    },

    isInvalidMandatory: function () {
        if (this.data.id) {
            return false;
        }
        return true;
    }
});<|endoftext|>


<commit_before>var Sequelize = require('sequelize');
<commit_msg>Rahul | Removed db_handler module<commit_after><|endoftext|>


<commit_before>"use strict";

const should = require("should");
const sinon = require("sinon");
const WebWorkerMainTemplatePlugin = require("../lib/webworker/WebWorkerMainTemplatePlugin");
const applyPluginWithOptions = require("./helpers/applyPluginWithOptions");

describe("WebWorkerMainTemplatePlugin", function() {
	let env;

	beforeEach(() => {
		env = {};
	});

	it("has apply function", function() {
		(new WebWorkerMainTemplatePlugin()).apply.should.be.a.Function();
	});

	describe("when applied", function() {
		beforeEach(function() {
			env.eventBindings = applyPluginWithOptions(WebWorkerMainTemplatePlugin);
			env.handlerContext = {
				requireFn: 'requireFn',
				indent: (value) => typeof value === 'string' ? value : value.join("\n"),
				asString: (values) => values.join("\n"),
				renderCurrentHashCode: (value) => value,
				outputOptions: {
					chunkFilename: 'chunkFilename'
				},
				applyPluginsWaterfall: (moduleName, fileName, data) => {
					return `"${moduleName}${data.hash}${data.hashWithLength()}${data.chunk && data.chunk.id || ''}"`;
				},
				renderAddModule: () => 'renderAddModuleSource();',
			};
		});

		it("binds five event handlers", function() {
			env.eventBindings.length.should.be.exactly(5);
		});

		describe("local-vars handler", function() {
			beforeEach(() => {
				env.eventBinding = env.eventBindings[0];
			});

			it("binds to local-vars event", () => {
				env.eventBinding.name.should.be.exactly("local-vars");
			});

			describe("when no chunks are provided", () => {
				beforeEach(() => {
					const chunk = {
						ids: [],
						chunks: []
					};
					env.source = env.eventBinding.handler.call(env.handlerContext, "moduleSource()", chunk);
				});

				it("returns the original source", () => {
					env.source.should.be.exactly("moduleSource()")
				});
			});

			describe("when chunks are provided", () => {
				beforeEach(() => {
					const chunk = {
						ids: [1, 2, 3],
						chunks: [
							'foo',
							'bar',
							'baz'
						]
					};
					env.source = env.eventBinding.handler.call(env.handlerContext, "moduleSource()", chunk, 'abc123');
				});

				it("returns the original source with installed mapping", () => {
					env.source.should.be.exactly(`
moduleSource()

// object to store loaded chunks
// "1" means "already loaded"
var installedChunks = {
1: 1,
2: 1,
3: 1
};
`.trim())
				});
			});
		});

		describe("require-ensure handler", () => {
			beforeEach(() => {
				env.eventBinding = env.eventBindings[1];
			});

			it("binds to require-ensure event", () => {
				env.eventBinding.name.should.be.exactly("require-ensure");
			});

			describe("when called", () => {
				beforeEach(() => {
					const chunk = {};
					env.source = env.eventBinding.handler.call(env.handlerContext, "moduleSource()", chunk, 'abc123');
				});

				it("creates import scripts call and promise resolve", () => {
					env.source.should.be.exactly(`
return new Promise(function(resolve) {
// "1" is the signal for "already loaded"
if(!installedChunks[chunkId]) {
importScripts("asset-path" + abc123 + "" + abc123 + "" + chunkId + "");
}
resolve();
});
`.trim())
				});
			});
		});

		describe("bootstrap handler", () => {
			beforeEach(() => {
				env.eventBinding = env.eventBindings[2];
			});

			it("binds to bootstrap event", () => {
				env.eventBinding.name.should.be.exactly("bootstrap");
			});

			describe("when no chunks are provided", () => {
				beforeEach(() => {
					const chunk = {
						ids: [],
						chunks: []
					};
					env.source = env.eventBinding.handler.call(env.handlerContext, "moduleSource()", chunk);
				});

				it("returns the original source", () => {
					env.source.should.be.exactly("moduleSource()")
				});
			});

			describe("when chunks are provided", () => {
				beforeEach(() => {
					const chunk = {
						ids: [1, 2, 3],
						chunks: [
							'foo',
							'bar',
							'baz'
						]
					};
					env.source = env.eventBinding.handler.call(env.handlerContext, "moduleSource()", chunk);
				});

				it("returns the original source with chunk callback", () => {
					env.source.should.be.exactly(`
moduleSource()
this["webpackChunk"] = function webpackChunkCallback(chunkIds, moreModules) {
for(var moduleId in moreModules) {
renderAddModuleSource();
}
while(chunkIds.length)
installedChunks[chunkIds.pop()] = 1;
};
`.trim())
				});
			});
		});

		describe("hot-bootstrap handler", () => {
			beforeEach(() => {
				env.eventBinding = env.eventBindings[3];
			});

			it("binds to hot-bootstrap event", () => {
				env.eventBinding.name.should.be.exactly("hot-bootstrap");
			});

			describe("when called", () => {
				beforeEach(() => {
					const chunk = {};
					env.source = env.eventBinding.handler.call(env.handlerContext, "moduleSource()", chunk, 'abc123');
				});

				it("returns the original source with hot update callback", () => {
					env.source.should.be.exactly(`
moduleSource()
var parentHotUpdateCallback = this["webpackHotUpdate"];
this["webpackHotUpdate"] = function webpackHotUpdateCallback(chunkId, moreModules) { // eslint-disable-line no-unused-vars
	hotAddUpdateChunk(chunkId, moreModules);
	if(parentHotUpdateCallback) parentHotUpdateCallback(chunkId, moreModules);
} ;

function hotDownloadUpdateChunk(chunkId) { // eslint-disable-line no-unused-vars
	importScripts(requireFn.p + "asset-path" + abc123 + "" + abc123 + "" + chunkId + "");
}

function hotDownloadManifest(requestTimeout) { // eslint-disable-line no-unused-vars
	requestTimeout = requestTimeout || 10000;
	return new Promise(function(resolve, reject) {
		if(typeof XMLHttpRequest === "undefined")
			return reject(new Error("No browser support"));
		try {
			var request = new XMLHttpRequest();
			var requestPath = requireFn.p + "asset-path" + abc123 + "" + abc123 + "";
			request.open("GET", requestPath, true);
			request.timeout = requestTimeout;
			request.send(null);
		} catch(err) {
			return reject(err);
		}
		request.onreadystatechange = function() {
			if(request.readyState !== 4) return;
			if(request.status === 0) {
				// timeout
				reject(new Error("Manifest request to " + requestPath + " timed out."));
			} else if(request.status === 404) {
				// no update available
				resolve();
			} else if(request.status !== 200 && request.status !== 304) {
				// other failure
				reject(new Error("Manifest request to " + requestPath + " failed."));
			} else {
				// success
				try {
					var update = JSON.parse(request.responseText);
				} catch(e) {
					reject(e);
					return;
				}
				resolve(update);
			}
		};
	});
}

function hotDisposeChunk(chunkId) { //eslint-disable-line no-unused-vars
	delete installedChunks[chunkId];
}
`.trim())
				});
			});
		});

		describe("hash handler", () => {
			beforeEach(() => {
				env.eventBinding = env.eventBindings[4];
				env.handlerContext = {
					outputOptions: {
						publicPath: "Alpha",
						filename: "Bravo",
						chunkFilename: "Charlie",
						chunkCallbackName: "Delta",
						library: "Echo"
					}
				};
				env.hashMock = {
					update: sinon.spy()
				};
				env.eventBinding.handler.call(env.handlerContext, env.hashMock);
			});

			it("binds to hash event", () => {
				env.eventBinding.name.should.be.exactly("hash");
			});

			it("updates hash object", () => {
				env.hashMock.update.callCount.should.be.exactly(7);
				sinon.assert.calledWith(env.hashMock.update, "webworker");
				sinon.assert.calledWith(env.hashMock.update, "3");
				sinon.assert.calledWith(env.hashMock.update, "Alpha");
				sinon.assert.calledWith(env.hashMock.update, "Bravo");
				sinon.assert.calledWith(env.hashMock.update, "Charlie");
				sinon.assert.calledWith(env.hashMock.update, "Delta");
				sinon.assert.calledWith(env.hashMock.update, "Echo");
			});
		});
	});
});
<commit_msg>fix tests for WebWorkerMainTemplatePlugin<commit_after>"use strict";

const should = require("should");
const sinon = require("sinon");
const WebWorkerMainTemplatePlugin = require("../lib/webworker/WebWorkerMainTemplatePlugin");
const applyPluginWithOptions = require("./helpers/applyPluginWithOptions");

const createMockChunk = (ids, chunks) => {
	return {
		ids: ids,
		_chunks: new Set(chunks),
		getChunks() {
			return this._chunks;
		}
	};
};

describe("WebWorkerMainTemplatePlugin", function () {
	let env;

	beforeEach(() => {
		env = {};
	});

	it("has apply function", function () {
		(new WebWorkerMainTemplatePlugin()).apply.should.be.a.Function();
	});

	describe("when applied", function () {
		beforeEach(function () {
			env.eventBindings = applyPluginWithOptions(WebWorkerMainTemplatePlugin);
			env.handlerContext = {
				requireFn: 'requireFn',
				indent: (value) => typeof value === 'string' ? value : value.join("\n"),
				asString: (values) => values.join("\n"),
				renderCurrentHashCode: (value) => value,
				outputOptions: {
					chunkFilename: 'chunkFilename'
				},
				applyPluginsWaterfall: (moduleName, fileName, data) => {
					return `"${moduleName}${data.hash}${data.hashWithLength()}${data.chunk && data.chunk.id || ''}"`;
				},
				renderAddModule: () => 'renderAddModuleSource();',
			};
		});

		it("binds five event handlers", function () {
			env.eventBindings.length.should.be.exactly(5);
		});

		describe("local-vars handler", function () {
			beforeEach(() => {
				env.eventBinding = env.eventBindings[0];
			});

			it("binds to local-vars event", () => {
				env.eventBinding.name.should.be.exactly("local-vars");
			});

			describe("when no chunks are provided", () => {
				beforeEach(() => {
					const chunk = createMockChunk();
					env.source = env.eventBinding.handler.call(env.handlerContext, "moduleSource()", chunk);
				});

				it("returns the original source", () => {
					env.source.should.be.exactly("moduleSource()")
				});
			});

			describe("when chunks are provided", () => {
				beforeEach(() => {
					const chunk = createMockChunk([1, 2, 3], [
						'foo',
						'bar',
						'baz'
					]);
					env.source = env.eventBinding.handler.call(env.handlerContext, "moduleSource()", chunk, 'abc123');
				});

				it("returns the original source with installed mapping", () => {
					env.source.should.be.exactly(`
moduleSource()

// object to store loaded chunks
// "1" means "already loaded"
var installedChunks = {
1: 1,
2: 1,
3: 1
};
`.trim())
				});
			});
		});

		describe("require-ensure handler", () => {
			beforeEach(() => {
				env.eventBinding = env.eventBindings[1];
			});

			it("binds to require-ensure event", () => {
				env.eventBinding.name.should.be.exactly("require-ensure");
			});

			describe("when called", () => {
				beforeEach(() => {
					const chunk = createMockChunk();
					env.source = env.eventBinding.handler.call(env.handlerContext, "moduleSource()", chunk, 'abc123');
				});

				it("creates import scripts call and promise resolve", () => {
					env.source.should.be.exactly(`
return new Promise(function(resolve) {
// "1" is the signal for "already loaded"
if(!installedChunks[chunkId]) {
importScripts("asset-path" + abc123 + "" + abc123 + "" + chunkId + "");
}
resolve();
});
`.trim())
				});
			});
		});

		describe("bootstrap handler", () => {
			beforeEach(() => {
				env.eventBinding = env.eventBindings[2];
			});

			it("binds to bootstrap event", () => {
				env.eventBinding.name.should.be.exactly("bootstrap");
			});

			describe("when no chunks are provided", () => {
				beforeEach(() => {
					const chunk = createMockChunk();
					env.source = env.eventBinding.handler.call(env.handlerContext, "moduleSource()", chunk);
				});

				it("returns the original source", () => {
					env.source.should.be.exactly("moduleSource()")
				});
			});

			describe("when chunks are provided", () => {
				beforeEach(() => {
					const chunk = createMockChunk([1, 2, 3], [
						'foo',
						'bar',
						'baz'
					]);
					env.source = env.eventBinding.handler.call(env.handlerContext, "moduleSource()", chunk);
				});

				it("returns the original source with chunk callback", () => {
					env.source.should.be.exactly(`
moduleSource()
this["webpackChunk"] = function webpackChunkCallback(chunkIds, moreModules) {
for(var moduleId in moreModules) {
renderAddModuleSource();
}
while(chunkIds.length)
installedChunks[chunkIds.pop()] = 1;
};
`.trim())
				});
			});
		});

		describe("hot-bootstrap handler", () => {
			beforeEach(() => {
				env.eventBinding = env.eventBindings[3];
			});

			it("binds to hot-bootstrap event", () => {
				env.eventBinding.name.should.be.exactly("hot-bootstrap");
			});

			describe("when called", () => {
				beforeEach(() => {
					const chunk = createMockChunk();
					env.source = env.eventBinding.handler.call(env.handlerContext, "moduleSource()", chunk, 'abc123');
				});

				it("returns the original source with hot update callback", () => {
					env.source.should.be.exactly(`
moduleSource()
var parentHotUpdateCallback = this["webpackHotUpdate"];
this["webpackHotUpdate"] = function webpackHotUpdateCallback(chunkId, moreModules) { // eslint-disable-line no-unused-vars
	hotAddUpdateChunk(chunkId, moreModules);
	if(parentHotUpdateCallback) parentHotUpdateCallback(chunkId, moreModules);
} ;

function hotDownloadUpdateChunk(chunkId) { // eslint-disable-line no-unused-vars
	importScripts(requireFn.p + "asset-path" + abc123 + "" + abc123 + "" + chunkId + "");
}

function hotDownloadManifest(requestTimeout) { // eslint-disable-line no-unused-vars
	requestTimeout = requestTimeout || 10000;
	return new Promise(function(resolve, reject) {
		if(typeof XMLHttpRequest === "undefined")
			return reject(new Error("No browser support"));
		try {
			var request = new XMLHttpRequest();
			var requestPath = requireFn.p + "asset-path" + abc123 + "" + abc123 + "";
			request.open("GET", requestPath, true);
			request.timeout = requestTimeout;
			request.send(null);
		} catch(err) {
			return reject(err);
		}
		request.onreadystatechange = function() {
			if(request.readyState !== 4) return;
			if(request.status === 0) {
				// timeout
				reject(new Error("Manifest request to " + requestPath + " timed out."));
			} else if(request.status === 404) {
				// no update available
				resolve();
			} else if(request.status !== 200 && request.status !== 304) {
				// other failure
				reject(new Error("Manifest request to " + requestPath + " failed."));
			} else {
				// success
				try {
					var update = JSON.parse(request.responseText);
				} catch(e) {
					reject(e);
					return;
				}
				resolve(update);
			}
		};
	});
}

function hotDisposeChunk(chunkId) { //eslint-disable-line no-unused-vars
	delete installedChunks[chunkId];
}
`.trim())
				});
			});
		});

		describe("hash handler", () => {
			beforeEach(() => {
				env.eventBinding = env.eventBindings[4];
				env.handlerContext = {
					outputOptions: {
						publicPath: "Alpha",
						filename: "Bravo",
						chunkFilename: "Charlie",
						chunkCallbackName: "Delta",
						library: "Echo"
					}
				};
				env.hashMock = {
					update: sinon.spy()
				};
				env.eventBinding.handler.call(env.handlerContext, env.hashMock);
			});

			it("binds to hash event", () => {
				env.eventBinding.name.should.be.exactly("hash");
			});

			it("updates hash object", () => {
				env.hashMock.update.callCount.should.be.exactly(7);
				sinon.assert.calledWith(env.hashMock.update, "webworker");
				sinon.assert.calledWith(env.hashMock.update, "3");
				sinon.assert.calledWith(env.hashMock.update, "Alpha");
				sinon.assert.calledWith(env.hashMock.update, "Bravo");
				sinon.assert.calledWith(env.hashMock.update, "Charlie");
				sinon.assert.calledWith(env.hashMock.update, "Delta");
				sinon.assert.calledWith(env.hashMock.update, "Echo");
			});
		});
	});
});
<|endoftext|>


<commit_before>
console.log('Updating package.json ...');

const fs = require('fs');
const path = require('path');
const prompt = require('prompt');

var packageJSON = JSON.parse(fs.readFileSync('package.json'));

// fields to delete
var delKeys = ['main', 'repository'];

delKeys.forEach(function(key) {
  delete packageJSON[key];
});

var promptVals = [
  {
    name: 'name',
    description: 'Project name',
    default: path.basename(process.cwd())
  },
  {
    name: 'author',
    description: 'Author',
  },
  {
    name: 'description',
    description: 'Description'
  },
  {
    name: 'version',
    description: 'Version',
    default: '1.0.0'
  },
  {
    name: 'license',
    description: 'License',
    default: 'MIT'
  }
];

function setKeys() {
  prompt.start();
  prompt.get(promptVals, function(err, result) {
    if (err) {
      console.log('Aborting...');
    }
    Object.keys(result).forEach(function(key) {
      packageJSON[key] = result[key];
    });
    fs.writeFileSync('package.json', JSON.stringify(packageJSON, null, 2));
    console.log('package.json written.');
  });
}

setKeys();
<commit_msg>Changed prompt message<commit_after>
console.log('Updating package.json ...');

const fs = require('fs');
const path = require('path');
const prompt = require('prompt');
prompt.message = '';

var packageJSON = JSON.parse(fs.readFileSync('package.json'));

// fields to delete
var delKeys = ['main', 'repository'];

delKeys.forEach(function(key) {
  delete packageJSON[key];
});

var promptVals = [
  {
    name: 'name',
    description: 'Project name',
    default: path.basename(process.cwd())
  },
  {
    name: 'author',
    description: 'Author',
  },
  {
    name: 'description',
    description: 'Description'
  },
  {
    name: 'version',
    description: 'Version',
    default: '1.0.0'
  },
  {
    name: 'license',
    description: 'License',
    default: 'MIT'
  }
];

function setKeys() {
  prompt.start();
  prompt.get(promptVals, function(err, result) {
    if (err) {
      console.log('Aborting...');
    }
    Object.keys(result).forEach(function(key) {
      packageJSON[key] = result[key];
    });
    fs.writeFileSync('package.json', JSON.stringify(packageJSON, null, 2));
    console.log('package.json written.');
  });
}

setKeys();
<|endoftext|>


<commit_before>import React from 'react';
import {NavigationMotion} from 'navigation-react-mobile';

export default ({stateNavigator}) => (
  <NavigationMotion
    unmountedStyle={state => state.unmountedStyle}
    mountedStyle={state => state.mountedStyle}
    crumbStyle={state => state.crumbStyle}
    duration={1000}
    stateNavigator={stateNavigator}>
    {({translateX = 0, translateY = 0}, scene, key, active) => (
      <div key={key}
        className="scene"
        style={{
          overflow: active ? 'auto' : 'hidden',
          transform: `translate(${translateX * innerWidth}px, ${translateY * innerHeight}px)`
        }}>
        {scene}

    )}
  </NavigationMotion>
);
<commit_msg>Changed to client width and height<commit_after>import React from 'react';
import {NavigationMotion} from 'navigation-react-mobile';

export default ({stateNavigator}) => (
  <NavigationMotion
    unmountedStyle={state => state.unmountedStyle}
    mountedStyle={state => state.mountedStyle}
    crumbStyle={state => state.crumbStyle}
    duration={1000}
    stateNavigator={stateNavigator}>
    {({translateX = 0, translateY = 0}, scene, key, active) => {
      var {clientWidth, clientHeight} = document.documentElement;
      return <div key={key}
        className="scene"
        style={{
          overflow: active ? 'auto' : 'hidden',
          transform: `translate(${translateX * clientWidth}px, ${translateY * clientHeight}px)`
        }}>
        {scene}

    }}
  </NavigationMotion>
);
<|endoftext|>


<commit_before>// Avoid `console` errors in browsers that lack a console.
(function() {
	var method;
	var noop = function() {};
	var methods = [
		'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
		'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
		'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
		'timeline', 'timelineEnd', 'timeStamp', 'trace', 'warn'
	];
	var length = methods.length;
	var console = (window.console = window.console || {});

	while (length--) {
		method = methods[length];

		// Only stub undefined methods.
		if (!console[method]) {
			console[method] = noop;
		}
	}
}());

(function () {
	"use strict";

	var Accordion = function(node, options) {
		var defaults = {
			fold : false
		};
		this.options = $.extend({}, defaults, options);
		this.$node = $(node);
		this.init();
		this.events();
	};

	Accordion.prototype.init = function() {
		var _this = this;

		_this.resize();
	};

	Accordion.prototype.events = function() {
		var _this = this;

		_this.$node.find('.acc-switch').on('click', function() {
			var $trigger = $(this),
				$item = $trigger.parents('.acc');

			$item.toggleClass('open');
			if ($item.hasClass('open')) {
				var $content = $item.find('.acc-content');

				if ($trigger.hasClass('loaded')) {
					$content.height(_this.setHeight($(this)));
				} else {
					var url = $trigger.attr('data-url');

					$content.load(url, function(){
						$content.height(_this.setHeight($(this)));
						$trigger.addClass('loaded');
					});
				}
			} else {
				$item.find('.acc-content').height(0);
			}

			if (_this.options.fold) {
				var $siblings = _this.$node.find('.acc-switch').not(this);
				$siblings.each(function() {
					$item.removeClass('open');
					$item.find('.acc-content').height(0);
				});
			}

			return false;
		});

		_this.$node.find('.acc-open-all').on('click', function() {
			_this.$node.find('.acc')
				.addClass('open')
				.each(function(){
					var $item = $(this);
					$item.find('.acc-content').height(_this.setHeight($item.find('.acc-switch')));
				});

			return false;
		});

		$(window).on('resize', function() {
			_this.resize();
		});
	};

	Accordion.prototype.resize = function() {
		var _this = this;

		_this.$node.find('.acc.open > a').each(function() {
			$(this).parents('.acc').find('.acc-content').height(_this.setHeight($(this)));
		});
	};

	Accordion.prototype.setHeight = function($node) {
		var h = 0;
		$node.parents('.acc').find('.acc-content').children().each(function() {
			h += $(this).outerHeight(true);
		});
		return h;
	};

	$.fn.accordion = function(options) {
		return $(this).each(function(){
			new Accordion(this, options);
		});
	};

})();

(function ( $, window, document, undefined ) {

	var defaults = {
		url: 'data/genome-data.json',
		counterText: 'Showing %1 to %2 of %3 entries'
	};

	function Genome( element, options ) {
		this.options = $.extend( {}, defaults, options) ;
		this._defaults = defaults;
		this.el = element;
		this.$el = $(element);

		this.init();
	}

	Genome.prototype.init = function () {
		var _this = this;

		_this.pagination = {
			$el: $(_this.options.pagination)
		};
		_this.$labels = $(_this.options.labels);
		_this.$tags = $(_this.options.tags);
		_this.$search = $(_this.options.search);
		_this.$counter = $(_this.options.counter);
		_this.$perPage = $(_this.options.perPage);
		_this.$sort = $(_this.options.sort);
		_this.scrollOffset = $('.navbar-fixed-top').outerHeight() + 10;

		_this.page = 0;
		_this.perPage = _this.$perPage.val();

		_this.filters = {
			excludeLabel: [],
			excludeTag: [],
			keyword: ''
		};

		$.getJSON(_this.options.url, function(data) {
			if (data) {
				_this.data = data.data;
				_this.buildList();
			}
		});

		_this.$labels.on('click', '.label', function(){
			var $this = $(this);

			$this.toggleClass('off');
			_this.filters.excludeLabel = updateArray($this.data('val'), _this.filters.excludeLabel, $this.hasClass('off'));

			_this.buildList();
		});

		_this.$tags.on('click', '.label', function(){
			var $this = $(this);

			$this.toggleClass('off');
			_this.filters.excludeTag = updateArray($this.data('val'), _this.filters.excludeTag, $this.hasClass('off'));

			_this.buildList();
		});

		_this.$search.on('keyup', function(){
			var $this = $(this);

			_this.filters.keyword = $(this).val();

			_this.buildList();
		});

		_this.pagination.$el
			.on('click', 'li', function(e) {
				e.preventDefault();
				var $this = $(this);

				if ($this.hasClass('disabled'))
					return false;

				if ($this.hasClass('prev')) {
					_this.page--;
				} else if ($this.hasClass('next')){
					_this.page++;
				} else {
					_this.page = $(this).data('page');
				}

				_this.updateList();
				_this.updatePagination();
				_this.updateCounter();
			});

		_this.$perPage.on('change', function(){
			_this.perPage = _this.$perPage.val();
			_this.page = 0;
			_this.updateList();
			_this.buildPagination();
			_this.updateCounter();
		});

		_this.$sort.on('change', function(){
			_this.page = 0;
			_this.sort(this.value, $(this).find(':selected').data('type'));
			_this.buildList();
			_this.updatePagination();
			_this.updateCounter();
		});
	};

	var updateArray = function(value, array, isAdd) {
		if (isAdd) {
			array.push(value);
		} else {
			var i = $.inArray(value, array);
			array.splice(i, 1);
		}

		return array;
	};

	var isMatch = function(keyword, item) {
		var escapedKeyword = keyword.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'),
			regex = new RegExp(escapedKeyword, 'i');
		return ((keyword === '') ||
		item.disease_trait && item.disease_trait.match(regex) ||
		item.rsid && item.rsid.match(regex) ||
		item.chromosome_position && item.chromosome_position.match(regex) ||
		item.risk_allele && item.risk_allele.match(regex) ||
		item.genotype && item.genotype.match(regex) ||
		item.p_value && String(item.p_value).match(regex) ||
		item.or_or_beta && String(item.or_or_beta).match(regex) ||
		item.risk && String(item.risk).match(regex) ||
		item.tags && item.tags.join(' ').match(regex)
		);
	};

	var anyInArray = function(needles, haystack) {
		var any = false;

		if (needles.length === 0 || haystack.length === 0) return true;

		for (var i = 0, n = needles.length; i < n; i++) {
			var needle = needles[i];
			any = any || $.inArray(needle, haystack) === -1;
		}

		return any;
	};

	Genome.prototype.buildList = function() {
		var _this = this;
		var html = '';

		_this.total = 0;

		for (var i in _this.data) {
			if (_this.data.hasOwnProperty(i)) {
				var item = _this.data[i];

				if ($.inArray(item.color, _this.filters.excludeLabel) === -1 &&
					(!item.tags || anyInArray(item.tags, _this.filters.excludeTag)) &&
					isMatch(_this.filters.keyword, item)
				) {
					html += '
= _this.perPage ? ' off-page' : '') + '">' +
					'
' +
					'
' +
					'
disease trait
' +
					' ' + item.disease_trait + '
' +
					'
' +
					'

rsid
' + (item.rsid ? item.rsid : '') + '
' +
					'

chromosome position
' + (item.chromosome_position ? item.chromosome_position : '') + '
' +
					'

risk allele
' + (item.risk_allele ? item.risk_allele : '') + '
' +
					'

genotype
' + (item.genotype ? item.genotype : '') + '
' +
					'

p value
' + (item.p_value ? item.p_value : '') + '
' +
					'

or
' + (item.or_or_beta ? item.or_or_beta : '') + '
' +
					'

risk
' + (item.risk ? item.risk : '') + '
' +
					'

tags
' + (item.tags ? item.tags.join(', ') : '') + '
' +
					'
more less
'+
					'
' +
					'
' +
					'

'
					+ '
';

					_this.total++;
				}
			}
		}

		_this.$el
			.html(html)
			.accordion();

		_this.page = 0;

		_this.$items = _this.$el.find('.acc');
		_this.$visible = _this.$items.not('.hidden');

		_this.updateCounter();
		_this.buildPagination();
	};

	Genome.prototype.buildPagination = function() {
		var _this = this,
			html = '
Previous
';

		_this.maxPage = Math.ceil(_this.total / _this.perPage);

		for (var i = 0; i < _this.maxPage; i++) {
			html += '
'+ (i+1) +'
';
		}

		html += '
Next
';

		_this.pagination.$el.html(html);
		_this.pagination.$prev = _this.pagination.$el.find('.prev');
		_this.pagination.$next = _this.pagination.$el.find('.next');
	};

	Genome.prototype.updateList = function() {
		var _this = this;

		_this.$items.addClass('off-page')
			.slice(_this.page * _this.perPage, (_this.page+1) * _this.perPage).removeClass('off-page');

		$('html, body').animate({
			scrollTop: _this.$el.offset().top - _this.scrollOffset
		}, 300);
	};

	Genome.prototype.updatePagination = function() {
		var _this = this;

		_this.pagination.$el.find('.active').removeClass('active');
		_this.pagination.$el.find('.page-'+ _this.page).addClass('active');

		_this.pagination.$prev.toggleClass('disabled', _this.page == 0);
		_this.pagination.$next.toggleClass('disabled', _this.page == _this.maxPage-1);
	};

	Genome.prototype.updateCounter = function() {
		var _this = this,
			text = _this.options.counterText;

		text = text.replace('%1', _this.page * _this.perPage + 1);
		text = text.replace('%2', Math.min((_this.page+1) * _this.perPage, _this.total));
		text = text.replace('%3', _this.$visible.length);

		_this.$counter.html(text);
	};

	Genome.prototype.sort = function(field, type) {
		var compare;

		switch(type) {
			case 'string': compare = compareStrings(field); break;
			case 'number': compare = compareNumbers(field); break;
			case 'array': compare = compareArrays(field); break;
			default: break;
		}

		this.data.sort(compare);
	};

	var compareNumbers = function(field){
		return function(a, b){
			return a[field] - b[field];
		}
	};

	var compareStrings = function(field) {
		return function(a, b) {
			var valueA = a[field].replace(/<.+?>/g, '').replace(/^\s*/g, '').toUpperCase(),
				valueB = b[field].replace(/<.+?>/g, '').replace(/^\s*/g, '').toUpperCase();

			if (valueA < valueB) {
				return -1;
			}
			if (valueA > valueB) {
				return 1;
			}
			return 0;
		}
	};

	var compareArrays = function(field){
		return function(a, b){
			var arrA = a[field] ? a[field].join() : '',
				arrB = b[field] ? b[field].join() : '';

			if (arrA < arrB) {
				return -1;
			}
			if (arrA > arrB) {
				return 1;
			}
			return 0;
		}
	};

	$.fn.genome = function(options) {
		return $(this).each(function(){
			new Genome(this, options);
		});
	};

})( jQuery, window, document );<commit_msg>genome - details<commit_after>// Avoid `console` errors in browsers that lack a console.
(function() {
	var method;
	var noop = function() {};
	var methods = [
		'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
		'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
		'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
		'timeline', 'timelineEnd', 'timeStamp', 'trace', 'warn'
	];
	var length = methods.length;
	var console = (window.console = window.console || {});

	while (length--) {
		method = methods[length];

		// Only stub undefined methods.
		if (!console[method]) {
			console[method] = noop;
		}
	}
}());

(function () {
	"use strict";

	var Accordion = function(node, options) {
		var defaults = {
			fold : false
		};
		this.options = $.extend({}, defaults, options);
		this.$node = $(node);
		this.init();
		this.events();
	};

	Accordion.prototype.init = function() {
		var _this = this;

		_this.resize();
	};

	Accordion.prototype.events = function() {
		var _this = this;

		_this.$node.find('.acc-switch').on('click', function() {
			var $trigger = $(this),
				$item = $trigger.parents('.acc');

			$item.toggleClass('open');
			if ($item.hasClass('open')) {
				var $content = $item.find('.acc-content');

				if ($trigger.hasClass('loaded')) {
					$content.height(_this.setHeight($(this)));
				} else {
					var url = $trigger.attr('data-url');

					$content.load(url, function(){
						$content.height(_this.setHeight($(this)));
						$trigger.addClass('loaded');
					});
				}
			} else {
				$item.find('.acc-content').height(0);
			}

			if (_this.options.fold) {
				var $siblings = _this.$node.find('.acc-switch').not(this);
				$siblings.each(function() {
					$item.removeClass('open');
					$item.find('.acc-content').height(0);
				});
			}

			return false;
		});

		_this.$node.find('.acc-open-all').on('click', function() {
			_this.$node.find('.acc')
				.addClass('open')
				.each(function(){
					var $item = $(this);
					$item.find('.acc-content').height(_this.setHeight($item.find('.acc-switch')));
				});

			return false;
		});

		$(window).on('resize', function() {
			_this.resize();
		});
	};

	Accordion.prototype.resize = function() {
		var _this = this;

		_this.$node.find('.acc.open > a').each(function() {
			$(this).parents('.acc').find('.acc-content').height(_this.setHeight($(this)));
		});
	};

	Accordion.prototype.setHeight = function($node) {
		var h = 0;
		$node.parents('.acc').find('.acc-content').children().each(function() {
			h += $(this).outerHeight(true);
		});
		return h;
	};

	$.fn.accordion = function(options) {
		return $(this).each(function(){
			new Accordion(this, options);
		});
	};

})();

(function ( $, window, document, undefined ) {

	var defaults = {
		url: 'data/genome-data.json',
		counterText: 'Showing %1 to %2 of %3 entries'
	};

	function Genome( element, options ) {
		this.options = $.extend( {}, defaults, options) ;
		this._defaults = defaults;
		this.el = element;
		this.$el = $(element);

		this.init();
	}

	Genome.prototype.init = function () {
		var _this = this;

		_this.pagination = {
			$el: $(_this.options.pagination)
		};
		_this.$labels = $(_this.options.labels);
		_this.$tags = $(_this.options.tags);
		_this.$search = $(_this.options.search);
		_this.$counter = $(_this.options.counter);
		_this.$perPage = $(_this.options.perPage);
		_this.$sort = $(_this.options.sort);
		_this.scrollOffset = $('.navbar-fixed-top').outerHeight() + 10;

		_this.page = 0;
		_this.perPage = _this.$perPage.val();

		_this.filters = {
			excludeLabel: [],
			excludeTag: [],
			keyword: ''
		};

		$.getJSON(_this.options.url, function(data) {
			if (data) {
				_this.data = data.data;
				_this.buildList();
			}
		});

		_this.$labels.on('click', '.label', function(){
			var $this = $(this);

			$this.toggleClass('off');
			_this.filters.excludeLabel = updateArray($this.data('val'), _this.filters.excludeLabel, $this.hasClass('off'));

			_this.buildList();
		});

		_this.$tags.on('click', '.label', function(){
			var $this = $(this);

			$this.toggleClass('off');
			_this.filters.excludeTag = updateArray($this.data('val'), _this.filters.excludeTag, $this.hasClass('off'));

			_this.buildList();
		});

		_this.$search.on('keyup', function(){
			var $this = $(this);

			_this.filters.keyword = $(this).val();

			_this.buildList();
		});

		_this.pagination.$el
			.on('click', 'li', function(e) {
				e.preventDefault();
				var $this = $(this);

				if ($this.hasClass('disabled'))
					return false;

				if ($this.hasClass('prev')) {
					_this.page--;
				} else if ($this.hasClass('next')){
					_this.page++;
				} else {
					_this.page = $(this).data('page');
				}

				_this.updateList();
				_this.updatePagination();
				_this.updateCounter();
			});

		_this.$perPage.on('change', function(){
			_this.perPage = _this.$perPage.val();
			_this.page = 0;
			_this.updateList();
			_this.buildPagination();
			_this.updateCounter();
		});

		_this.$sort.on('change', function(){
			_this.page = 0;
			_this.sort(this.value, $(this).find(':selected').data('type'));
			_this.buildList();
			_this.updatePagination();
			_this.updateCounter();
		});
	};

	var updateArray = function(value, array, isAdd) {
		if (isAdd) {
			array.push(value);
		} else {
			var i = $.inArray(value, array);
			array.splice(i, 1);
		}

		return array;
	};

	var isMatch = function(keyword, item) {
		var escapedKeyword = keyword.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'),
			regex = new RegExp(escapedKeyword, 'i');
		return ((keyword === '') ||
		item.disease_trait && item.disease_trait.match(regex) ||
		item.rsid && item.rsid.match(regex) ||
		item.chromosome_position && item.chromosome_position.match(regex) ||
		item.risk_allele && item.risk_allele.match(regex) ||
		item.genotype && item.genotype.match(regex) ||
		item.p_value && String(item.p_value).match(regex) ||
		item.or_or_beta && String(item.or_or_beta).match(regex) ||
		item.risk && String(item.risk).match(regex) ||
		item.tags && item.tags.join(' ').match(regex)
		);
	};

	var anyInArray = function(needles, haystack) {
		var any = false;

		if (needles.length === 0 || haystack.length === 0) return true;

		for (var i = 0, n = needles.length; i < n; i++) {
			var needle = needles[i];
			any = any || $.inArray(needle, haystack) === -1;
		}

		return any;
	};

	Genome.prototype.buildList = function() {
		var _this = this;
		var html = '';

		_this.total = 0;

		for (var i in _this.data) {
			if (_this.data.hasOwnProperty(i)) {
				var item = _this.data[i];

				if ($.inArray(item.color, _this.filters.excludeLabel) === -1 &&
					(!item.tags || anyInArray(item.tags, _this.filters.excludeTag)) &&
					isMatch(_this.filters.keyword, item)
				) {
					html += '
= _this.perPage ? ' off-page' : '') + '">' +
					'
' +
					'
' +
					'
disease trait
' +
					' ' + item.disease_trait + '
' +
					'
' +
					'

rsid
' + (item.rsid ? item.rsid : '') + '
' +
					'

chromosome position
' + (item.chromosome_position ? item.chromosome_position : '') + '
' +
					'

risk allele
' + (item.risk_allele ? item.risk_allele : '') + '
' +
					'

genotype
' + (item.genotype ? item.genotype : '') + '
' +
					'

p value
' + (item.p_value ? item.p_value : '') + '
' +
					'

or
' + (item.or_or_beta ? item.or_or_beta : '') + '
' +
					'

risk
' + (item.risk ? item.risk : '') + '
' +
					'

tags
' + (item.tags ? item.tags.join(', ') : '') + '
' +
					'
more less
'+
					'
' +
					'
' +
					'

'
					+ '
';

					_this.total++;
				}
			}
		}

		_this.$el
			.html(html)
			.accordion();

		_this.page = 0;

		_this.$items = _this.$el.find('.acc');
		_this.$visible = _this.$items.not('.hidden');

		_this.updateCounter();
		_this.buildPagination();
	};

	Genome.prototype.buildPagination = function() {
		var _this = this,
			html = '
Previous
';

		_this.maxPage = Math.ceil(_this.total / _this.perPage);

		for (var i = 0; i < _this.maxPage; i++) {
			html += '
'+ (i+1) +'
';
		}

		html += '
Next
';

		_this.pagination.$el.html(html);
		_this.pagination.$prev = _this.pagination.$el.find('.prev');
		_this.pagination.$next = _this.pagination.$el.find('.next');
	};

	Genome.prototype.updateList = function() {
		var _this = this;

		_this.$items.addClass('off-page')
			.slice(_this.page * _this.perPage, (_this.page+1) * _this.perPage).removeClass('off-page');

		$('html, body').animate({
			scrollTop: _this.$el.offset().top - _this.scrollOffset
		}, 300);
	};

	Genome.prototype.updatePagination = function() {
		var _this = this;

		_this.pagination.$el.find('.active').removeClass('active');
		_this.pagination.$el.find('.page-'+ _this.page).addClass('active');

		_this.pagination.$prev.toggleClass('disabled', _this.page == 0);
		_this.pagination.$next.toggleClass('disabled', _this.page == _this.maxPage-1);
	};

	Genome.prototype.updateCounter = function() {
		var _this = this,
			text = _this.options.counterText;

		text = text.replace('%1', _this.page * _this.perPage + 1);
		text = text.replace('%2', Math.min((_this.page+1) * _this.perPage, _this.total));
		text = text.replace('%3', _this.$visible.length);

		_this.$counter.html(text);
	};

	Genome.prototype.sort = function(field, type) {
		var compare;

		switch(type) {
			case 'string': compare = compareStrings(field); break;
			case 'number': compare = compareNumbers(field); break;
			case 'array': compare = compareArrays(field); break;
			default: break;
		}

		this.data.sort(compare);
	};

	var compareNumbers = function(field){
		return function(a, b){
			return a[field] - b[field];
		}
	};

	var compareStrings = function(field) {
		return function(a, b) {
			var valueA = a[field].replace(/<.+?>/g, '').replace(/^\s*/g, '').toUpperCase(),
				valueB = b[field].replace(/<.+?>/g, '').replace(/^\s*/g, '').toUpperCase();

			if (valueA < valueB) {
				return -1;
			}
			if (valueA > valueB) {
				return 1;
			}
			return 0;
		}
	};

	var compareArrays = function(field){
		return function(a, b){
			var arrA = a[field] ? a[field].join() : '',
				arrB = b[field] ? b[field].join() : '';

			if (arrA < arrB) {
				return -1;
			}
			if (arrA > arrB) {
				return 1;
			}
			return 0;
		}
	};

	$.fn.genome = function(options) {
		return $(this).each(function(){
			new Genome(this, options);
		});
	};

})( jQuery, window, document );<|endoftext|>


<commit_before>'use strict';

const webdriver = require('selenium-webdriver');
const chrome = require('selenium-webdriver/chrome');
const proxy = require('selenium-webdriver/proxy');
const pick = require('lodash.pick');
const isEmpty = require('lodash.isempty');
const chromedriver = require('alto-saxophone').chromedriver;
const log = require('intel').getLogger('browsertime.chrome');
const get = require('lodash.get');
const path = require('path');
const defaultChromeOptions = require('./chromeOptions');
const getViewPort = require('../../support/getViewPort');

let hasConfiguredChromeDriverService = false;
const timelineTraceCategories = '-*,devtools.timeline';

/**
 * Configure a WebDriver builder based on the specified options.
 * @param builder
 * @param {Object} options the options for a web driver.
 */
module.exports.configureBuilder = function(builder, baseDir, options) {
  const chromeConfig = options.chrome || {};
  const moduleRootPath = path.resolve(__dirname, '..', '..', '..');

  if (!hasConfiguredChromeDriverService) {
    const chromedriverPath = get(
      chromeConfig,
      'chromedriverPath',
      chromedriver.binPath()
    );

    let serviceBuilder = new chrome.ServiceBuilder(chromedriverPath);
    if (options.verbose >= 2) {
      serviceBuilder.loggingTo(`${baseDir}/chromedriver.log`);
      if (options.verbose >= 3) serviceBuilder.enableVerboseLogging();
    }
    chrome.setDefaultService(serviceBuilder.build());

    hasConfiguredChromeDriverService = true;
  }

  let logPrefs = new webdriver.logging.Preferences();
  logPrefs.setLevel(
    webdriver.logging.Type.PERFORMANCE,
    webdriver.logging.Level.ALL
  );

  if (chromeConfig.collectConsoleLog) {
    logPrefs.setLevel(
      webdriver.logging.Type.BROWSER,
      webdriver.logging.Level.ALL
    );
  }

  let chromeOptions = new chrome.Options();

  const proxySettings = pick(options.proxy, ['http', 'https']);

  if (!isEmpty(proxySettings)) {
    chromeOptions.setProxy(proxy.manual(proxySettings));
  }

  chromeOptions.setLoggingPrefs(logPrefs);

  if (options.headless) {
    chromeOptions.headless();
  }

  // If we run in Docker we need to always use no-sandbox
  if (options.docker) {
    chromeOptions.addArguments('--no-sandbox');
  }
  const viewPort = getViewPort(options);
  // If viewport is defined (only on desktop) then set start args
  if (viewPort) {
    chromeOptions.addArguments('--window-position=0,0');
    chromeOptions.addArguments('--window-size=' + viewPort.replace('x', ','));
  }

  const perfLogConf = { enableNetwork: true, enablePage: true };

  if (chromeConfig.traceCategories || chromeConfig.timeline) {
    // Trace categories always wins
    perfLogConf.traceCategories = chromeConfig.traceCategories
      ? chromeConfig.traceCategories
      : timelineTraceCategories;
    if (chromeConfig.traceCategories) {
      log.info('Use Chrome trace categories: %s', chromeConfig.traceCategories);
    }
  }

  // headless mode doesn't work with extensions
  if (!chromeConfig.disableWebExtensions && !options.headless) {
    chromeOptions.addExtensions(
      path.resolve(moduleRootPath, 'vendor', 'browsertime-extension.crx')
    );
  }

  if (options.extension) {
    const extensions = !Array.isArray(options.extension)
      ? [options.extension]
      : options.extension;
    for (const extension of extensions) {
      chromeOptions.addExtensions(extension);
    }
  }

  chromeOptions.setPerfLoggingPrefs(perfLogConf);

  if (options.userAgent) {
    chromeOptions.addArguments('--user-agent=' + options.userAgent);
  }

  if (chromeConfig.collectNetLog) {
    // FIXME this shouldn't hard code path to external storage
    const dir = !chromeConfig.android ? baseDir : '/sdcard';
    chromeOptions.addArguments(`--log-net-log=${dir}/chromeNetlog.json`);
    chromeOptions.addArguments('--net-log-capture-mode=0');
  }

  chromeOptions.addArguments(defaultChromeOptions);

  if (chromeConfig.args) {
    chromeOptions.addArguments(chromeConfig.args);
  }

  if (chromeConfig.binaryPath) {
    chromeOptions.setChromeBinaryPath(chromeConfig.binaryPath);
  }

  if (chromeConfig.mobileEmulation) {
    chromeOptions.setMobileEmulation(chromeConfig.mobileEmulation);
  }

  const android = chromeConfig.android;
  if (android) {
    if (android.package) {
      chromeOptions.androidPackage(android.package);
    } else {
      chromeOptions.androidChrome();
    }
    chromeOptions.androidDeviceSerial(android.deviceSerial);
  }

  builder
    .getCapabilities()
    .set('pageLoadStrategy', get(options, 'pageLoadStrategy', 'normal'));

  builder.setChromeOptions(chromeOptions);
};
<commit_msg>disable gpu with xvfb (#659)<commit_after>'use strict';

const webdriver = require('selenium-webdriver');
const chrome = require('selenium-webdriver/chrome');
const proxy = require('selenium-webdriver/proxy');
const pick = require('lodash.pick');
const isEmpty = require('lodash.isempty');
const chromedriver = require('alto-saxophone').chromedriver;
const log = require('intel').getLogger('browsertime.chrome');
const get = require('lodash.get');
const path = require('path');
const defaultChromeOptions = require('./chromeOptions');
const getViewPort = require('../../support/getViewPort');

let hasConfiguredChromeDriverService = false;
const timelineTraceCategories = '-*,devtools.timeline';

/**
 * Configure a WebDriver builder based on the specified options.
 * @param builder
 * @param {Object} options the options for a web driver.
 */
module.exports.configureBuilder = function(builder, baseDir, options) {
  const chromeConfig = options.chrome || {};
  const moduleRootPath = path.resolve(__dirname, '..', '..', '..');

  if (!hasConfiguredChromeDriverService) {
    const chromedriverPath = get(
      chromeConfig,
      'chromedriverPath',
      chromedriver.binPath()
    );

    let serviceBuilder = new chrome.ServiceBuilder(chromedriverPath);
    if (options.verbose >= 2) {
      serviceBuilder.loggingTo(`${baseDir}/chromedriver.log`);
      if (options.verbose >= 3) serviceBuilder.enableVerboseLogging();
    }
    chrome.setDefaultService(serviceBuilder.build());

    hasConfiguredChromeDriverService = true;
  }

  let logPrefs = new webdriver.logging.Preferences();
  logPrefs.setLevel(
    webdriver.logging.Type.PERFORMANCE,
    webdriver.logging.Level.ALL
  );

  if (chromeConfig.collectConsoleLog) {
    logPrefs.setLevel(
      webdriver.logging.Type.BROWSER,
      webdriver.logging.Level.ALL
    );
  }

  let chromeOptions = new chrome.Options();

  const proxySettings = pick(options.proxy, ['http', 'https']);

  if (!isEmpty(proxySettings)) {
    chromeOptions.setProxy(proxy.manual(proxySettings));
  }

  chromeOptions.setLoggingPrefs(logPrefs);

  if (options.headless) {
    chromeOptions.headless();
  }

  // If we run in Docker we need to always use no-sandbox
  if (options.docker) {
    chromeOptions.addArguments('--no-sandbox');
  }

  if (options.xvfb) {
    chromeOptions.addArguments('--disable-gpu');
  }

  const viewPort = getViewPort(options);
  // If viewport is defined (only on desktop) then set start args
  if (viewPort) {
    chromeOptions.addArguments('--window-position=0,0');
    chromeOptions.addArguments('--window-size=' + viewPort.replace('x', ','));
  }

  const perfLogConf = { enableNetwork: true, enablePage: true };

  if (chromeConfig.traceCategories || chromeConfig.timeline) {
    // Trace categories always wins
    perfLogConf.traceCategories = chromeConfig.traceCategories
      ? chromeConfig.traceCategories
      : timelineTraceCategories;
    if (chromeConfig.traceCategories) {
      log.info('Use Chrome trace categories: %s', chromeConfig.traceCategories);
    }
  }

  // headless mode doesn't work with extensions
  if (!chromeConfig.disableWebExtensions && !options.headless) {
    chromeOptions.addExtensions(
      path.resolve(moduleRootPath, 'vendor', 'browsertime-extension.crx')
    );
  }

  if (options.extension) {
    const extensions = !Array.isArray(options.extension)
      ? [options.extension]
      : options.extension;
    for (const extension of extensions) {
      chromeOptions.addExtensions(extension);
    }
  }

  chromeOptions.setPerfLoggingPrefs(perfLogConf);

  if (options.userAgent) {
    chromeOptions.addArguments('--user-agent=' + options.userAgent);
  }

  if (chromeConfig.collectNetLog) {
    // FIXME this shouldn't hard code path to external storage
    const dir = !chromeConfig.android ? baseDir : '/sdcard';
    chromeOptions.addArguments(`--log-net-log=${dir}/chromeNetlog.json`);
    chromeOptions.addArguments('--net-log-capture-mode=0');
  }

  chromeOptions.addArguments(defaultChromeOptions);

  if (chromeConfig.args) {
    chromeOptions.addArguments(chromeConfig.args);
  }

  if (chromeConfig.binaryPath) {
    chromeOptions.setChromeBinaryPath(chromeConfig.binaryPath);
  }

  if (chromeConfig.mobileEmulation) {
    chromeOptions.setMobileEmulation(chromeConfig.mobileEmulation);
  }

  const android = chromeConfig.android;
  if (android) {
    if (android.package) {
      chromeOptions.androidPackage(android.package);
    } else {
      chromeOptions.androidChrome();
    }
    chromeOptions.androidDeviceSerial(android.deviceSerial);
  }

  builder
    .getCapabilities()
    .set('pageLoadStrategy', get(options, 'pageLoadStrategy', 'normal'));

  builder.setChromeOptions(chromeOptions);
};
<|endoftext|>


<commit_before>window.ParsleyConfig = window.ParsleyConfig || {};

(function ($) {
  window.ParsleyConfig = $.extend( true, {}, window.ParsleyConfig, {
    messages: {
      // parsley //////////////////////////////////////
        defaultMessage: "Поле заполнено некорректно."
      , type: {
            email:      "Поле должно быть адресом электронной почты."
          , url:        "Поле должно быть ссылкой на сайт."
          , urlstrict:  "Поле должно быть ссылкой на сайт."
          , number:     "Поле должно быть числом."
          , digits:     "Поле должно содержать только цифры."
          , dateIso:    "Поле должно быть датой в формате (ГГГГ-ММ-ДД)."
          , alphanum:   "Поле должно содержать только  цифры и буквы"
        }
      , notnull:        "Поле должно быть не нулевым."
      , notblank:       "Поле не должно быть пустым."
      , required:       "Поле обязательно для заполнения."
      , regexp:         "Поле заполнено некорректно."
      , min:            "Значение поля должно быть больше %s."
      , max:            "Значение поля должно быть меньше %s."
      , range:          "Значение поля должно быть между %s и %s."
      , minlength:      "В поле должно быть минимум %s символов."
      , maxlength:      "В поле должно быть не больше %s символов."
      , rangelength:    "В поле должно быть от %s до %s символов."
      , equalto:        "Значения полей должны быть одинаковыми."

      // parsley.extend ///////////////////////////////
    }
  });
}(window.jQuery || window.Zepto));
<commit_msg>verbal case<commit_after>window.ParsleyConfig = window.ParsleyConfig || {};

(function ($) {
  window.ParsleyConfig = $.extend( true, {}, window.ParsleyConfig, {
    messages: {
      // parsley //////////////////////////////////////
        defaultMessage: "Поле заполнено некорректно."
      , type: {
            email:      "Поле должно быть адресом электронной почты."
          , url:        "Поле должно быть ссылкой на сайт."
          , urlstrict:  "Поле должно быть ссылкой на сайт."
          , number:     "Поле должно быть числом."
          , digits:     "Поле должно содержать только цифры."
          , dateIso:    "Поле должно быть датой в формате (ГГГГ-ММ-ДД)."
          , alphanum:   "Поле должно содержать только  цифры и буквы"
        }
      , notnull:        "Поле должно быть не нулевым."
      , notblank:       "Поле не должно быть пустым."
      , required:       "Поле обязательно для заполнения."
      , regexp:         "Поле заполнено некорректно."
      , min:            "Значение поля должно быть больше %s."
      , max:            "Значение поля должно быть меньше %s."
      , range:          "Значение поля должно быть между %s и %s."
      , minlength:      "В поле должно быть минимум %s символов(а)."
      , maxlength:      "В поле должно быть не больше %s символов(а)."
      , rangelength:    "В поле должно быть от %s до %s символов(а)."
      , equalto:        "Значения полей должны быть одинаковыми."

      // parsley.extend ///////////////////////////////
    }
  });
}(window.jQuery || window.Zepto));
<|endoftext|>


<commit_before>(function() {
    'use strict';

    angular
        .module('<%=angularAppName%>')
        .controller('NavbarController', NavbarController);

    NavbarController.$inject = ['$location', '$state', 'Auth', 'Principal', 'ENV', 'LoginService'];

    function NavbarController ($location, $state, Auth, Principal, ENV, LoginService) {
        var vm = this;

        vm.isNavbarCollapsed = true;
        vm.isAuthenticated = Principal.isAuthenticated;
        vm.inProduction = ENV === 'prod';
        vm.login = login;
        vm.logout = logout;
        vm.toggleNavbar = toggleNavbar;
        vm.collapseNavbar = collapseNavbar;
        vm.$state = $state;

        function login () {
            collapseNavbar();
            LoginService.open();
        }

        function logout () {
            collapseNavbar();
            Auth.logout();
            $state.go('home');
        }

        function toggleNavbar () {
            vm.isNavbarCollapsed = !vm.isNavbarCollapsed;
        }

        function collapseNavbar () {
            vm.isNavbarCollapsed = true;
        }
    }
})();
<commit_msg>remove unused injection<commit_after>(function() {
    'use strict';

    angular
        .module('<%=angularAppName%>')
        .controller('NavbarController', NavbarController);

    NavbarController.$inject = ['$state', 'Auth', 'Principal', 'ENV', 'LoginService'];

    function NavbarController ($state, Auth, Principal, ENV, LoginService) {
        var vm = this;

        vm.isNavbarCollapsed = true;
        vm.isAuthenticated = Principal.isAuthenticated;
        vm.inProduction = ENV === 'prod';
        vm.login = login;
        vm.logout = logout;
        vm.toggleNavbar = toggleNavbar;
        vm.collapseNavbar = collapseNavbar;
        vm.$state = $state;

        function login () {
            collapseNavbar();
            LoginService.open();
        }

        function logout () {
            collapseNavbar();
            Auth.logout();
            $state.go('home');
        }

        function toggleNavbar () {
            vm.isNavbarCollapsed = !vm.isNavbarCollapsed;
        }

        function collapseNavbar () {
            vm.isNavbarCollapsed = true;
        }
    }
})();
<|endoftext|>


<commit_before>/**
 * @author mrdoob / http://mrdoob.com/
 */

var fs = require( 'fs' );

var srcFolder = '../examples/js/';
var dstFolder = '../examples/jsm/';

var files = [
	{ path: 'controls/OrbitControls.js', ignoreList: [] },
	{ path: 'controls/MapControls.js', ignoreList: [] },
	{ path: 'controls/TrackballControls.js', ignoreList: [] },
	// { path: 'controls/TransformControls.js', ignoreList: [] },
	{ path: 'exporters/GLTFExporter.js', ignoreList: [ 'AnimationClip', 'Camera', 'Geometry', 'Material', 'Mesh', 'Object3D', 'RGBFormat', 'Scenes', 'ShaderMaterial', 'VertexColors' ] },
	{ path: 'exporters/MMDExporter.js', ignoreList: [] },
	{ path: 'exporters/OBJExporter.js', ignoreList: [] },
	{ path: 'exporters/PLYExporter.js', ignoreList: [] },
	{ path: 'exporters/STLExporter.js', ignoreList: [] },
	{ path: 'exporters/TypedGeometryExporter.js', ignoreList: [] },
	{ path: 'loaders/GLTFLoader.js', ignoreList: [ 'NoSide', 'Matrix2', 'DDSLoader' ] },
	{ path: 'loaders/OBJLoader.js', ignoreList: [] },
	{ path: 'loaders/MTLLoader.js', ignoreList: [] }
];

for ( var i = 0; i < files.length; i ++ ) {

	var file = files[ i ];
	convert( file.path, file.ignoreList );

}

//

function convert( path, ignoreList ) {

	var contents = fs.readFileSync( srcFolder + path, 'utf8' );

	var className = '';
	var dependencies = {};

	// imports

	contents = contents.replace( /^\/\*+[^*]*\*+(?:[^/*][^*]*\*+)*\//, function ( match, p1 ) {

		return `${match}\n\n_IMPORTS_`;

	} );

	// class name

	contents = contents.replace( /THREE\.([a-zA-Z0-9]+) = /g, function ( match, p1 ) {

		className = p1;

		console.log( className );

		return `var ${p1} = `;

	} );

	contents = contents.replace( /(\'?)THREE\.([a-zA-Z0-9]+)(\.{0,1})/g, function ( match, p1, p2, p3 ) {

		if ( p1 === '\'' ) return match; // Inside a string
		if ( p2 === className ) return `${p2}${p3}`;

		if ( p1 === 'Math' ) {

			dependencies[ '_Math' ] = true;

			return '_Math.';

		}

		return match;

	} );

	// methods

	contents = contents.replace( /new THREE\.([a-zA-Z0-9]+)\(/g, function ( match, p1 ) {

		if ( ignoreList.includes( p1 ) ) return match;

		dependencies[ p1 ] = true;

		return `new ${p1}(`;

	} );

	// constants

	contents = contents.replace( /(\'?)THREE\.([a-zA-Z0-9]+)/g, function ( match, p1, p2 ) {

		if ( ignoreList.includes( p2 ) ) return match;
		if ( p1 === '\'' ) return match; // Inside a string
		if ( p2 === className ) return p2;

		if ( p2 === 'Math' || p2 === '_Math' ) {

			dependencies[ '_Math' ] = true;

			return '_Math';

		}

		dependencies[ p2 ] = true;

		// console.log( match, p2 );

		return `${p2}`;

	} );

	//

	var keys = Object.keys( dependencies )
		.filter( value => value !== className )
		.map( value => value === '_Math' ? 'Math as _Math' : value )
		.map( value => '\n\t' + value )
		.sort()
		.toString();
	var imports = `import {${keys}\n} from "../../../build/three.module.js";`;
	var exports = `export { ${className} };\n`;

	var output = contents.replace( '_IMPORTS_', keys ? imports : '' ) + '\n' + exports;

	// console.log( output );

	fs.writeFileSync( dstFolder + path, output, 'utf-8' );

};
<commit_msg>JSM: Clean up.<commit_after>/**
 * @author mrdoob / http://mrdoob.com/
 */

var fs = require( 'fs' );

var srcFolder = '../examples/js/';
var dstFolder = '../examples/jsm/';

var files = [
	{ path: 'controls/OrbitControls.js', ignoreList: [] },
	{ path: 'controls/MapControls.js', ignoreList: [] },
	{ path: 'controls/TrackballControls.js', ignoreList: [] },
	// { path: 'controls/TransformControls.js', ignoreList: [] },
	{ path: 'exporters/GLTFExporter.js', ignoreList: [ 'AnimationClip', 'Camera', 'Geometry', 'Material', 'Mesh', 'Object3D', 'RGBFormat', 'Scenes', 'ShaderMaterial', 'VertexColors' ] },
	{ path: 'exporters/MMDExporter.js', ignoreList: [] },
	{ path: 'exporters/OBJExporter.js', ignoreList: [] },
	{ path: 'exporters/PLYExporter.js', ignoreList: [] },
	{ path: 'exporters/STLExporter.js', ignoreList: [] },
	{ path: 'exporters/TypedGeometryExporter.js', ignoreList: [] },
	{ path: 'loaders/GLTFLoader.js', ignoreList: [ 'NoSide', 'Matrix2', 'DDSLoader' ] },
	{ path: 'loaders/OBJLoader.js', ignoreList: [] },
	{ path: 'loaders/MTLLoader.js', ignoreList: [] }
];

for ( var i = 0; i < files.length; i ++ ) {

	var file = files[ i ];
	convert( file.path, file.ignoreList );

}

//

function convert( path, ignoreList ) {

	var contents = fs.readFileSync( srcFolder + path, 'utf8' );

	var className = '';
	var dependencies = {};

	// imports

	contents = contents.replace( /^\/\*+[^*]*\*+(?:[^/*][^*]*\*+)*\//, function ( match ) {

		return `${match}\n\n_IMPORTS_`;

	} );

	// class name

	contents = contents.replace( /THREE\.([a-zA-Z0-9]+) = /g, function ( match, p1 ) {

		className = p1;

		console.log( className );

		return `var ${p1} = `;

	} );

	contents = contents.replace( /(\'?)THREE\.([a-zA-Z0-9]+)(\.{0,1})/g, function ( match, p1, p2, p3 ) {

		if ( p1 === '\'' ) return match; // Inside a string
		if ( p2 === className ) return `${p2}${p3}`;

		if ( p1 === 'Math' ) {

			dependencies[ '_Math' ] = true;

			return '_Math.';

		}

		return match;

	} );

	// methods

	contents = contents.replace( /new THREE\.([a-zA-Z0-9]+)\(/g, function ( match, p1 ) {

		if ( ignoreList.includes( p1 ) ) return match;

		dependencies[ p1 ] = true;

		return `new ${p1}(`;

	} );

	// constants

	contents = contents.replace( /(\'?)THREE\.([a-zA-Z0-9]+)/g, function ( match, p1, p2 ) {

		if ( ignoreList.includes( p2 ) ) return match;
		if ( p1 === '\'' ) return match; // Inside a string
		if ( p2 === className ) return p2;

		if ( p2 === 'Math' || p2 === '_Math' ) {

			dependencies[ '_Math' ] = true;

			return '_Math';

		}

		dependencies[ p2 ] = true;

		// console.log( match, p2 );

		return `${p2}`;

	} );

	//

	var keys = Object.keys( dependencies )
		.filter( value => value !== className )
		.map( value => value === '_Math' ? 'Math as _Math' : value )
		.map( value => '\n\t' + value )
		.sort()
		.toString();
	var imports = `import {${keys}\n} from "../../../build/three.module.js";`;
	var exports = `export { ${className} };\n`;

	var output = contents.replace( '_IMPORTS_', keys ? imports : '' ) + '\n' + exports;

	// console.log( output );

	fs.writeFileSync( dstFolder + path, output, 'utf-8' );

};
<|endoftext|>